clang  3.9.0
SemaDeclCXX.cpp
Go to the documentation of this file.
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 
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
20 #include "clang/AST/CharUnits.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/RecordLayout.h"
25 #include "clang/AST/StmtVisitor.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/AST/TypeOrdering.h"
29 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Sema/DeclSpec.h"
35 #include "clang/Sema/Lookup.h"
37 #include "clang/Sema/Scope.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/Template.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/SmallString.h"
42 #include <map>
43 #include <set>
44 
45 using namespace clang;
46 
47 //===----------------------------------------------------------------------===//
48 // CheckDefaultArgumentVisitor
49 //===----------------------------------------------------------------------===//
50 
51 namespace {
52  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
53  /// the default argument of a parameter to determine whether it
54  /// contains any ill-formed subexpressions. For example, this will
55  /// diagnose the use of local variables or parameters within the
56  /// default argument expression.
57  class CheckDefaultArgumentVisitor
58  : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
59  Expr *DefaultArg;
60  Sema *S;
61 
62  public:
63  CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
64  : DefaultArg(defarg), S(s) {}
65 
66  bool VisitExpr(Expr *Node);
67  bool VisitDeclRefExpr(DeclRefExpr *DRE);
68  bool VisitCXXThisExpr(CXXThisExpr *ThisE);
69  bool VisitLambdaExpr(LambdaExpr *Lambda);
70  bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
71  };
72 
73  /// VisitExpr - Visit all of the children of this expression.
74  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
75  bool IsInvalid = false;
76  for (Stmt *SubStmt : Node->children())
77  IsInvalid |= Visit(SubStmt);
78  return IsInvalid;
79  }
80 
81  /// VisitDeclRefExpr - Visit a reference to a declaration, to
82  /// determine whether this declaration can be used in the default
83  /// argument expression.
84  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
85  NamedDecl *Decl = DRE->getDecl();
86  if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
87  // C++ [dcl.fct.default]p9
88  // Default arguments are evaluated each time the function is
89  // called. The order of evaluation of function arguments is
90  // unspecified. Consequently, parameters of a function shall not
91  // be used in default argument expressions, even if they are not
92  // evaluated. Parameters of a function declared before a default
93  // argument expression are in scope and can hide namespace and
94  // class member names.
95  return S->Diag(DRE->getLocStart(),
96  diag::err_param_default_argument_references_param)
97  << Param->getDeclName() << DefaultArg->getSourceRange();
98  } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
99  // C++ [dcl.fct.default]p7
100  // Local variables shall not be used in default argument
101  // expressions.
102  if (VDecl->isLocalVarDecl())
103  return S->Diag(DRE->getLocStart(),
104  diag::err_param_default_argument_references_local)
105  << VDecl->getDeclName() << DefaultArg->getSourceRange();
106  }
107 
108  return false;
109  }
110 
111  /// VisitCXXThisExpr - Visit a C++ "this" expression.
112  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
113  // C++ [dcl.fct.default]p8:
114  // The keyword this shall not be used in a default argument of a
115  // member function.
116  return S->Diag(ThisE->getLocStart(),
117  diag::err_param_default_argument_references_this)
118  << ThisE->getSourceRange();
119  }
120 
121  bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
122  bool Invalid = false;
124  i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
125  Expr *E = *i;
126 
127  // Look through bindings.
128  if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
129  E = OVE->getSourceExpr();
130  assert(E && "pseudo-object binding without source expression?");
131  }
132 
133  Invalid |= Visit(E);
134  }
135  return Invalid;
136  }
137 
138  bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
139  // C++11 [expr.lambda.prim]p13:
140  // A lambda-expression appearing in a default argument shall not
141  // implicitly or explicitly capture any entity.
142  if (Lambda->capture_begin() == Lambda->capture_end())
143  return false;
144 
145  return S->Diag(Lambda->getLocStart(),
146  diag::err_lambda_capture_default_arg);
147  }
148 }
149 
150 void
152  const CXXMethodDecl *Method) {
153  // If we have an MSAny spec already, don't bother.
154  if (!Method || ComputedEST == EST_MSAny)
155  return;
156 
157  const FunctionProtoType *Proto
158  = Method->getType()->getAs<FunctionProtoType>();
159  Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160  if (!Proto)
161  return;
162 
164 
165  // If we have a throw-all spec at this point, ignore the function.
166  if (ComputedEST == EST_None)
167  return;
168 
169  switch(EST) {
170  // If this function can throw any exceptions, make a note of that.
171  case EST_MSAny:
172  case EST_None:
173  ClearExceptions();
174  ComputedEST = EST;
175  return;
176  // FIXME: If the call to this decl is using any of its default arguments, we
177  // need to search them for potentially-throwing calls.
178  // If this function has a basic noexcept, it doesn't affect the outcome.
179  case EST_BasicNoexcept:
180  return;
181  // If we're still at noexcept(true) and there's a nothrow() callee,
182  // change to that specification.
183  case EST_DynamicNone:
184  if (ComputedEST == EST_BasicNoexcept)
185  ComputedEST = EST_DynamicNone;
186  return;
187  // Check out noexcept specs.
189  {
191  Proto->getNoexceptSpec(Self->Context);
192  assert(NR != FunctionProtoType::NR_NoNoexcept &&
193  "Must have noexcept result for EST_ComputedNoexcept.");
194  assert(NR != FunctionProtoType::NR_Dependent &&
195  "Should not generate implicit declarations for dependent cases, "
196  "and don't know how to handle them anyway.");
197  // noexcept(false) -> no spec on the new function
198  if (NR == FunctionProtoType::NR_Throw) {
199  ClearExceptions();
200  ComputedEST = EST_None;
201  }
202  // noexcept(true) won't change anything either.
203  return;
204  }
205  default:
206  break;
207  }
208  assert(EST == EST_Dynamic && "EST case not considered earlier.");
209  assert(ComputedEST != EST_None &&
210  "Shouldn't collect exceptions when throw-all is guaranteed.");
211  ComputedEST = EST_Dynamic;
212  // Record the exceptions in this function's exception specification.
213  for (const auto &E : Proto->exceptions())
214  if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
215  Exceptions.push_back(E);
216 }
217 
219  if (!E || ComputedEST == EST_MSAny)
220  return;
221 
222  // FIXME:
223  //
224  // C++0x [except.spec]p14:
225  // [An] implicit exception-specification specifies the type-id T if and
226  // only if T is allowed by the exception-specification of a function directly
227  // invoked by f's implicit definition; f shall allow all exceptions if any
228  // function it directly invokes allows all exceptions, and f shall allow no
229  // exceptions if every function it directly invokes allows no exceptions.
230  //
231  // Note in particular that if an implicit exception-specification is generated
232  // for a function containing a throw-expression, that specification can still
233  // be noexcept(true).
234  //
235  // Note also that 'directly invoked' is not defined in the standard, and there
236  // is no indication that we should only consider potentially-evaluated calls.
237  //
238  // Ultimately we should implement the intent of the standard: the exception
239  // specification should be the set of exceptions which can be thrown by the
240  // implicit definition. For now, we assume that any non-nothrow expression can
241  // throw any exception.
242 
243  if (Self->canThrow(E))
244  ComputedEST = EST_None;
245 }
246 
247 bool
249  SourceLocation EqualLoc) {
250  if (RequireCompleteType(Param->getLocation(), Param->getType(),
251  diag::err_typecheck_decl_incomplete_type)) {
252  Param->setInvalidDecl();
253  return true;
254  }
255 
256  // C++ [dcl.fct.default]p5
257  // A default argument expression is implicitly converted (clause
258  // 4) to the parameter type. The default argument expression has
259  // the same semantic constraints as the initializer expression in
260  // a declaration of a variable of the parameter type, using the
261  // copy-initialization semantics (8.5).
263  Param);
265  EqualLoc);
266  InitializationSequence InitSeq(*this, Entity, Kind, Arg);
267  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
268  if (Result.isInvalid())
269  return true;
270  Arg = Result.getAs<Expr>();
271 
272  CheckCompletedExpr(Arg, EqualLoc);
273  Arg = MaybeCreateExprWithCleanups(Arg);
274 
275  // Okay: add the default argument to the parameter
276  Param->setDefaultArg(Arg);
277 
278  // We have already instantiated this parameter; provide each of the
279  // instantiations with the uninstantiated default argument.
281  = UnparsedDefaultArgInstantiations.find(Param);
282  if (InstPos != UnparsedDefaultArgInstantiations.end()) {
283  for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
284  InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
285 
286  // We're done tracking this parameter's instantiations.
287  UnparsedDefaultArgInstantiations.erase(InstPos);
288  }
289 
290  return false;
291 }
292 
293 /// ActOnParamDefaultArgument - Check whether the default argument
294 /// provided for a function parameter is well-formed. If so, attach it
295 /// to the parameter declaration.
296 void
298  Expr *DefaultArg) {
299  if (!param || !DefaultArg)
300  return;
301 
302  ParmVarDecl *Param = cast<ParmVarDecl>(param);
303  UnparsedDefaultArgLocs.erase(Param);
304 
305  // Default arguments are only permitted in C++
306  if (!getLangOpts().CPlusPlus) {
307  Diag(EqualLoc, diag::err_param_default_argument)
308  << DefaultArg->getSourceRange();
309  Param->setInvalidDecl();
310  return;
311  }
312 
313  // Check for unexpanded parameter packs.
315  Param->setInvalidDecl();
316  return;
317  }
318 
319  // C++11 [dcl.fct.default]p3
320  // A default argument expression [...] shall not be specified for a
321  // parameter pack.
322  if (Param->isParameterPack()) {
323  Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
324  << DefaultArg->getSourceRange();
325  return;
326  }
327 
328  // Check that the default argument is well-formed
329  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
330  if (DefaultArgChecker.Visit(DefaultArg)) {
331  Param->setInvalidDecl();
332  return;
333  }
334 
335  SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
336 }
337 
338 /// ActOnParamUnparsedDefaultArgument - We've seen a default
339 /// argument for a function parameter, but we can't parse it yet
340 /// because we're inside a class definition. Note that this default
341 /// argument will be parsed later.
343  SourceLocation EqualLoc,
344  SourceLocation ArgLoc) {
345  if (!param)
346  return;
347 
348  ParmVarDecl *Param = cast<ParmVarDecl>(param);
349  Param->setUnparsedDefaultArg();
350  UnparsedDefaultArgLocs[Param] = ArgLoc;
351 }
352 
353 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
354 /// the default argument for the parameter param failed.
356  SourceLocation EqualLoc) {
357  if (!param)
358  return;
359 
360  ParmVarDecl *Param = cast<ParmVarDecl>(param);
361  Param->setInvalidDecl();
362  UnparsedDefaultArgLocs.erase(Param);
363  Param->setDefaultArg(new(Context)
364  OpaqueValueExpr(EqualLoc,
365  Param->getType().getNonReferenceType(),
366  VK_RValue));
367 }
368 
369 /// CheckExtraCXXDefaultArguments - Check for any extra default
370 /// arguments in the declarator, which is not a function declaration
371 /// or definition and therefore is not permitted to have default
372 /// arguments. This routine should be invoked for every declarator
373 /// that is not a function declaration or definition.
375  // C++ [dcl.fct.default]p3
376  // A default argument expression shall be specified only in the
377  // parameter-declaration-clause of a function declaration or in a
378  // template-parameter (14.1). It shall not be specified for a
379  // parameter pack. If it is specified in a
380  // parameter-declaration-clause, it shall not occur within a
381  // declarator or abstract-declarator of a parameter-declaration.
382  bool MightBeFunction = D.isFunctionDeclarationContext();
383  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
384  DeclaratorChunk &chunk = D.getTypeObject(i);
385  if (chunk.Kind == DeclaratorChunk::Function) {
386  if (MightBeFunction) {
387  // This is a function declaration. It can have default arguments, but
388  // keep looking in case its return type is a function type with default
389  // arguments.
390  MightBeFunction = false;
391  continue;
392  }
393  for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
394  ++argIdx) {
395  ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
396  if (Param->hasUnparsedDefaultArg()) {
397  CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
398  SourceRange SR;
399  if (Toks->size() > 1)
400  SR = SourceRange((*Toks)[1].getLocation(),
401  Toks->back().getLocation());
402  else
403  SR = UnparsedDefaultArgLocs[Param];
404  Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
405  << SR;
406  delete Toks;
407  chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
408  } else if (Param->getDefaultArg()) {
409  Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
410  << Param->getDefaultArg()->getSourceRange();
411  Param->setDefaultArg(nullptr);
412  }
413  }
414  } else if (chunk.Kind != DeclaratorChunk::Paren) {
415  MightBeFunction = false;
416  }
417  }
418 }
419 
421  for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
422  const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
423  if (!PVD->hasDefaultArg())
424  return false;
425  if (!PVD->hasInheritedDefaultArg())
426  return true;
427  }
428  return false;
429 }
430 
431 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
432 /// function, once we already know that they have the same
433 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
434 /// error, false otherwise.
436  Scope *S) {
437  bool Invalid = false;
438 
439  // The declaration context corresponding to the scope is the semantic
440  // parent, unless this is a local function declaration, in which case
441  // it is that surrounding function.
442  DeclContext *ScopeDC = New->isLocalExternDecl()
443  ? New->getLexicalDeclContext()
444  : New->getDeclContext();
445 
446  // Find the previous declaration for the purpose of default arguments.
447  FunctionDecl *PrevForDefaultArgs = Old;
448  for (/**/; PrevForDefaultArgs;
449  // Don't bother looking back past the latest decl if this is a local
450  // extern declaration; nothing else could work.
451  PrevForDefaultArgs = New->isLocalExternDecl()
452  ? nullptr
453  : PrevForDefaultArgs->getPreviousDecl()) {
454  // Ignore hidden declarations.
455  if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
456  continue;
457 
458  if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
459  !New->isCXXClassMember()) {
460  // Ignore default arguments of old decl if they are not in
461  // the same scope and this is not an out-of-line definition of
462  // a member function.
463  continue;
464  }
465 
466  if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
467  // If only one of these is a local function declaration, then they are
468  // declared in different scopes, even though isDeclInScope may think
469  // they're in the same scope. (If both are local, the scope check is
470  // sufficent, and if neither is local, then they are in the same scope.)
471  continue;
472  }
473 
474  // We found the right previous declaration.
475  break;
476  }
477 
478  // C++ [dcl.fct.default]p4:
479  // For non-template functions, default arguments can be added in
480  // later declarations of a function in the same
481  // scope. Declarations in different scopes have completely
482  // distinct sets of default arguments. That is, declarations in
483  // inner scopes do not acquire default arguments from
484  // declarations in outer scopes, and vice versa. In a given
485  // function declaration, all parameters subsequent to a
486  // parameter with a default argument shall have default
487  // arguments supplied in this or previous declarations. A
488  // default argument shall not be redefined by a later
489  // declaration (not even to the same value).
490  //
491  // C++ [dcl.fct.default]p6:
492  // Except for member functions of class templates, the default arguments
493  // in a member function definition that appears outside of the class
494  // definition are added to the set of default arguments provided by the
495  // member function declaration in the class definition.
496  for (unsigned p = 0, NumParams = PrevForDefaultArgs
497  ? PrevForDefaultArgs->getNumParams()
498  : 0;
499  p < NumParams; ++p) {
500  ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
501  ParmVarDecl *NewParam = New->getParamDecl(p);
502 
503  bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
504  bool NewParamHasDfl = NewParam->hasDefaultArg();
505 
506  if (OldParamHasDfl && NewParamHasDfl) {
507  unsigned DiagDefaultParamID =
508  diag::err_param_default_argument_redefinition;
509 
510  // MSVC accepts that default parameters be redefined for member functions
511  // of template class. The new default parameter's value is ignored.
512  Invalid = true;
513  if (getLangOpts().MicrosoftExt) {
514  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
515  if (MD && MD->getParent()->getDescribedClassTemplate()) {
516  // Merge the old default argument into the new parameter.
517  NewParam->setHasInheritedDefaultArg();
518  if (OldParam->hasUninstantiatedDefaultArg())
519  NewParam->setUninstantiatedDefaultArg(
520  OldParam->getUninstantiatedDefaultArg());
521  else
522  NewParam->setDefaultArg(OldParam->getInit());
523  DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
524  Invalid = false;
525  }
526  }
527 
528  // FIXME: If we knew where the '=' was, we could easily provide a fix-it
529  // hint here. Alternatively, we could walk the type-source information
530  // for NewParam to find the last source location in the type... but it
531  // isn't worth the effort right now. This is the kind of test case that
532  // is hard to get right:
533  // int f(int);
534  // void g(int (*fp)(int) = f);
535  // void g(int (*fp)(int) = &f);
536  Diag(NewParam->getLocation(), DiagDefaultParamID)
537  << NewParam->getDefaultArgRange();
538 
539  // Look for the function declaration where the default argument was
540  // actually written, which may be a declaration prior to Old.
541  for (auto Older = PrevForDefaultArgs;
542  OldParam->hasInheritedDefaultArg(); /**/) {
543  Older = Older->getPreviousDecl();
544  OldParam = Older->getParamDecl(p);
545  }
546 
547  Diag(OldParam->getLocation(), diag::note_previous_definition)
548  << OldParam->getDefaultArgRange();
549  } else if (OldParamHasDfl) {
550  // Merge the old default argument into the new parameter.
551  // It's important to use getInit() here; getDefaultArg()
552  // strips off any top-level ExprWithCleanups.
553  NewParam->setHasInheritedDefaultArg();
554  if (OldParam->hasUnparsedDefaultArg())
555  NewParam->setUnparsedDefaultArg();
556  else if (OldParam->hasUninstantiatedDefaultArg())
557  NewParam->setUninstantiatedDefaultArg(
558  OldParam->getUninstantiatedDefaultArg());
559  else
560  NewParam->setDefaultArg(OldParam->getInit());
561  } else if (NewParamHasDfl) {
562  if (New->getDescribedFunctionTemplate()) {
563  // Paragraph 4, quoted above, only applies to non-template functions.
564  Diag(NewParam->getLocation(),
565  diag::err_param_default_argument_template_redecl)
566  << NewParam->getDefaultArgRange();
567  Diag(PrevForDefaultArgs->getLocation(),
568  diag::note_template_prev_declaration)
569  << false;
570  } else if (New->getTemplateSpecializationKind()
573  // C++ [temp.expr.spec]p21:
574  // Default function arguments shall not be specified in a declaration
575  // or a definition for one of the following explicit specializations:
576  // - the explicit specialization of a function template;
577  // - the explicit specialization of a member function template;
578  // - the explicit specialization of a member function of a class
579  // template where the class template specialization to which the
580  // member function specialization belongs is implicitly
581  // instantiated.
582  Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
584  << New->getDeclName()
585  << NewParam->getDefaultArgRange();
586  } else if (New->getDeclContext()->isDependentContext()) {
587  // C++ [dcl.fct.default]p6 (DR217):
588  // Default arguments for a member function of a class template shall
589  // be specified on the initial declaration of the member function
590  // within the class template.
591  //
592  // Reading the tea leaves a bit in DR217 and its reference to DR205
593  // leads me to the conclusion that one cannot add default function
594  // arguments for an out-of-line definition of a member function of a
595  // dependent type.
596  int WhichKind = 2;
597  if (CXXRecordDecl *Record
598  = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
599  if (Record->getDescribedClassTemplate())
600  WhichKind = 0;
601  else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
602  WhichKind = 1;
603  else
604  WhichKind = 2;
605  }
606 
607  Diag(NewParam->getLocation(),
608  diag::err_param_default_argument_member_template_redecl)
609  << WhichKind
610  << NewParam->getDefaultArgRange();
611  }
612  }
613  }
614 
615  // DR1344: If a default argument is added outside a class definition and that
616  // default argument makes the function a special member function, the program
617  // is ill-formed. This can only happen for constructors.
618  if (isa<CXXConstructorDecl>(New) &&
620  CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
621  OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
622  if (NewSM != OldSM) {
623  ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
624  assert(NewParam->hasDefaultArg());
625  Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
626  << NewParam->getDefaultArgRange() << NewSM;
627  Diag(Old->getLocation(), diag::note_previous_declaration);
628  }
629  }
630 
631  const FunctionDecl *Def;
632  // C++11 [dcl.constexpr]p1: If any declaration of a function or function
633  // template has a constexpr specifier then all its declarations shall
634  // contain the constexpr specifier.
635  if (New->isConstexpr() != Old->isConstexpr()) {
636  Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
637  << New << New->isConstexpr();
638  Diag(Old->getLocation(), diag::note_previous_declaration);
639  Invalid = true;
640  } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
641  Old->isDefined(Def)) {
642  // C++11 [dcl.fcn.spec]p4:
643  // If the definition of a function appears in a translation unit before its
644  // first declaration as inline, the program is ill-formed.
645  Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
646  Diag(Def->getLocation(), diag::note_previous_definition);
647  Invalid = true;
648  }
649 
650  // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
651  // argument expression, that declaration shall be a definition and shall be
652  // the only declaration of the function or function template in the
653  // translation unit.
654  if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
656  Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
657  Diag(Old->getLocation(), diag::note_previous_declaration);
658  Invalid = true;
659  }
660 
661  if (CheckEquivalentExceptionSpec(Old, New))
662  Invalid = true;
663 
664  return Invalid;
665 }
666 
667 /// \brief Merge the exception specifications of two variable declarations.
668 ///
669 /// This is called when there's a redeclaration of a VarDecl. The function
670 /// checks if the redeclaration might have an exception specification and
671 /// validates compatibility and merges the specs if necessary.
673  // Shortcut if exceptions are disabled.
674  if (!getLangOpts().CXXExceptions)
675  return;
676 
677  assert(Context.hasSameType(New->getType(), Old->getType()) &&
678  "Should only be called if types are otherwise the same.");
679 
680  QualType NewType = New->getType();
681  QualType OldType = Old->getType();
682 
683  // We're only interested in pointers and references to functions, as well
684  // as pointers to member functions.
685  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
686  NewType = R->getPointeeType();
687  OldType = OldType->getAs<ReferenceType>()->getPointeeType();
688  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
689  NewType = P->getPointeeType();
690  OldType = OldType->getAs<PointerType>()->getPointeeType();
691  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
692  NewType = M->getPointeeType();
693  OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
694  }
695 
696  if (!NewType->isFunctionProtoType())
697  return;
698 
699  // There's lots of special cases for functions. For function pointers, system
700  // libraries are hopefully not as broken so that we don't need these
701  // workarounds.
703  OldType->getAs<FunctionProtoType>(), Old->getLocation(),
704  NewType->getAs<FunctionProtoType>(), New->getLocation())) {
705  New->setInvalidDecl();
706  }
707 }
708 
709 /// CheckCXXDefaultArguments - Verify that the default arguments for a
710 /// function declaration are well-formed according to C++
711 /// [dcl.fct.default].
713  unsigned NumParams = FD->getNumParams();
714  unsigned p;
715 
716  // Find first parameter with a default argument
717  for (p = 0; p < NumParams; ++p) {
718  ParmVarDecl *Param = FD->getParamDecl(p);
719  if (Param->hasDefaultArg())
720  break;
721  }
722 
723  // C++11 [dcl.fct.default]p4:
724  // In a given function declaration, each parameter subsequent to a parameter
725  // with a default argument shall have a default argument supplied in this or
726  // a previous declaration or shall be a function parameter pack. A default
727  // argument shall not be redefined by a later declaration (not even to the
728  // same value).
729  unsigned LastMissingDefaultArg = 0;
730  for (; p < NumParams; ++p) {
731  ParmVarDecl *Param = FD->getParamDecl(p);
732  if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
733  if (Param->isInvalidDecl())
734  /* We already complained about this parameter. */;
735  else if (Param->getIdentifier())
736  Diag(Param->getLocation(),
737  diag::err_param_default_argument_missing_name)
738  << Param->getIdentifier();
739  else
740  Diag(Param->getLocation(),
741  diag::err_param_default_argument_missing);
742 
743  LastMissingDefaultArg = p;
744  }
745  }
746 
747  if (LastMissingDefaultArg > 0) {
748  // Some default arguments were missing. Clear out all of the
749  // default arguments up to (and including) the last missing
750  // default argument, so that we leave the function parameters
751  // in a semantically valid state.
752  for (p = 0; p <= LastMissingDefaultArg; ++p) {
753  ParmVarDecl *Param = FD->getParamDecl(p);
754  if (Param->hasDefaultArg()) {
755  Param->setDefaultArg(nullptr);
756  }
757  }
758  }
759 }
760 
761 // CheckConstexprParameterTypes - Check whether a function's parameter types
762 // are all literal types. If so, return true. If not, produce a suitable
763 // diagnostic and return false.
764 static bool CheckConstexprParameterTypes(Sema &SemaRef,
765  const FunctionDecl *FD) {
766  unsigned ArgIndex = 0;
767  const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
769  e = FT->param_type_end();
770  i != e; ++i, ++ArgIndex) {
771  const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
772  SourceLocation ParamLoc = PD->getLocation();
773  if (!(*i)->isDependentType() &&
774  SemaRef.RequireLiteralType(ParamLoc, *i,
775  diag::err_constexpr_non_literal_param,
776  ArgIndex+1, PD->getSourceRange(),
777  isa<CXXConstructorDecl>(FD)))
778  return false;
779  }
780  return true;
781 }
782 
783 /// \brief Get diagnostic %select index for tag kind for
784 /// record diagnostic message.
785 /// WARNING: Indexes apply to particular diagnostics only!
786 ///
787 /// \returns diagnostic %select index.
788 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
789  switch (Tag) {
790  case TTK_Struct: return 0;
791  case TTK_Interface: return 1;
792  case TTK_Class: return 2;
793  default: llvm_unreachable("Invalid tag kind for record diagnostic!");
794  }
795 }
796 
797 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
798 // the requirements of a constexpr function definition or a constexpr
799 // constructor definition. If so, return true. If not, produce appropriate
800 // diagnostics and return false.
801 //
802 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
804  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
805  if (MD && MD->isInstance()) {
806  // C++11 [dcl.constexpr]p4:
807  // The definition of a constexpr constructor shall satisfy the following
808  // constraints:
809  // - the class shall not have any virtual base classes;
810  const CXXRecordDecl *RD = MD->getParent();
811  if (RD->getNumVBases()) {
812  Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
813  << isa<CXXConstructorDecl>(NewFD)
815  for (const auto &I : RD->vbases())
816  Diag(I.getLocStart(),
817  diag::note_constexpr_virtual_base_here) << I.getSourceRange();
818  return false;
819  }
820  }
821 
822  if (!isa<CXXConstructorDecl>(NewFD)) {
823  // C++11 [dcl.constexpr]p3:
824  // The definition of a constexpr function shall satisfy the following
825  // constraints:
826  // - it shall not be virtual;
827  const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
828  if (Method && Method->isVirtual()) {
829  Method = Method->getCanonicalDecl();
830  Diag(Method->getLocation(), diag::err_constexpr_virtual);
831 
832  // If it's not obvious why this function is virtual, find an overridden
833  // function which uses the 'virtual' keyword.
834  const CXXMethodDecl *WrittenVirtual = Method;
835  while (!WrittenVirtual->isVirtualAsWritten())
836  WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
837  if (WrittenVirtual != Method)
838  Diag(WrittenVirtual->getLocation(),
839  diag::note_overridden_virtual_function);
840  return false;
841  }
842 
843  // - its return type shall be a literal type;
844  QualType RT = NewFD->getReturnType();
845  if (!RT->isDependentType() &&
846  RequireLiteralType(NewFD->getLocation(), RT,
847  diag::err_constexpr_non_literal_return))
848  return false;
849  }
850 
851  // - each of its parameter types shall be a literal type;
852  if (!CheckConstexprParameterTypes(*this, NewFD))
853  return false;
854 
855  return true;
856 }
857 
858 /// Check the given declaration statement is legal within a constexpr function
859 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
860 ///
861 /// \return true if the body is OK (maybe only as an extension), false if we
862 /// have diagnosed a problem.
863 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
864  DeclStmt *DS, SourceLocation &Cxx1yLoc) {
865  // C++11 [dcl.constexpr]p3 and p4:
866  // The definition of a constexpr function(p3) or constructor(p4) [...] shall
867  // contain only
868  for (const auto *DclIt : DS->decls()) {
869  switch (DclIt->getKind()) {
870  case Decl::StaticAssert:
871  case Decl::Using:
872  case Decl::UsingShadow:
873  case Decl::UsingDirective:
874  case Decl::UnresolvedUsingTypename:
875  case Decl::UnresolvedUsingValue:
876  // - static_assert-declarations
877  // - using-declarations,
878  // - using-directives,
879  continue;
880 
881  case Decl::Typedef:
882  case Decl::TypeAlias: {
883  // - typedef declarations and alias-declarations that do not define
884  // classes or enumerations,
885  const auto *TN = cast<TypedefNameDecl>(DclIt);
886  if (TN->getUnderlyingType()->isVariablyModifiedType()) {
887  // Don't allow variably-modified types in constexpr functions.
888  TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
889  SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
890  << TL.getSourceRange() << TL.getType()
891  << isa<CXXConstructorDecl>(Dcl);
892  return false;
893  }
894  continue;
895  }
896 
897  case Decl::Enum:
898  case Decl::CXXRecord:
899  // C++1y allows types to be defined, not just declared.
900  if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
901  SemaRef.Diag(DS->getLocStart(),
902  SemaRef.getLangOpts().CPlusPlus14
903  ? diag::warn_cxx11_compat_constexpr_type_definition
904  : diag::ext_constexpr_type_definition)
905  << isa<CXXConstructorDecl>(Dcl);
906  continue;
907 
908  case Decl::EnumConstant:
909  case Decl::IndirectField:
910  case Decl::ParmVar:
911  // These can only appear with other declarations which are banned in
912  // C++11 and permitted in C++1y, so ignore them.
913  continue;
914 
915  case Decl::Var: {
916  // C++1y [dcl.constexpr]p3 allows anything except:
917  // a definition of a variable of non-literal type or of static or
918  // thread storage duration or for which no initialization is performed.
919  const auto *VD = cast<VarDecl>(DclIt);
920  if (VD->isThisDeclarationADefinition()) {
921  if (VD->isStaticLocal()) {
922  SemaRef.Diag(VD->getLocation(),
923  diag::err_constexpr_local_var_static)
924  << isa<CXXConstructorDecl>(Dcl)
925  << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
926  return false;
927  }
928  if (!VD->getType()->isDependentType() &&
929  SemaRef.RequireLiteralType(
930  VD->getLocation(), VD->getType(),
931  diag::err_constexpr_local_var_non_literal_type,
932  isa<CXXConstructorDecl>(Dcl)))
933  return false;
934  if (!VD->getType()->isDependentType() &&
935  !VD->hasInit() && !VD->isCXXForRangeDecl()) {
936  SemaRef.Diag(VD->getLocation(),
937  diag::err_constexpr_local_var_no_init)
938  << isa<CXXConstructorDecl>(Dcl);
939  return false;
940  }
941  }
942  SemaRef.Diag(VD->getLocation(),
943  SemaRef.getLangOpts().CPlusPlus14
944  ? diag::warn_cxx11_compat_constexpr_local_var
945  : diag::ext_constexpr_local_var)
946  << isa<CXXConstructorDecl>(Dcl);
947  continue;
948  }
949 
950  case Decl::NamespaceAlias:
951  case Decl::Function:
952  // These are disallowed in C++11 and permitted in C++1y. Allow them
953  // everywhere as an extension.
954  if (!Cxx1yLoc.isValid())
955  Cxx1yLoc = DS->getLocStart();
956  continue;
957 
958  default:
959  SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
960  << isa<CXXConstructorDecl>(Dcl);
961  return false;
962  }
963  }
964 
965  return true;
966 }
967 
968 /// Check that the given field is initialized within a constexpr constructor.
969 ///
970 /// \param Dcl The constexpr constructor being checked.
971 /// \param Field The field being checked. This may be a member of an anonymous
972 /// struct or union nested within the class being checked.
973 /// \param Inits All declarations, including anonymous struct/union members and
974 /// indirect members, for which any initialization was provided.
975 /// \param Diagnosed Set to true if an error is produced.
976 static void CheckConstexprCtorInitializer(Sema &SemaRef,
977  const FunctionDecl *Dcl,
978  FieldDecl *Field,
979  llvm::SmallSet<Decl*, 16> &Inits,
980  bool &Diagnosed) {
981  if (Field->isInvalidDecl())
982  return;
983 
984  if (Field->isUnnamedBitfield())
985  return;
986 
987  // Anonymous unions with no variant members and empty anonymous structs do not
988  // need to be explicitly initialized. FIXME: Anonymous structs that contain no
989  // indirect fields don't need initializing.
990  if (Field->isAnonymousStructOrUnion() &&
991  (Field->getType()->isUnionType()
993  : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
994  return;
995 
996  if (!Inits.count(Field)) {
997  if (!Diagnosed) {
998  SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
999  Diagnosed = true;
1000  }
1001  SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1002  } else if (Field->isAnonymousStructOrUnion()) {
1003  const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1004  for (auto *I : RD->fields())
1005  // If an anonymous union contains an anonymous struct of which any member
1006  // is initialized, all members must be initialized.
1007  if (!RD->isUnion() || Inits.count(I))
1008  CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1009  }
1010 }
1011 
1012 /// Check the provided statement is allowed in a constexpr function
1013 /// definition.
1014 static bool
1016  SmallVectorImpl<SourceLocation> &ReturnStmts,
1017  SourceLocation &Cxx1yLoc) {
1018  // - its function-body shall be [...] a compound-statement that contains only
1019  switch (S->getStmtClass()) {
1020  case Stmt::NullStmtClass:
1021  // - null statements,
1022  return true;
1023 
1024  case Stmt::DeclStmtClass:
1025  // - static_assert-declarations
1026  // - using-declarations,
1027  // - using-directives,
1028  // - typedef declarations and alias-declarations that do not define
1029  // classes or enumerations,
1030  if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1031  return false;
1032  return true;
1033 
1034  case Stmt::ReturnStmtClass:
1035  // - and exactly one return statement;
1036  if (isa<CXXConstructorDecl>(Dcl)) {
1037  // C++1y allows return statements in constexpr constructors.
1038  if (!Cxx1yLoc.isValid())
1039  Cxx1yLoc = S->getLocStart();
1040  return true;
1041  }
1042 
1043  ReturnStmts.push_back(S->getLocStart());
1044  return true;
1045 
1046  case Stmt::CompoundStmtClass: {
1047  // C++1y allows compound-statements.
1048  if (!Cxx1yLoc.isValid())
1049  Cxx1yLoc = S->getLocStart();
1050 
1051  CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1052  for (auto *BodyIt : CompStmt->body()) {
1053  if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1054  Cxx1yLoc))
1055  return false;
1056  }
1057  return true;
1058  }
1059 
1060  case Stmt::AttributedStmtClass:
1061  if (!Cxx1yLoc.isValid())
1062  Cxx1yLoc = S->getLocStart();
1063  return true;
1064 
1065  case Stmt::IfStmtClass: {
1066  // C++1y allows if-statements.
1067  if (!Cxx1yLoc.isValid())
1068  Cxx1yLoc = S->getLocStart();
1069 
1070  IfStmt *If = cast<IfStmt>(S);
1071  if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1072  Cxx1yLoc))
1073  return false;
1074  if (If->getElse() &&
1075  !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1076  Cxx1yLoc))
1077  return false;
1078  return true;
1079  }
1080 
1081  case Stmt::WhileStmtClass:
1082  case Stmt::DoStmtClass:
1083  case Stmt::ForStmtClass:
1084  case Stmt::CXXForRangeStmtClass:
1085  case Stmt::ContinueStmtClass:
1086  // C++1y allows all of these. We don't allow them as extensions in C++11,
1087  // because they don't make sense without variable mutation.
1088  if (!SemaRef.getLangOpts().CPlusPlus14)
1089  break;
1090  if (!Cxx1yLoc.isValid())
1091  Cxx1yLoc = S->getLocStart();
1092  for (Stmt *SubStmt : S->children())
1093  if (SubStmt &&
1094  !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1095  Cxx1yLoc))
1096  return false;
1097  return true;
1098 
1099  case Stmt::SwitchStmtClass:
1100  case Stmt::CaseStmtClass:
1101  case Stmt::DefaultStmtClass:
1102  case Stmt::BreakStmtClass:
1103  // C++1y allows switch-statements, and since they don't need variable
1104  // mutation, we can reasonably allow them in C++11 as an extension.
1105  if (!Cxx1yLoc.isValid())
1106  Cxx1yLoc = S->getLocStart();
1107  for (Stmt *SubStmt : S->children())
1108  if (SubStmt &&
1109  !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1110  Cxx1yLoc))
1111  return false;
1112  return true;
1113 
1114  default:
1115  if (!isa<Expr>(S))
1116  break;
1117 
1118  // C++1y allows expression-statements.
1119  if (!Cxx1yLoc.isValid())
1120  Cxx1yLoc = S->getLocStart();
1121  return true;
1122  }
1123 
1124  SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1125  << isa<CXXConstructorDecl>(Dcl);
1126  return false;
1127 }
1128 
1129 /// Check the body for the given constexpr function declaration only contains
1130 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1131 ///
1132 /// \return true if the body is OK, false if we have diagnosed a problem.
1134  if (isa<CXXTryStmt>(Body)) {
1135  // C++11 [dcl.constexpr]p3:
1136  // The definition of a constexpr function shall satisfy the following
1137  // constraints: [...]
1138  // - its function-body shall be = delete, = default, or a
1139  // compound-statement
1140  //
1141  // C++11 [dcl.constexpr]p4:
1142  // In the definition of a constexpr constructor, [...]
1143  // - its function-body shall not be a function-try-block;
1144  Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1145  << isa<CXXConstructorDecl>(Dcl);
1146  return false;
1147  }
1148 
1149  SmallVector<SourceLocation, 4> ReturnStmts;
1150 
1151  // - its function-body shall be [...] a compound-statement that contains only
1152  // [... list of cases ...]
1153  CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1154  SourceLocation Cxx1yLoc;
1155  for (auto *BodyIt : CompBody->body()) {
1156  if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1157  return false;
1158  }
1159 
1160  if (Cxx1yLoc.isValid())
1161  Diag(Cxx1yLoc,
1162  getLangOpts().CPlusPlus14
1163  ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1164  : diag::ext_constexpr_body_invalid_stmt)
1165  << isa<CXXConstructorDecl>(Dcl);
1166 
1167  if (const CXXConstructorDecl *Constructor
1168  = dyn_cast<CXXConstructorDecl>(Dcl)) {
1169  const CXXRecordDecl *RD = Constructor->getParent();
1170  // DR1359:
1171  // - every non-variant non-static data member and base class sub-object
1172  // shall be initialized;
1173  // DR1460:
1174  // - if the class is a union having variant members, exactly one of them
1175  // shall be initialized;
1176  if (RD->isUnion()) {
1177  if (Constructor->getNumCtorInitializers() == 0 &&
1178  RD->hasVariantMembers()) {
1179  Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1180  return false;
1181  }
1182  } else if (!Constructor->isDependentContext() &&
1183  !Constructor->isDelegatingConstructor()) {
1184  assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1185 
1186  // Skip detailed checking if we have enough initializers, and we would
1187  // allow at most one initializer per member.
1188  bool AnyAnonStructUnionMembers = false;
1189  unsigned Fields = 0;
1191  E = RD->field_end(); I != E; ++I, ++Fields) {
1192  if (I->isAnonymousStructOrUnion()) {
1193  AnyAnonStructUnionMembers = true;
1194  break;
1195  }
1196  }
1197  // DR1460:
1198  // - if the class is a union-like class, but is not a union, for each of
1199  // its anonymous union members having variant members, exactly one of
1200  // them shall be initialized;
1201  if (AnyAnonStructUnionMembers ||
1202  Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1203  // Check initialization of non-static data members. Base classes are
1204  // always initialized so do not need to be checked. Dependent bases
1205  // might not have initializers in the member initializer list.
1206  llvm::SmallSet<Decl*, 16> Inits;
1207  for (const auto *I: Constructor->inits()) {
1208  if (FieldDecl *FD = I->getMember())
1209  Inits.insert(FD);
1210  else if (IndirectFieldDecl *ID = I->getIndirectMember())
1211  Inits.insert(ID->chain_begin(), ID->chain_end());
1212  }
1213 
1214  bool Diagnosed = false;
1215  for (auto *I : RD->fields())
1216  CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
1217  if (Diagnosed)
1218  return false;
1219  }
1220  }
1221  } else {
1222  if (ReturnStmts.empty()) {
1223  // C++1y doesn't require constexpr functions to contain a 'return'
1224  // statement. We still do, unless the return type might be void, because
1225  // otherwise if there's no return statement, the function cannot
1226  // be used in a core constant expression.
1227  bool OK = getLangOpts().CPlusPlus14 &&
1228  (Dcl->getReturnType()->isVoidType() ||
1229  Dcl->getReturnType()->isDependentType());
1230  Diag(Dcl->getLocation(),
1231  OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1232  : diag::err_constexpr_body_no_return);
1233  if (!OK)
1234  return false;
1235  } else if (ReturnStmts.size() > 1) {
1236  Diag(ReturnStmts.back(),
1237  getLangOpts().CPlusPlus14
1238  ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1239  : diag::ext_constexpr_body_multiple_return);
1240  for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1241  Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1242  }
1243  }
1244 
1245  // C++11 [dcl.constexpr]p5:
1246  // if no function argument values exist such that the function invocation
1247  // substitution would produce a constant expression, the program is
1248  // ill-formed; no diagnostic required.
1249  // C++11 [dcl.constexpr]p3:
1250  // - every constructor call and implicit conversion used in initializing the
1251  // return value shall be one of those allowed in a constant expression.
1252  // C++11 [dcl.constexpr]p4:
1253  // - every constructor involved in initializing non-static data members and
1254  // base class sub-objects shall be a constexpr constructor.
1256  if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1257  Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1258  << isa<CXXConstructorDecl>(Dcl);
1259  for (size_t I = 0, N = Diags.size(); I != N; ++I)
1260  Diag(Diags[I].first, Diags[I].second);
1261  // Don't return false here: we allow this for compatibility in
1262  // system headers.
1263  }
1264 
1265  return true;
1266 }
1267 
1268 /// isCurrentClassName - Determine whether the identifier II is the
1269 /// name of the class type currently being defined. In the case of
1270 /// nested classes, this will only return true if II is the name of
1271 /// the innermost class.
1273  const CXXScopeSpec *SS) {
1274  assert(getLangOpts().CPlusPlus && "No class names in C!");
1275 
1276  CXXRecordDecl *CurDecl;
1277  if (SS && SS->isSet() && !SS->isInvalid()) {
1278  DeclContext *DC = computeDeclContext(*SS, true);
1279  CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1280  } else
1281  CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1282 
1283  if (CurDecl && CurDecl->getIdentifier())
1284  return &II == CurDecl->getIdentifier();
1285  return false;
1286 }
1287 
1288 /// \brief Determine whether the identifier II is a typo for the name of
1289 /// the class type currently being defined. If so, update it to the identifier
1290 /// that should have been used.
1292  assert(getLangOpts().CPlusPlus && "No class names in C!");
1293 
1294  if (!getLangOpts().SpellChecking)
1295  return false;
1296 
1297  CXXRecordDecl *CurDecl;
1298  if (SS && SS->isSet() && !SS->isInvalid()) {
1299  DeclContext *DC = computeDeclContext(*SS, true);
1300  CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1301  } else
1302  CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1303 
1304  if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1305  3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1306  < II->getLength()) {
1307  II = CurDecl->getIdentifier();
1308  return true;
1309  }
1310 
1311  return false;
1312 }
1313 
1314 /// \brief Determine whether the given class is a base class of the given
1315 /// class, including looking at dependent bases.
1316 static bool findCircularInheritance(const CXXRecordDecl *Class,
1317  const CXXRecordDecl *Current) {
1319 
1320  Class = Class->getCanonicalDecl();
1321  while (true) {
1322  for (const auto &I : Current->bases()) {
1323  CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
1324  if (!Base)
1325  continue;
1326 
1327  Base = Base->getDefinition();
1328  if (!Base)
1329  continue;
1330 
1331  if (Base->getCanonicalDecl() == Class)
1332  return true;
1333 
1334  Queue.push_back(Base);
1335  }
1336 
1337  if (Queue.empty())
1338  return false;
1339 
1340  Current = Queue.pop_back_val();
1341  }
1342 
1343  return false;
1344 }
1345 
1346 /// \brief Check the validity of a C++ base class specifier.
1347 ///
1348 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1349 /// and returns NULL otherwise.
1352  SourceRange SpecifierRange,
1353  bool Virtual, AccessSpecifier Access,
1354  TypeSourceInfo *TInfo,
1355  SourceLocation EllipsisLoc) {
1356  QualType BaseType = TInfo->getType();
1357 
1358  // C++ [class.union]p1:
1359  // A union shall not have base classes.
1360  if (Class->isUnion()) {
1361  Diag(Class->getLocation(), diag::err_base_clause_on_union)
1362  << SpecifierRange;
1363  return nullptr;
1364  }
1365 
1366  if (EllipsisLoc.isValid() &&
1368  Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1369  << TInfo->getTypeLoc().getSourceRange();
1370  EllipsisLoc = SourceLocation();
1371  }
1372 
1373  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1374 
1375  if (BaseType->isDependentType()) {
1376  // Make sure that we don't have circular inheritance among our dependent
1377  // bases. For non-dependent bases, the check for completeness below handles
1378  // this.
1379  if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1380  if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1381  ((BaseDecl = BaseDecl->getDefinition()) &&
1382  findCircularInheritance(Class, BaseDecl))) {
1383  Diag(BaseLoc, diag::err_circular_inheritance)
1384  << BaseType << Context.getTypeDeclType(Class);
1385 
1386  if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1387  Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1388  << BaseType;
1389 
1390  return nullptr;
1391  }
1392  }
1393 
1394  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1395  Class->getTagKind() == TTK_Class,
1396  Access, TInfo, EllipsisLoc);
1397  }
1398 
1399  // Base specifiers must be record types.
1400  if (!BaseType->isRecordType()) {
1401  Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1402  return nullptr;
1403  }
1404 
1405  // C++ [class.union]p1:
1406  // A union shall not be used as a base class.
1407  if (BaseType->isUnionType()) {
1408  Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1409  return nullptr;
1410  }
1411 
1412  // For the MS ABI, propagate DLL attributes to base class templates.
1414  if (Attr *ClassAttr = getDLLAttr(Class)) {
1415  if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1416  BaseType->getAsCXXRecordDecl())) {
1417  propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
1418  BaseLoc);
1419  }
1420  }
1421  }
1422 
1423  // C++ [class.derived]p2:
1424  // The class-name in a base-specifier shall not be an incompletely
1425  // defined class.
1426  if (RequireCompleteType(BaseLoc, BaseType,
1427  diag::err_incomplete_base_class, SpecifierRange)) {
1428  Class->setInvalidDecl();
1429  return nullptr;
1430  }
1431 
1432  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1433  RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1434  assert(BaseDecl && "Record type has no declaration");
1435  BaseDecl = BaseDecl->getDefinition();
1436  assert(BaseDecl && "Base type is not incomplete, but has no definition");
1437  CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1438  assert(CXXBaseDecl && "Base type is not a C++ type");
1439 
1440  // A class which contains a flexible array member is not suitable for use as a
1441  // base class:
1442  // - If the layout determines that a base comes before another base,
1443  // the flexible array member would index into the subsequent base.
1444  // - If the layout determines that base comes before the derived class,
1445  // the flexible array member would index into the derived class.
1446  if (CXXBaseDecl->hasFlexibleArrayMember()) {
1447  Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1448  << CXXBaseDecl->getDeclName();
1449  return nullptr;
1450  }
1451 
1452  // C++ [class]p3:
1453  // If a class is marked final and it appears as a base-type-specifier in
1454  // base-clause, the program is ill-formed.
1455  if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
1456  Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1457  << CXXBaseDecl->getDeclName()
1458  << FA->isSpelledAsSealed();
1459  Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1460  << CXXBaseDecl->getDeclName() << FA->getRange();
1461  return nullptr;
1462  }
1463 
1464  if (BaseDecl->isInvalidDecl())
1465  Class->setInvalidDecl();
1466 
1467  // Create the base specifier.
1468  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1469  Class->getTagKind() == TTK_Class,
1470  Access, TInfo, EllipsisLoc);
1471 }
1472 
1473 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1474 /// one entry in the base class list of a class specifier, for
1475 /// example:
1476 /// class foo : public bar, virtual private baz {
1477 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1478 BaseResult
1479 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1480  ParsedAttributes &Attributes,
1481  bool Virtual, AccessSpecifier Access,
1482  ParsedType basetype, SourceLocation BaseLoc,
1483  SourceLocation EllipsisLoc) {
1484  if (!classdecl)
1485  return true;
1486 
1487  AdjustDeclIfTemplate(classdecl);
1488  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1489  if (!Class)
1490  return true;
1491 
1492  // We haven't yet attached the base specifiers.
1493  Class->setIsParsingBaseSpecifiers();
1494 
1495  // We do not support any C++11 attributes on base-specifiers yet.
1496  // Diagnose any attributes we see.
1497  if (!Attributes.empty()) {
1498  for (AttributeList *Attr = Attributes.getList(); Attr;
1499  Attr = Attr->getNext()) {
1500  if (Attr->isInvalid() ||
1502  continue;
1503  Diag(Attr->getLoc(),
1505  ? diag::warn_unknown_attribute_ignored
1506  : diag::err_base_specifier_attribute)
1507  << Attr->getName();
1508  }
1509  }
1510 
1511  TypeSourceInfo *TInfo = nullptr;
1512  GetTypeFromParser(basetype, &TInfo);
1513 
1514  if (EllipsisLoc.isInvalid() &&
1515  DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1516  UPPC_BaseType))
1517  return true;
1518 
1519  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1520  Virtual, Access, TInfo,
1521  EllipsisLoc))
1522  return BaseSpec;
1523  else
1524  Class->setInvalidDecl();
1525 
1526  return true;
1527 }
1528 
1529 /// Use small set to collect indirect bases. As this is only used
1530 /// locally, there's no need to abstract the small size parameter.
1531 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
1532 
1533 /// \brief Recursively add the bases of Type. Don't add Type itself.
1534 static void
1536  const QualType &Type)
1537 {
1538  // Even though the incoming type is a base, it might not be
1539  // a class -- it could be a template parm, for instance.
1540  if (auto Rec = Type->getAs<RecordType>()) {
1541  auto Decl = Rec->getAsCXXRecordDecl();
1542 
1543  // Iterate over its bases.
1544  for (const auto &BaseSpec : Decl->bases()) {
1545  QualType Base = Context.getCanonicalType(BaseSpec.getType())
1546  .getUnqualifiedType();
1547  if (Set.insert(Base).second)
1548  // If we've not already seen it, recurse.
1549  NoteIndirectBases(Context, Set, Base);
1550  }
1551  }
1552 }
1553 
1554 /// \brief Performs the actual work of attaching the given base class
1555 /// specifiers to a C++ class.
1558  if (Bases.empty())
1559  return false;
1560 
1561  // Used to keep track of which base types we have already seen, so
1562  // that we can properly diagnose redundant direct base types. Note
1563  // that the key is always the unqualified canonical type of the base
1564  // class.
1565  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1566 
1567  // Used to track indirect bases so we can see if a direct base is
1568  // ambiguous.
1569  IndirectBaseSet IndirectBaseTypes;
1570 
1571  // Copy non-redundant base specifiers into permanent storage.
1572  unsigned NumGoodBases = 0;
1573  bool Invalid = false;
1574  for (unsigned idx = 0; idx < Bases.size(); ++idx) {
1575  QualType NewBaseType
1576  = Context.getCanonicalType(Bases[idx]->getType());
1577  NewBaseType = NewBaseType.getLocalUnqualifiedType();
1578 
1579  CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1580  if (KnownBase) {
1581  // C++ [class.mi]p3:
1582  // A class shall not be specified as a direct base class of a
1583  // derived class more than once.
1584  Diag(Bases[idx]->getLocStart(),
1585  diag::err_duplicate_base_class)
1586  << KnownBase->getType()
1587  << Bases[idx]->getSourceRange();
1588 
1589  // Delete the duplicate base class specifier; we're going to
1590  // overwrite its pointer later.
1591  Context.Deallocate(Bases[idx]);
1592 
1593  Invalid = true;
1594  } else {
1595  // Okay, add this new base class.
1596  KnownBase = Bases[idx];
1597  Bases[NumGoodBases++] = Bases[idx];
1598 
1599  // Note this base's direct & indirect bases, if there could be ambiguity.
1600  if (Bases.size() > 1)
1601  NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
1602 
1603  if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1604  const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1605  if (Class->isInterface() &&
1606  (!RD->isInterface() ||
1607  KnownBase->getAccessSpecifier() != AS_public)) {
1608  // The Microsoft extension __interface does not permit bases that
1609  // are not themselves public interfaces.
1610  Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1611  << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1612  << RD->getSourceRange();
1613  Invalid = true;
1614  }
1615  if (RD->hasAttr<WeakAttr>())
1616  Class->addAttr(WeakAttr::CreateImplicit(Context));
1617  }
1618  }
1619  }
1620 
1621  // Attach the remaining base class specifiers to the derived class.
1622  Class->setBases(Bases.data(), NumGoodBases);
1623 
1624  for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
1625  // Check whether this direct base is inaccessible due to ambiguity.
1626  QualType BaseType = Bases[idx]->getType();
1627  CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
1628  .getUnqualifiedType();
1629 
1630  if (IndirectBaseTypes.count(CanonicalBase)) {
1631  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1632  /*DetectVirtual=*/true);
1633  bool found
1634  = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
1635  assert(found);
1636  (void)found;
1637 
1638  if (Paths.isAmbiguous(CanonicalBase))
1639  Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
1640  << BaseType << getAmbiguousPathsDisplayString(Paths)
1641  << Bases[idx]->getSourceRange();
1642  else
1643  assert(Bases[idx]->isVirtual());
1644  }
1645 
1646  // Delete the base class specifier, since its data has been copied
1647  // into the CXXRecordDecl.
1648  Context.Deallocate(Bases[idx]);
1649  }
1650 
1651  return Invalid;
1652 }
1653 
1654 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
1655 /// class, after checking whether there are any duplicate base
1656 /// classes.
1657 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
1659  if (!ClassDecl || Bases.empty())
1660  return;
1661 
1662  AdjustDeclIfTemplate(ClassDecl);
1663  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
1664 }
1665 
1666 /// \brief Determine whether the type \p Derived is a C++ class that is
1667 /// derived from the type \p Base.
1669  if (!getLangOpts().CPlusPlus)
1670  return false;
1671 
1672  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1673  if (!DerivedRD)
1674  return false;
1675 
1676  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1677  if (!BaseRD)
1678  return false;
1679 
1680  // If either the base or the derived type is invalid, don't try to
1681  // check whether one is derived from the other.
1682  if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1683  return false;
1684 
1685  // FIXME: In a modules build, do we need the entire path to be visible for us
1686  // to be able to use the inheritance relationship?
1687  if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
1688  return false;
1689 
1690  return DerivedRD->isDerivedFrom(BaseRD);
1691 }
1692 
1693 /// \brief Determine whether the type \p Derived is a C++ class that is
1694 /// derived from the type \p Base.
1696  CXXBasePaths &Paths) {
1697  if (!getLangOpts().CPlusPlus)
1698  return false;
1699 
1700  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1701  if (!DerivedRD)
1702  return false;
1703 
1704  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1705  if (!BaseRD)
1706  return false;
1707 
1708  if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
1709  return false;
1710 
1711  return DerivedRD->isDerivedFrom(BaseRD, Paths);
1712 }
1713 
1715  CXXCastPath &BasePathArray) {
1716  assert(BasePathArray.empty() && "Base path array must be empty!");
1717  assert(Paths.isRecordingPaths() && "Must record paths!");
1718 
1719  const CXXBasePath &Path = Paths.front();
1720 
1721  // We first go backward and check if we have a virtual base.
1722  // FIXME: It would be better if CXXBasePath had the base specifier for
1723  // the nearest virtual base.
1724  unsigned Start = 0;
1725  for (unsigned I = Path.size(); I != 0; --I) {
1726  if (Path[I - 1].Base->isVirtual()) {
1727  Start = I - 1;
1728  break;
1729  }
1730  }
1731 
1732  // Now add all bases.
1733  for (unsigned I = Start, E = Path.size(); I != E; ++I)
1734  BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1735 }
1736 
1737 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1738 /// conversion (where Derived and Base are class types) is
1739 /// well-formed, meaning that the conversion is unambiguous (and
1740 /// that all of the base classes are accessible). Returns true
1741 /// and emits a diagnostic if the code is ill-formed, returns false
1742 /// otherwise. Loc is the location where this routine should point to
1743 /// if there is an error, and Range is the source range to highlight
1744 /// if there is an error.
1745 ///
1746 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
1747 /// diagnostic for the respective type of error will be suppressed, but the
1748 /// check for ill-formed code will still be performed.
1749 bool
1751  unsigned InaccessibleBaseID,
1752  unsigned AmbigiousBaseConvID,
1753  SourceLocation Loc, SourceRange Range,
1755  CXXCastPath *BasePath,
1756  bool IgnoreAccess) {
1757  // First, determine whether the path from Derived to Base is
1758  // ambiguous. This is slightly more expensive than checking whether
1759  // the Derived to Base conversion exists, because here we need to
1760  // explore multiple paths to determine if there is an ambiguity.
1761  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1762  /*DetectVirtual=*/false);
1763  bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
1764  assert(DerivationOkay &&
1765  "Can only be used with a derived-to-base conversion");
1766  (void)DerivationOkay;
1767 
1769  if (!IgnoreAccess) {
1770  // Check that the base class can be accessed.
1771  switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1772  InaccessibleBaseID)) {
1773  case AR_inaccessible:
1774  return true;
1775  case AR_accessible:
1776  case AR_dependent:
1777  case AR_delayed:
1778  break;
1779  }
1780  }
1781 
1782  // Build a base path if necessary.
1783  if (BasePath)
1784  BuildBasePathArray(Paths, *BasePath);
1785  return false;
1786  }
1787 
1788  if (AmbigiousBaseConvID) {
1789  // We know that the derived-to-base conversion is ambiguous, and
1790  // we're going to produce a diagnostic. Perform the derived-to-base
1791  // search just one more time to compute all of the possible paths so
1792  // that we can print them out. This is more expensive than any of
1793  // the previous derived-to-base checks we've done, but at this point
1794  // performance isn't as much of an issue.
1795  Paths.clear();
1796  Paths.setRecordingPaths(true);
1797  bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
1798  assert(StillOkay && "Can only be used with a derived-to-base conversion");
1799  (void)StillOkay;
1800 
1801  // Build up a textual representation of the ambiguous paths, e.g.,
1802  // D -> B -> A, that will be used to illustrate the ambiguous
1803  // conversions in the diagnostic. We only print one of the paths
1804  // to each base class subobject.
1805  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1806 
1807  Diag(Loc, AmbigiousBaseConvID)
1808  << Derived << Base << PathDisplayStr << Range << Name;
1809  }
1810  return true;
1811 }
1812 
1813 bool
1815  SourceLocation Loc, SourceRange Range,
1816  CXXCastPath *BasePath,
1817  bool IgnoreAccess) {
1819  Derived, Base, diag::err_upcast_to_inaccessible_base,
1820  diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
1821  BasePath, IgnoreAccess);
1822 }
1823 
1824 
1825 /// @brief Builds a string representing ambiguous paths from a
1826 /// specific derived class to different subobjects of the same base
1827 /// class.
1828 ///
1829 /// This function builds a string that can be used in error messages
1830 /// to show the different paths that one can take through the
1831 /// inheritance hierarchy to go from the derived class to different
1832 /// subobjects of a base class. The result looks something like this:
1833 /// @code
1834 /// struct D -> struct B -> struct A
1835 /// struct D -> struct C -> struct A
1836 /// @endcode
1838  std::string PathDisplayStr;
1839  std::set<unsigned> DisplayedPaths;
1840  for (CXXBasePaths::paths_iterator Path = Paths.begin();
1841  Path != Paths.end(); ++Path) {
1842  if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1843  // We haven't displayed a path to this particular base
1844  // class subobject yet.
1845  PathDisplayStr += "\n ";
1846  PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1847  for (CXXBasePath::const_iterator Element = Path->begin();
1848  Element != Path->end(); ++Element)
1849  PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1850  }
1851  }
1852 
1853  return PathDisplayStr;
1854 }
1855 
1856 //===----------------------------------------------------------------------===//
1857 // C++ class member Handling
1858 //===----------------------------------------------------------------------===//
1859 
1860 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1862  SourceLocation ASLoc,
1864  AttributeList *Attrs) {
1865  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1867  ASLoc, ColonLoc);
1868  CurContext->addHiddenDecl(ASDecl);
1869  return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1870 }
1871 
1872 /// CheckOverrideControl - Check C++11 override control semantics.
1874  if (D->isInvalidDecl())
1875  return;
1876 
1877  // We only care about "override" and "final" declarations.
1878  if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1879  return;
1880 
1881  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1882 
1883  // We can't check dependent instance methods.
1884  if (MD && MD->isInstance() &&
1885  (MD->getParent()->hasAnyDependentBases() ||
1886  MD->getType()->isDependentType()))
1887  return;
1888 
1889  if (MD && !MD->isVirtual()) {
1890  // If we have a non-virtual method, check if if hides a virtual method.
1891  // (In that case, it's most likely the method has the wrong type.)
1892  SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1893  FindHiddenVirtualMethods(MD, OverloadedMethods);
1894 
1895  if (!OverloadedMethods.empty()) {
1896  if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1897  Diag(OA->getLocation(),
1898  diag::override_keyword_hides_virtual_member_function)
1899  << "override" << (OverloadedMethods.size() > 1);
1900  } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1901  Diag(FA->getLocation(),
1902  diag::override_keyword_hides_virtual_member_function)
1903  << (FA->isSpelledAsSealed() ? "sealed" : "final")
1904  << (OverloadedMethods.size() > 1);
1905  }
1906  NoteHiddenVirtualMethods(MD, OverloadedMethods);
1907  MD->setInvalidDecl();
1908  return;
1909  }
1910  // Fall through into the general case diagnostic.
1911  // FIXME: We might want to attempt typo correction here.
1912  }
1913 
1914  if (!MD || !MD->isVirtual()) {
1915  if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1916  Diag(OA->getLocation(),
1917  diag::override_keyword_only_allowed_on_virtual_member_functions)
1918  << "override" << FixItHint::CreateRemoval(OA->getLocation());
1919  D->dropAttr<OverrideAttr>();
1920  }
1921  if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1922  Diag(FA->getLocation(),
1923  diag::override_keyword_only_allowed_on_virtual_member_functions)
1924  << (FA->isSpelledAsSealed() ? "sealed" : "final")
1925  << FixItHint::CreateRemoval(FA->getLocation());
1926  D->dropAttr<FinalAttr>();
1927  }
1928  return;
1929  }
1930 
1931  // C++11 [class.virtual]p5:
1932  // If a function is marked with the virt-specifier override and
1933  // does not override a member function of a base class, the program is
1934  // ill-formed.
1935  bool HasOverriddenMethods =
1937  if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1938  Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1939  << MD->getDeclName();
1940 }
1941 
1943  if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
1944  return;
1945  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1946  if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
1947  isa<CXXDestructorDecl>(MD))
1948  return;
1949 
1950  SourceLocation Loc = MD->getLocation();
1951  SourceLocation SpellingLoc = Loc;
1952  if (getSourceManager().isMacroArgExpansion(Loc))
1953  SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
1954  SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
1955  if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
1956  return;
1957 
1958  if (MD->size_overridden_methods() > 0) {
1959  Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
1960  << MD->getDeclName();
1961  const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
1962  Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
1963  }
1964 }
1965 
1966 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1967 /// function overrides a virtual member function marked 'final', according to
1968 /// C++11 [class.virtual]p4.
1970  const CXXMethodDecl *Old) {
1971  FinalAttr *FA = Old->getAttr<FinalAttr>();
1972  if (!FA)
1973  return false;
1974 
1975  Diag(New->getLocation(), diag::err_final_function_overridden)
1976  << New->getDeclName()
1977  << FA->isSpelledAsSealed();
1978  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1979  return true;
1980 }
1981 
1982 static bool InitializationHasSideEffects(const FieldDecl &FD) {
1983  const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1984  // FIXME: Destruction of ObjC lifetime types has side-effects.
1985  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1986  return !RD->isCompleteDefinition() ||
1987  !RD->hasTrivialDefaultConstructor() ||
1988  !RD->hasTrivialDestructor();
1989  return false;
1990 }
1991 
1993  for (AttributeList *it = list; it != nullptr; it = it->getNext())
1994  if (it->isDeclspecPropertyAttribute())
1995  return it;
1996  return nullptr;
1997 }
1998 
1999 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2000 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2001 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2002 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2003 /// present (but parsing it has been deferred).
2004 NamedDecl *
2006  MultiTemplateParamsArg TemplateParameterLists,
2007  Expr *BW, const VirtSpecifiers &VS,
2008  InClassInitStyle InitStyle) {
2009  const DeclSpec &DS = D.getDeclSpec();
2011  DeclarationName Name = NameInfo.getName();
2012  SourceLocation Loc = NameInfo.getLoc();
2013 
2014  // For anonymous bitfields, the location should point to the type.
2015  if (Loc.isInvalid())
2016  Loc = D.getLocStart();
2017 
2018  Expr *BitWidth = static_cast<Expr*>(BW);
2019 
2020  assert(isa<CXXRecordDecl>(CurContext));
2021  assert(!DS.isFriendSpecified());
2022 
2023  bool isFunc = D.isDeclarationOfFunction();
2024 
2025  if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2026  // The Microsoft extension __interface only permits public member functions
2027  // and prohibits constructors, destructors, operators, non-public member
2028  // functions, static methods and data members.
2029  unsigned InvalidDecl;
2030  bool ShowDeclName = true;
2031  if (!isFunc)
2032  InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2033  else if (AS != AS_public)
2034  InvalidDecl = 2;
2035  else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2036  InvalidDecl = 3;
2037  else switch (Name.getNameKind()) {
2039  InvalidDecl = 4;
2040  ShowDeclName = false;
2041  break;
2042 
2044  InvalidDecl = 5;
2045  ShowDeclName = false;
2046  break;
2047 
2050  InvalidDecl = 6;
2051  break;
2052 
2053  default:
2054  InvalidDecl = 0;
2055  break;
2056  }
2057 
2058  if (InvalidDecl) {
2059  if (ShowDeclName)
2060  Diag(Loc, diag::err_invalid_member_in_interface)
2061  << (InvalidDecl-1) << Name;
2062  else
2063  Diag(Loc, diag::err_invalid_member_in_interface)
2064  << (InvalidDecl-1) << "";
2065  return nullptr;
2066  }
2067  }
2068 
2069  // C++ 9.2p6: A member shall not be declared to have automatic storage
2070  // duration (auto, register) or with the extern storage-class-specifier.
2071  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2072  // data members and cannot be applied to names declared const or static,
2073  // and cannot be applied to reference members.
2074  switch (DS.getStorageClassSpec()) {
2076  case DeclSpec::SCS_typedef:
2077  case DeclSpec::SCS_static:
2078  break;
2079  case DeclSpec::SCS_mutable:
2080  if (isFunc) {
2081  Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2082 
2083  // FIXME: It would be nicer if the keyword was ignored only for this
2084  // declarator. Otherwise we could get follow-up errors.
2086  }
2087  break;
2088  default:
2090  diag::err_storageclass_invalid_for_member);
2092  break;
2093  }
2094 
2095  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2097  !isFunc);
2098 
2099  if (DS.isConstexprSpecified() && isInstField) {
2101  Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2102  SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2103  if (InitStyle == ICIS_NoInit) {
2104  B << 0 << 0;
2106  B << FixItHint::CreateRemoval(ConstexprLoc);
2107  else {
2108  B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2110  const char *PrevSpec;
2111  unsigned DiagID;
2112  bool Failed = D.getMutableDeclSpec().SetTypeQual(
2113  DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2114  (void)Failed;
2115  assert(!Failed && "Making a constexpr member const shouldn't fail");
2116  }
2117  } else {
2118  B << 1;
2119  const char *PrevSpec;
2120  unsigned DiagID;
2122  *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2124  assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2125  "This is the only DeclSpec that should fail to be applied");
2126  B << 1;
2127  } else {
2128  B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2129  isInstField = false;
2130  }
2131  }
2132  }
2133 
2134  NamedDecl *Member;
2135  if (isInstField) {
2136  CXXScopeSpec &SS = D.getCXXScopeSpec();
2137 
2138  // Data members must have identifiers for names.
2139  if (!Name.isIdentifier()) {
2140  Diag(Loc, diag::err_bad_variable_name)
2141  << Name;
2142  return nullptr;
2143  }
2144 
2145  IdentifierInfo *II = Name.getAsIdentifierInfo();
2146 
2147  // Member field could not be with "template" keyword.
2148  // So TemplateParameterLists should be empty in this case.
2149  if (TemplateParameterLists.size()) {
2150  TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2151  if (TemplateParams->size()) {
2152  // There is no such thing as a member field template.
2153  Diag(D.getIdentifierLoc(), diag::err_template_member)
2154  << II
2155  << SourceRange(TemplateParams->getTemplateLoc(),
2156  TemplateParams->getRAngleLoc());
2157  } else {
2158  // There is an extraneous 'template<>' for this member.
2159  Diag(TemplateParams->getTemplateLoc(),
2160  diag::err_template_member_noparams)
2161  << II
2162  << SourceRange(TemplateParams->getTemplateLoc(),
2163  TemplateParams->getRAngleLoc());
2164  }
2165  return nullptr;
2166  }
2167 
2168  if (SS.isSet() && !SS.isInvalid()) {
2169  // The user provided a superfluous scope specifier inside a class
2170  // definition:
2171  //
2172  // class X {
2173  // int X::member;
2174  // };
2175  if (DeclContext *DC = computeDeclContext(SS, false))
2177  else
2178  Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2179  << Name << SS.getRange();
2180 
2181  SS.clear();
2182  }
2183 
2184  AttributeList *MSPropertyAttr =
2186  if (MSPropertyAttr) {
2187  Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2188  BitWidth, InitStyle, AS, MSPropertyAttr);
2189  if (!Member)
2190  return nullptr;
2191  isInstField = false;
2192  } else {
2193  Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2194  BitWidth, InitStyle, AS);
2195  assert(Member && "HandleField never returns null");
2196  }
2197  } else {
2198  Member = HandleDeclarator(S, D, TemplateParameterLists);
2199  if (!Member)
2200  return nullptr;
2201 
2202  // Non-instance-fields can't have a bitfield.
2203  if (BitWidth) {
2204  if (Member->isInvalidDecl()) {
2205  // don't emit another diagnostic.
2206  } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
2207  // C++ 9.6p3: A bit-field shall not be a static member.
2208  // "static member 'A' cannot be a bit-field"
2209  Diag(Loc, diag::err_static_not_bitfield)
2210  << Name << BitWidth->getSourceRange();
2211  } else if (isa<TypedefDecl>(Member)) {
2212  // "typedef member 'x' cannot be a bit-field"
2213  Diag(Loc, diag::err_typedef_not_bitfield)
2214  << Name << BitWidth->getSourceRange();
2215  } else {
2216  // A function typedef ("typedef int f(); f a;").
2217  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2218  Diag(Loc, diag::err_not_integral_type_bitfield)
2219  << Name << cast<ValueDecl>(Member)->getType()
2220  << BitWidth->getSourceRange();
2221  }
2222 
2223  BitWidth = nullptr;
2224  Member->setInvalidDecl();
2225  }
2226 
2227  Member->setAccess(AS);
2228 
2229  // If we have declared a member function template or static data member
2230  // template, set the access of the templated declaration as well.
2231  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2232  FunTmpl->getTemplatedDecl()->setAccess(AS);
2233  else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2234  VarTmpl->getTemplatedDecl()->setAccess(AS);
2235  }
2236 
2237  if (VS.isOverrideSpecified())
2238  Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
2239  if (VS.isFinalSpecified())
2240  Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2241  VS.isFinalSpelledSealed()));
2242 
2243  if (VS.getLastLocation().isValid()) {
2244  // Update the end location of a method that has a virt-specifiers.
2245  if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2246  MD->setRangeEnd(VS.getLastLocation());
2247  }
2248 
2249  CheckOverrideControl(Member);
2250 
2251  assert((Name || isInstField) && "No identifier for non-field ?");
2252 
2253  if (isInstField) {
2254  FieldDecl *FD = cast<FieldDecl>(Member);
2255  FieldCollector->Add(FD);
2256 
2257  if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
2258  // Remember all explicit private FieldDecls that have a name, no side
2259  // effects and are not part of a dependent type declaration.
2260  if (!FD->isImplicit() && FD->getDeclName() &&
2261  FD->getAccess() == AS_private &&
2262  !FD->hasAttr<UnusedAttr>() &&
2263  !FD->getParent()->isDependentContext() &&
2265  UnusedPrivateFields.insert(FD);
2266  }
2267  }
2268 
2269  return Member;
2270 }
2271 
2272 namespace {
2273  class UninitializedFieldVisitor
2274  : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2275  Sema &S;
2276  // List of Decls to generate a warning on. Also remove Decls that become
2277  // initialized.
2278  llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
2279  // List of base classes of the record. Classes are removed after their
2280  // initializers.
2281  llvm::SmallPtrSetImpl<QualType> &BaseClasses;
2282  // Vector of decls to be removed from the Decl set prior to visiting the
2283  // nodes. These Decls may have been initialized in the prior initializer.
2284  llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
2285  // If non-null, add a note to the warning pointing back to the constructor.
2286  const CXXConstructorDecl *Constructor;
2287  // Variables to hold state when processing an initializer list. When
2288  // InitList is true, special case initialization of FieldDecls matching
2289  // InitListFieldDecl.
2290  bool InitList;
2291  FieldDecl *InitListFieldDecl;
2292  llvm::SmallVector<unsigned, 4> InitFieldIndex;
2293 
2294  public:
2296  UninitializedFieldVisitor(Sema &S,
2297  llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2298  llvm::SmallPtrSetImpl<QualType> &BaseClasses)
2299  : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
2300  Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
2301 
2302  // Returns true if the use of ME is not an uninitialized use.
2303  bool IsInitListMemberExprInitialized(MemberExpr *ME,
2304  bool CheckReferenceOnly) {
2306  bool ReferenceField = false;
2307  while (ME) {
2308  FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2309  if (!FD)
2310  return false;
2311  Fields.push_back(FD);
2312  if (FD->getType()->isReferenceType())
2313  ReferenceField = true;
2314  ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2315  }
2316 
2317  // Binding a reference to an unintialized field is not an
2318  // uninitialized use.
2319  if (CheckReferenceOnly && !ReferenceField)
2320  return true;
2321 
2322  llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2323  // Discard the first field since it is the field decl that is being
2324  // initialized.
2325  for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2326  UsedFieldIndex.push_back((*I)->getFieldIndex());
2327  }
2328 
2329  for (auto UsedIter = UsedFieldIndex.begin(),
2330  UsedEnd = UsedFieldIndex.end(),
2331  OrigIter = InitFieldIndex.begin(),
2332  OrigEnd = InitFieldIndex.end();
2333  UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2334  if (*UsedIter < *OrigIter)
2335  return true;
2336  if (*UsedIter > *OrigIter)
2337  break;
2338  }
2339 
2340  return false;
2341  }
2342 
2343  void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2344  bool AddressOf) {
2345  if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2346  return;
2347 
2348  // FieldME is the inner-most MemberExpr that is not an anonymous struct
2349  // or union.
2350  MemberExpr *FieldME = ME;
2351 
2352  bool AllPODFields = FieldME->getType().isPODType(S.Context);
2353 
2354  Expr *Base = ME;
2355  while (MemberExpr *SubME =
2356  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
2357 
2358  if (isa<VarDecl>(SubME->getMemberDecl()))
2359  return;
2360 
2361  if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
2362  if (!FD->isAnonymousStructOrUnion())
2363  FieldME = SubME;
2364 
2365  if (!FieldME->getType().isPODType(S.Context))
2366  AllPODFields = false;
2367 
2368  Base = SubME->getBase();
2369  }
2370 
2371  if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
2372  return;
2373 
2374  if (AddressOf && AllPODFields)
2375  return;
2376 
2377  ValueDecl* FoundVD = FieldME->getMemberDecl();
2378 
2379  if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
2380  while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
2381  BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
2382  }
2383 
2384  if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
2385  QualType T = BaseCast->getType();
2386  if (T->isPointerType() &&
2387  BaseClasses.count(T->getPointeeType())) {
2388  S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
2389  << T->getPointeeType() << FoundVD;
2390  }
2391  }
2392  }
2393 
2394  if (!Decls.count(FoundVD))
2395  return;
2396 
2397  const bool IsReference = FoundVD->getType()->isReferenceType();
2398 
2399  if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2400  // Special checking for initializer lists.
2401  if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2402  return;
2403  }
2404  } else {
2405  // Prevent double warnings on use of unbounded references.
2406  if (CheckReferenceOnly && !IsReference)
2407  return;
2408  }
2409 
2410  unsigned diag = IsReference
2411  ? diag::warn_reference_field_is_uninit
2412  : diag::warn_field_is_uninit;
2413  S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2414  if (Constructor)
2415  S.Diag(Constructor->getLocation(),
2416  diag::note_uninit_in_this_constructor)
2417  << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2418 
2419  }
2420 
2421  void HandleValue(Expr *E, bool AddressOf) {
2422  E = E->IgnoreParens();
2423 
2424  if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2425  HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2426  AddressOf /*AddressOf*/);
2427  return;
2428  }
2429 
2430  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2431  Visit(CO->getCond());
2432  HandleValue(CO->getTrueExpr(), AddressOf);
2433  HandleValue(CO->getFalseExpr(), AddressOf);
2434  return;
2435  }
2436 
2437  if (BinaryConditionalOperator *BCO =
2438  dyn_cast<BinaryConditionalOperator>(E)) {
2439  Visit(BCO->getCond());
2440  HandleValue(BCO->getFalseExpr(), AddressOf);
2441  return;
2442  }
2443 
2444  if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
2445  HandleValue(OVE->getSourceExpr(), AddressOf);
2446  return;
2447  }
2448 
2449  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2450  switch (BO->getOpcode()) {
2451  default:
2452  break;
2453  case(BO_PtrMemD):
2454  case(BO_PtrMemI):
2455  HandleValue(BO->getLHS(), AddressOf);
2456  Visit(BO->getRHS());
2457  return;
2458  case(BO_Comma):
2459  Visit(BO->getLHS());
2460  HandleValue(BO->getRHS(), AddressOf);
2461  return;
2462  }
2463  }
2464 
2465  Visit(E);
2466  }
2467 
2468  void CheckInitListExpr(InitListExpr *ILE) {
2469  InitFieldIndex.push_back(0);
2470  for (auto Child : ILE->children()) {
2471  if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2472  CheckInitListExpr(SubList);
2473  } else {
2474  Visit(Child);
2475  }
2476  ++InitFieldIndex.back();
2477  }
2478  InitFieldIndex.pop_back();
2479  }
2480 
2481  void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
2482  FieldDecl *Field, const Type *BaseClass) {
2483  // Remove Decls that may have been initialized in the previous
2484  // initializer.
2485  for (ValueDecl* VD : DeclsToRemove)
2486  Decls.erase(VD);
2487  DeclsToRemove.clear();
2488 
2489  Constructor = FieldConstructor;
2490  InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2491 
2492  if (ILE && Field) {
2493  InitList = true;
2494  InitListFieldDecl = Field;
2495  InitFieldIndex.clear();
2496  CheckInitListExpr(ILE);
2497  } else {
2498  InitList = false;
2499  Visit(E);
2500  }
2501 
2502  if (Field)
2503  Decls.erase(Field);
2504  if (BaseClass)
2505  BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
2506  }
2507 
2508  void VisitMemberExpr(MemberExpr *ME) {
2509  // All uses of unbounded reference fields will warn.
2510  HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
2511  }
2512 
2513  void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2514  if (E->getCastKind() == CK_LValueToRValue) {
2515  HandleValue(E->getSubExpr(), false /*AddressOf*/);
2516  return;
2517  }
2518 
2519  Inherited::VisitImplicitCastExpr(E);
2520  }
2521 
2522  void VisitCXXConstructExpr(CXXConstructExpr *E) {
2523  if (E->getConstructor()->isCopyConstructor()) {
2524  Expr *ArgExpr = E->getArg(0);
2525  if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2526  if (ILE->getNumInits() == 1)
2527  ArgExpr = ILE->getInit(0);
2528  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
2529  if (ICE->getCastKind() == CK_NoOp)
2530  ArgExpr = ICE->getSubExpr();
2531  HandleValue(ArgExpr, false /*AddressOf*/);
2532  return;
2533  }
2534  Inherited::VisitCXXConstructExpr(E);
2535  }
2536 
2537  void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2538  Expr *Callee = E->getCallee();
2539  if (isa<MemberExpr>(Callee)) {
2540  HandleValue(Callee, false /*AddressOf*/);
2541  for (auto Arg : E->arguments())
2542  Visit(Arg);
2543  return;
2544  }
2545 
2546  Inherited::VisitCXXMemberCallExpr(E);
2547  }
2548 
2549  void VisitCallExpr(CallExpr *E) {
2550  // Treat std::move as a use.
2551  if (E->getNumArgs() == 1) {
2552  if (FunctionDecl *FD = E->getDirectCallee()) {
2553  if (FD->isInStdNamespace() && FD->getIdentifier() &&
2554  FD->getIdentifier()->isStr("move")) {
2555  HandleValue(E->getArg(0), false /*AddressOf*/);
2556  return;
2557  }
2558  }
2559  }
2560 
2561  Inherited::VisitCallExpr(E);
2562  }
2563 
2564  void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
2565  Expr *Callee = E->getCallee();
2566 
2567  if (isa<UnresolvedLookupExpr>(Callee))
2568  return Inherited::VisitCXXOperatorCallExpr(E);
2569 
2570  Visit(Callee);
2571  for (auto Arg : E->arguments())
2572  HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
2573  }
2574 
2575  void VisitBinaryOperator(BinaryOperator *E) {
2576  // If a field assignment is detected, remove the field from the
2577  // uninitiailized field set.
2578  if (E->getOpcode() == BO_Assign)
2579  if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2580  if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2581  if (!FD->getType()->isReferenceType())
2582  DeclsToRemove.push_back(FD);
2583 
2584  if (E->isCompoundAssignmentOp()) {
2585  HandleValue(E->getLHS(), false /*AddressOf*/);
2586  Visit(E->getRHS());
2587  return;
2588  }
2589 
2590  Inherited::VisitBinaryOperator(E);
2591  }
2592 
2593  void VisitUnaryOperator(UnaryOperator *E) {
2594  if (E->isIncrementDecrementOp()) {
2595  HandleValue(E->getSubExpr(), false /*AddressOf*/);
2596  return;
2597  }
2598  if (E->getOpcode() == UO_AddrOf) {
2599  if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2600  HandleValue(ME->getBase(), true /*AddressOf*/);
2601  return;
2602  }
2603  }
2604 
2605  Inherited::VisitUnaryOperator(E);
2606  }
2607  };
2608 
2609  // Diagnose value-uses of fields to initialize themselves, e.g.
2610  // foo(foo)
2611  // where foo is not also a parameter to the constructor.
2612  // Also diagnose across field uninitialized use such as
2613  // x(y), y(x)
2614  // TODO: implement -Wuninitialized and fold this into that framework.
2615  static void DiagnoseUninitializedFields(
2616  Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2617 
2618  if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2619  Constructor->getLocation())) {
2620  return;
2621  }
2622 
2623  if (Constructor->isInvalidDecl())
2624  return;
2625 
2626  const CXXRecordDecl *RD = Constructor->getParent();
2627 
2628  if (RD->getDescribedClassTemplate())
2629  return;
2630 
2631  // Holds fields that are uninitialized.
2632  llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2633 
2634  // At the beginning, all fields are uninitialized.
2635  for (auto *I : RD->decls()) {
2636  if (auto *FD = dyn_cast<FieldDecl>(I)) {
2637  UninitializedFields.insert(FD);
2638  } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
2639  UninitializedFields.insert(IFD->getAnonField());
2640  }
2641  }
2642 
2643  llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
2644  for (auto I : RD->bases())
2645  UninitializedBaseClasses.insert(I.getType().getCanonicalType());
2646 
2647  if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
2648  return;
2649 
2650  UninitializedFieldVisitor UninitializedChecker(SemaRef,
2651  UninitializedFields,
2652  UninitializedBaseClasses);
2653 
2654  for (const auto *FieldInit : Constructor->inits()) {
2655  if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
2656  break;
2657 
2658  Expr *InitExpr = FieldInit->getInit();
2659  if (!InitExpr)
2660  continue;
2661 
2662  if (CXXDefaultInitExpr *Default =
2663  dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2664  InitExpr = Default->getExpr();
2665  if (!InitExpr)
2666  continue;
2667  // In class initializers will point to the constructor.
2668  UninitializedChecker.CheckInitializer(InitExpr, Constructor,
2669  FieldInit->getAnyMember(),
2670  FieldInit->getBaseClass());
2671  } else {
2672  UninitializedChecker.CheckInitializer(InitExpr, nullptr,
2673  FieldInit->getAnyMember(),
2674  FieldInit->getBaseClass());
2675  }
2676  }
2677  }
2678 } // namespace
2679 
2680 /// \brief Enter a new C++ default initializer scope. After calling this, the
2681 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2682 /// parsing or instantiating the initializer failed.
2684  // Create a synthetic function scope to represent the call to the constructor
2685  // that notionally surrounds a use of this initializer.
2687 }
2688 
2689 /// \brief This is invoked after parsing an in-class initializer for a
2690 /// non-static C++ class member, and after instantiating an in-class initializer
2691 /// in a class template. Such actions are deferred until the class is complete.
2693  SourceLocation InitLoc,
2694  Expr *InitExpr) {
2695  // Pop the notional constructor scope we created earlier.
2696  PopFunctionScopeInfo(nullptr, D);
2697 
2698  FieldDecl *FD = dyn_cast<FieldDecl>(D);
2699  assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
2700  "must set init style when field is created");
2701 
2702  if (!InitExpr) {
2703  D->setInvalidDecl();
2704  if (FD)
2706  return;
2707  }
2708 
2710  FD->setInvalidDecl();
2712  return;
2713  }
2714 
2715  ExprResult Init = InitExpr;
2716  if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2719  ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2720  : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2721  InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2722  Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2723  if (Init.isInvalid()) {
2724  FD->setInvalidDecl();
2725  return;
2726  }
2727  }
2728 
2729  // C++11 [class.base.init]p7:
2730  // The initialization of each base and member constitutes a
2731  // full-expression.
2732  Init = ActOnFinishFullExpr(Init.get(), InitLoc);
2733  if (Init.isInvalid()) {
2734  FD->setInvalidDecl();
2735  return;
2736  }
2737 
2738  InitExpr = Init.get();
2739 
2740  FD->setInClassInitializer(InitExpr);
2741 }
2742 
2743 /// \brief Find the direct and/or virtual base specifiers that
2744 /// correspond to the given base type, for use in base initialization
2745 /// within a constructor.
2746 static bool FindBaseInitializer(Sema &SemaRef,
2747  CXXRecordDecl *ClassDecl,
2748  QualType BaseType,
2749  const CXXBaseSpecifier *&DirectBaseSpec,
2750  const CXXBaseSpecifier *&VirtualBaseSpec) {
2751  // First, check for a direct base class.
2752  DirectBaseSpec = nullptr;
2753  for (const auto &Base : ClassDecl->bases()) {
2754  if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
2755  // We found a direct base of this type. That's what we're
2756  // initializing.
2757  DirectBaseSpec = &Base;
2758  break;
2759  }
2760  }
2761 
2762  // Check for a virtual base class.
2763  // FIXME: We might be able to short-circuit this if we know in advance that
2764  // there are no virtual bases.
2765  VirtualBaseSpec = nullptr;
2766  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2767  // We haven't found a base yet; search the class hierarchy for a
2768  // virtual base class.
2769  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2770  /*DetectVirtual=*/false);
2771  if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
2772  SemaRef.Context.getTypeDeclType(ClassDecl),
2773  BaseType, Paths)) {
2774  for (CXXBasePaths::paths_iterator Path = Paths.begin();
2775  Path != Paths.end(); ++Path) {
2776  if (Path->back().Base->isVirtual()) {
2777  VirtualBaseSpec = Path->back().Base;
2778  break;
2779  }
2780  }
2781  }
2782  }
2783 
2784  return DirectBaseSpec || VirtualBaseSpec;
2785 }
2786 
2787 /// \brief Handle a C++ member initializer using braced-init-list syntax.
2789 Sema::ActOnMemInitializer(Decl *ConstructorD,
2790  Scope *S,
2791  CXXScopeSpec &SS,
2792  IdentifierInfo *MemberOrBase,
2793  ParsedType TemplateTypeTy,
2794  const DeclSpec &DS,
2795  SourceLocation IdLoc,
2796  Expr *InitList,
2797  SourceLocation EllipsisLoc) {
2798  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2799  DS, IdLoc, InitList,
2800  EllipsisLoc);
2801 }
2802 
2803 /// \brief Handle a C++ member initializer using parentheses syntax.
2805 Sema::ActOnMemInitializer(Decl *ConstructorD,
2806  Scope *S,
2807  CXXScopeSpec &SS,
2808  IdentifierInfo *MemberOrBase,
2809  ParsedType TemplateTypeTy,
2810  const DeclSpec &DS,
2811  SourceLocation IdLoc,
2812  SourceLocation LParenLoc,
2813  ArrayRef<Expr *> Args,
2814  SourceLocation RParenLoc,
2815  SourceLocation EllipsisLoc) {
2816  Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2817  Args, RParenLoc);
2818  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2819  DS, IdLoc, List, EllipsisLoc);
2820 }
2821 
2822 namespace {
2823 
2824 // Callback to only accept typo corrections that can be a valid C++ member
2825 // intializer: either a non-static field member or a base class.
2826 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2827 public:
2828  explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2829  : ClassDecl(ClassDecl) {}
2830 
2831  bool ValidateCandidate(const TypoCorrection &candidate) override {
2832  if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2833  if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2834  return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2835  return isa<TypeDecl>(ND);
2836  }
2837  return false;
2838  }
2839 
2840 private:
2841  CXXRecordDecl *ClassDecl;
2842 };
2843 
2844 }
2845 
2846 /// \brief Handle a C++ member initializer.
2848 Sema::BuildMemInitializer(Decl *ConstructorD,
2849  Scope *S,
2850  CXXScopeSpec &SS,
2851  IdentifierInfo *MemberOrBase,
2852  ParsedType TemplateTypeTy,
2853  const DeclSpec &DS,
2854  SourceLocation IdLoc,
2855  Expr *Init,
2856  SourceLocation EllipsisLoc) {
2858  if (!Res.isUsable())
2859  return true;
2860  Init = Res.get();
2861 
2862  if (!ConstructorD)
2863  return true;
2864 
2865  AdjustDeclIfTemplate(ConstructorD);
2866 
2867  CXXConstructorDecl *Constructor
2868  = dyn_cast<CXXConstructorDecl>(ConstructorD);
2869  if (!Constructor) {
2870  // The user wrote a constructor initializer on a function that is
2871  // not a C++ constructor. Ignore the error for now, because we may
2872  // have more member initializers coming; we'll diagnose it just
2873  // once in ActOnMemInitializers.
2874  return true;
2875  }
2876 
2877  CXXRecordDecl *ClassDecl = Constructor->getParent();
2878 
2879  // C++ [class.base.init]p2:
2880  // Names in a mem-initializer-id are looked up in the scope of the
2881  // constructor's class and, if not found in that scope, are looked
2882  // up in the scope containing the constructor's definition.
2883  // [Note: if the constructor's class contains a member with the
2884  // same name as a direct or virtual base class of the class, a
2885  // mem-initializer-id naming the member or base class and composed
2886  // of a single identifier refers to the class member. A
2887  // mem-initializer-id for the hidden base class may be specified
2888  // using a qualified name. ]
2889  if (!SS.getScopeRep() && !TemplateTypeTy) {
2890  // Look for a member, first.
2891  DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
2892  if (!Result.empty()) {
2893  ValueDecl *Member;
2894  if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2895  (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2896  if (EllipsisLoc.isValid())
2897  Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2898  << MemberOrBase
2899  << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2900 
2901  return BuildMemberInitializer(Member, Init, IdLoc);
2902  }
2903  }
2904  }
2905  // It didn't name a member, so see if it names a class.
2906  QualType BaseType;
2907  TypeSourceInfo *TInfo = nullptr;
2908 
2909  if (TemplateTypeTy) {
2910  BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2911  } else if (DS.getTypeSpecType() == TST_decltype) {
2912  BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2913  } else {
2914  LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2915  LookupParsedName(R, S, &SS);
2916 
2917  TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2918  if (!TyD) {
2919  if (R.isAmbiguous()) return true;
2920 
2921  // We don't want access-control diagnostics here.
2922  R.suppressDiagnostics();
2923 
2924  if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2925  bool NotUnknownSpecialization = false;
2926  DeclContext *DC = computeDeclContext(SS, false);
2927  if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2928  NotUnknownSpecialization = !Record->hasAnyDependentBases();
2929 
2930  if (!NotUnknownSpecialization) {
2931  // When the scope specifier can refer to a member of an unknown
2932  // specialization, we take it as a type name.
2935  *MemberOrBase, IdLoc);
2936  if (BaseType.isNull())
2937  return true;
2938 
2939  R.clear();
2940  R.setLookupName(MemberOrBase);
2941  }
2942  }
2943 
2944  // If no results were found, try to correct typos.
2945  TypoCorrection Corr;
2946  if (R.empty() && BaseType.isNull() &&
2947  (Corr = CorrectTypo(
2948  R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2949  llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
2950  CTK_ErrorRecovery, ClassDecl))) {
2951  if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2952  // We have found a non-static data member with a similar
2953  // name to what was typed; complain and initialize that
2954  // member.
2955  diagnoseTypo(Corr,
2956  PDiag(diag::err_mem_init_not_member_or_class_suggest)
2957  << MemberOrBase << true);
2958  return BuildMemberInitializer(Member, Init, IdLoc);
2959  } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2960  const CXXBaseSpecifier *DirectBaseSpec;
2961  const CXXBaseSpecifier *VirtualBaseSpec;
2962  if (FindBaseInitializer(*this, ClassDecl,
2964  DirectBaseSpec, VirtualBaseSpec)) {
2965  // We have found a direct or virtual base class with a
2966  // similar name to what was typed; complain and initialize
2967  // that base class.
2968  diagnoseTypo(Corr,
2969  PDiag(diag::err_mem_init_not_member_or_class_suggest)
2970  << MemberOrBase << false,
2971  PDiag() /*Suppress note, we provide our own.*/);
2972 
2973  const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2974  : VirtualBaseSpec;
2975  Diag(BaseSpec->getLocStart(),
2976  diag::note_base_class_specified_here)
2977  << BaseSpec->getType()
2978  << BaseSpec->getSourceRange();
2979 
2980  TyD = Type;
2981  }
2982  }
2983  }
2984 
2985  if (!TyD && BaseType.isNull()) {
2986  Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2987  << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2988  return true;
2989  }
2990  }
2991 
2992  if (BaseType.isNull()) {
2993  BaseType = Context.getTypeDeclType(TyD);
2994  MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
2995  if (SS.isSet()) {
2996  BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2997  BaseType);
2998  TInfo = Context.CreateTypeSourceInfo(BaseType);
3000  TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3003  }
3004  }
3005  }
3006 
3007  if (!TInfo)
3008  TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3009 
3010  return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3011 }
3012 
3013 /// Checks a member initializer expression for cases where reference (or
3014 /// pointer) members are bound to by-value parameters (or their addresses).
3016  Expr *Init,
3017  SourceLocation IdLoc) {
3018  QualType MemberTy = Member->getType();
3019 
3020  // We only handle pointers and references currently.
3021  // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3022  if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3023  return;
3024 
3025  const bool IsPointer = MemberTy->isPointerType();
3026  if (IsPointer) {
3027  if (const UnaryOperator *Op
3028  = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3029  // The only case we're worried about with pointers requires taking the
3030  // address.
3031  if (Op->getOpcode() != UO_AddrOf)
3032  return;
3033 
3034  Init = Op->getSubExpr();
3035  } else {
3036  // We only handle address-of expression initializers for pointers.
3037  return;
3038  }
3039  }
3040 
3041  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3042  // We only warn when referring to a non-reference parameter declaration.
3043  const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3044  if (!Parameter || Parameter->getType()->isReferenceType())
3045  return;
3046 
3047  S.Diag(Init->getExprLoc(),
3048  IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3049  : diag::warn_bind_ref_member_to_parameter)
3050  << Member << Parameter << Init->getSourceRange();
3051  } else {
3052  // Other initializers are fine.
3053  return;
3054  }
3055 
3056  S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3057  << (unsigned)IsPointer;
3058 }
3059 
3062  SourceLocation IdLoc) {
3063  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3064  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3065  assert((DirectMember || IndirectMember) &&
3066  "Member must be a FieldDecl or IndirectFieldDecl");
3067 
3069  return true;
3070 
3071  if (Member->isInvalidDecl())
3072  return true;
3073 
3074  MultiExprArg Args;
3075  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3076  Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3077  } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3078  Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3079  } else {
3080  // Template instantiation doesn't reconstruct ParenListExprs for us.
3081  Args = Init;
3082  }
3083 
3084  SourceRange InitRange = Init->getSourceRange();
3085 
3086  if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3087  // Can't check initialization for a member of dependent type or when
3088  // any of the arguments are type-dependent expressions.
3090  } else {
3091  bool InitList = false;
3092  if (isa<InitListExpr>(Init)) {
3093  InitList = true;
3094  Args = Init;
3095  }
3096 
3097  // Initialize the member.
3098  InitializedEntity MemberEntity =
3099  DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3100  : InitializedEntity::InitializeMember(IndirectMember,
3101  nullptr);
3103  InitList ? InitializationKind::CreateDirectList(IdLoc)
3104  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3105  InitRange.getEnd());
3106 
3107  InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3108  ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3109  nullptr);
3110  if (MemberInit.isInvalid())
3111  return true;
3112 
3113  CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3114 
3115  // C++11 [class.base.init]p7:
3116  // The initialization of each base and member constitutes a
3117  // full-expression.
3118  MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
3119  if (MemberInit.isInvalid())
3120  return true;
3121 
3122  Init = MemberInit.get();
3123  }
3124 
3125  if (DirectMember) {
3126  return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3127  InitRange.getBegin(), Init,
3128  InitRange.getEnd());
3129  } else {
3130  return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3131  InitRange.getBegin(), Init,
3132  InitRange.getEnd());
3133  }
3134 }
3135 
3138  CXXRecordDecl *ClassDecl) {
3139  SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
3140  if (!LangOpts.CPlusPlus11)
3141  return Diag(NameLoc, diag::err_delegating_ctor)
3142  << TInfo->getTypeLoc().getLocalSourceRange();
3143  Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
3144 
3145  bool InitList = true;
3146  MultiExprArg Args = Init;
3147  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3148  InitList = false;
3149  Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3150  }
3151 
3152  SourceRange InitRange = Init->getSourceRange();
3153  // Initialize the object.
3155  QualType(ClassDecl->getTypeForDecl(), 0));
3157  InitList ? InitializationKind::CreateDirectList(NameLoc)
3158  : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3159  InitRange.getEnd());
3160  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
3161  ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
3162  Args, nullptr);
3163  if (DelegationInit.isInvalid())
3164  return true;
3165 
3166  assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3167  "Delegating constructor with no target?");
3168 
3169  // C++11 [class.base.init]p7:
3170  // The initialization of each base and member constitutes a
3171  // full-expression.
3172  DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3173  InitRange.getBegin());
3174  if (DelegationInit.isInvalid())
3175  return true;
3176 
3177  // If we are in a dependent context, template instantiation will
3178  // perform this type-checking again. Just save the arguments that we
3179  // received in a ParenListExpr.
3180  // FIXME: This isn't quite ideal, since our ASTs don't capture all
3181  // of the information that we have about the base
3182  // initializer. However, deconstructing the ASTs is a dicey process,
3183  // and this approach is far more likely to get the corner cases right.
3185  DelegationInit = Init;
3186 
3187  return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
3188  DelegationInit.getAs<Expr>(),
3189  InitRange.getEnd());
3190 }
3191 
3194  Expr *Init, CXXRecordDecl *ClassDecl,
3195  SourceLocation EllipsisLoc) {
3196  SourceLocation BaseLoc
3197  = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
3198 
3199  if (!BaseType->isDependentType() && !BaseType->isRecordType())
3200  return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3201  << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3202 
3203  // C++ [class.base.init]p2:
3204  // [...] Unless the mem-initializer-id names a nonstatic data
3205  // member of the constructor's class or a direct or virtual base
3206  // of that class, the mem-initializer is ill-formed. A
3207  // mem-initializer-list can initialize a base class using any
3208  // name that denotes that base class type.
3209  bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
3210 
3211  SourceRange InitRange = Init->getSourceRange();
3212  if (EllipsisLoc.isValid()) {
3213  // This is a pack expansion.
3214  if (!BaseType->containsUnexpandedParameterPack()) {
3215  Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
3216  << SourceRange(BaseLoc, InitRange.getEnd());
3217 
3218  EllipsisLoc = SourceLocation();
3219  }
3220  } else {
3221  // Check for any unexpanded parameter packs.
3222  if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3223  return true;
3224 
3226  return true;
3227  }
3228 
3229  // Check for direct and virtual base classes.
3230  const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3231  const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
3232  if (!Dependent) {
3234  BaseType))
3235  return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
3236 
3237  FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3238  VirtualBaseSpec);
3239 
3240  // C++ [base.class.init]p2:
3241  // Unless the mem-initializer-id names a nonstatic data member of the
3242  // constructor's class or a direct or virtual base of that class, the
3243  // mem-initializer is ill-formed.
3244  if (!DirectBaseSpec && !VirtualBaseSpec) {
3245  // If the class has any dependent bases, then it's possible that
3246  // one of those types will resolve to the same type as
3247  // BaseType. Therefore, just treat this as a dependent base
3248  // class initialization. FIXME: Should we try to check the
3249  // initialization anyway? It seems odd.
3250  if (ClassDecl->hasAnyDependentBases())
3251  Dependent = true;
3252  else
3253  return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3254  << BaseType << Context.getTypeDeclType(ClassDecl)
3255  << BaseTInfo->getTypeLoc().getLocalSourceRange();
3256  }
3257  }
3258 
3259  if (Dependent) {
3261 
3262  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3263  /*IsVirtual=*/false,
3264  InitRange.getBegin(), Init,
3265  InitRange.getEnd(), EllipsisLoc);
3266  }
3267 
3268  // C++ [base.class.init]p2:
3269  // If a mem-initializer-id is ambiguous because it designates both
3270  // a direct non-virtual base class and an inherited virtual base
3271  // class, the mem-initializer is ill-formed.
3272  if (DirectBaseSpec && VirtualBaseSpec)
3273  return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
3274  << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3275 
3276  const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
3277  if (!BaseSpec)
3278  BaseSpec = VirtualBaseSpec;
3279 
3280  // Initialize the base.
3281  bool InitList = true;
3282  MultiExprArg Args = Init;
3283  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3284  InitList = false;
3285  Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3286  }
3287 
3288  InitializedEntity BaseEntity =
3289  InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3291  InitList ? InitializationKind::CreateDirectList(BaseLoc)
3292  : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3293  InitRange.getEnd());
3294  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
3295  ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
3296  if (BaseInit.isInvalid())
3297  return true;
3298 
3299  // C++11 [class.base.init]p7:
3300  // The initialization of each base and member constitutes a
3301  // full-expression.
3302  BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
3303  if (BaseInit.isInvalid())
3304  return true;
3305 
3306  // If we are in a dependent context, template instantiation will
3307  // perform this type-checking again. Just save the arguments that we
3308  // received in a ParenListExpr.
3309  // FIXME: This isn't quite ideal, since our ASTs don't capture all
3310  // of the information that we have about the base
3311  // initializer. However, deconstructing the ASTs is a dicey process,
3312  // and this approach is far more likely to get the corner cases right.
3314  BaseInit = Init;
3315 
3316  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3317  BaseSpec->isVirtual(),
3318  InitRange.getBegin(),
3319  BaseInit.getAs<Expr>(),
3320  InitRange.getEnd(), EllipsisLoc);
3321 }
3322 
3323 // Create a static_cast<T&&>(expr).
3324 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3325  if (T.isNull()) T = E->getType();
3326  QualType TargetType = SemaRef.BuildReferenceType(
3327  T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
3328  SourceLocation ExprLoc = E->getLocStart();
3329  TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3330  TargetType, ExprLoc);
3331 
3332  return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3333  SourceRange(ExprLoc, ExprLoc),
3334  E->getSourceRange()).get();
3335 }
3336 
3337 /// ImplicitInitializerKind - How an implicit base or member initializer should
3338 /// initialize its base or member.
3344 };
3345 
3346 static bool
3348  ImplicitInitializerKind ImplicitInitKind,
3349  CXXBaseSpecifier *BaseSpec,
3350  bool IsInheritedVirtualBase,
3351  CXXCtorInitializer *&CXXBaseInit) {
3352  InitializedEntity InitEntity
3353  = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3354  IsInheritedVirtualBase);
3355 
3356  ExprResult BaseInit;
3357 
3358  switch (ImplicitInitKind) {
3359  case IIK_Inherit:
3360  case IIK_Default: {
3361  InitializationKind InitKind
3362  = InitializationKind::CreateDefault(Constructor->getLocation());
3363  InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3364  BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3365  break;
3366  }
3367 
3368  case IIK_Move:
3369  case IIK_Copy: {
3370  bool Moving = ImplicitInitKind == IIK_Move;
3371  ParmVarDecl *Param = Constructor->getParamDecl(0);
3372  QualType ParamType = Param->getType().getNonReferenceType();
3373 
3374  Expr *CopyCtorArg =
3376  SourceLocation(), Param, false,
3377  Constructor->getLocation(), ParamType,
3378  VK_LValue, nullptr);
3379 
3380  SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3381 
3382  // Cast to the base class to avoid ambiguities.
3383  QualType ArgTy =
3384  SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3385  ParamType.getQualifiers());
3386 
3387  if (Moving) {
3388  CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3389  }
3390 
3391  CXXCastPath BasePath;
3392  BasePath.push_back(BaseSpec);
3393  CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3394  CK_UncheckedDerivedToBase,
3395  Moving ? VK_XValue : VK_LValue,
3396  &BasePath).get();
3397 
3398  InitializationKind InitKind
3399  = InitializationKind::CreateDirect(Constructor->getLocation(),
3401  InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3402  BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
3403  break;
3404  }
3405  }
3406 
3407  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
3408  if (BaseInit.isInvalid())
3409  return true;
3410 
3411  CXXBaseInit =
3412  new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3413  SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3414  SourceLocation()),
3415  BaseSpec->isVirtual(),
3416  SourceLocation(),
3417  BaseInit.getAs<Expr>(),
3418  SourceLocation(),
3419  SourceLocation());
3420 
3421  return false;
3422 }
3423 
3424 static bool RefersToRValueRef(Expr *MemRef) {
3425  ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3426  return Referenced->getType()->isRValueReferenceType();
3427 }
3428 
3429 static bool
3431  ImplicitInitializerKind ImplicitInitKind,
3432  FieldDecl *Field, IndirectFieldDecl *Indirect,
3433  CXXCtorInitializer *&CXXMemberInit) {
3434  if (Field->isInvalidDecl())
3435  return true;
3436 
3437  SourceLocation Loc = Constructor->getLocation();
3438 
3439  if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3440  bool Moving = ImplicitInitKind == IIK_Move;
3441  ParmVarDecl *Param = Constructor->getParamDecl(0);
3442  QualType ParamType = Param->getType().getNonReferenceType();
3443 
3444  // Suppress copying zero-width bitfields.
3445  if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3446  return false;
3447 
3448  Expr *MemberExprBase =
3450  SourceLocation(), Param, false,
3451  Loc, ParamType, VK_LValue, nullptr);
3452 
3453  SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3454 
3455  if (Moving) {
3456  MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3457  }
3458 
3459  // Build a reference to this field within the parameter.
3460  CXXScopeSpec SS;
3461  LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3463  MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3464  : cast<ValueDecl>(Field), AS_public);
3465  MemberLookup.resolveKind();
3466  ExprResult CtorArg
3467  = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
3468  ParamType, Loc,
3469  /*IsArrow=*/false,
3470  SS,
3471  /*TemplateKWLoc=*/SourceLocation(),
3472  /*FirstQualifierInScope=*/nullptr,
3473  MemberLookup,
3474  /*TemplateArgs=*/nullptr,
3475  /*S*/nullptr);
3476  if (CtorArg.isInvalid())
3477  return true;
3478 
3479  // C++11 [class.copy]p15:
3480  // - if a member m has rvalue reference type T&&, it is direct-initialized
3481  // with static_cast<T&&>(x.m);
3482  if (RefersToRValueRef(CtorArg.get())) {
3483  CtorArg = CastForMoving(SemaRef, CtorArg.get());
3484  }
3485 
3486  // When the field we are copying is an array, create index variables for
3487  // each dimension of the array. We use these index variables to subscript
3488  // the source array, and other clients (e.g., CodeGen) will perform the
3489  // necessary iteration with these index variables.
3490  SmallVector<VarDecl *, 4> IndexVariables;
3491  QualType BaseType = Field->getType();
3492  QualType SizeType = SemaRef.Context.getSizeType();
3493  bool InitializingArray = false;
3494  while (const ConstantArrayType *Array
3495  = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3496  InitializingArray = true;
3497  // Create the iteration variable for this array index.
3498  IdentifierInfo *IterationVarName = nullptr;
3499  {
3500  SmallString<8> Str;
3501  llvm::raw_svector_ostream OS(Str);
3502  OS << "__i" << IndexVariables.size();
3503  IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3504  }
3505  VarDecl *IterationVar
3506  = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3507  IterationVarName, SizeType,
3508  SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3509  SC_None);
3510  IndexVariables.push_back(IterationVar);
3511 
3512  // Create a reference to the iteration variable.
3513  ExprResult IterationVarRef
3514  = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3515  assert(!IterationVarRef.isInvalid() &&
3516  "Reference to invented variable cannot fail!");
3517  IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
3518  assert(!IterationVarRef.isInvalid() &&
3519  "Conversion of invented variable cannot fail!");
3520 
3521  // Subscript the array with this iteration variable.
3522  CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3523  IterationVarRef.get(),
3524  Loc);
3525  if (CtorArg.isInvalid())
3526  return true;
3527 
3528  BaseType = Array->getElementType();
3529  }
3530 
3531  // The array subscript expression is an lvalue, which is wrong for moving.
3532  if (Moving && InitializingArray)
3533  CtorArg = CastForMoving(SemaRef, CtorArg.get());
3534 
3535  // Construct the entity that we will be initializing. For an array, this
3536  // will be first element in the array, which may require several levels
3537  // of array-subscript entities.
3539  Entities.reserve(1 + IndexVariables.size());
3540  if (Indirect)
3541  Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3542  else
3543  Entities.push_back(InitializedEntity::InitializeMember(Field));
3544  for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3545  Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3546  0,
3547  Entities.back()));
3548 
3549  // Direct-initialize to use the copy constructor.
3550  InitializationKind InitKind =
3552 
3553  Expr *CtorArgE = CtorArg.getAs<Expr>();
3554  InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
3555  CtorArgE);
3556 
3557  ExprResult MemberInit
3558  = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3559  MultiExprArg(&CtorArgE, 1));
3560  MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3561  if (MemberInit.isInvalid())
3562  return true;
3563 
3564  if (Indirect) {
3565  assert(IndexVariables.size() == 0 &&
3566  "Indirect field improperly initialized");
3567  CXXMemberInit
3568  = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3569  Loc, Loc,
3570  MemberInit.getAs<Expr>(),
3571  Loc);
3572  } else
3573  CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3574  Loc, MemberInit.getAs<Expr>(),
3575  Loc,
3576  IndexVariables.data(),
3577  IndexVariables.size());
3578  return false;
3579  }
3580 
3581  assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3582  "Unhandled implicit init kind!");
3583 
3584  QualType FieldBaseElementType =
3585  SemaRef.Context.getBaseElementType(Field->getType());
3586 
3587  if (FieldBaseElementType->isRecordType()) {
3588  InitializedEntity InitEntity
3589  = Indirect? InitializedEntity::InitializeMember(Indirect)
3591  InitializationKind InitKind =
3593 
3594  InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3595  ExprResult MemberInit =
3596  InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3597 
3598  MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3599  if (MemberInit.isInvalid())
3600  return true;
3601 
3602  if (Indirect)
3603  CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3604  Indirect, Loc,
3605  Loc,
3606  MemberInit.get(),
3607  Loc);
3608  else
3609  CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3610  Field, Loc, Loc,
3611  MemberInit.get(),
3612  Loc);
3613  return false;
3614  }
3615 
3616  if (!Field->getParent()->isUnion()) {
3617  if (FieldBaseElementType->isReferenceType()) {
3618  SemaRef.Diag(Constructor->getLocation(),
3619  diag::err_uninitialized_member_in_ctor)
3620  << (int)Constructor->isImplicit()
3621  << SemaRef.Context.getTagDeclType(Constructor->getParent())
3622  << 0 << Field->getDeclName();
3623  SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3624  return true;
3625  }
3626 
3627  if (FieldBaseElementType.isConstQualified()) {
3628  SemaRef.Diag(Constructor->getLocation(),
3629  diag::err_uninitialized_member_in_ctor)
3630  << (int)Constructor->isImplicit()
3631  << SemaRef.Context.getTagDeclType(Constructor->getParent())
3632  << 1 << Field->getDeclName();
3633  SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3634  return true;
3635  }
3636  }
3637 
3638  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3639  FieldBaseElementType->isObjCRetainableType() &&
3640  FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3641  FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3642  // ARC:
3643  // Default-initialize Objective-C pointers to NULL.
3644  CXXMemberInit
3645  = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3646  Loc, Loc,
3647  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3648  Loc);
3649  return false;
3650  }
3651 
3652  // Nothing to initialize.
3653  CXXMemberInit = nullptr;
3654  return false;
3655 }
3656 
3657 namespace {
3658 struct BaseAndFieldInfo {
3659  Sema &S;
3660  CXXConstructorDecl *Ctor;
3661  bool AnyErrorsInInits;
3663  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3665  llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
3666 
3667  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3668  : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3669  bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3670  if (Ctor->getInheritedConstructor())
3671  IIK = IIK_Inherit;
3672  else if (Generated && Ctor->isCopyConstructor())
3673  IIK = IIK_Copy;
3674  else if (Generated && Ctor->isMoveConstructor())
3675  IIK = IIK_Move;
3676  else
3677  IIK = IIK_Default;
3678  }
3679 
3680  bool isImplicitCopyOrMove() const {
3681  switch (IIK) {
3682  case IIK_Copy:
3683  case IIK_Move:
3684  return true;
3685 
3686  case IIK_Default:
3687  case IIK_Inherit:
3688  return false;
3689  }
3690 
3691  llvm_unreachable("Invalid ImplicitInitializerKind!");
3692  }
3693 
3694  bool addFieldInitializer(CXXCtorInitializer *Init) {
3695  AllToInit.push_back(Init);
3696 
3697  // Check whether this initializer makes the field "used".
3698  if (Init->getInit()->HasSideEffects(S.Context))
3699  S.UnusedPrivateFields.remove(Init->getAnyMember());
3700 
3701  return false;
3702  }
3703 
3704  bool isInactiveUnionMember(FieldDecl *Field) {
3705  RecordDecl *Record = Field->getParent();
3706  if (!Record->isUnion())
3707  return false;
3708 
3709  if (FieldDecl *Active =
3710  ActiveUnionMember.lookup(Record->getCanonicalDecl()))
3711  return Active != Field->getCanonicalDecl();
3712 
3713  // In an implicit copy or move constructor, ignore any in-class initializer.
3714  if (isImplicitCopyOrMove())
3715  return true;
3716 
3717  // If there's no explicit initialization, the field is active only if it
3718  // has an in-class initializer...
3719  if (Field->hasInClassInitializer())
3720  return false;
3721  // ... or it's an anonymous struct or union whose class has an in-class
3722  // initializer.
3723  if (!Field->isAnonymousStructOrUnion())
3724  return true;
3725  CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3726  return !FieldRD->hasInClassInitializer();
3727  }
3728 
3729  /// \brief Determine whether the given field is, or is within, a union member
3730  /// that is inactive (because there was an initializer given for a different
3731  /// member of the union, or because the union was not initialized at all).
3732  bool isWithinInactiveUnionMember(FieldDecl *Field,
3733  IndirectFieldDecl *Indirect) {
3734  if (!Indirect)
3735  return isInactiveUnionMember(Field);
3736 
3737  for (auto *C : Indirect->chain()) {
3738  FieldDecl *Field = dyn_cast<FieldDecl>(C);
3739  if (Field && isInactiveUnionMember(Field))
3740  return true;
3741  }
3742  return false;
3743  }
3744 };
3745 }
3746 
3747 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3748 /// array type.
3750  if (T->isIncompleteArrayType())
3751  return true;
3752 
3753  while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3754  if (!ArrayT->getSize())
3755  return true;
3756 
3757  T = ArrayT->getElementType();
3758  }
3759 
3760  return false;
3761 }
3762 
3763 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3764  FieldDecl *Field,
3765  IndirectFieldDecl *Indirect = nullptr) {
3766  if (Field->isInvalidDecl())
3767  return false;
3768 
3769  // Overwhelmingly common case: we have a direct initializer for this field.
3770  if (CXXCtorInitializer *Init =
3771  Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
3772  return Info.addFieldInitializer(Init);
3773 
3774  // C++11 [class.base.init]p8:
3775  // if the entity is a non-static data member that has a
3776  // brace-or-equal-initializer and either
3777  // -- the constructor's class is a union and no other variant member of that
3778  // union is designated by a mem-initializer-id or
3779  // -- the constructor's class is not a union, and, if the entity is a member
3780  // of an anonymous union, no other member of that union is designated by
3781  // a mem-initializer-id,
3782  // the entity is initialized as specified in [dcl.init].
3783  //
3784  // We also apply the same rules to handle anonymous structs within anonymous
3785  // unions.
3786  if (Info.isWithinInactiveUnionMember(Field, Indirect))
3787  return false;
3788 
3789  if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3790  ExprResult DIE =
3791  SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
3792  if (DIE.isInvalid())
3793  return true;
3794  CXXCtorInitializer *Init;
3795  if (Indirect)
3796  Init = new (SemaRef.Context)
3797  CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
3798  SourceLocation(), DIE.get(), SourceLocation());
3799  else
3800  Init = new (SemaRef.Context)
3801  CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
3802  SourceLocation(), DIE.get(), SourceLocation());
3803  return Info.addFieldInitializer(Init);
3804  }
3805 
3806  // Don't initialize incomplete or zero-length arrays.
3807  if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3808  return false;
3809 
3810  // Don't try to build an implicit initializer if there were semantic
3811  // errors in any of the initializers (and therefore we might be
3812  // missing some that the user actually wrote).
3813  if (Info.AnyErrorsInInits)
3814  return false;
3815 
3816  CXXCtorInitializer *Init = nullptr;
3817  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3818  Indirect, Init))
3819  return true;
3820 
3821  if (!Init)
3822  return false;
3823 
3824  return Info.addFieldInitializer(Init);
3825 }
3826 
3827 bool
3829  CXXCtorInitializer *Initializer) {
3830  assert(Initializer->isDelegatingInitializer());
3831  Constructor->setNumCtorInitializers(1);
3832  CXXCtorInitializer **initializer =
3833  new (Context) CXXCtorInitializer*[1];
3834  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3835  Constructor->setCtorInitializers(initializer);
3836 
3837  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3838  MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3839  DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3840  }
3841 
3842  DelegatingCtorDecls.push_back(Constructor);
3843 
3844  DiagnoseUninitializedFields(*this, Constructor);
3845 
3846  return false;
3847 }
3848 
3849 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3850  ArrayRef<CXXCtorInitializer *> Initializers) {
3851  if (Constructor->isDependentContext()) {
3852  // Just store the initializers as written, they will be checked during
3853  // instantiation.
3854  if (!Initializers.empty()) {
3855  Constructor->setNumCtorInitializers(Initializers.size());
3856  CXXCtorInitializer **baseOrMemberInitializers =
3857  new (Context) CXXCtorInitializer*[Initializers.size()];
3858  memcpy(baseOrMemberInitializers, Initializers.data(),
3859  Initializers.size() * sizeof(CXXCtorInitializer*));
3860  Constructor->setCtorInitializers(baseOrMemberInitializers);
3861  }
3862 
3863  // Let template instantiation know whether we had errors.
3864  if (AnyErrors)
3865  Constructor->setInvalidDecl();
3866 
3867  return false;
3868  }
3869 
3870  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3871 
3872  // We need to build the initializer AST according to order of construction
3873  // and not what user specified in the Initializers list.
3874  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3875  if (!ClassDecl)
3876  return true;
3877 
3878  bool HadError = false;
3879 
3880  for (unsigned i = 0; i < Initializers.size(); i++) {
3881  CXXCtorInitializer *Member = Initializers[i];
3882 
3883  if (Member->isBaseInitializer())
3884  Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3885  else {
3886  Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
3887 
3888  if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3889  for (auto *C : F->chain()) {
3890  FieldDecl *FD = dyn_cast<FieldDecl>(C);
3891  if (FD && FD->getParent()->isUnion())
3892  Info.ActiveUnionMember.insert(std::make_pair(
3893  FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3894  }
3895  } else if (FieldDecl *FD = Member->getMember()) {
3896  if (FD->getParent()->isUnion())
3897  Info.ActiveUnionMember.insert(std::make_pair(
3898  FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3899  }
3900  }
3901  }
3902 
3903  // Keep track of the direct virtual bases.
3904  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3905  for (auto &I : ClassDecl->bases()) {
3906  if (I.isVirtual())
3907  DirectVBases.insert(&I);
3908  }
3909 
3910  // Push virtual bases before others.
3911  for (auto &VBase : ClassDecl->vbases()) {
3913  = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
3914  // [class.base.init]p7, per DR257:
3915  // A mem-initializer where the mem-initializer-id names a virtual base
3916  // class is ignored during execution of a constructor of any class that
3917  // is not the most derived class.
3918  if (ClassDecl->isAbstract()) {
3919  // FIXME: Provide a fixit to remove the base specifier. This requires
3920  // tracking the location of the associated comma for a base specifier.
3921  Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3922  << VBase.getType() << ClassDecl;
3923  DiagnoseAbstractType(ClassDecl);
3924  }
3925 
3926  Info.AllToInit.push_back(Value);
3927  } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3928  // [class.base.init]p8, per DR257:
3929  // If a given [...] base class is not named by a mem-initializer-id
3930  // [...] and the entity is not a virtual base class of an abstract
3931  // class, then [...] the entity is default-initialized.
3932  bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
3933  CXXCtorInitializer *CXXBaseInit;
3934  if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3935  &VBase, IsInheritedVirtualBase,
3936  CXXBaseInit)) {
3937  HadError = true;
3938  continue;
3939  }
3940 
3941  Info.AllToInit.push_back(CXXBaseInit);
3942  }
3943  }
3944 
3945  // Non-virtual bases.
3946  for (auto &Base : ClassDecl->bases()) {
3947  // Virtuals are in the virtual base list and already constructed.
3948  if (Base.isVirtual())
3949  continue;
3950 
3952  = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
3953  Info.AllToInit.push_back(Value);
3954  } else if (!AnyErrors) {
3955  CXXCtorInitializer *CXXBaseInit;
3956  if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3957  &Base, /*IsInheritedVirtualBase=*/false,
3958  CXXBaseInit)) {
3959  HadError = true;
3960  continue;
3961  }
3962 
3963  Info.AllToInit.push_back(CXXBaseInit);
3964  }
3965  }
3966 
3967  // Fields.
3968  for (auto *Mem : ClassDecl->decls()) {
3969  if (auto *F = dyn_cast<FieldDecl>(Mem)) {
3970  // C++ [class.bit]p2:
3971  // A declaration for a bit-field that omits the identifier declares an
3972  // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3973  // initialized.
3974  if (F->isUnnamedBitfield())
3975  continue;
3976 
3977  // If we're not generating the implicit copy/move constructor, then we'll
3978  // handle anonymous struct/union fields based on their individual
3979  // indirect fields.
3980  if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3981  continue;
3982 
3983  if (CollectFieldInitializer(*this, Info, F))
3984  HadError = true;
3985  continue;
3986  }
3987 
3988  // Beyond this point, we only consider default initialization.
3989  if (Info.isImplicitCopyOrMove())
3990  continue;
3991 
3992  if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
3993  if (F->getType()->isIncompleteArrayType()) {
3994  assert(ClassDecl->hasFlexibleArrayMember() &&
3995  "Incomplete array type is not valid");
3996  continue;
3997  }
3998 
3999  // Initialize each field of an anonymous struct individually.
4000  if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4001  HadError = true;
4002 
4003  continue;
4004  }
4005  }
4006 
4007  unsigned NumInitializers = Info.AllToInit.size();
4008  if (NumInitializers > 0) {
4009  Constructor->setNumCtorInitializers(NumInitializers);
4010  CXXCtorInitializer **baseOrMemberInitializers =
4011  new (Context) CXXCtorInitializer*[NumInitializers];
4012  memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4013  NumInitializers * sizeof(CXXCtorInitializer*));
4014  Constructor->setCtorInitializers(baseOrMemberInitializers);
4015 
4016  // Constructors implicitly reference the base and member
4017  // destructors.
4018  MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4019  Constructor->getParent());
4020  }
4021 
4022  return HadError;
4023 }
4024 
4026  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4027  const RecordDecl *RD = RT->getDecl();
4028  if (RD->isAnonymousStructOrUnion()) {
4029  for (auto *Field : RD->fields())
4030  PopulateKeysForFields(Field, IdealInits);
4031  return;
4032  }
4033  }
4034  IdealInits.push_back(Field->getCanonicalDecl());
4035 }
4036 
4037 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4038  return Context.getCanonicalType(BaseType).getTypePtr();
4039 }
4040 
4041 static const void *GetKeyForMember(ASTContext &Context,
4042  CXXCtorInitializer *Member) {
4043  if (!Member->isAnyMemberInitializer())
4044  return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4045 
4046  return Member->getAnyMember()->getCanonicalDecl();
4047 }
4048 
4050  Sema &SemaRef, const CXXConstructorDecl *Constructor,
4052  if (Constructor->getDeclContext()->isDependentContext())
4053  return;
4054 
4055  // Don't check initializers order unless the warning is enabled at the
4056  // location of at least one initializer.
4057  bool ShouldCheckOrder = false;
4058  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4059  CXXCtorInitializer *Init = Inits[InitIndex];
4060  if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4061  Init->getSourceLocation())) {
4062  ShouldCheckOrder = true;
4063  break;
4064  }
4065  }
4066  if (!ShouldCheckOrder)
4067  return;
4068 
4069  // Build the list of bases and members in the order that they'll
4070  // actually be initialized. The explicit initializers should be in
4071  // this same order but may be missing things.
4072  SmallVector<const void*, 32> IdealInitKeys;
4073 
4074  const CXXRecordDecl *ClassDecl = Constructor->getParent();
4075 
4076  // 1. Virtual bases.
4077  for (const auto &VBase : ClassDecl->vbases())
4078  IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4079 
4080  // 2. Non-virtual bases.
4081  for (const auto &Base : ClassDecl->bases()) {
4082  if (Base.isVirtual())
4083  continue;
4084  IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4085  }
4086 
4087  // 3. Direct fields.
4088  for (auto *Field : ClassDecl->fields()) {
4089  if (Field->isUnnamedBitfield())
4090  continue;
4091 
4092  PopulateKeysForFields(Field, IdealInitKeys);
4093  }
4094 
4095  unsigned NumIdealInits = IdealInitKeys.size();
4096  unsigned IdealIndex = 0;
4097 
4098  CXXCtorInitializer *PrevInit = nullptr;
4099  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4100  CXXCtorInitializer *Init = Inits[InitIndex];
4101  const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4102 
4103  // Scan forward to try to find this initializer in the idealized
4104  // initializers list.
4105  for (; IdealIndex != NumIdealInits; ++IdealIndex)
4106  if (InitKey == IdealInitKeys[IdealIndex])
4107  break;
4108 
4109  // If we didn't find this initializer, it must be because we
4110  // scanned past it on a previous iteration. That can only
4111  // happen if we're out of order; emit a warning.
4112  if (IdealIndex == NumIdealInits && PrevInit) {
4114  SemaRef.Diag(PrevInit->getSourceLocation(),
4115  diag::warn_initializer_out_of_order);
4116 
4117  if (PrevInit->isAnyMemberInitializer())
4118  D << 0 << PrevInit->getAnyMember()->getDeclName();
4119  else
4120  D << 1 << PrevInit->getTypeSourceInfo()->getType();
4121 
4122  if (Init->isAnyMemberInitializer())
4123  D << 0 << Init->getAnyMember()->getDeclName();
4124  else
4125  D << 1 << Init->getTypeSourceInfo()->getType();
4126 
4127  // Move back to the initializer's location in the ideal list.
4128  for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4129  if (InitKey == IdealInitKeys[IdealIndex])
4130  break;
4131 
4132  assert(IdealIndex < NumIdealInits &&
4133  "initializer not found in initializer list");
4134  }
4135 
4136  PrevInit = Init;
4137  }
4138 }
4139 
4140 namespace {
4141 bool CheckRedundantInit(Sema &S,
4142  CXXCtorInitializer *Init,
4143  CXXCtorInitializer *&PrevInit) {
4144  if (!PrevInit) {
4145  PrevInit = Init;
4146  return false;
4147  }
4148 
4149  if (FieldDecl *Field = Init->getAnyMember())
4150  S.Diag(Init->getSourceLocation(),
4151  diag::err_multiple_mem_initialization)
4152  << Field->getDeclName()
4153  << Init->getSourceRange();
4154  else {
4155  const Type *BaseClass = Init->getBaseClass();
4156  assert(BaseClass && "neither field nor base");
4157  S.Diag(Init->getSourceLocation(),
4158  diag::err_multiple_base_initialization)
4159  << QualType(BaseClass, 0)
4160  << Init->getSourceRange();
4161  }
4162  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4163  << 0 << PrevInit->getSourceRange();
4164 
4165  return true;
4166 }
4167 
4168 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4169 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4170 
4171 bool CheckRedundantUnionInit(Sema &S,
4172  CXXCtorInitializer *Init,
4173  RedundantUnionMap &Unions) {
4174  FieldDecl *Field = Init->getAnyMember();
4175  RecordDecl *Parent = Field->getParent();
4176  NamedDecl *Child = Field;
4177 
4178  while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
4179  if (Parent->isUnion()) {
4180  UnionEntry &En = Unions[Parent];
4181  if (En.first && En.first != Child) {
4182  S.Diag(Init->getSourceLocation(),
4183  diag::err_multiple_mem_union_initialization)
4184  << Field->getDeclName()
4185  << Init->getSourceRange();
4186  S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4187  << 0 << En.second->getSourceRange();
4188  return true;
4189  }
4190  if (!En.first) {
4191  En.first = Child;
4192  En.second = Init;
4193  }
4194  if (!Parent->isAnonymousStructOrUnion())
4195  return false;
4196  }
4197 
4198  Child = Parent;
4199  Parent = cast<RecordDecl>(Parent->getDeclContext());
4200  }
4201 
4202  return false;
4203 }
4204 }
4205 
4206 /// ActOnMemInitializers - Handle the member initializers for a constructor.
4207 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
4210  bool AnyErrors) {
4211  if (!ConstructorDecl)
4212  return;
4213 
4214  AdjustDeclIfTemplate(ConstructorDecl);
4215 
4216  CXXConstructorDecl *Constructor
4217  = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
4218 
4219  if (!Constructor) {
4220  Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4221  return;
4222  }
4223 
4224  // Mapping for the duplicate initializers check.
4225  // For member initializers, this is keyed with a FieldDecl*.
4226  // For base initializers, this is keyed with a Type*.
4227  llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
4228 
4229  // Mapping for the inconsistent anonymous-union initializers check.
4230  RedundantUnionMap MemberUnions;
4231 
4232  bool HadError = false;
4233  for (unsigned i = 0; i < MemInits.size(); i++) {
4234  CXXCtorInitializer *Init = MemInits[i];
4235 
4236  // Set the source order index.
4237  Init->setSourceOrder(i);
4238 
4239  if (Init->isAnyMemberInitializer()) {
4240  const void *Key = GetKeyForMember(Context, Init);
4241  if (CheckRedundantInit(*this, Init, Members[Key]) ||
4242  CheckRedundantUnionInit(*this, Init, MemberUnions))
4243  HadError = true;
4244  } else if (Init->isBaseInitializer()) {
4245  const void *Key = GetKeyForMember(Context, Init);
4246  if (CheckRedundantInit(*this, Init, Members[Key]))
4247  HadError = true;
4248  } else {
4249  assert(Init->isDelegatingInitializer());
4250  // This must be the only initializer
4251  if (MemInits.size() != 1) {
4252  Diag(Init->getSourceLocation(),
4253  diag::err_delegating_initializer_alone)
4254  << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
4255  // We will treat this as being the only initializer.
4256  }
4257  SetDelegatingInitializer(Constructor, MemInits[i]);
4258  // Return immediately as the initializer is set.
4259  return;
4260  }
4261  }
4262 
4263  if (HadError)
4264  return;
4265 
4266  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
4267 
4268  SetCtorInitializers(Constructor, AnyErrors, MemInits);
4269 
4270  DiagnoseUninitializedFields(*this, Constructor);
4271 }
4272 
4273 void
4275  CXXRecordDecl *ClassDecl) {
4276  // Ignore dependent contexts. Also ignore unions, since their members never
4277  // have destructors implicitly called.
4278  if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
4279  return;
4280 
4281  // FIXME: all the access-control diagnostics are positioned on the
4282  // field/base declaration. That's probably good; that said, the
4283  // user might reasonably want to know why the destructor is being
4284  // emitted, and we currently don't say.
4285 
4286  // Non-static data members.
4287  for (auto *Field : ClassDecl->fields()) {
4288  if (Field->isInvalidDecl())
4289  continue;
4290 
4291  // Don't destroy incomplete or zero-length arrays.
4293  continue;
4294 
4295  QualType FieldType = Context.getBaseElementType(Field->getType());
4296 
4297  const RecordType* RT = FieldType->getAs<RecordType>();
4298  if (!RT)
4299  continue;
4300 
4301  CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4302  if (FieldClassDecl->isInvalidDecl())
4303  continue;
4304  if (FieldClassDecl->hasIrrelevantDestructor())
4305  continue;
4306  // The destructor for an implicit anonymous union member is never invoked.
4307  if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4308  continue;
4309 
4310  CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
4311  assert(Dtor && "No dtor found for FieldClassDecl!");
4312  CheckDestructorAccess(Field->getLocation(), Dtor,
4313  PDiag(diag::err_access_dtor_field)
4314  << Field->getDeclName()
4315  << FieldType);
4316 
4317  MarkFunctionReferenced(Location, Dtor);
4318  DiagnoseUseOfDecl(Dtor, Location);
4319  }
4320 
4321  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4322 
4323  // Bases.
4324  for (const auto &Base : ClassDecl->bases()) {
4325  // Bases are always records in a well-formed non-dependent class.
4326  const RecordType *RT = Base.getType()->getAs<RecordType>();
4327 
4328  // Remember direct virtual bases.
4329  if (Base.isVirtual())
4330  DirectVirtualBases.insert(RT);
4331 
4332  CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4333  // If our base class is invalid, we probably can't get its dtor anyway.
4334  if (BaseClassDecl->isInvalidDecl())
4335  continue;
4336  if (BaseClassDecl->hasIrrelevantDestructor())
4337  continue;
4338 
4339  CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4340  assert(Dtor && "No dtor found for BaseClassDecl!");
4341 
4342  // FIXME: caret should be on the start of the class name
4343  CheckDestructorAccess(Base.getLocStart(), Dtor,
4344  PDiag(diag::err_access_dtor_base)
4345  << Base.getType()
4346  << Base.getSourceRange(),
4347  Context.getTypeDeclType(ClassDecl));
4348 
4349  MarkFunctionReferenced(Location, Dtor);
4350  DiagnoseUseOfDecl(Dtor, Location);
4351  }
4352 
4353  // Virtual bases.
4354  for (const auto &VBase : ClassDecl->vbases()) {
4355  // Bases are always records in a well-formed non-dependent class.
4356  const RecordType *RT = VBase.getType()->castAs<RecordType>();
4357 
4358  // Ignore direct virtual bases.
4359  if (DirectVirtualBases.count(RT))
4360  continue;
4361 
4362  CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4363  // If our base class is invalid, we probably can't get its dtor anyway.
4364  if (BaseClassDecl->isInvalidDecl())
4365  continue;
4366  if (BaseClassDecl->hasIrrelevantDestructor())
4367  continue;
4368 
4369  CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4370  assert(Dtor && "No dtor found for BaseClassDecl!");
4372  ClassDecl->getLocation(), Dtor,
4373  PDiag(diag::err_access_dtor_vbase)
4374  << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
4375  Context.getTypeDeclType(ClassDecl)) ==
4376  AR_accessible) {
4378  Context.getTypeDeclType(ClassDecl), VBase.getType(),
4379  diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4380  SourceRange(), DeclarationName(), nullptr);
4381  }
4382 
4383  MarkFunctionReferenced(Location, Dtor);
4384  DiagnoseUseOfDecl(Dtor, Location);
4385  }
4386 }
4387 
4388 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
4389  if (!CDtorDecl)
4390  return;
4391 
4392  if (CXXConstructorDecl *Constructor
4393  = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
4394  SetCtorInitializers(Constructor, /*AnyErrors=*/false);
4395  DiagnoseUninitializedFields(*this, Constructor);
4396  }
4397 }
4398 
4400  if (!getLangOpts().CPlusPlus)
4401  return false;
4402 
4403  const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
4404  if (!RD)
4405  return false;
4406 
4407  // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
4408  // class template specialization here, but doing so breaks a lot of code.
4409 
4410  // We can't answer whether something is abstract until it has a
4411  // definition. If it's currently being defined, we'll walk back
4412  // over all the declarations when we have a full definition.
4413  const CXXRecordDecl *Def = RD->getDefinition();
4414  if (!Def || Def->isBeingDefined())
4415  return false;
4416 
4417  return RD->isAbstract();
4418 }
4419 
4421  TypeDiagnoser &Diagnoser) {
4422  if (!isAbstractType(Loc, T))
4423  return false;
4424 
4425  T = Context.getBaseElementType(T);
4426  Diagnoser.diagnose(*this, Loc, T);
4428  return true;
4429 }
4430 
4432  // Check if we've already emitted the list of pure virtual functions
4433  // for this class.
4435  return;
4436 
4437  // If the diagnostic is suppressed, don't emit the notes. We're only
4438  // going to emit them once, so try to attach them to a diagnostic we're
4439  // actually going to show.
4441  return;
4442 
4443  CXXFinalOverriderMap FinalOverriders;
4444  RD->getFinalOverriders(FinalOverriders);
4445 
4446  // Keep a set of seen pure methods so we won't diagnose the same method
4447  // more than once.
4448  llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4449 
4450  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4451  MEnd = FinalOverriders.end();
4452  M != MEnd;
4453  ++M) {
4454  for (OverridingMethods::iterator SO = M->second.begin(),
4455  SOEnd = M->second.end();
4456  SO != SOEnd; ++SO) {
4457  // C++ [class.abstract]p4:
4458  // A class is abstract if it contains or inherits at least one
4459  // pure virtual function for which the final overrider is pure
4460  // virtual.
4461 
4462  //
4463  if (SO->second.size() != 1)
4464  continue;
4465 
4466  if (!SO->second.front().Method->isPure())
4467  continue;
4468 
4469  if (!SeenPureMethods.insert(SO->second.front().Method).second)
4470  continue;
4471 
4472  Diag(SO->second.front().Method->getLocation(),
4473  diag::note_pure_virtual_function)
4474  << SO->second.front().Method->getDeclName() << RD->getDeclName();
4475  }
4476  }
4477 
4480  PureVirtualClassDiagSet->insert(RD);
4481 }
4482 
4483 namespace {
4484 struct AbstractUsageInfo {
4485  Sema &S;
4486  CXXRecordDecl *Record;
4487  CanQualType AbstractType;
4488  bool Invalid;
4489 
4490  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4491  : S(S), Record(Record),
4492  AbstractType(S.Context.getCanonicalType(
4493  S.Context.getTypeDeclType(Record))),
4494  Invalid(false) {}
4495 
4496  void DiagnoseAbstractType() {
4497  if (Invalid) return;
4498  S.DiagnoseAbstractType(Record);
4499  Invalid = true;
4500  }
4501 
4502  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4503 };
4504 
4505 struct CheckAbstractUsage {
4506  AbstractUsageInfo &Info;
4507  const NamedDecl *Ctx;
4508 
4509  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4510  : Info(Info), Ctx(Ctx) {}
4511 
4512  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4513  switch (TL.getTypeLocClass()) {
4514 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4515 #define TYPELOC(CLASS, PARENT) \
4516  case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
4517 #include "clang/AST/TypeLocNodes.def"
4518  }
4519  }
4520 
4521  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4523  for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4524  if (!TL.getParam(I))
4525  continue;
4526 
4528  if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4529  }
4530  }
4531 
4532  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4534  }
4535 
4537  // Visit the type parameters from a permissive context.
4538  for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4539  TemplateArgumentLoc TAL = TL.getArgLoc(I);
4541  if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4542  Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4543  // TODO: other template argument types?
4544  }
4545  }
4546 
4547  // Visit pointee types from a permissive context.
4548 #define CheckPolymorphic(Type) \
4549  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4550  Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4551  }
4557 
4558  /// Handle all the types we haven't given a more specific
4559  /// implementation for above.
4560  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4561  // Every other kind of type that we haven't called out already
4562  // that has an inner type is either (1) sugar or (2) contains that
4563  // inner type in some way as a subobject.
4564  if (TypeLoc Next = TL.getNextTypeLoc())
4565  return Visit(Next, Sel);
4566 
4567  // If there's no inner type and we're in a permissive context,
4568  // don't diagnose.
4569  if (Sel == Sema::AbstractNone) return;
4570 
4571  // Check whether the type matches the abstract type.
4572  QualType T = TL.getType();
4573  if (T->isArrayType()) {
4575  T = Info.S.Context.getBaseElementType(T);
4576  }
4578  if (CT != Info.AbstractType) return;
4579 
4580  // It matched; do some magic.
4581  if (Sel == Sema::AbstractArrayType) {
4582  Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4583  << T << TL.getSourceRange();
4584  } else {
4585  Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4586  << Sel << T << TL.getSourceRange();
4587  }
4588  Info.DiagnoseAbstractType();
4589  }
4590 };
4591 
4592 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4594  CheckAbstractUsage(*this, D).Visit(TL, Sel);
4595 }
4596 
4597 }
4598 
4599 /// Check for invalid uses of an abstract type in a method declaration.
4600 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4601  CXXMethodDecl *MD) {
4602  // No need to do the check on definitions, which require that
4603  // the return/param types be complete.
4604  if (MD->doesThisDeclarationHaveABody())
4605  return;
4606 
4607  // For safety's sake, just ignore it if we don't have type source
4608  // information. This should never happen for non-implicit methods,
4609  // but...
4610  if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4611  Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4612 }
4613 
4614 /// Check for invalid uses of an abstract type within a class definition.
4615 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4616  CXXRecordDecl *RD) {
4617  for (auto *D : RD->decls()) {
4618  if (D->isImplicit()) continue;
4619 
4620  // Methods and method templates.
4621  if (isa<CXXMethodDecl>(D)) {
4622  CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4623  } else if (isa<FunctionTemplateDecl>(D)) {
4624  FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4625  CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4626 
4627  // Fields and static variables.
4628  } else if (isa<FieldDecl>(D)) {
4629  FieldDecl *FD = cast<FieldDecl>(D);
4630  if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4631  Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4632  } else if (isa<VarDecl>(D)) {
4633  VarDecl *VD = cast<VarDecl>(D);
4634  if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4635  Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4636 
4637  // Nested classes and class templates.
4638  } else if (isa<CXXRecordDecl>(D)) {
4639  CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4640  } else if (isa<ClassTemplateDecl>(D)) {
4642  cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4643  }
4644  }
4645 }
4646 
4648  Attr *ClassAttr = getDLLAttr(Class);
4649  if (!ClassAttr)
4650  return;
4651 
4652  assert(ClassAttr->getKind() == attr::DLLExport);
4653 
4655 
4657  // Don't go any further if this is just an explicit instantiation
4658  // declaration.
4659  return;
4660 
4661  for (Decl *Member : Class->decls()) {
4662  auto *MD = dyn_cast<CXXMethodDecl>(Member);
4663  if (!MD)
4664  continue;
4665 
4666  if (Member->getAttr<DLLExportAttr>()) {
4667  if (MD->isUserProvided()) {
4668  // Instantiate non-default class member functions ...
4669 
4670  // .. except for certain kinds of template specializations.
4671  if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4672  continue;
4673 
4674  S.MarkFunctionReferenced(Class->getLocation(), MD);
4675 
4676  // The function will be passed to the consumer when its definition is
4677  // encountered.
4678  } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4679  MD->isCopyAssignmentOperator() ||
4680  MD->isMoveAssignmentOperator()) {
4681  // Synthesize and instantiate non-trivial implicit methods, explicitly
4682  // defaulted methods, and the copy and move assignment operators. The
4683  // latter are exported even if they are trivial, because the address of
4684  // an operator can be taken and should compare equal accross libraries.
4685  DiagnosticErrorTrap Trap(S.Diags);
4686  S.MarkFunctionReferenced(Class->getLocation(), MD);
4687  if (Trap.hasErrorOccurred()) {
4688  S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
4689  << Class->getName() << !S.getLangOpts().CPlusPlus11;
4690  break;
4691  }
4692 
4693  // There is no later point when we will see the definition of this
4694  // function, so pass it to the consumer now.
4696  }
4697  }
4698  }
4699 }
4700 
4701 /// \brief Check class-level dllimport/dllexport attribute.
4703  Attr *ClassAttr = getDLLAttr(Class);
4704 
4705  // MSVC inherits DLL attributes to partial class template specializations.
4706  if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4707  if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4708  if (Attr *TemplateAttr =
4709  getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4710  auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
4711  A->setInherited(true);
4712  ClassAttr = A;
4713  }
4714  }
4715  }
4716 
4717  if (!ClassAttr)
4718  return;
4719 
4720  if (!Class->isExternallyVisible()) {
4721  Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
4722  << Class << ClassAttr;
4723  return;
4724  }
4725 
4727  !ClassAttr->isInherited()) {
4728  // Diagnose dll attributes on members of class with dll attribute.
4729  for (Decl *Member : Class->decls()) {
4730  if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4731  continue;
4732  InheritableAttr *MemberAttr = getDLLAttr(Member);
4733  if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4734  continue;
4735 
4736  Diag(MemberAttr->getLocation(),
4737  diag::err_attribute_dll_member_of_dll_class)
4738  << MemberAttr << ClassAttr;
4739  Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4740  Member->setInvalidDecl();
4741  }
4742  }
4743 
4744  if (Class->getDescribedClassTemplate())
4745  // Don't inherit dll attribute until the template is instantiated.
4746  return;
4747 
4748  // The class is either imported or exported.
4749  const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4750 
4752 
4753  // Ignore explicit dllexport on explicit class template instantiation declarations.
4754  if (ClassExported && !ClassAttr->isInherited() &&
4756  Class->dropAttr<DLLExportAttr>();
4757  return;
4758  }
4759 
4760  // Force declaration of implicit members so they can inherit the attribute.
4762 
4763  // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4764  // seem to be true in practice?
4765 
4766  for (Decl *Member : Class->decls()) {
4767  VarDecl *VD = dyn_cast<VarDecl>(Member);
4768  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4769 
4770  // Only methods and static fields inherit the attributes.
4771  if (!VD && !MD)
4772  continue;
4773 
4774  if (MD) {
4775  // Don't process deleted methods.
4776  if (MD->isDeleted())
4777  continue;
4778 
4779  if (MD->isInlined()) {
4780  // MinGW does not import or export inline methods.
4782  continue;
4783 
4784  // MSVC versions before 2015 don't export the move assignment operators
4785  // and move constructor, so don't attempt to import/export them if
4786  // we have a definition.
4787  auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
4788  if ((MD->isMoveAssignmentOperator() ||
4789  (Ctor && Ctor->isMoveConstructor())) &&
4791  continue;
4792 
4793  // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
4794  // operator is exported anyway.
4796  (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
4797  continue;
4798  }
4799  }
4800 
4801  if (!cast<NamedDecl>(Member)->isExternallyVisible())
4802  continue;
4803 
4804  if (!getDLLAttr(Member)) {
4805  auto *NewAttr =
4806  cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
4807  NewAttr->setInherited(true);
4808  Member->addAttr(NewAttr);
4809  }
4810  }
4811 
4812  if (ClassExported)
4813  DelayedDllExportClasses.push_back(Class);
4814 }
4815 
4816 /// \brief Perform propagation of DLL attributes from a derived class to a
4817 /// templated base class for MS compatibility.
4819  CXXRecordDecl *Class, Attr *ClassAttr,
4820  ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
4821  if (getDLLAttr(
4822  BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
4823  // If the base class template has a DLL attribute, don't try to change it.
4824  return;
4825  }
4826 
4827  auto TSK = BaseTemplateSpec->getSpecializationKind();
4828  if (!getDLLAttr(BaseTemplateSpec) &&
4830  TSK == TSK_ImplicitInstantiation)) {
4831  // The template hasn't been instantiated yet (or it has, but only as an
4832  // explicit instantiation declaration or implicit instantiation, which means
4833  // we haven't codegenned any members yet), so propagate the attribute.
4834  auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
4835  NewAttr->setInherited(true);
4836  BaseTemplateSpec->addAttr(NewAttr);
4837 
4838  // If the template is already instantiated, checkDLLAttributeRedeclaration()
4839  // needs to be run again to work see the new attribute. Otherwise this will
4840  // get run whenever the template is instantiated.
4841  if (TSK != TSK_Undeclared)
4842  checkClassLevelDLLAttribute(BaseTemplateSpec);
4843 
4844  return;
4845  }
4846 
4847  if (getDLLAttr(BaseTemplateSpec)) {
4848  // The template has already been specialized or instantiated with an
4849  // attribute, explicitly or through propagation. We should not try to change
4850  // it.
4851  return;
4852  }
4853 
4854  // The template was previously instantiated or explicitly specialized without
4855  // a dll attribute, It's too late for us to add an attribute, so warn that
4856  // this is unsupported.
4857  Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
4858  << BaseTemplateSpec->isExplicitSpecialization();
4859  Diag(ClassAttr->getLocation(), diag::note_attribute);
4860  if (BaseTemplateSpec->isExplicitSpecialization()) {
4861  Diag(BaseTemplateSpec->getLocation(),
4862  diag::note_template_class_explicit_specialization_was_here)
4863  << BaseTemplateSpec;
4864  } else {
4865  Diag(BaseTemplateSpec->getPointOfInstantiation(),
4866  diag::note_template_class_instantiation_was_here)
4867  << BaseTemplateSpec;
4868  }
4869 }
4870 
4872  SourceLocation DefaultLoc) {
4873  switch (S.getSpecialMember(MD)) {
4875  S.DefineImplicitDefaultConstructor(DefaultLoc,
4876  cast<CXXConstructorDecl>(MD));
4877  break;
4879  S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
4880  break;
4882  S.DefineImplicitCopyAssignment(DefaultLoc, MD);
4883  break;
4884  case Sema::CXXDestructor:
4885  S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
4886  break;
4888  S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
4889  break;
4891  S.DefineImplicitMoveAssignment(DefaultLoc, MD);
4892  break;
4893  case Sema::CXXInvalid:
4894  llvm_unreachable("Invalid special member.");
4895  }
4896 }
4897 
4898 /// \brief Perform semantic checks on a class definition that has been
4899 /// completing, introducing implicitly-declared members, checking for
4900 /// abstract types, etc.
4902  if (!Record)
4903  return;
4904 
4905  if (Record->isAbstract() && !Record->isInvalidDecl()) {
4906  AbstractUsageInfo Info(*this, Record);
4907  CheckAbstractClassUsage(Info, Record);
4908  }
4909 
4910  // If this is not an aggregate type and has no user-declared constructor,
4911  // complain about any non-static data members of reference or const scalar
4912  // type, since they will never get initializers.
4913  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4914  !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4915  !Record->isLambda()) {
4916  bool Complained = false;
4917  for (const auto *F : Record->fields()) {
4918  if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4919  continue;
4920 
4921  if (F->getType()->isReferenceType() ||
4922  (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4923  if (!Complained) {
4924  Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4925  << Record->getTagKind() << Record;
4926  Complained = true;
4927  }
4928 
4929  Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4930  << F->getType()->isReferenceType()
4931  << F->getDeclName();
4932  }
4933  }
4934  }
4935 
4936  if (Record->getIdentifier()) {
4937  // C++ [class.mem]p13:
4938  // If T is the name of a class, then each of the following shall have a
4939  // name different from T:
4940  // - every member of every anonymous union that is a member of class T.
4941  //
4942  // C++ [class.mem]p14:
4943  // In addition, if class T has a user-declared constructor (12.1), every
4944  // non-static data member of class T shall have a name different from T.
4945  DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4946  for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4947  ++I) {
4948  NamedDecl *D = *I;
4949  if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4950  isa<IndirectFieldDecl>(D)) {
4951  Diag(D->getLocation(), diag::err_member_name_of_class)
4952  << D->getDeclName();
4953  break;
4954  }
4955  }
4956  }
4957 
4958  // Warn if the class has virtual methods but non-virtual public destructor.
4959  if (Record->isPolymorphic() && !Record->isDependentType()) {
4960  CXXDestructorDecl *dtor = Record->getDestructor();
4961  if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4962  !Record->hasAttr<FinalAttr>())
4963  Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4964  diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4965  }
4966 
4967  if (Record->isAbstract()) {
4968  if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4969  Diag(Record->getLocation(), diag::warn_abstract_final_class)
4970  << FA->isSpelledAsSealed();
4971  DiagnoseAbstractType(Record);
4972  }
4973  }
4974 
4975  bool HasMethodWithOverrideControl = false,
4976  HasOverridingMethodWithoutOverrideControl = false;
4977  if (!Record->isDependentType()) {
4978  for (auto *M : Record->methods()) {
4979  // See if a method overloads virtual methods in a base
4980  // class without overriding any.
4981  if (!M->isStatic())
4983  if (M->hasAttr<OverrideAttr>())
4984  HasMethodWithOverrideControl = true;
4985  else if (M->size_overridden_methods() > 0)
4986  HasOverridingMethodWithoutOverrideControl = true;
4987  // Check whether the explicitly-defaulted special members are valid.
4988  if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4990 
4991  // For an explicitly defaulted or deleted special member, we defer
4992  // determining triviality until the class is complete. That time is now!
4994  if (!M->isImplicit() && !M->isUserProvided()) {
4995  if (CSM != CXXInvalid) {
4996  M->setTrivial(SpecialMemberIsTrivial(M, CSM));
4997 
4998  // Inform the class that we've finished declaring this member.
5000  }
5001  }
5002 
5003  if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
5004  M->hasAttr<DLLExportAttr>()) {
5006  M->isTrivial() &&
5007  (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
5008  CSM == CXXDestructor))
5009  M->dropAttr<DLLExportAttr>();
5010 
5011  if (M->hasAttr<DLLExportAttr>()) {
5012  DefineImplicitSpecialMember(*this, M, M->getLocation());
5014  }
5015  }
5016  }
5017  }
5018 
5019  if (HasMethodWithOverrideControl &&
5020  HasOverridingMethodWithoutOverrideControl) {
5021  // At least one method has the 'override' control declared.
5022  // Diagnose all other overridden methods which do not have 'override' specified on them.
5023  for (auto *M : Record->methods())
5025  }
5026 
5027  // ms_struct is a request to use the same ABI rules as MSVC. Check
5028  // whether this class uses any C++ features that are implemented
5029  // completely differently in MSVC, and if so, emit a diagnostic.
5030  // That diagnostic defaults to an error, but we allow projects to
5031  // map it down to a warning (or ignore it). It's a fairly common
5032  // practice among users of the ms_struct pragma to mass-annotate
5033  // headers, sweeping up a bunch of types that the project doesn't
5034  // really rely on MSVC-compatible layout for. We must therefore
5035  // support "ms_struct except for C++ stuff" as a secondary ABI.
5036  if (Record->isMsStruct(Context) &&
5037  (Record->isPolymorphic() || Record->getNumBases())) {
5038  Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
5039  }
5040 
5042 }
5043 
5044 /// Look up the special member function that would be called by a special
5045 /// member function for a subobject of class type.
5046 ///
5047 /// \param Class The class type of the subobject.
5048 /// \param CSM The kind of special member function.
5049 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5050 /// \param ConstRHS True if this is a copy operation with a const object
5051 /// on its RHS, that is, if the argument to the outer special member
5052 /// function is 'const' and this is not a field marked 'mutable'.
5054  Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5055  unsigned FieldQuals, bool ConstRHS) {
5056  unsigned LHSQuals = 0;
5057  if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5058  LHSQuals = FieldQuals;
5059 
5060  unsigned RHSQuals = FieldQuals;
5061  if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5062  RHSQuals = 0;
5063  else if (ConstRHS)
5064  RHSQuals |= Qualifiers::Const;
5065 
5066  return S.LookupSpecialMember(Class, CSM,
5067  RHSQuals & Qualifiers::Const,
5068  RHSQuals & Qualifiers::Volatile,
5069  false,
5070  LHSQuals & Qualifiers::Const,
5071  LHSQuals & Qualifiers::Volatile);
5072 }
5073 
5075  Sema &S;
5076  SourceLocation UseLoc;
5077 
5078  /// A mapping from the base classes through which the constructor was
5079  /// inherited to the using shadow declaration in that base class (or a null
5080  /// pointer if the constructor was declared in that base class).
5081  llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
5082  InheritedFromBases;
5083 
5084 public:
5087  : S(S), UseLoc(UseLoc) {
5088  bool DiagnosedMultipleConstructedBases = false;
5089  CXXRecordDecl *ConstructedBase = nullptr;
5090  UsingDecl *ConstructedBaseUsing = nullptr;
5091 
5092  // Find the set of such base class subobjects and check that there's a
5093  // unique constructed subobject.
5094  for (auto *D : Shadow->redecls()) {
5095  auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
5096  auto *DNominatedBase = DShadow->getNominatedBaseClass();
5097  auto *DConstructedBase = DShadow->getConstructedBaseClass();
5098 
5099  InheritedFromBases.insert(
5100  std::make_pair(DNominatedBase->getCanonicalDecl(),
5101  DShadow->getNominatedBaseClassShadowDecl()));
5102  if (DShadow->constructsVirtualBase())
5103  InheritedFromBases.insert(
5104  std::make_pair(DConstructedBase->getCanonicalDecl(),
5105  DShadow->getConstructedBaseClassShadowDecl()));
5106  else
5107  assert(DNominatedBase == DConstructedBase);
5108 
5109  // [class.inhctor.init]p2:
5110  // If the constructor was inherited from multiple base class subobjects
5111  // of type B, the program is ill-formed.
5112  if (!ConstructedBase) {
5113  ConstructedBase = DConstructedBase;
5114  ConstructedBaseUsing = D->getUsingDecl();
5115  } else if (ConstructedBase != DConstructedBase &&
5116  !Shadow->isInvalidDecl()) {
5117  if (!DiagnosedMultipleConstructedBases) {
5118  S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
5119  << Shadow->getTargetDecl();
5120  S.Diag(ConstructedBaseUsing->getLocation(),
5121  diag::note_ambiguous_inherited_constructor_using)
5122  << ConstructedBase;
5123  DiagnosedMultipleConstructedBases = true;
5124  }
5125  S.Diag(D->getUsingDecl()->getLocation(),
5126  diag::note_ambiguous_inherited_constructor_using)
5127  << DConstructedBase;
5128  }
5129  }
5130 
5131  if (DiagnosedMultipleConstructedBases)
5132  Shadow->setInvalidDecl();
5133  }
5134 
5135  /// Find the constructor to use for inherited construction of a base class,
5136  /// and whether that base class constructor inherits the constructor from a
5137  /// virtual base class (in which case it won't actually invoke it).
5138  std::pair<CXXConstructorDecl *, bool>
5140  auto It = InheritedFromBases.find(Base->getCanonicalDecl());
5141  if (It == InheritedFromBases.end())
5142  return std::make_pair(nullptr, false);
5143 
5144  // This is an intermediary class.
5145  if (It->second)
5146  return std::make_pair(
5147  S.findInheritingConstructor(UseLoc, Ctor, It->second),
5148  It->second->constructsVirtualBase());
5149 
5150  // This is the base class from which the constructor was inherited.
5151  return std::make_pair(Ctor, false);
5152  }
5153 };
5154 
5155 /// Is the special member function which would be selected to perform the
5156 /// specified operation on the specified class type a constexpr constructor?
5157 static bool
5159  Sema::CXXSpecialMember CSM, unsigned Quals,
5160  bool ConstRHS,
5161  CXXConstructorDecl *InheritedCtor = nullptr,
5162  Sema::InheritedConstructorInfo *Inherited = nullptr) {
5163  // If we're inheriting a constructor, see if we need to call it for this base
5164  // class.
5165  if (InheritedCtor) {
5166  assert(CSM == Sema::CXXDefaultConstructor);
5167  auto BaseCtor =
5168  Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
5169  if (BaseCtor)
5170  return BaseCtor->isConstexpr();
5171  }
5172 
5173  if (CSM == Sema::CXXDefaultConstructor)
5174  return ClassDecl->hasConstexprDefaultConstructor();
5175 
5177  lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
5178  if (!SMOR || !SMOR->getMethod())
5179  // A constructor we wouldn't select can't be "involved in initializing"
5180  // anything.
5181  return true;
5182  return SMOR->getMethod()->isConstexpr();
5183 }
5184 
5185 /// Determine whether the specified special member function would be constexpr
5186 /// if it were implicitly defined.
5188  Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
5189  bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
5190  Sema::InheritedConstructorInfo *Inherited = nullptr) {
5191  if (!S.getLangOpts().CPlusPlus11)
5192  return false;
5193 
5194  // C++11 [dcl.constexpr]p4:
5195  // In the definition of a constexpr constructor [...]
5196  bool Ctor = true;
5197  switch (CSM) {
5199  if (Inherited)
5200  break;
5201  // Since default constructor lookup is essentially trivial (and cannot
5202  // involve, for instance, template instantiation), we compute whether a
5203  // defaulted default constructor is constexpr directly within CXXRecordDecl.
5204  //
5205  // This is important for performance; we need to know whether the default
5206  // constructor is constexpr to determine whether the type is a literal type.
5207  return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5208 
5211  // For copy or move constructors, we need to perform overload resolution.
5212  break;
5213 
5216  if (!S.getLangOpts().CPlusPlus14)
5217  return false;
5218  // In C++1y, we need to perform overload resolution.
5219  Ctor = false;
5220  break;
5221 
5222  case Sema::CXXDestructor:
5223  case Sema::CXXInvalid:
5224  return false;
5225  }
5226 
5227  // -- if the class is a non-empty union, or for each non-empty anonymous
5228  // union member of a non-union class, exactly one non-static data member
5229  // shall be initialized; [DR1359]
5230  //
5231  // If we squint, this is guaranteed, since exactly one non-static data member
5232  // will be initialized (if the constructor isn't deleted), we just don't know
5233  // which one.
5234  if (Ctor && ClassDecl->isUnion())
5235  return CSM == Sema::CXXDefaultConstructor
5236  ? ClassDecl->hasInClassInitializer() ||
5237  !ClassDecl->hasVariantMembers()
5238  : true;
5239 
5240  // -- the class shall not have any virtual base classes;
5241  if (Ctor && ClassDecl->getNumVBases())
5242  return false;
5243 
5244  // C++1y [class.copy]p26:
5245  // -- [the class] is a literal type, and
5246  if (!Ctor && !ClassDecl->isLiteral())
5247  return false;
5248 
5249  // -- every constructor involved in initializing [...] base class
5250  // sub-objects shall be a constexpr constructor;
5251  // -- the assignment operator selected to copy/move each direct base
5252  // class is a constexpr function, and
5253  for (const auto &B : ClassDecl->bases()) {
5254  const RecordType *BaseType = B.getType()->getAs<RecordType>();
5255  if (!BaseType) continue;
5256 
5257  CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
5258  if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
5259  InheritedCtor, Inherited))
5260  return false;
5261  }
5262 
5263  // -- every constructor involved in initializing non-static data members
5264  // [...] shall be a constexpr constructor;
5265  // -- every non-static data member and base class sub-object shall be
5266  // initialized
5267  // -- for each non-static data member of X that is of class type (or array
5268  // thereof), the assignment operator selected to copy/move that member is
5269  // a constexpr function
5270  for (const auto *F : ClassDecl->fields()) {
5271  if (F->isInvalidDecl())
5272  continue;
5273  if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
5274  continue;
5275  QualType BaseType = S.Context.getBaseElementType(F->getType());
5276  if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
5277  CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5278  if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5279  BaseType.getCVRQualifiers(),
5280  ConstArg && !F->isMutable()))
5281  return false;
5282  } else if (CSM == Sema::CXXDefaultConstructor) {
5283  return false;
5284  }
5285  }
5286 
5287  // All OK, it's constexpr!
5288  return true;
5289 }
5290 
5293  switch (S.getSpecialMember(MD)) {
5295  return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5304  case Sema::CXXDestructor:
5305  return S.ComputeDefaultedDtorExceptionSpec(MD);
5306  case Sema::CXXInvalid:
5307  break;
5308  }
5309  assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5310  "only special members have implicit exception specs");
5312  cast<CXXConstructorDecl>(MD));
5313 }
5314 
5316  CXXMethodDecl *MD) {
5318 
5319  // Build an exception specification pointing back at this member.
5321  EPI.ExceptionSpec.SourceDecl = MD;
5322 
5323  // Set the calling convention to the default for C++ instance methods.
5324  EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5325  S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5326  /*IsCXXMethod=*/true));
5327  return EPI;
5328 }
5329 
5331  const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5332  if (FPT->getExceptionSpecType() != EST_Unevaluated)
5333  return;
5334 
5335  // Evaluate the exception specification.
5336  auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
5337 
5338  // Update the type of the special member to use it.
5339  UpdateExceptionSpec(MD, ESI);
5340 
5341  // A user-provided destructor can be defined outside the class. When that
5342  // happens, be sure to update the exception specification on both
5343  // declarations.
5344  const FunctionProtoType *CanonicalFPT =
5346  if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
5348 }
5349 
5351  CXXRecordDecl *RD = MD->getParent();
5353 
5354  assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5355  "not an explicitly-defaulted special member");
5356 
5357  // Whether this was the first-declared instance of the constructor.
5358  // This affects whether we implicitly add an exception spec and constexpr.
5359  bool First = MD == MD->getCanonicalDecl();
5360 
5361  bool HadError = false;
5362 
5363  // C++11 [dcl.fct.def.default]p1:
5364  // A function that is explicitly defaulted shall
5365  // -- be a special member function (checked elsewhere),
5366  // -- have the same type (except for ref-qualifiers, and except that a
5367  // copy operation can take a non-const reference) as an implicit
5368  // declaration, and
5369  // -- not have default arguments.
5370  unsigned ExpectedParams = 1;
5371  if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5372  ExpectedParams = 0;
5373  if (MD->getNumParams() != ExpectedParams) {
5374  // This also checks for default arguments: a copy or move constructor with a
5375  // default argument is classified as a default constructor, and assignment
5376  // operations and destructors can't have default arguments.
5377  Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5378  << CSM << MD->getSourceRange();
5379  HadError = true;
5380  } else if (MD->isVariadic()) {
5381  Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5382  << CSM << MD->getSourceRange();
5383  HadError = true;
5384  }
5385 
5387 
5388  bool CanHaveConstParam = false;
5389  if (CSM == CXXCopyConstructor)
5390  CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
5391  else if (CSM == CXXCopyAssignment)
5392  CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
5393 
5394  QualType ReturnType = Context.VoidTy;
5395  if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5396  // Check for return type matching.
5397  ReturnType = Type->getReturnType();
5398  QualType ExpectedReturnType =
5400  if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5401  Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5402  << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5403  HadError = true;
5404  }
5405 
5406  // A defaulted special member cannot have cv-qualifiers.
5407  if (Type->getTypeQuals()) {
5408  Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
5409  << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
5410  HadError = true;
5411  }
5412  }
5413 
5414  // Check for parameter type matching.
5415  QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
5416  bool HasConstParam = false;
5417  if (ExpectedParams && ArgType->isReferenceType()) {
5418  // Argument must be reference to possibly-const T.
5419  QualType ReferentType = ArgType->getPointeeType();
5420  HasConstParam = ReferentType.isConstQualified();
5421 
5422  if (ReferentType.isVolatileQualified()) {
5423  Diag(MD->getLocation(),
5424  diag::err_defaulted_special_member_volatile_param) << CSM;
5425  HadError = true;
5426  }
5427 
5428  if (HasConstParam && !CanHaveConstParam) {
5429  if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5430  Diag(MD->getLocation(),
5431  diag::err_defaulted_special_member_copy_const_param)
5432  << (CSM == CXXCopyAssignment);
5433  // FIXME: Explain why this special member can't be const.
5434  } else {
5435  Diag(MD->getLocation(),
5436  diag::err_defaulted_special_member_move_const_param)
5437  << (CSM == CXXMoveAssignment);
5438  }
5439  HadError = true;
5440  }
5441  } else if (ExpectedParams) {
5442  // A copy assignment operator can take its argument by value, but a
5443  // defaulted one cannot.
5444  assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
5445  Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
5446  HadError = true;
5447  }
5448 
5449  // C++11 [dcl.fct.def.default]p2:
5450  // An explicitly-defaulted function may be declared constexpr only if it
5451  // would have been implicitly declared as constexpr,
5452  // Do not apply this rule to members of class templates, since core issue 1358
5453  // makes such functions always instantiate to constexpr functions. For
5454  // functions which cannot be constexpr (for non-constructors in C++11 and for
5455  // destructors in C++1y), this is checked elsewhere.
5456  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5457  HasConstParam);
5458  if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
5459  : isa<CXXConstructorDecl>(MD)) &&
5460  MD->isConstexpr() && !Constexpr &&
5462  Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
5463  // FIXME: Explain why the special member can't be constexpr.
5464  HadError = true;
5465  }
5466 
5467  // and may have an explicit exception-specification only if it is compatible
5468  // with the exception-specification on the implicit declaration.
5469  if (Type->hasExceptionSpec()) {
5470  // Delay the check if this is the first declaration of the special member,
5471  // since we may not have parsed some necessary in-class initializers yet.
5472  if (First) {
5473  // If the exception specification needs to be instantiated, do so now,
5474  // before we clobber it with an EST_Unevaluated specification below.
5475  if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5477  Type = MD->getType()->getAs<FunctionProtoType>();
5478  }
5479  DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
5480  } else
5482  }
5483 
5484  // If a function is explicitly defaulted on its first declaration,
5485  if (First) {
5486  // -- it is implicitly considered to be constexpr if the implicit
5487  // definition would be,
5488  MD->setConstexpr(Constexpr);
5489 
5490  // -- it is implicitly considered to have the same exception-specification
5491  // as if it had been implicitly declared,
5494  EPI.ExceptionSpec.SourceDecl = MD;
5495  MD->setType(Context.getFunctionType(ReturnType,
5496  llvm::makeArrayRef(&ArgType,
5497  ExpectedParams),
5498  EPI));
5499  }
5500 
5501  if (ShouldDeleteSpecialMember(MD, CSM)) {
5502  if (First) {
5503  SetDeclDeleted(MD, MD->getLocation());
5504  } else {
5505  // C++11 [dcl.fct.def.default]p4:
5506  // [For a] user-provided explicitly-defaulted function [...] if such a
5507  // function is implicitly defined as deleted, the program is ill-formed.
5508  Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
5509  ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
5510  HadError = true;
5511  }
5512  }
5513 
5514  if (HadError)
5515  MD->setInvalidDecl();
5516 }
5517 
5518 /// Check whether the exception specification provided for an
5519 /// explicitly-defaulted special member matches the exception specification
5520 /// that would have been generated for an implicit special member, per
5521 /// C++11 [dcl.fct.def.default]p2.
5523  CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
5524  // If the exception specification was explicitly specified but hadn't been
5525  // parsed when the method was defaulted, grab it now.
5526  if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
5527  SpecifiedType =
5529 
5530  // Compute the implicit exception specification.
5531  CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5532  /*IsCXXMethod=*/true);
5534  EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5535  .getExceptionSpec();
5536  const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
5538 
5539  // Ensure that it matches.
5541  PDiag(diag::err_incorrect_defaulted_exception_spec)
5542  << getSpecialMember(MD), PDiag(),
5543  ImplicitType, SourceLocation(),
5544  SpecifiedType, MD->getLocation());
5545 }
5546 
5548  decltype(DelayedExceptionSpecChecks) Checks;
5549  decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
5550 
5551  std::swap(Checks, DelayedExceptionSpecChecks);
5552  std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5553 
5554  // Perform any deferred checking of exception specifications for virtual
5555  // destructors.
5556  for (auto &Check : Checks)
5557  CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
5558 
5559  // Check that any explicitly-defaulted methods have exception specifications
5560  // compatible with their implicit exception specifications.
5561  for (auto &Spec : Specs)
5562  CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
5563 }
5564 
5565 namespace {
5566 struct SpecialMemberDeletionInfo {
5567  Sema &S;
5568  CXXMethodDecl *MD;
5571  bool Diagnose;
5572 
5573  // Properties of the special member, computed for convenience.
5574  bool IsConstructor, IsAssignment, IsMove, ConstArg;
5575  SourceLocation Loc;
5576 
5577  bool AllFieldsAreConst;
5578 
5579  SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
5581  Sema::InheritedConstructorInfo *ICI, bool Diagnose)
5582  : S(S), MD(MD), CSM(CSM), ICI(ICI), Diagnose(Diagnose),
5583  IsConstructor(false), IsAssignment(false), IsMove(false),
5584  ConstArg(false), Loc(MD->getLocation()), AllFieldsAreConst(true) {
5585  switch (CSM) {
5588  IsConstructor = true;
5589  break;
5591  IsConstructor = true;
5592  IsMove = true;
5593  break;
5595  IsAssignment = true;
5596  break;
5598  IsAssignment = true;
5599  IsMove = true;
5600  break;
5601  case Sema::CXXDestructor:
5602  break;
5603  case Sema::CXXInvalid:
5604  llvm_unreachable("invalid special member kind");
5605  }
5606 
5607  if (MD->getNumParams()) {
5608  if (const ReferenceType *RT =
5609  MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5610  ConstArg = RT->getPointeeType().isConstQualified();
5611  }
5612  }
5613 
5614  bool inUnion() const { return MD->getParent()->isUnion(); }
5615 
5616  Sema::CXXSpecialMember getEffectiveCSM() {
5617  return ICI ? Sema::CXXInvalid : CSM;
5618  }
5619 
5620  /// Look up the corresponding special member in the given class.
5622  unsigned Quals, bool IsMutable) {
5623  return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5624  ConstArg && !IsMutable);
5625  }
5626 
5627  typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
5628 
5629  bool shouldDeleteForBase(CXXBaseSpecifier *Base);
5630  bool shouldDeleteForField(FieldDecl *FD);
5631  bool shouldDeleteForAllConstMembers();
5632 
5633  bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5634  unsigned Quals);
5635  bool shouldDeleteForSubobjectCall(Subobject Subobj,
5637  bool IsDtorCallInCtor);
5638 
5639  bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
5640 };
5641 }
5642 
5643 /// Is the given special member inaccessible when used on the given
5644 /// sub-object.
5645 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5646  CXXMethodDecl *target) {
5647  /// If we're operating on a base class, the object type is the
5648  /// type of this special member.
5649  QualType objectTy;
5650  AccessSpecifier access = target->getAccess();
5651  if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5652  objectTy = S.Context.getTypeDeclType(MD->getParent());
5653  access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5654 
5655  // If we're operating on a field, the object type is the type of the field.
5656  } else {
5657  objectTy = S.Context.getTypeDeclType(target->getParent());
5658  }
5659 
5660  return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5661 }
5662 
5663 /// Check whether we should delete a special member due to the implicit
5664 /// definition containing a call to a special member of a subobject.
5665 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5666  Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5667  bool IsDtorCallInCtor) {
5668  CXXMethodDecl *Decl = SMOR->getMethod();
5669  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5670 
5671  int DiagKind = -1;
5672 
5674  DiagKind = !Decl ? 0 : 1;
5676  DiagKind = 2;
5677  else if (!isAccessible(Subobj, Decl))
5678  DiagKind = 3;
5679  else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5680  !Decl->isTrivial()) {
5681  // A member of a union must have a trivial corresponding special member.
5682  // As a weird special case, a destructor call from a union's constructor
5683  // must be accessible and non-deleted, but need not be trivial. Such a
5684  // destructor is never actually called, but is semantically checked as
5685  // if it were.
5686  DiagKind = 4;
5687  }
5688 
5689  if (DiagKind == -1)
5690  return false;
5691 
5692  if (Diagnose) {
5693  if (Field) {
5694  S.Diag(Field->getLocation(),
5695  diag::note_deleted_special_member_class_subobject)
5696  << getEffectiveCSM() << MD->getParent() << /*IsField*/true
5697  << Field << DiagKind << IsDtorCallInCtor;
5698  } else {
5699  CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5700  S.Diag(Base->getLocStart(),
5701  diag::note_deleted_special_member_class_subobject)
5702  << getEffectiveCSM() << MD->getParent() << /*IsField*/false
5703  << Base->getType() << DiagKind << IsDtorCallInCtor;
5704  }
5705 
5706  if (DiagKind == 1)
5707  S.NoteDeletedFunction(Decl);
5708  // FIXME: Explain inaccessibility if DiagKind == 3.
5709  }
5710 
5711  return true;
5712 }
5713 
5714 /// Check whether we should delete a special member function due to having a
5715 /// direct or virtual base class or non-static data member of class type M.
5716 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
5717  CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
5718  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5719  bool IsMutable = Field && Field->isMutable();
5720 
5721  // C++11 [class.ctor]p5:
5722  // -- any direct or virtual base class, or non-static data member with no
5723  // brace-or-equal-initializer, has class type M (or array thereof) and
5724  // either M has no default constructor or overload resolution as applied
5725  // to M's default constructor results in an ambiguity or in a function
5726  // that is deleted or inaccessible
5727  // C++11 [class.copy]p11, C++11 [class.copy]p23:
5728  // -- a direct or virtual base class B that cannot be copied/moved because
5729  // overload resolution, as applied to B's corresponding special member,
5730  // results in an ambiguity or a function that is deleted or inaccessible
5731  // from the defaulted special member
5732  // C++11 [class.dtor]p5:
5733  // -- any direct or virtual base class [...] has a type with a destructor
5734  // that is deleted or inaccessible
5735  if (!(CSM == Sema::CXXDefaultConstructor &&
5736  Field && Field->hasInClassInitializer()) &&
5737  shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5738  false))
5739  return true;
5740 
5741  // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5742  // -- any direct or virtual base class or non-static data member has a
5743  // type with a destructor that is deleted or inaccessible
5744  if (IsConstructor) {
5747  false, false, false, false, false);
5748  if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5749  return true;
5750  }
5751 
5752  return false;
5753 }
5754 
5755 /// Check whether we should delete a special member function due to the class
5756 /// having a particular direct or virtual base class.
5757 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
5758  CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
5759  // If program is correct, BaseClass cannot be null, but if it is, the error
5760  // must be reported elsewhere.
5761  if (!BaseClass)
5762  return false;
5763  // If we have an inheriting constructor, check whether we're calling an
5764  // inherited constructor instead of a default constructor.
5765  if (ICI) {
5766  assert(CSM == Sema::CXXDefaultConstructor);
5767  auto *BaseCtor =
5768  ICI->findConstructorForBase(BaseClass, cast<CXXConstructorDecl>(MD)
5769  ->getInheritedConstructor()
5770  .getConstructor())
5771  .first;
5772  if (BaseCtor) {
5773  if (BaseCtor->isDeleted() && Diagnose) {
5774  S.Diag(Base->getLocStart(),
5775  diag::note_deleted_special_member_class_subobject)
5776  << getEffectiveCSM() << MD->getParent() << /*IsField*/false
5777  << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
5778  S.NoteDeletedFunction(BaseCtor);
5779  }
5780  return BaseCtor->isDeleted();
5781  }
5782  }
5783  return shouldDeleteForClassSubobject(BaseClass, Base, 0);
5784 }
5785 
5786 /// Check whether we should delete a special member function due to the class
5787 /// having a particular non-static data member.
5788 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5789  QualType FieldType = S.Context.getBaseElementType(FD->getType());
5790  CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5791 
5792  if (CSM == Sema::CXXDefaultConstructor) {
5793  // For a default constructor, all references must be initialized in-class
5794  // and, if a union, it must have a non-const member.
5795  if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5796  if (Diagnose)
5797  S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5798  << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
5799  return true;
5800  }
5801  // C++11 [class.ctor]p5: any non-variant non-static data member of
5802  // const-qualified type (or array thereof) with no
5803  // brace-or-equal-initializer does not have a user-provided default
5804  // constructor.
5805  if (!inUnion() && FieldType.isConstQualified() &&
5806  !FD->hasInClassInitializer() &&
5807  (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5808  if (Diagnose)
5809  S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5810  << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
5811  return true;
5812  }
5813 
5814  if (inUnion() && !FieldType.isConstQualified())
5815  AllFieldsAreConst = false;
5816  } else if (CSM == Sema::CXXCopyConstructor) {
5817  // For a copy constructor, data members must not be of rvalue reference
5818  // type.
5819  if (FieldType->isRValueReferenceType()) {
5820  if (Diagnose)
5821  S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5822  << MD->getParent() << FD << FieldType;
5823  return true;
5824  }
5825  } else if (IsAssignment) {
5826  // For an assignment operator, data members must not be of reference type.
5827  if (FieldType->isReferenceType()) {
5828  if (Diagnose)
5829  S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5830  << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
5831  return true;
5832  }
5833  if (!FieldRecord && FieldType.isConstQualified()) {
5834  // C++11 [class.copy]p23:
5835  // -- a non-static data member of const non-class type (or array thereof)
5836  if (Diagnose)
5837  S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5838  << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
5839  return true;
5840  }
5841  }
5842 
5843  if (FieldRecord) {
5844  // Some additional restrictions exist on the variant members.
5845  if (!inUnion() && FieldRecord->isUnion() &&
5846  FieldRecord->isAnonymousStructOrUnion()) {
5847  bool AllVariantFieldsAreConst = true;
5848 
5849  // FIXME: Handle anonymous unions declared within anonymous unions.
5850  for (auto *UI : FieldRecord->fields()) {
5851  QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
5852 
5853  if (!UnionFieldType.isConstQualified())
5854  AllVariantFieldsAreConst = false;
5855 
5856  CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5857  if (UnionFieldRecord &&
5858  shouldDeleteForClassSubobject(UnionFieldRecord, UI,
5859  UnionFieldType.getCVRQualifiers()))
5860  return true;
5861  }
5862 
5863  // At least one member in each anonymous union must be non-const
5864  if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
5865  !FieldRecord->field_empty()) {
5866  if (Diagnose)
5867  S.Diag(FieldRecord->getLocation(),
5868  diag::note_deleted_default_ctor_all_const)
5869  << !!ICI << MD->getParent() << /*anonymous union*/1;
5870  return true;
5871  }
5872 
5873  // Don't check the implicit member of the anonymous union type.
5874  // This is technically non-conformant, but sanity demands it.
5875  return false;
5876  }
5877 
5878  if (shouldDeleteForClassSubobject(FieldRecord, FD,
5879  FieldType.getCVRQualifiers()))
5880  return true;
5881  }
5882 
5883  return false;
5884 }
5885 
5886 /// C++11 [class.ctor] p5:
5887 /// A defaulted default constructor for a class X is defined as deleted if
5888 /// X is a union and all of its variant members are of const-qualified type.
5889 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
5890  // This is a silly definition, because it gives an empty union a deleted
5891  // default constructor. Don't do that.
5892  if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5893  !MD->getParent()->field_empty()) {
5894  if (Diagnose)
5895  S.Diag(MD->getParent()->getLocation(),
5896  diag::note_deleted_default_ctor_all_const)
5897  << !!ICI << MD->getParent() << /*not anonymous union*/0;
5898  return true;
5899  }
5900  return false;
5901 }
5902 
5903 /// Determine whether a defaulted special member function should be defined as
5904 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5905 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
5908  bool Diagnose) {
5909  if (MD->isInvalidDecl())
5910  return false;
5911  CXXRecordDecl *RD = MD->getParent();
5912  assert(!RD->isDependentType() && "do deletion after instantiation");
5913  if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
5914  return false;
5915 
5916  // C++11 [expr.lambda.prim]p19:
5917  // The closure type associated with a lambda-expression has a
5918  // deleted (8.4.3) default constructor and a deleted copy
5919  // assignment operator.
5920  if (RD->isLambda() &&
5921  (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5922  if (Diagnose)
5923  Diag(RD->getLocation(), diag::note_lambda_decl);
5924  return true;
5925  }
5926 
5927  // For an anonymous struct or union, the copy and assignment special members
5928  // will never be used, so skip the check. For an anonymous union declared at
5929  // namespace scope, the constructor and destructor are used.
5930  if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5932  return false;
5933 
5934  // C++11 [class.copy]p7, p18:
5935  // If the class definition declares a move constructor or move assignment
5936  // operator, an implicitly declared copy constructor or copy assignment
5937  // operator is defined as deleted.
5938  if (MD->isImplicit() &&
5939  (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5940  CXXMethodDecl *UserDeclaredMove = nullptr;
5941 
5942  // In Microsoft mode, a user-declared move only causes the deletion of the
5943  // corresponding copy operation, not both copy operations.
5944  if (RD->hasUserDeclaredMoveConstructor() &&
5945  (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
5946  if (!Diagnose) return true;
5947 
5948  // Find any user-declared move constructor.
5949  for (auto *I : RD->ctors()) {
5950  if (I->isMoveConstructor()) {
5951  UserDeclaredMove = I;
5952  break;
5953  }
5954  }
5955  assert(UserDeclaredMove);
5956  } else if (RD->hasUserDeclaredMoveAssignment() &&
5957  (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
5958  if (!Diagnose) return true;
5959 
5960  // Find any user-declared move assignment operator.
5961  for (auto *I : RD->methods()) {
5962  if (I->isMoveAssignmentOperator()) {
5963  UserDeclaredMove = I;
5964  break;
5965  }
5966  }
5967  assert(UserDeclaredMove);
5968  }
5969 
5970  if (UserDeclaredMove) {
5971  Diag(UserDeclaredMove->getLocation(),
5972  diag::note_deleted_copy_user_declared_move)
5973  << (CSM == CXXCopyAssignment) << RD
5974  << UserDeclaredMove->isMoveAssignmentOperator();
5975  return true;
5976  }
5977  }
5978 
5979  // Do access control from the special member function
5980  ContextRAII MethodContext(*this, MD);
5981 
5982  // C++11 [class.dtor]p5:
5983  // -- for a virtual destructor, lookup of the non-array deallocation function
5984  // results in an ambiguity or in a function that is deleted or inaccessible
5985  if (CSM == CXXDestructor && MD->isVirtual()) {
5986  FunctionDecl *OperatorDelete = nullptr;
5989  if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5990  OperatorDelete, false)) {
5991  if (Diagnose)
5992  Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5993  return true;
5994  }
5995  }
5996 
5997  SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
5998 
5999  for (auto &BI : RD->bases())
6000  if (!BI.isVirtual() &&
6001  SMI.shouldDeleteForBase(&BI))
6002  return true;
6003 
6004  // Per DR1611, do not consider virtual bases of constructors of abstract
6005  // classes, since we are not going to construct them.
6006  if (!RD->isAbstract() || !SMI.IsConstructor) {
6007  for (auto &BI : RD->vbases())
6008  if (SMI.shouldDeleteForBase(&BI))
6009  return true;
6010  }
6011 
6012  for (auto *FI : RD->fields())
6013  if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
6014  SMI.shouldDeleteForField(FI))
6015  return true;
6016 
6017  if (SMI.shouldDeleteForAllConstMembers())
6018  return true;
6019 
6020  if (getLangOpts().CUDA) {
6021  // We should delete the special member in CUDA mode if target inference
6022  // failed.
6023  return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
6024  Diagnose);
6025  }
6026 
6027  return false;
6028 }
6029 
6030 /// Perform lookup for a special member of the specified kind, and determine
6031 /// whether it is trivial. If the triviality can be determined without the
6032 /// lookup, skip it. This is intended for use when determining whether a
6033 /// special member of a containing object is trivial, and thus does not ever
6034 /// perform overload resolution for default constructors.
6035 ///
6036 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
6037 /// member that was most likely to be intended to be trivial, if any.
6039  Sema::CXXSpecialMember CSM, unsigned Quals,
6040  bool ConstRHS, CXXMethodDecl **Selected) {
6041  if (Selected)
6042  *Selected = nullptr;
6043 
6044  switch (CSM) {
6045  case Sema::CXXInvalid:
6046  llvm_unreachable("not a special member");
6047 
6049  // C++11 [class.ctor]p5:
6050  // A default constructor is trivial if:
6051  // - all the [direct subobjects] have trivial default constructors
6052  //
6053  // Note, no overload resolution is performed in this case.
6054  if (RD->hasTrivialDefaultConstructor())
6055  return true;
6056 
6057  if (Selected) {
6058  // If there's a default constructor which could have been trivial, dig it
6059  // out. Otherwise, if there's any user-provided default constructor, point
6060  // to that as an example of why there's not a trivial one.
6061  CXXConstructorDecl *DefCtor = nullptr;
6064  for (auto *CI : RD->ctors()) {
6065  if (!CI->isDefaultConstructor())
6066  continue;
6067  DefCtor = CI;
6068  if (!DefCtor->isUserProvided())
6069  break;
6070  }
6071 
6072  *Selected = DefCtor;
6073  }
6074 
6075  return false;
6076 
6077  case Sema::CXXDestructor:
6078  // C++11 [class.dtor]p5:
6079  // A destructor is trivial if:
6080  // - all the direct [subobjects] have trivial destructors
6081  if (RD->hasTrivialDestructor())
6082  return true;
6083 
6084  if (Selected) {
6085  if (RD->needsImplicitDestructor())
6087  *Selected = RD->getDestructor();
6088  }
6089 
6090  return false;
6091 
6093  // C++11 [class.copy]p12:
6094  // A copy constructor is trivial if:
6095  // - the constructor selected to copy each direct [subobject] is trivial
6096  if (RD->hasTrivialCopyConstructor()) {
6097  if (Quals == Qualifiers::Const)
6098  // We must either select the trivial copy constructor or reach an
6099  // ambiguity; no need to actually perform overload resolution.
6100  return true;
6101  } else if (!Selected) {
6102  return false;
6103  }
6104  // In C++98, we are not supposed to perform overload resolution here, but we
6105  // treat that as a language defect, as suggested on cxx-abi-dev, to treat
6106  // cases like B as having a non-trivial copy constructor:
6107  // struct A { template<typename T> A(T&); };
6108  // struct B { mutable A a; };
6109  goto NeedOverloadResolution;
6110 
6112  // C++11 [class.copy]p25:
6113  // A copy assignment operator is trivial if:
6114  // - the assignment operator selected to copy each direct [subobject] is
6115  // trivial
6116  if (RD->hasTrivialCopyAssignment()) {
6117  if (Quals == Qualifiers::Const)
6118  return true;
6119  } else if (!Selected) {
6120  return false;
6121  }
6122  // In C++98, we are not supposed to perform overload resolution here, but we
6123  // treat that as a language defect.
6124  goto NeedOverloadResolution;
6125 
6128  NeedOverloadResolution:
6130  lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
6131 
6132  // The standard doesn't describe how to behave if the lookup is ambiguous.
6133  // We treat it as not making the member non-trivial, just like the standard
6134  // mandates for the default constructor. This should rarely matter, because
6135  // the member will also be deleted.
6137  return true;
6138 
6139  if (!SMOR->getMethod()) {
6140  assert(SMOR->getKind() ==
6142  return false;
6143  }
6144 
6145  // We deliberately don't check if we found a deleted special member. We're
6146  // not supposed to!
6147  if (Selected)
6148  *Selected = SMOR->getMethod();
6149  return SMOR->getMethod()->isTrivial();
6150  }
6151 
6152  llvm_unreachable("unknown special method kind");
6153 }
6154 
6156  for (auto *CI : RD->ctors())
6157  if (!CI->isImplicit())
6158  return CI;
6159 
6160  // Look for constructor templates.
6161  typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
6162  for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
6163  if (CXXConstructorDecl *CD =
6164  dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
6165  return CD;
6166  }
6167 
6168  return nullptr;
6169 }
6170 
6171 /// The kind of subobject we are checking for triviality. The values of this
6172 /// enumeration are used in diagnostics.
6174  /// The subobject is a base class.
6176  /// The subobject is a non-static data member.
6178  /// The object is actually the complete object.
6180 };
6181 
6182 /// Check whether the special member selected for a given type would be trivial.
6184  QualType SubType, bool ConstRHS,
6187  bool Diagnose) {
6188  CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
6189  if (!SubRD)
6190  return true;
6191 
6192  CXXMethodDecl *Selected;
6193  if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
6194  ConstRHS, Diagnose ? &Selected : nullptr))
6195  return true;
6196 
6197  if (Diagnose) {
6198  if (ConstRHS)
6199  SubType.addConst();
6200 
6201  if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6202  S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6203  << Kind << SubType.getUnqualifiedType();
6204  if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6205  S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6206  } else if (!Selected)
6207  S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6208  << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6209  else if (Selected->isUserProvided()) {
6210  if (Kind == TSK_CompleteObject)
6211  S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6212  << Kind << SubType.getUnqualifiedType() << CSM;
6213  else {
6214  S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6215  << Kind << SubType.getUnqualifiedType() << CSM;
6216  S.Diag(Selected->getLocation(), diag::note_declared_at);
6217  }
6218  } else {
6219  if (Kind != TSK_CompleteObject)
6220  S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6221  << Kind << SubType.getUnqualifiedType() << CSM;
6222 
6223  // Explain why the defaulted or deleted special member isn't trivial.
6224  S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6225  }
6226  }
6227 
6228  return false;
6229 }
6230 
6231 /// Check whether the members of a class type allow a special member to be
6232 /// trivial.
6235  bool ConstArg, bool Diagnose) {
6236  for (const auto *FI : RD->fields()) {
6237  if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
6238  continue;
6239 
6240  QualType FieldType = S.Context.getBaseElementType(FI->getType());
6241 
6242  // Pretend anonymous struct or union members are members of this class.
6243  if (FI->isAnonymousStructOrUnion()) {
6244  if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
6245  CSM, ConstArg, Diagnose))
6246  return false;
6247  continue;
6248  }
6249 
6250  // C++11 [class.ctor]p5:
6251  // A default constructor is trivial if [...]
6252  // -- no non-static data member of its class has a
6253  // brace-or-equal-initializer
6254  if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
6255  if (Diagnose)
6256  S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
6257  return false;
6258  }
6259 
6260  // Objective C ARC 4.3.5:
6261  // [...] nontrivally ownership-qualified types are [...] not trivially
6262  // default constructible, copy constructible, move constructible, copy
6263  // assignable, move assignable, or destructible [...]
6264  if (S.getLangOpts().ObjCAutoRefCount &&
6265  FieldType.hasNonTrivialObjCLifetime()) {
6266  if (Diagnose)
6267  S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
6268  << RD << FieldType.getObjCLifetime();
6269  return false;
6270  }
6271 
6272  bool ConstRHS = ConstArg && !FI->isMutable();
6273  if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
6274  CSM, TSK_Field, Diagnose))
6275  return false;
6276  }
6277 
6278  return true;
6279 }
6280 
6281 /// Diagnose why the specified class does not have a trivial special member of
6282 /// the given kind.
6284  QualType Ty = Context.getRecordType(RD);
6285 
6286  bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
6287  checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
6288  TSK_CompleteObject, /*Diagnose*/true);
6289 }
6290 
6291 /// Determine whether a defaulted or deleted special member function is trivial,
6292 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6293 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6295  bool Diagnose) {
6296  assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
6297 
6298  CXXRecordDecl *RD = MD->getParent();
6299 
6300  bool ConstArg = false;
6301 
6302  // C++11 [class.copy]p12, p25: [DR1593]
6303  // A [special member] is trivial if [...] its parameter-type-list is
6304  // equivalent to the parameter-type-list of an implicit declaration [...]
6305  switch (CSM) {
6306  case CXXDefaultConstructor:
6307  case CXXDestructor:
6308  // Trivial default constructors and destructors cannot have parameters.
6309  break;
6310 
6311  case CXXCopyConstructor:
6312  case CXXCopyAssignment: {
6313  // Trivial copy operations always have const, non-volatile parameter types.
6314  ConstArg = true;
6315  const ParmVarDecl *Param0 = MD->getParamDecl(0);
6316  const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
6317  if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
6318  if (Diagnose)
6319  Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6320  << Param0->getSourceRange() << Param0->getType()
6323  return false;
6324  }
6325  break;
6326  }
6327 
6328  case CXXMoveConstructor:
6329  case CXXMoveAssignment: {
6330  // Trivial move operations always have non-cv-qualified parameters.
6331  const ParmVarDecl *Param0 = MD->getParamDecl(0);
6332  const RValueReferenceType *RT =
6333  Param0->getType()->getAs<RValueReferenceType>();
6334  if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6335  if (Diagnose)
6336  Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6337  << Param0->getSourceRange() << Param0->getType()
6339  return false;
6340  }
6341  break;
6342  }
6343 
6344  case CXXInvalid:
6345  llvm_unreachable("not a special member");
6346  }
6347 
6348  if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6349  if (Diagnose)
6350  Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6351  diag::note_nontrivial_default_arg)
6353  return false;
6354  }
6355  if (MD->isVariadic()) {
6356  if (Diagnose)
6357  Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6358  return false;
6359  }
6360 
6361  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6362  // A copy/move [constructor or assignment operator] is trivial if
6363  // -- the [member] selected to copy/move each direct base class subobject
6364  // is trivial
6365  //
6366  // C++11 [class.copy]p12, C++11 [class.copy]p25:
6367  // A [default constructor or destructor] is trivial if
6368  // -- all the direct base classes have trivial [default constructors or
6369  // destructors]
6370  for (const auto &BI : RD->bases())
6371  if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
6372  ConstArg, CSM, TSK_BaseClass, Diagnose))
6373  return false;
6374 
6375  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6376  // A copy/move [constructor or assignment operator] for a class X is
6377  // trivial if
6378  // -- for each non-static data member of X that is of class type (or array
6379  // thereof), the constructor selected to copy/move that member is
6380  // trivial
6381  //
6382  // C++11 [class.copy]p12, C++11 [class.copy]p25:
6383  // A [default constructor or destructor] is trivial if
6384  // -- for all of the non-static data members of its class that are of class
6385  // type (or array thereof), each such class has a trivial [default
6386  // constructor or destructor]
6387  if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6388  return false;
6389 
6390  // C++11 [class.dtor]p5:
6391  // A destructor is trivial if [...]
6392  // -- the destructor is not virtual
6393  if (CSM == CXXDestructor && MD->isVirtual()) {
6394  if (Diagnose)
6395  Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6396  return false;
6397  }
6398 
6399  // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6400  // A [special member] for class X is trivial if [...]
6401  // -- class X has no virtual functions and no virtual base classes
6402  if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6403  if (!Diagnose)
6404  return false;
6405 
6406  if (RD->getNumVBases()) {
6407  // Check for virtual bases. We already know that the corresponding
6408  // member in all bases is trivial, so vbases must all be direct.
6409  CXXBaseSpecifier &BS = *RD->vbases_begin();
6410  assert(BS.isVirtual());
6411  Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6412  return false;
6413  }
6414 
6415  // Must have a virtual method.
6416  for (const auto *MI : RD->methods()) {
6417  if (MI->isVirtual()) {
6418  SourceLocation MLoc = MI->getLocStart();
6419  Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6420  return false;
6421  }
6422  }
6423 
6424  llvm_unreachable("dynamic class with no vbases and no virtual functions");
6425  }
6426 
6427  // Looks like it's trivial!
6428  return true;
6429 }
6430 
6431 namespace {
6432 struct FindHiddenVirtualMethod {
6433  Sema *S;
6434  CXXMethodDecl *Method;
6435  llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
6436  SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6437 
6438 private:
6439  /// Check whether any most overriden method from MD in Methods
6440  static bool CheckMostOverridenMethods(
6441  const CXXMethodDecl *MD,
6442  const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
6443  if (MD->size_overridden_methods() == 0)
6444  return Methods.count(MD->getCanonicalDecl());
6446  E = MD->end_overridden_methods();
6447  I != E; ++I)
6448  if (CheckMostOverridenMethods(*I, Methods))
6449  return true;
6450  return false;
6451  }
6452 
6453 public:
6454  /// Member lookup function that determines whether a given C++
6455  /// method overloads virtual methods in a base class without overriding any,
6456  /// to be used with CXXRecordDecl::lookupInBases().
6457  bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
6458  RecordDecl *BaseRecord =
6459  Specifier->getType()->getAs<RecordType>()->getDecl();
6460 
6461  DeclarationName Name = Method->getDeclName();
6462  assert(Name.getNameKind() == DeclarationName::Identifier);
6463 
6464  bool foundSameNameMethod = false;
6465  SmallVector<CXXMethodDecl *, 8> overloadedMethods;
6466  for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
6467  Path.Decls = Path.Decls.slice(1)) {
6468  NamedDecl *D = Path.Decls.front();
6469  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6470  MD = MD->getCanonicalDecl();
6471  foundSameNameMethod = true;
6472  // Interested only in hidden virtual methods.
6473  if (!MD->isVirtual())
6474  continue;
6475  // If the method we are checking overrides a method from its base
6476  // don't warn about the other overloaded methods. Clang deviates from
6477  // GCC by only diagnosing overloads of inherited virtual functions that
6478  // do not override any other virtual functions in the base. GCC's
6479  // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6480  // function from a base class. These cases may be better served by a
6481  // warning (not specific to virtual functions) on call sites when the
6482  // call would select a different function from the base class, were it
6483  // visible.
6484  // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
6485  if (!S->IsOverload(Method, MD, false))
6486  return true;
6487  // Collect the overload only if its hidden.
6488  if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
6489  overloadedMethods.push_back(MD);
6490  }
6491  }
6492 
6493  if (foundSameNameMethod)
6494  OverloadedMethods.append(overloadedMethods.begin(),
6495  overloadedMethods.end());
6496  return foundSameNameMethod;
6497  }
6498 };
6499 } // end anonymous namespace
6500 
6501 /// \brief Add the most overriden methods from MD to Methods
6503  llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
6504  if (MD->size_overridden_methods() == 0)
6505  Methods.insert(MD->getCanonicalDecl());
6507  E = MD->end_overridden_methods();
6508  I != E; ++I)
6509  AddMostOverridenMethods(*I, Methods);
6510 }
6511 
6512 /// \brief Check if a method overloads virtual methods in a base class without
6513 /// overriding any.
6515  SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6516  if (!MD->getDeclName().isIdentifier())
6517  return;
6518 
6519  CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6520  /*bool RecordPaths=*/false,
6521  /*bool DetectVirtual=*/false);
6522  FindHiddenVirtualMethod FHVM;
6523  FHVM.Method = MD;
6524  FHVM.S = this;
6525 
6526  // Keep the base methods that were overriden or introduced in the subclass
6527  // by 'using' in a set. A base method not in this set is hidden.
6528  CXXRecordDecl *DC = MD->getParent();
6530  for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6531  NamedDecl *ND = *I;
6532  if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
6533  ND = shad->getTargetDecl();
6534  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6535  AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
6536  }
6537 
6538  if (DC->lookupInBases(FHVM, Paths))
6539  OverloadedMethods = FHVM.OverloadedMethods;
6540 }
6541 
6543  SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6544  for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6545  CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6546  PartialDiagnostic PD = PDiag(
6547  diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6548  HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6549  Diag(overloadedMD->getLocation(), PD);
6550  }
6551 }
6552 
6553 /// \brief Diagnose methods which overload virtual methods in a base class
6554 /// without overriding any.
6556  if (MD->isInvalidDecl())
6557  return;
6558 
6559  if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
6560  return;
6561 
6562  SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6563  FindHiddenVirtualMethods(MD, OverloadedMethods);
6564  if (!OverloadedMethods.empty()) {
6565  Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6566  << MD << (OverloadedMethods.size() > 1);
6567 
6568  NoteHiddenVirtualMethods(MD, OverloadedMethods);
6569  }
6570 }
6571 
6573  Decl *TagDecl,
6574  SourceLocation LBrac,
6575  SourceLocation RBrac,
6576  AttributeList *AttrList) {
6577  if (!TagDecl)
6578  return;
6579 
6580  AdjustDeclIfTemplate(TagDecl);
6581 
6582  for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6583  if (l->getKind() != AttributeList::AT_Visibility)
6584  continue;
6585  l->setInvalid();
6586  Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6587  l->getName();
6588  }
6589 
6590  ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
6591  // strict aliasing violation!
6592  reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
6593  FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
6594 
6596  dyn_cast_or_null<CXXRecordDecl>(TagDecl));
6597 }
6598 
6599 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6600 /// special functions, such as the default constructor, copy
6601 /// constructor, or destructor, to the given C++ class (C++
6602 /// [special]p1). This routine can only be executed just before the
6603 /// definition of the class is complete.
6605  if (ClassDecl->needsImplicitDefaultConstructor()) {
6607 
6608  if (ClassDecl->hasInheritedConstructor())
6610  }
6611 
6612  if (ClassDecl->needsImplicitCopyConstructor()) {
6614 
6615  // If the properties or semantics of the copy constructor couldn't be
6616  // determined while the class was being declared, force a declaration
6617  // of it now.
6618  if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
6619  ClassDecl->hasInheritedConstructor())
6620  DeclareImplicitCopyConstructor(ClassDecl);
6621  }
6622 
6623  if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
6625 
6626  if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
6627  ClassDecl->hasInheritedConstructor())
6628  DeclareImplicitMoveConstructor(ClassDecl);
6629  }
6630 
6631  if (ClassDecl->needsImplicitCopyAssignment()) {
6633 
6634  // If we have a dynamic class, then the copy assignment operator may be
6635  // virtual, so we have to declare it immediately. This ensures that, e.g.,
6636  // it shows up in the right place in the vtable and that we diagnose
6637  // problems with the implicit exception specification.
6638  if (ClassDecl->isDynamicClass() ||
6640  ClassDecl->hasInheritedAssignment())
6641  DeclareImplicitCopyAssignment(ClassDecl);
6642  }
6643 
6644  if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
6646 
6647  // Likewise for the move assignment operator.
6648  if (ClassDecl->isDynamicClass() ||
6650  ClassDecl->hasInheritedAssignment())
6651  DeclareImplicitMoveAssignment(ClassDecl);
6652  }
6653 
6654  if (ClassDecl->needsImplicitDestructor()) {
6656 
6657  // If we have a dynamic class, then the destructor may be virtual, so we
6658  // have to declare the destructor immediately. This ensures that, e.g., it
6659  // shows up in the right place in the vtable and that we diagnose problems
6660  // with the implicit exception specification.
6661  if (ClassDecl->isDynamicClass() ||
6663  DeclareImplicitDestructor(ClassDecl);
6664  }
6665 }
6666 
6668  if (!D)
6669  return 0;
6670 
6671  // The order of template parameters is not important here. All names
6672  // get added to the same scope.
6674 
6675  if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6676  D = TD->getTemplatedDecl();
6677 
6678  if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6679  ParameterLists.push_back(PSD->getTemplateParameters());
6680 
6681  if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6682  for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6683  ParameterLists.push_back(DD->getTemplateParameterList(i));
6684 
6685  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6686  if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6687  ParameterLists.push_back(FTD->getTemplateParameters());
6688  }
6689  }
6690 
6691  if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6692  for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6693  ParameterLists.push_back(TD->getTemplateParameterList(i));
6694 
6695  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6697  ParameterLists.push_back(CTD->getTemplateParameters());
6698  }
6699  }
6700 
6701  unsigned Count = 0;
6702  for (TemplateParameterList *Params : ParameterLists) {
6703  if (Params->size() > 0)
6704  // Ignore explicit specializations; they don't contribute to the template
6705  // depth.
6706  ++Count;
6707  for (NamedDecl *Param : *Params) {
6708  if (Param->getDeclName()) {
6709  S->AddDecl(Param);
6710  IdResolver.AddDecl(Param);
6711  }
6712  }
6713  }
6714 
6715  return Count;
6716 }
6717 
6719  if (!RecordD) return;
6720  AdjustDeclIfTemplate(RecordD);
6721  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
6722  PushDeclContext(S, Record);
6723 }
6724 
6726  if (!RecordD) return;
6727  PopDeclContext();
6728 }
6729 
6730 /// This is used to implement the constant expression evaluation part of the
6731 /// attribute enable_if extension. There is nothing in standard C++ which would
6732 /// require reentering parameters.
6734  if (!Param)
6735  return;
6736 
6737  S->AddDecl(Param);
6738  if (Param->getDeclName())
6739  IdResolver.AddDecl(Param);
6740 }
6741 
6742 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6743 /// parsing a top-level (non-nested) C++ class, and we are now
6744 /// parsing those parts of the given Method declaration that could
6745 /// not be parsed earlier (C++ [class.mem]p2), such as default
6746 /// arguments. This action should enter the scope of the given
6747 /// Method declaration as if we had just parsed the qualified method
6748 /// name. However, it should not bring the parameters into scope;
6749 /// that will be performed by ActOnDelayedCXXMethodParameter.
6751 }
6752 
6753 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
6754 /// C++ method declaration. We're (re-)introducing the given
6755 /// function parameter into scope for use in parsing later parts of
6756 /// the method declaration. For example, we could see an
6757 /// ActOnParamDefaultArgument event for this parameter.
6759  if (!ParamD)
6760  return;
6761 
6762  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
6763 
6764  // If this parameter has an unparsed default argument, clear it out
6765  // to make way for the parsed default argument.
6766  if (Param->hasUnparsedDefaultArg())
6767  Param->setDefaultArg(nullptr);
6768 
6769  S->AddDecl(Param);
6770  if (Param->getDeclName())
6771  IdResolver.AddDecl(Param);
6772 }
6773 
6774 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6775 /// processing the delayed method declaration for Method. The method
6776 /// declaration is now considered finished. There may be a separate
6777 /// ActOnStartOfFunctionDef action later (not necessarily
6778 /// immediately!) for this method, if it was also defined inside the
6779 /// class body.
6781  if (!MethodD)
6782  return;
6783 
6784  AdjustDeclIfTemplate(MethodD);
6785 
6786  FunctionDecl *Method = cast<FunctionDecl>(MethodD);
6787 
6788  // Now that we have our default arguments, check the constructor
6789  // again. It could produce additional diagnostics or affect whether
6790  // the class has implicitly-declared destructors, among other
6791  // things.
6792  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6793  CheckConstructor(Constructor);
6794 
6795  // Check the default arguments, which we may have added.
6796  if (!Method->isInvalidDecl())
6797  CheckCXXDefaultArguments(Method);
6798 }
6799 
6800 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6801 /// the well-formedness of the constructor declarator @p D with type @p
6802 /// R. If there are any errors in the declarator, this routine will
6803 /// emit diagnostics and set the invalid bit to true. In any case, the type
6804 /// will be updated to reflect a well-formed type for the constructor and
6805 /// returned.
6807  StorageClass &SC) {
6808  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6809 
6810  // C++ [class.ctor]p3:
6811  // A constructor shall not be virtual (10.3) or static (9.4). A
6812  // constructor can be invoked for a const, volatile or const
6813  // volatile object. A constructor shall not be declared const,
6814  // volatile, or const volatile (9.3.2).
6815  if (isVirtual) {
6816  if (!D.isInvalidType())
6817  Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6818  << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6819  << SourceRange(D.getIdentifierLoc());
6820  D.setInvalidType();
6821  }
6822  if (SC == SC_Static) {
6823  if (!D.isInvalidType())
6824  Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6825  << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6826  << SourceRange(D.getIdentifierLoc());
6827  D.setInvalidType();
6828  SC = SC_None;
6829  }
6830 
6831  if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6833  diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6837  D.setInvalidType();
6838  }
6839 
6841  if (FTI.TypeQuals != 0) {
6842  if (FTI.TypeQuals & Qualifiers::Const)
6843  Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6844  << "const" << SourceRange(D.getIdentifierLoc());
6845  if (FTI.TypeQuals & Qualifiers::Volatile)
6846  Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6847  << "volatile" << SourceRange(D.getIdentifierLoc());
6848  if (FTI.TypeQuals & Qualifiers::Restrict)
6849  Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6850  << "restrict" << SourceRange(D.getIdentifierLoc());
6851  D.setInvalidType();
6852  }
6853 
6854  // C++0x [class.ctor]p4:
6855  // A constructor shall not be declared with a ref-qualifier.
6856  if (FTI.hasRefQualifier()) {
6857  Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6858  << FTI.RefQualifierIsLValueRef
6860  D.setInvalidType();
6861  }
6862 
6863  // Rebuild the function type "R" without any type qualifiers (in
6864  // case any of the errors above fired) and with "void" as the
6865  // return type, since constructors don't have return types.
6866  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6867  if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
6868  return R;
6869 
6871  EPI.TypeQuals = 0;
6872  EPI.RefQualifier = RQ_None;
6873 
6874  return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
6875 }
6876 
6877 /// CheckConstructor - Checks a fully-formed constructor for
6878 /// well-formedness, issuing any diagnostics required. Returns true if
6879 /// the constructor declarator is invalid.
6881  CXXRecordDecl *ClassDecl
6882  = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6883  if (!ClassDecl)
6884  return Constructor->setInvalidDecl();
6885 
6886  // C++ [class.copy]p3:
6887  // A declaration of a constructor for a class X is ill-formed if
6888  // its first parameter is of type (optionally cv-qualified) X and
6889  // either there are no other parameters or else all other
6890  // parameters have default arguments.
6891  if (!Constructor->isInvalidDecl() &&
6892  ((Constructor->getNumParams() == 1) ||
6893  (Constructor->getNumParams() > 1 &&
6894  Constructor->getParamDecl(1)->hasDefaultArg())) &&
6895  Constructor->getTemplateSpecializationKind()
6897  QualType ParamType = Constructor->getParamDecl(0)->getType();
6898  QualType ClassTy = Context.getTagDeclType(ClassDecl);
6899  if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
6900  SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
6901  const char *ConstRef
6902  = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6903  : " const &";
6904  Diag(ParamLoc, diag::err_constructor_byvalue_arg)
6905  << FixItHint::CreateInsertion(ParamLoc, ConstRef);
6906 
6907  // FIXME: Rather that making the constructor invalid, we should endeavor
6908  // to fix the type.
6909  Constructor->setInvalidDecl();
6910  }
6911  }
6912 }
6913 
6914 /// CheckDestructor - Checks a fully-formed destructor definition for
6915 /// well-formedness, issuing any diagnostics required. Returns true
6916 /// on error.
6918  CXXRecordDecl *RD = Destructor->getParent();
6919 
6920  if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
6921  SourceLocation Loc;
6922 
6923  if (!Destructor->isImplicit())
6924  Loc = Destructor->getLocation();
6925  else
6926  Loc = RD->getLocation();
6927 
6928  // If we have a virtual destructor, look up the deallocation function
6929  FunctionDecl *OperatorDelete = nullptr;
6930  DeclarationName Name =
6932  if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
6933  return true;
6934  // If there's no class-specific operator delete, look up the global
6935  // non-array delete.
6936  if (!OperatorDelete)
6937  OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
6938 
6939  MarkFunctionReferenced(Loc, OperatorDelete);
6940 
6941  Destructor->setOperatorDelete(OperatorDelete);
6942  }
6943 
6944  return false;
6945 }
6946 
6947 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6948 /// the well-formednes of the destructor declarator @p D with type @p
6949 /// R. If there are any errors in the declarator, this routine will
6950 /// emit diagnostics and set the declarator to invalid. Even if this happens,
6951 /// will be updated to reflect a well-formed type for the destructor and
6952 /// returned.
6954  StorageClass& SC) {
6955  // C++ [class.dtor]p1:
6956  // [...] A typedef-name that names a class is a class-name
6957  // (7.1.3); however, a typedef-name that names a class shall not
6958  // be used as the identifier in the declarator for a destructor
6959  // declaration.
6960  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
6961  if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
6962  Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6963  << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
6964  else if (const TemplateSpecializationType *TST =
6965  DeclaratorType->getAs<TemplateSpecializationType>())
6966  if (TST->isTypeAlias())
6967  Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6968  << DeclaratorType << 1;
6969 
6970  // C++ [class.dtor]p2:
6971  // A destructor is used to destroy objects of its class type. A
6972  // destructor takes no parameters, and no return type can be
6973  // specified for it (not even void). The address of a destructor
6974  // shall not be taken. A destructor shall not be static. A
6975  // destructor can be invoked for a const, volatile or const
6976  // volatile object. A destructor shall not be declared const,
6977  // volatile or const volatile (9.3.2).
6978  if (SC == SC_Static) {
6979  if (!D.isInvalidType())
6980  Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6981  << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6984 
6985  SC = SC_None;
6986  }
6987  if (!D.isInvalidType()) {
6988  // Destructors don't have return types, but the parser will
6989  // happily parse something like:
6990  //
6991  // class X {
6992  // float ~X();
6993  // };
6994  //
6995  // The return type will be eliminated later.
6996  if (D.getDeclSpec().hasTypeSpecifier())
6997  Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6999  << SourceRange(D.getIdentifierLoc());
7000  else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7001  diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
7002  SourceLocation(),
7007  D.setInvalidType();
7008  }
7009  }
7010 
7012  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
7013  if (FTI.TypeQuals & Qualifiers::Const)
7014  Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7015  << "const" << SourceRange(D.getIdentifierLoc());
7016  if (FTI.TypeQuals & Qualifiers::Volatile)
7017  Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7018  << "volatile" << SourceRange(D.getIdentifierLoc());
7019  if (FTI.TypeQuals & Qualifiers::Restrict)
7020  Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7021  << "restrict" << SourceRange(D.getIdentifierLoc());
7022  D.setInvalidType();
7023  }
7024 
7025  // C++0x [class.dtor]p2:
7026  // A destructor shall not be declared with a ref-qualifier.
7027  if (FTI.hasRefQualifier()) {
7028  Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
7031  D.setInvalidType();
7032  }
7033 
7034  // Make sure we don't have any parameters.
7035  if (FTIHasNonVoidParameters(FTI)) {
7036  Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
7037 
7038  // Delete the parameters.
7039  FTI.freeParams();
7040  D.setInvalidType();
7041  }
7042 
7043  // Make sure the destructor isn't variadic.
7044  if (FTI.isVariadic) {
7045  Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
7046  D.setInvalidType();
7047  }
7048 
7049  // Rebuild the function type "R" without any type qualifiers or
7050  // parameters (in case any of the errors above fired) and with
7051  // "void" as the return type, since destructors don't have return
7052  // types.
7053  if (!D.isInvalidType())
7054  return R;
7055 
7056  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7058  EPI.Variadic = false;
7059  EPI.TypeQuals = 0;
7060  EPI.RefQualifier = RQ_None;
7061  return Context.getFunctionType(Context.VoidTy, None, EPI);
7062 }
7063 
7064 static void extendLeft(SourceRange &R, SourceRange Before) {
7065  if (Before.isInvalid())
7066  return;
7067  R.setBegin(Before.getBegin());
7068  if (R.getEnd().isInvalid())
7069  R.setEnd(Before.getEnd());
7070 }
7071 
7073  if (After.isInvalid())
7074  return;
7075  if (R.getBegin().isInvalid())
7076  R.setBegin(After.getBegin());
7077  R.setEnd(After.getEnd());
7078 }
7079 
7080 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
7081 /// well-formednes of the conversion function declarator @p D with
7082 /// type @p R. If there are any errors in the declarator, this routine
7083 /// will emit diagnostics and return true. Otherwise, it will return
7084 /// false. Either way, the type @p R will be updated to reflect a
7085 /// well-formed type for the conversion operator.
7087  StorageClass& SC) {
7088  // C++ [class.conv.fct]p1:
7089  // Neither parameter types nor return type can be specified. The
7090  // type of a conversion function (8.3.5) is "function taking no
7091  // parameter returning conversion-type-id."
7092  if (SC == SC_Static) {
7093  if (!D.isInvalidType())
7094  Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
7096  << D.getName().getSourceRange();
7097  D.setInvalidType();
7098  SC = SC_None;
7099  }
7100 
7101  TypeSourceInfo *ConvTSI = nullptr;
7102  QualType ConvType =
7104 
7105  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
7106  // Conversion functions don't have return types, but the parser will
7107  // happily parse something like:
7108  //
7109  // class X {
7110  // float operator bool();
7111  // };
7112  //
7113  // The return type will be changed later anyway.
7114  Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
7116  << SourceRange(D.getIdentifierLoc());
7117  D.setInvalidType();
7118  }
7119 
7120  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7121 
7122  // Make sure we don't have any parameters.
7123  if (Proto->getNumParams() > 0) {
7124  Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
7125 
7126  // Delete the parameters.
7128  D.setInvalidType();
7129  } else if (Proto->isVariadic()) {
7130  Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
7131  D.setInvalidType();
7132  }
7133 
7134  // Diagnose "&operator bool()" and other such nonsense. This
7135  // is actually a gcc extension which we don't support.
7136  if (Proto->getReturnType() != ConvType) {
7137  bool NeedsTypedef = false;
7138  SourceRange Before, After;
7139 
7140  // Walk the chunks and extract information on them for our diagnostic.
7141  bool PastFunctionChunk = false;
7142  for (auto &Chunk : D.type_objects()) {
7143  switch (Chunk.Kind) {
7145  if (!PastFunctionChunk) {
7146  if (Chunk.Fun.HasTrailingReturnType) {
7147  TypeSourceInfo *TRT = nullptr;
7148  GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
7149  if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
7150  }
7151  PastFunctionChunk = true;
7152  break;
7153  }
7154  // Fall through.
7156  NeedsTypedef = true;
7157  extendRight(After, Chunk.getSourceRange());
7158  break;
7159 
7164  case DeclaratorChunk::Pipe:
7165  extendLeft(Before, Chunk.getSourceRange());
7166  break;
7167 
7169  extendLeft(Before, Chunk.Loc);
7170  extendRight(After, Chunk.EndLoc);
7171  break;
7172  }
7173  }
7174 
7175  SourceLocation Loc = Before.isValid() ? Before.getBegin() :
7176  After.isValid() ? After.getBegin() :
7177  D.getIdentifierLoc();
7178  auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
7179  DB << Before << After;
7180 
7181  if (!NeedsTypedef) {
7182  DB << /*don't need a typedef*/0;
7183 
7184  // If we can provide a correct fix-it hint, do so.
7185  if (After.isInvalid() && ConvTSI) {
7186  SourceLocation InsertLoc =
7188  DB << FixItHint::CreateInsertion(InsertLoc, " ")
7190  InsertLoc, CharSourceRange::getTokenRange(Before))
7191  << FixItHint::CreateRemoval(Before);
7192  }
7193  } else if (!Proto->getReturnType()->isDependentType()) {
7194  DB << /*typedef*/1 << Proto->getReturnType();
7195  } else if (getLangOpts().CPlusPlus11) {
7196  DB << /*alias template*/2 << Proto->getReturnType();
7197  } else {
7198  DB << /*might not be fixable*/3;
7199  }
7200 
7201  // Recover by incorporating the other type chunks into the result type.
7202  // Note, this does *not* change the name of the function. This is compatible
7203  // with the GCC extension:
7204  // struct S { &operator int(); } s;
7205  // int &r = s.operator int(); // ok in GCC
7206  // S::operator int&() {} // error in GCC, function name is 'operator int'.
7207  ConvType = Proto->getReturnType();
7208  }
7209 
7210  // C++ [class.conv.fct]p4:
7211  // The conversion-type-id shall not represent a function type nor
7212  // an array type.
7213  if (ConvType->isArrayType()) {
7214  Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7215  ConvType = Context.getPointerType(ConvType);
7216  D.setInvalidType();
7217  } else if (ConvType->isFunctionType()) {
7218  Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7219  ConvType = Context.getPointerType(ConvType);
7220  D.setInvalidType();
7221  }
7222 
7223  // Rebuild the function type "R" without any parameters (in case any
7224  // of the errors above fired) and with the conversion type as the
7225  // return type.
7226  if (D.isInvalidType())
7227  R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
7228 
7229  // C++0x explicit conversion operators.
7230  if (D.getDeclSpec().isExplicitSpecified())
7232  getLangOpts().CPlusPlus11 ?
7233  diag::warn_cxx98_compat_explicit_conversion_functions :
7234  diag::ext_explicit_conversion_functions)
7236 }
7237 
7238 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
7239 /// the declaration of the given C++ conversion function. This routine
7240 /// is responsible for recording the conversion function in the C++
7241 /// class, if possible.
7243  assert(Conversion && "Expected to receive a conversion function declaration");
7244 
7245  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
7246 
7247  // Make sure we aren't redeclaring the conversion function.
7248  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
7249 
7250  // C++ [class.conv.fct]p1:
7251  // [...] A conversion function is never used to convert a
7252  // (possibly cv-qualified) object to the (possibly cv-qualified)
7253  // same object type (or a reference to it), to a (possibly
7254  // cv-qualified) base class of that type (or a reference to it),
7255  // or to (possibly cv-qualified) void.
7256  // FIXME: Suppress this warning if the conversion function ends up being a
7257  // virtual function that overrides a virtual function in a base class.
7258  QualType ClassType
7260  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
7261  ConvType = ConvTypeRef->getPointeeType();
7262  if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
7264  /* Suppress diagnostics for instantiations. */;
7265  else if (ConvType->isRecordType()) {
7266  ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
7267  if (ConvType == ClassType)
7268  Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
7269  << ClassType;
7270  else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
7271  Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
7272  << ClassType << ConvType;
7273  } else if (ConvType->isVoidType()) {
7274  Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
7275  << ClassType << ConvType;
7276  }
7277 
7278  if (FunctionTemplateDecl *ConversionTemplate
7279  = Conversion->getDescribedFunctionTemplate())
7280  return ConversionTemplate;
7281 
7282  return Conversion;
7283 }
7284 
7285 //===----------------------------------------------------------------------===//
7286 // Namespace Handling
7287 //===----------------------------------------------------------------------===//
7288 
7289 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
7290 /// reopened.
7292  SourceLocation Loc,
7293  IdentifierInfo *II, bool *IsInline,
7294  NamespaceDecl *PrevNS) {
7295  assert(*IsInline != PrevNS->isInline());
7296 
7297  // HACK: Work around a bug in libstdc++4.6's <atomic>, where
7298  // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
7299  // inline namespaces, with the intention of bringing names into namespace std.
7300  //
7301  // We support this just well enough to get that case working; this is not
7302  // sufficient to support reopening namespaces as inline in general.
7303  if (*IsInline && II && II->getName().startswith("__atomic") &&
7305  // Mark all prior declarations of the namespace as inline.
7306  for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
7307  NS = NS->getPreviousDecl())
7308  NS->setInline(*IsInline);
7309  // Patch up the lookup table for the containing namespace. This isn't really
7310  // correct, but it's good enough for this particular case.
7311  for (auto *I : PrevNS->decls())
7312  if (auto *ND = dyn_cast<NamedDecl>(I))
7313  PrevNS->getParent()->makeDeclVisibleInContext(ND);
7314  return;
7315  }
7316 
7317  if (PrevNS->isInline())
7318  // The user probably just forgot the 'inline', so suggest that it
7319  // be added back.
7320  S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
7321  << FixItHint::CreateInsertion(KeywordLoc, "inline ");
7322  else
7323  S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
7324 
7325  S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
7326  *IsInline = PrevNS->isInline();
7327 }
7328 
7329 /// ActOnStartNamespaceDef - This is called at the start of a namespace
7330 /// definition.
7332  SourceLocation InlineLoc,
7333  SourceLocation NamespaceLoc,
7334  SourceLocation IdentLoc,
7335  IdentifierInfo *II,
7336  SourceLocation LBrace,
7337  AttributeList *AttrList,
7338  UsingDirectiveDecl *&UD) {
7339  SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
7340  // For anonymous namespace, take the location of the left brace.
7341  SourceLocation Loc = II ? IdentLoc : LBrace;
7342  bool IsInline = InlineLoc.isValid();
7343  bool IsInvalid = false;
7344  bool IsStd = false;
7345  bool AddToKnown = false;
7346  Scope *DeclRegionScope = NamespcScope->getParent();
7347 
7348  NamespaceDecl *PrevNS = nullptr;
7349  if (II) {
7350  // C++ [namespace.def]p2:
7351  // The identifier in an original-namespace-definition shall not
7352  // have been previously defined in the declarative region in
7353  // which the original-namespace-definition appears. The
7354  // identifier in an original-namespace-definition is the name of
7355  // the namespace. Subsequently in that declarative region, it is
7356  // treated as an original-namespace-name.
7357  //
7358  // Since namespace names are unique in their scope, and we don't
7359  // look through using directives, just look for any ordinary names
7360  // as if by qualified name lookup.
7361  LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration);
7363  NamedDecl *PrevDecl =
7364  R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
7365  PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
7366 
7367  if (PrevNS) {
7368  // This is an extended namespace definition.
7369  if (IsInline != PrevNS->isInline())
7370  DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
7371  &IsInline, PrevNS);
7372  } else if (PrevDecl) {
7373  // This is an invalid name redefinition.
7374  Diag(Loc, diag::err_redefinition_different_kind)
7375  << II;
7376  Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7377  IsInvalid = true;
7378  // Continue on to push Namespc as current DeclContext and return it.
7379  } else if (II->isStr("std") &&
7381  // This is the first "real" definition of the namespace "std", so update
7382  // our cache of the "std" namespace to point at this definition.
7383  PrevNS = getStdNamespace();
7384  IsStd = true;
7385  AddToKnown = !IsInline;
7386  } else {
7387  // We've seen this namespace for the first time.
7388  AddToKnown = !IsInline;
7389  }
7390  } else {
7391  // Anonymous namespaces.
7392 
7393  // Determine whether the parent already has an anonymous namespace.
7395  if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7396  PrevNS = TU->getAnonymousNamespace();
7397  } else {
7398  NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
7399  PrevNS = ND->getAnonymousNamespace();
7400  }
7401 
7402  if (PrevNS && IsInline != PrevNS->isInline())
7403  DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
7404  &IsInline, PrevNS);
7405  }
7406 
7407  NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
7408  StartLoc, Loc, II, PrevNS);
7409  if (IsInvalid)
7410  Namespc->setInvalidDecl();
7411 
7412  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
7413 
7414  // FIXME: Should we be merging attributes?
7415  if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
7417 
7418  if (IsStd)
7419  StdNamespace = Namespc;
7420  if (AddToKnown)
7421  KnownNamespaces[Namespc] = false;
7422 
7423  if (II) {
7424  PushOnScopeChains(Namespc, DeclRegionScope);
7425  } else {
7426  // Link the anonymous namespace into its parent.
7428  if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7429  TU->setAnonymousNamespace(Namespc);
7430  } else {
7431  cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
7432  }
7433 
7434  CurContext->addDecl(Namespc);
7435 
7436  // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
7437  // behaves as if it were replaced by
7438  // namespace unique { /* empty body */ }
7439  // using namespace unique;
7440  // namespace unique { namespace-body }
7441  // where all occurrences of 'unique' in a translation unit are
7442  // replaced by the same identifier and this identifier differs
7443  // from all other identifiers in the entire program.
7444 
7445  // We just create the namespace with an empty name and then add an
7446  // implicit using declaration, just like the standard suggests.
7447  //
7448  // CodeGen enforces the "universally unique" aspect by giving all
7449  // declarations semantically contained within an anonymous
7450  // namespace internal linkage.
7451 
7452  if (!PrevNS) {
7453  UD = UsingDirectiveDecl::Create(Context, Parent,
7454  /* 'using' */ LBrace,
7455  /* 'namespace' */ SourceLocation(),
7456  /* qualifier */ NestedNameSpecifierLoc(),
7457  /* identifier */ SourceLocation(),
7458  Namespc,
7459  /* Ancestor */ Parent);
7460  UD->setImplicit();
7461  Parent->addDecl(UD);
7462  }
7463  }
7464 
7465  ActOnDocumentableDecl(Namespc);
7466 
7467  // Although we could have an invalid decl (i.e. the namespace name is a
7468  // redefinition), push it as current DeclContext and try to continue parsing.
7469  // FIXME: We should be able to push Namespc here, so that the each DeclContext
7470  // for the namespace has the declarations that showed up in that particular
7471  // namespace definition.
7472  PushDeclContext(NamespcScope, Namespc);
7473  return Namespc;
7474 }
7475 
7476 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7477 /// is a namespace alias, returns the namespace it points to.
7479  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7480  return AD->getNamespace();
7481  return dyn_cast_or_null<NamespaceDecl>(D);
7482 }
7483 
7484 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
7485 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
7487  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7488  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
7489  Namespc->setRBraceLoc(RBrace);
7490  PopDeclContext();
7491  if (Namespc->hasAttr<VisibilityAttr>())
7492  PopPragmaVisibility(true, RBrace);
7493 }
7494 
7496  return cast_or_null<CXXRecordDecl>(
7498 }
7499 
7501  return cast_or_null<NamespaceDecl>(
7503 }
7504 
7505 /// \brief Retrieve the special "std" namespace, which may require us to
7506 /// implicitly define the namespace.
7508  if (!StdNamespace) {
7509  // The "std" namespace has not yet been defined, so build one implicitly.
7512  /*Inline=*/false,
7514  &PP.getIdentifierTable().get("std"),
7515  /*PrevDecl=*/nullptr);
7516  getStdNamespace()->setImplicit(true);
7517  }
7518 
7519  return getStdNamespace();
7520 }
7521 
7523  assert(getLangOpts().CPlusPlus &&
7524  "Looking for std::initializer_list outside of C++.");
7525 
7526  // We're looking for implicit instantiations of
7527  // template <typename E> class std::initializer_list.
7528 
7529  if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7530  return false;
7531 
7532  ClassTemplateDecl *Template = nullptr;
7533  const TemplateArgument *Arguments = nullptr;
7534 
7535  if (const RecordType *RT = Ty->getAs<RecordType>()) {
7536 
7537  ClassTemplateSpecializationDecl *Specialization =
7538  dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7539  if (!Specialization)
7540  return false;
7541 
7542  Template = Specialization->getSpecializedTemplate();
7543  Arguments = Specialization->getTemplateArgs().data();
7544  } else if (const TemplateSpecializationType *TST =
7546  Template = dyn_cast_or_null<ClassTemplateDecl>(
7547  TST->getTemplateName().getAsTemplateDecl());
7548  Arguments = TST->getArgs();
7549  }
7550  if (!Template)
7551  return false;
7552 
7553  if (!StdInitializerList) {
7554  // Haven't recognized std::initializer_list yet, maybe this is it.
7555  CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7556  if (TemplateClass->getIdentifier() !=
7557  &PP.getIdentifierTable().get("initializer_list") ||
7559  TemplateClass->getDeclContext()))
7560  return false;
7561  // This is a template called std::initializer_list, but is it the right
7562  // template?
7563  TemplateParameterList *Params = Template->getTemplateParameters();
7564  if (Params->getMinRequiredArguments() != 1)
7565  return false;
7566  if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7567  return false;
7568 
7569  // It's the right template.
7570  StdInitializerList = Template;
7571  }
7572 
7574  return false;
7575 
7576  // This is an instance of std::initializer_list. Find the argument type.
7577  if (Element)
7578  *Element = Arguments[0].getAsType();
7579  return true;
7580 }
7581 
7583  NamespaceDecl *Std = S.getStdNamespace();
7584  if (!Std) {
7585  S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7586  return nullptr;
7587  }
7588 
7589  LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7591  if (!S.LookupQualifiedName(Result, Std)) {
7592  S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7593  return nullptr;
7594  }
7595  ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7596  if (!Template) {
7597  Result.suppressDiagnostics();
7598  // We found something weird. Complain about the first thing we found.
7599  NamedDecl *Found = *Result.begin();
7600  S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
7601  return nullptr;
7602  }
7603 
7604  // We found some template called std::initializer_list. Now verify that it's
7605  // correct.
7606  TemplateParameterList *Params = Template->getTemplateParameters();
7607  if (Params->getMinRequiredArguments() != 1 ||
7608  !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
7609  S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
7610  return nullptr;
7611  }
7612 
7613  return Template;
7614 }
7615 
7617  if (!StdInitializerList) {
7619  if (!StdInitializerList)
7620  return QualType();
7621  }
7622 
7623  TemplateArgumentListInfo Args(Loc, Loc);
7626  Loc)));
7627  return Context.getCanonicalType(
7629 }
7630 
7632  // C++ [dcl.init.list]p2:
7633  // A constructor is an initializer-list constructor if its first parameter
7634  // is of type std::initializer_list<E> or reference to possibly cv-qualified
7635  // std::initializer_list<E> for some type E, and either there are no other
7636  // parameters or else all other parameters have default arguments.
7637  if (Ctor->getNumParams() < 1 ||
7638  (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7639  return false;
7640 
7641  QualType ArgType = Ctor->getParamDecl(0)->getType();
7642  if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7643  ArgType = RT->getPointeeType().getUnqualifiedType();
7644 
7645  return isStdInitializerList(ArgType, nullptr);
7646 }
7647 
7648 /// \brief Determine whether a using statement is in a context where it will be
7649 /// apply in all contexts.
7651  switch (CurContext->getDeclKind()) {
7652  case Decl::TranslationUnit:
7653  return true;
7654  case Decl::LinkageSpec:
7655  return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7656  default:
7657  return false;
7658  }
7659 }
7660 
7661 namespace {
7662 
7663 // Callback to only accept typo corrections that are namespaces.
7664 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
7665 public:
7666  bool ValidateCandidate(const TypoCorrection &candidate) override {
7667  if (NamedDecl *ND = candidate.getCorrectionDecl())
7668  return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
7669  return false;
7670  }
7671 };
7672 
7673 }
7674 
7676  CXXScopeSpec &SS,
7677  SourceLocation IdentLoc,
7678  IdentifierInfo *Ident) {
7679  R.clear();
7680  if (TypoCorrection Corrected =
7681  S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
7682  llvm::make_unique<NamespaceValidatorCCC>(),
7684  if (DeclContext *DC = S.computeDeclContext(SS, false)) {
7685  std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7686  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
7687  Ident->getName().equals(CorrectedStr);
7688  S.diagnoseTypo(Corrected,
7689  S.PDiag(diag::err_using_directive_member_suggest)
7690  << Ident << DC << DroppedSpecifier << SS.getRange(),
7691  S.PDiag(diag::note_namespace_defined_here));
7692  } else {
7693  S.diagnoseTypo(Corrected,
7694  S.PDiag(diag::err_using_directive_suggest) << Ident,
7695  S.PDiag(diag::note_namespace_defined_here));
7696  }
7697  R.addDecl(Corrected.getFoundDecl());
7698  return true;
7699  }
7700  return false;
7701 }
7702 
7704  SourceLocation UsingLoc,
7705  SourceLocation NamespcLoc,
7706  CXXScopeSpec &SS,
7707  SourceLocation IdentLoc,
7708  IdentifierInfo *NamespcName,
7709  AttributeList *AttrList) {
7710  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7711  assert(NamespcName && "Invalid NamespcName.");
7712  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
7713 
7714  // This can only happen along a recovery path.
7715  while (S->isTemplateParamScope())
7716  S = S->getParent();
7717  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7718 
7719  UsingDirectiveDecl *UDir = nullptr;
7720  NestedNameSpecifier *Qualifier = nullptr;
7721  if (SS.isSet())
7722  Qualifier = SS.getScopeRep();
7723 
7724  // Lookup namespace name.
7725  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7726  LookupParsedName(R, S, &SS);
7727  if (R.isAmbiguous())
7728  return nullptr;
7729 
7730  if (R.empty()) {
7731  R.clear();
7732  // Allow "using namespace std;" or "using namespace ::std;" even if
7733  // "std" hasn't been defined yet, for GCC compatibility.
7734  if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7735  NamespcName->isStr("std")) {
7736  Diag(IdentLoc, diag::ext_using_undefined_std);
7738  R.resolveKind();
7739  }
7740  // Otherwise, attempt typo correction.
7741  else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
7742  }
7743 
7744  if (!R.empty()) {
7745  NamedDecl *Named = R.getRepresentativeDecl();
7747  assert(NS && "expected namespace decl");
7748 
7749  // The use of a nested name specifier may trigger deprecation warnings.
7750  DiagnoseUseOfDecl(Named, IdentLoc);
7751 
7752  // C++ [namespace.udir]p1:
7753  // A using-directive specifies that the names in the nominated
7754  // namespace can be used in the scope in which the
7755  // using-directive appears after the using-directive. During
7756  // unqualified name lookup (3.4.1), the names appear as if they
7757  // were declared in the nearest enclosing namespace which
7758  // contains both the using-directive and the nominated
7759  // namespace. [Note: in this context, "contains" means "contains
7760  // directly or indirectly". ]
7761 
7762  // Find enclosing context containing both using-directive and
7763  // nominated namespace.
7764  DeclContext *CommonAncestor = cast<DeclContext>(NS);
7765  while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7766  CommonAncestor = CommonAncestor->getParent();
7767 
7768  UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
7770  IdentLoc, Named, CommonAncestor);
7771 
7774  Diag(IdentLoc, diag::warn_using_directive_in_header);
7775  }
7776 
7777  PushUsingDirective(S, UDir);
7778  } else {
7779  Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7780  }
7781 
7782  if (UDir)
7783  ProcessDeclAttributeList(S, UDir, AttrList);
7784 
7785  return UDir;
7786 }
7787 
7789  // If the scope has an associated entity and the using directive is at
7790  // namespace or translation unit scope, add the UsingDirectiveDecl into
7791  // its lookup structure so qualified name lookup can find it.
7792  DeclContext *Ctx = S->getEntity();
7793  if (Ctx && !Ctx->isFunctionOrMethod())
7794  Ctx->addDecl(UDir);
7795  else
7796  // Otherwise, it is at block scope. The using-directives will affect lookup
7797  // only to the end of the scope.
7798  S->PushUsingDirective(UDir);
7799 }
7800 
7801 
7803  AccessSpecifier AS,
7804  bool HasUsingKeyword,
7805  SourceLocation UsingLoc,
7806  CXXScopeSpec &SS,
7807  UnqualifiedId &Name,
7808  AttributeList *AttrList,
7809  bool HasTypenameKeyword,
7810  SourceLocation TypenameLoc) {
7811  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7812 
7813  switch (Name.getKind()) {
7819  break;
7820 
7823  // C++11 inheriting constructors.
7824  Diag(Name.getLocStart(),
7825  getLangOpts().CPlusPlus11 ?
7826  diag::warn_cxx98_compat_using_decl_constructor :
7827  diag::err_using_decl_constructor)
7828  << SS.getRange();
7829 
7830  if (getLangOpts().CPlusPlus11) break;
7831 
7832  return nullptr;
7833 
7835  Diag(Name.getLocStart(), diag::err_using_decl_destructor)
7836  << SS.getRange();
7837  return nullptr;
7838 
7840  Diag(Name.getLocStart(), diag::err_using_decl_template_id)
7842  return nullptr;
7843  }
7844 
7845  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7846  DeclarationName TargetName = TargetNameInfo.getName();
7847  if (!TargetName)
7848  return nullptr;
7849 
7850  // Warn about access declarations.
7851  if (!HasUsingKeyword) {
7852  Diag(Name.getLocStart(),
7853  getLangOpts().CPlusPlus11 ? diag::err_access_decl
7854  : diag::warn_access_decl_deprecated)
7855  << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
7856  }
7857 
7860  return nullptr;
7861 
7862  NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
7863  TargetNameInfo, AttrList,
7864  /* IsInstantiation */ false,
7865  HasTypenameKeyword, TypenameLoc);
7866  if (UD)
7867  PushOnScopeChains(UD, S, /*AddToContext*/ false);
7868 
7869  return UD;
7870 }
7871 
7872 /// \brief Determine whether a using declaration considers the given
7873 /// declarations as "equivalent", e.g., if they are redeclarations of
7874 /// the same entity or are both typedefs of the same type.
7875 static bool
7877  if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
7878  return true;
7879 
7880  if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7881  if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
7882  return Context.hasSameType(TD1->getUnderlyingType(),
7883  TD2->getUnderlyingType());
7884 
7885  return false;
7886 }
7887 
7888 
7889 /// Determines whether to create a using shadow decl for a particular
7890 /// decl, given the set of decls existing prior to this using lookup.
7892  const LookupResult &Previous,
7893  UsingShadowDecl *&PrevShadow) {
7894  // Diagnose finding a decl which is not from a base class of the
7895  // current class. We do this now because there are cases where this
7896  // function will silently decide not to build a shadow decl, which
7897  // will pre-empt further diagnostics.
7898  //
7899  // We don't need to do this in C++11 because we do the check once on
7900  // the qualifier.
7901  //
7902  // FIXME: diagnose the following if we care enough:
7903  // struct A { int foo; };
7904  // struct B : A { using A::foo; };
7905  // template <class T> struct C : A {};
7906  // template <class T> struct D : C<T> { using B::foo; } // <---
7907  // This is invalid (during instantiation) in C++03 because B::foo
7908  // resolves to the using decl in B, which is not a base class of D<T>.
7909  // We can't diagnose it immediately because C<T> is an unknown
7910  // specialization. The UsingShadowDecl in D<T> then points directly
7911  // to A::foo, which will look well-formed when we instantiate.
7912  // The right solution is to not collapse the shadow-decl chain.
7913  if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
7914  DeclContext *OrigDC = Orig->getDeclContext();
7915 
7916  // Handle enums and anonymous structs.
7917  if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7918  CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7919  while (OrigRec->isAnonymousStructOrUnion())
7920  OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7921 
7922  if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7923  if (OrigDC == CurContext) {
7924  Diag(Using->getLocation(),
7925  diag::err_using_decl_nested_name_specifier_is_current_class)
7926  << Using->getQualifierLoc().getSourceRange();
7927  Diag(Orig->getLocation(), diag::note_using_decl_target);
7928  return true;
7929  }
7930 
7931  Diag(Using->getQualifierLoc().getBeginLoc(),
7932  diag::err_using_decl_nested_name_specifier_is_not_base_class)
7933  << Using->getQualifier()
7934  << cast<CXXRecordDecl>(CurContext)
7935  << Using->getQualifierLoc().getSourceRange();
7936  Diag(Orig->getLocation(), diag::note_using_decl_target);
7937  return true;
7938  }
7939  }
7940 
7941  if (Previous.empty()) return false;
7942 
7943  NamedDecl *Target = Orig;
7944  if (isa<UsingShadowDecl>(Target))
7945  Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7946 
7947  // If the target happens to be one of the previous declarations, we
7948  // don't have a conflict.
7949  //
7950  // FIXME: but we might be increasing its access, in which case we
7951  // should redeclare it.
7952  NamedDecl *NonTag = nullptr, *Tag = nullptr;
7953  bool FoundEquivalentDecl = false;
7954  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7955  I != E; ++I) {
7956  NamedDecl *D = (*I)->getUnderlyingDecl();
7957  // We can have UsingDecls in our Previous results because we use the same
7958  // LookupResult for checking whether the UsingDecl itself is a valid
7959  // redeclaration.
7960  if (isa<UsingDecl>(D))
7961  continue;
7962 
7963  if (IsEquivalentForUsingDecl(Context, D, Target)) {
7964  if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7965  PrevShadow = Shadow;
7966  FoundEquivalentDecl = true;
7967  } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
7968  // We don't conflict with an existing using shadow decl of an equivalent
7969  // declaration, but we're not a redeclaration of it.
7970  FoundEquivalentDecl = true;
7971  }
7972 
7973  if (isVisible(D))
7974  (isa<TagDecl>(D) ? Tag : NonTag) = D;
7975  }
7976 
7977  if (FoundEquivalentDecl)
7978  return false;
7979 
7980  if (FunctionDecl *FD = Target->getAsFunction()) {
7981  NamedDecl *OldDecl = nullptr;
7982  switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7983  /*IsForUsingDecl*/ true)) {
7984  case Ovl_Overload:
7985  return false;
7986 
7987  case Ovl_NonFunction:
7988  Diag(Using->getLocation(), diag::err_using_decl_conflict);
7989  break;
7990 
7991  // We found a decl with the exact signature.
7992  case Ovl_Match:
7993  // If we're in a record, we want to hide the target, so we
7994  // return true (without a diagnostic) to tell the caller not to
7995  // build a shadow decl.
7996  if (CurContext->isRecord())
7997  return true;
7998 
7999  // If we're not in a record, this is an error.
8000  Diag(Using->getLocation(), diag::err_using_decl_conflict);
8001  break;
8002  }
8003 
8004  Diag(Target->getLocation(), diag::note_using_decl_target);
8005  Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
8006  return true;
8007  }
8008 
8009  // Target is not a function.
8010 
8011  if (isa<TagDecl>(Target)) {
8012  // No conflict between a tag and a non-tag.
8013  if (!Tag) return false;
8014 
8015  Diag(Using->getLocation(), diag::err_using_decl_conflict);
8016  Diag(Target->getLocation(), diag::note_using_decl_target);
8017  Diag(Tag->getLocation(), diag::note_using_decl_conflict);
8018  return true;
8019  }
8020 
8021  // No conflict between a tag and a non-tag.
8022  if (!NonTag) return false;
8023 
8024  Diag(Using->getLocation(), diag::err_using_decl_conflict);
8025  Diag(Target->getLocation(), diag::note_using_decl_target);
8026  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
8027  return true;
8028 }
8029 
8030 /// Determine whether a direct base class is a virtual base class.
8031 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
8032  if (!Derived->getNumVBases())
8033  return false;
8034  for (auto &B : Derived->bases())
8035  if (B.getType()->getAsCXXRecordDecl() == Base)
8036  return B.isVirtual();
8037  llvm_unreachable("not a direct base class");
8038 }
8039 
8040 /// Builds a shadow declaration corresponding to a 'using' declaration.
8042  UsingDecl *UD,
8043  NamedDecl *Orig,
8044  UsingShadowDecl *PrevDecl) {
8045  // If we resolved to another shadow declaration, just coalesce them.
8046  NamedDecl *Target = Orig;
8047  if (isa<UsingShadowDecl>(Target)) {
8048  Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
8049  assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
8050  }
8051 
8052  NamedDecl *NonTemplateTarget = Target;
8053  if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
8054  NonTemplateTarget = TargetTD->getTemplatedDecl();
8055 
8056  UsingShadowDecl *Shadow;
8057  if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
8058  bool IsVirtualBase =
8059  isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
8060  UD->getQualifier()->getAsRecordDecl());
8062  Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
8063  } else {
8064  Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
8065  Target);
8066  }
8067  UD->addShadowDecl(Shadow);
8068 
8069  Shadow->setAccess(UD->getAccess());
8070  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
8071  Shadow->setInvalidDecl();
8072 
8073  Shadow->setPreviousDecl(PrevDecl);
8074 
8075  if (S)
8076  PushOnScopeChains(Shadow, S);
8077  else
8078  CurContext->addDecl(Shadow);
8079 
8080 
8081  return Shadow;
8082 }
8083 
8084 /// Hides a using shadow declaration. This is required by the current
8085 /// using-decl implementation when a resolvable using declaration in a
8086 /// class is followed by a declaration which would hide or override
8087 /// one or more of the using decl's targets; for example:
8088 ///
8089 /// struct Base { void foo(int); };
8090 /// struct Derived : Base {
8091 /// using Base::foo;
8092 /// void foo(int);
8093 /// };
8094 ///
8095 /// The governing language is C++03 [namespace.udecl]p12:
8096 ///
8097 /// When a using-declaration brings names from a base class into a
8098 /// derived class scope, member functions in the derived class
8099 /// override and/or hide member functions with the same name and
8100 /// parameter types in a base class (rather than conflicting).
8101 ///
8102 /// There are two ways to implement this:
8103 /// (1) optimistically create shadow decls when they're not hidden
8104 /// by existing declarations, or
8105 /// (2) don't create any shadow decls (or at least don't make them
8106 /// visible) until we've fully parsed/instantiated the class.
8107 /// The problem with (1) is that we might have to retroactively remove
8108 /// a shadow decl, which requires several O(n) operations because the
8109 /// decl structures are (very reasonably) not designed for removal.
8110 /// (2) avoids this but is very fiddly and phase-dependent.
8112  if (Shadow->getDeclName().getNameKind() ==
8114  cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
8115 
8116  // Remove it from the DeclContext...
8117  Shadow->getDeclContext()->removeDecl(Shadow);
8118 
8119  // ...and the scope, if applicable...
8120  if (S) {
8121  S->RemoveDecl(Shadow);
8122  IdResolver.RemoveDecl(Shadow);
8123  }
8124 
8125  // ...and the using decl.
8126  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
8127 
8128  // TODO: complain somehow if Shadow was used. It shouldn't
8129  // be possible for this to happen, because...?
8130 }
8131 
8132 /// Find the base specifier for a base class with the given type.
8134  QualType DesiredBase,
8135  bool &AnyDependentBases) {
8136  // Check whether the named type is a direct base class.
8137  CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
8138  for (auto &Base : Derived->bases()) {
8139  CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
8140  if (CanonicalDesiredBase == BaseType)
8141  return &Base;
8142  if (BaseType->isDependentType())
8143  AnyDependentBases = true;
8144  }
8145  return nullptr;
8146 }
8147 
8148 namespace {
8149 class UsingValidatorCCC : public CorrectionCandidateCallback {
8150 public:
8151  UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
8152  NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
8153  : HasTypenameKeyword(HasTypenameKeyword),
8154  IsInstantiation(IsInstantiation), OldNNS(NNS),
8155  RequireMemberOf(RequireMemberOf) {}
8156 
8157  bool ValidateCandidate(const TypoCorrection &Candidate) override {
8158  NamedDecl *ND = Candidate.getCorrectionDecl();
8159 
8160  // Keywords are not valid here.
8161  if (!ND || isa<NamespaceDecl>(ND))
8162  return false;
8163 
8164  // Completely unqualified names are invalid for a 'using' declaration.
8165  if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
8166  return false;
8167 
8168  // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
8169  // reject.
8170 
8171  if (RequireMemberOf) {
8172  auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8173  if (FoundRecord && FoundRecord->isInjectedClassName()) {
8174  // No-one ever wants a using-declaration to name an injected-class-name
8175  // of a base class, unless they're declaring an inheriting constructor.
8176  ASTContext &Ctx = ND->getASTContext();
8177  if (!Ctx.getLangOpts().CPlusPlus11)
8178  return false;
8179  QualType FoundType = Ctx.getRecordType(FoundRecord);
8180 
8181  // Check that the injected-class-name is named as a member of its own
8182  // type; we don't want to suggest 'using Derived::Base;', since that
8183  // means something else.
8184  NestedNameSpecifier *Specifier =
8185  Candidate.WillReplaceSpecifier()
8186  ? Candidate.getCorrectionSpecifier()
8187  : OldNNS;
8188  if (!Specifier->getAsType() ||
8189  !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
8190  return false;
8191 
8192  // Check that this inheriting constructor declaration actually names a
8193  // direct base class of the current class.
8194  bool AnyDependentBases = false;
8195  if (!findDirectBaseWithType(RequireMemberOf,
8196  Ctx.getRecordType(FoundRecord),
8197  AnyDependentBases) &&
8198  !AnyDependentBases)
8199  return false;
8200  } else {
8201  auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
8202  if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
8203  return false;
8204 
8205  // FIXME: Check that the base class member is accessible?
8206  }
8207  } else {
8208  auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8209  if (FoundRecord && FoundRecord->isInjectedClassName())
8210  return false;
8211  }
8212 
8213  if (isa<TypeDecl>(ND))
8214  return HasTypenameKeyword || !IsInstantiation;
8215 
8216  return !HasTypenameKeyword;
8217  }
8218 
8219 private:
8220  bool HasTypenameKeyword;
8221  bool IsInstantiation;
8222  NestedNameSpecifier *OldNNS;
8223  CXXRecordDecl *RequireMemberOf;
8224 };
8225 } // end anonymous namespace
8226 
8227 /// Builds a using declaration.
8228 ///
8229 /// \param IsInstantiation - Whether this call arises from an
8230 /// instantiation of an unresolved using declaration. We treat
8231 /// the lookup differently for these declarations.
8233  SourceLocation UsingLoc,
8234  CXXScopeSpec &SS,
8235  DeclarationNameInfo NameInfo,
8236  AttributeList *AttrList,
8237  bool IsInstantiation,
8238  bool HasTypenameKeyword,
8239  SourceLocation TypenameLoc) {
8240  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8241  SourceLocation IdentLoc = NameInfo.getLoc();
8242  assert(IdentLoc.isValid() && "Invalid TargetName location.");
8243 
8244  // FIXME: We ignore attributes for now.
8245 
8246  if (SS.isEmpty()) {
8247  Diag(IdentLoc, diag::err_using_requires_qualname);
8248  return nullptr;
8249  }
8250 
8251  // For an inheriting constructor declaration, the name of the using
8252  // declaration is the name of a constructor in this class, not in the
8253  // base class.
8254  DeclarationNameInfo UsingName = NameInfo;
8256  if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
8259 
8260  // Do the redeclaration lookup in the current scope.
8261  LookupResult Previous(*this, UsingName, LookupUsingDeclName,
8263  Previous.setHideTags(false);
8264  if (S) {
8265  LookupName(Previous, S);
8266 
8267  // It is really dumb that we have to do this.
8268  LookupResult::Filter F = Previous.makeFilter();
8269  while (F.hasNext()) {
8270  NamedDecl *D = F.next();
8271  if (!isDeclInScope(D, CurContext, S))
8272  F.erase();
8273  // If we found a local extern declaration that's not ordinarily visible,
8274  // and this declaration is being added to a non-block scope, ignore it.
8275  // We're only checking for scope conflicts here, not also for violations
8276  // of the linkage rules.
8277  else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
8278  !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
8279  F.erase();
8280  }
8281  F.done();
8282  } else {
8283  assert(IsInstantiation && "no scope in non-instantiation");
8284  assert(CurContext->isRecord() && "scope not record in instantiation");
8285  LookupQualifiedName(Previous, CurContext);
8286  }
8287 
8288  // Check for invalid redeclarations.
8289  if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
8290  SS, IdentLoc, Previous))
8291  return nullptr;
8292 
8293  // Check for bad qualifiers.
8294  if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
8295  return nullptr;
8296 
8297  DeclContext *LookupContext = computeDeclContext(SS);
8298  NamedDecl *D;
8300  if (!LookupContext) {
8301  if (HasTypenameKeyword) {
8302  // FIXME: not all declaration name kinds are legal here
8304  UsingLoc, TypenameLoc,
8305  QualifierLoc,
8306  IdentLoc, NameInfo.getName());
8307  } else {
8309  QualifierLoc, NameInfo);
8310  }
8311  D->setAccess(AS);
8312  CurContext->addDecl(D);
8313  return D;
8314  }
8315 
8316  auto Build = [&](bool Invalid) {
8317  UsingDecl *UD =
8318  UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
8319  UsingName, HasTypenameKeyword);
8320  UD->setAccess(AS);
8321  CurContext->addDecl(UD);
8322  UD->setInvalidDecl(Invalid);
8323  return UD;
8324  };
8325  auto BuildInvalid = [&]{ return Build(true); };
8326  auto BuildValid = [&]{ return Build(false); };
8327 
8328  if (RequireCompleteDeclContext(SS, LookupContext))
8329  return BuildInvalid();
8330 
8331  // Look up the target name.
8332  LookupResult R(*this, NameInfo, LookupOrdinaryName);
8333 
8334  // Unlike most lookups, we don't always want to hide tag
8335  // declarations: tag names are visible through the using declaration
8336  // even if hidden by ordinary names, *except* in a dependent context
8337  // where it's important for the sanity of two-phase lookup.
8338  if (!IsInstantiation)
8339  R.setHideTags(false);
8340 
8341  // For the purposes of this lookup, we have a base object type
8342  // equal to that of the current context.
8343  if (CurContext->isRecord()) {
8345  Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
8346  }
8347 
8348  LookupQualifiedName(R, LookupContext);
8349 
8350  // Try to correct typos if possible. If constructor name lookup finds no
8351  // results, that means the named class has no explicit constructors, and we
8352  // suppressed declaring implicit ones (probably because it's dependent or
8353  // invalid).
8354  if (R.empty() &&
8356  if (TypoCorrection Corrected = CorrectTypo(
8357  R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
8358  llvm::make_unique<UsingValidatorCCC>(
8359  HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
8360  dyn_cast<CXXRecordDecl>(CurContext)),
8361  CTK_ErrorRecovery)) {
8362  // We reject any correction for which ND would be NULL.
8363  NamedDecl *ND = Corrected.getCorrectionDecl();
8364 
8365  // We reject candidates where DroppedSpecifier == true, hence the
8366  // literal '0' below.
8367  diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
8368  << NameInfo.getName() << LookupContext << 0
8369  << SS.getRange());
8370 
8371  // If we corrected to an inheriting constructor, handle it as one.
8372  auto *RD = dyn_cast<CXXRecordDecl>(ND);
8373  if (RD && RD->isInjectedClassName()) {
8374  // The parent of the injected class name is the class itself.
8375  RD = cast<CXXRecordDecl>(RD->getParent());
8376 
8377  // Fix up the information we'll use to build the using declaration.
8378  if (Corrected.WillReplaceSpecifier()) {
8380  Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
8381  QualifierLoc.getSourceRange());
8382  QualifierLoc = Builder.getWithLocInContext(Context);
8383  }
8384 
8385  // In this case, the name we introduce is the name of a derived class
8386  // constructor.
8387  auto *CurClass = cast<CXXRecordDecl>(CurContext);
8390  UsingName.setNamedTypeInfo(nullptr);
8391  for (auto *Ctor : LookupConstructors(RD))
8392  R.addDecl(Ctor);
8393  R.resolveKind();
8394  } else {
8395  // FIXME: Pick up all the declarations if we found an overloaded
8396  // function.
8397  UsingName.setName(ND->getDeclName());
8398  R.addDecl(ND);
8399  }
8400  } else {
8401  Diag(IdentLoc, diag::err_no_member)
8402  << NameInfo.getName() << LookupContext << SS.getRange();
8403  return BuildInvalid();
8404  }
8405  }
8406 
8407  if (R.isAmbiguous())
8408  return BuildInvalid();
8409 
8410  if (HasTypenameKeyword) {
8411  // If we asked for a typename and got a non-type decl, error out.
8412  if (!R.getAsSingle<TypeDecl>()) {
8413  Diag(IdentLoc, diag::err_using_typename_non_type);
8414  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8415  Diag((*I)->getUnderlyingDecl()->getLocation(),
8416  diag::note_using_decl_target);
8417  return BuildInvalid();
8418  }
8419  } else {
8420  // If we asked for a non-typename and we got a type, error out,
8421  // but only if this is an instantiation of an unresolved using
8422  // decl. Otherwise just silently find the type name.
8423  if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
8424  Diag(IdentLoc, diag::err_using_dependent_value_is_type);
8425  Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
8426  return BuildInvalid();
8427  }
8428  }
8429 
8430  // C++14 [namespace.udecl]p6:
8431  // A using-declaration shall not name a namespace.
8432  if (R.getAsSingle<NamespaceDecl>()) {
8433  Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
8434  << SS.getRange();
8435  return BuildInvalid();
8436  }
8437 
8438  // C++14 [namespace.udecl]p7:
8439  // A using-declaration shall not name a scoped enumerator.
8440  if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
8441  if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
8442  Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
8443  << SS.getRange();
8444  return BuildInvalid();
8445  }
8446  }
8447 
8448  UsingDecl *UD = BuildValid();
8449 
8450  // Some additional rules apply to inheriting constructors.
8451  if (UsingName.getName().getNameKind() ==
8453  // Suppress access diagnostics; the access check is instead performed at the
8454  // point of use for an inheriting constructor.
8455  R.suppressDiagnostics();
8457  return UD;
8458  }
8459 
8460  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8461  UsingShadowDecl *PrevDecl = nullptr;
8462  if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
8463  BuildUsingShadowDecl(S, UD, *I, PrevDecl);
8464  }
8465 
8466  return UD;
8467 }
8468 
8469 /// Additional checks for a using declaration referring to a constructor name.
8471  assert(!UD->hasTypename() && "expecting a constructor name");
8472 
8473  const Type *SourceType = UD->getQualifier()->getAsType();
8474  assert(SourceType &&
8475  "Using decl naming constructor doesn't have type in scope spec.");
8476  CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
8477 
8478  // Check whether the named type is a direct base class.
8479  bool AnyDependentBases = false;
8480  auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
8481  AnyDependentBases);
8482  if (!Base && !AnyDependentBases) {
8483  Diag(UD->getUsingLoc(),
8484  diag::err_using_decl_constructor_not_in_direct_base)
8485  << UD->getNameInfo().getSourceRange()
8486  << QualType(SourceType, 0) << TargetClass;
8487  UD->setInvalidDecl();
8488  return true;
8489  }
8490 
8491  if (Base)
8492  Base->setInheritConstructors();
8493 
8494  return false;
8495 }
8496 
8497 /// Checks that the given using declaration is not an invalid
8498 /// redeclaration. Note that this is checking only for the using decl
8499 /// itself, not for any ill-formedness among the UsingShadowDecls.
8501  bool HasTypenameKeyword,
8502  const CXXScopeSpec &SS,
8503  SourceLocation NameLoc,
8504  const LookupResult &Prev) {
8505  // C++03 [namespace.udecl]p8:
8506  // C++0x [namespace.udecl]p10:
8507  // A using-declaration is a declaration and can therefore be used
8508  // repeatedly where (and only where) multiple declarations are
8509  // allowed.
8510  //
8511  // That's in non-member contexts.
8513  return false;
8514 
8515  NestedNameSpecifier *Qual = SS.getScopeRep();
8516 
8517  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8518  NamedDecl *D = *I;
8519 
8520  bool DTypename;
8521  NestedNameSpecifier *DQual;
8522  if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
8523  DTypename = UD->hasTypename();
8524  DQual = UD->getQualifier();
8525  } else if (UnresolvedUsingValueDecl *UD
8526  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8527  DTypename = false;
8528  DQual = UD->getQualifier();
8529  } else if (UnresolvedUsingTypenameDecl *UD
8530  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8531  DTypename = true;
8532  DQual = UD->getQualifier();
8533  } else continue;
8534 
8535  // using decls differ if one says 'typename' and the other doesn't.
8536  // FIXME: non-dependent using decls?
8537  if (HasTypenameKeyword != DTypename) continue;
8538 
8539  // using decls differ if they name different scopes (but note that
8540  // template instantiation can cause this check to trigger when it
8541  // didn't before instantiation).
8544  continue;
8545 
8546  Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
8547  Diag(D->getLocation(), diag::note_using_decl) << 1;
8548  return true;
8549  }
8550 
8551  return false;
8552 }
8553 
8554 
8555 /// Checks that the given nested-name qualifier used in a using decl
8556 /// in the current context is appropriately related to the current
8557 /// scope. If an error is found, diagnoses it and returns true.
8559  const CXXScopeSpec &SS,
8560  const DeclarationNameInfo &NameInfo,
8561  SourceLocation NameLoc) {
8562  DeclContext *NamedContext = computeDeclContext(SS);
8563 
8564  if (!CurContext->isRecord()) {
8565  // C++03 [namespace.udecl]p3:
8566  // C++0x [namespace.udecl]p8:
8567  // A using-declaration for a class member shall be a member-declaration.
8568 
8569  // If we weren't able to compute a valid scope, it must be a
8570  // dependent class scope.
8571  if (!NamedContext || NamedContext->getRedeclContext()->isRecord()) {
8572  auto *RD = NamedContext
8573  ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
8574  : nullptr;
8575  if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
8576  RD = nullptr;
8577 
8578  Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8579  << SS.getRange();
8580 
8581  // If we have a complete, non-dependent source type, try to suggest a
8582  // way to get the same effect.
8583  if (!RD)
8584  return true;
8585 
8586  // Find what this using-declaration was referring to.
8587  LookupResult R(*this, NameInfo, LookupOrdinaryName);
8588  R.setHideTags(false);
8589  R.suppressDiagnostics();
8590  LookupQualifiedName(R, RD);
8591 
8592  if (R.getAsSingle<TypeDecl>()) {
8593  if (getLangOpts().CPlusPlus11) {
8594  // Convert 'using X::Y;' to 'using Y = X::Y;'.
8595  Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8596  << 0 // alias declaration
8598  NameInfo.getName().getAsString() +
8599  " = ");
8600  } else {
8601  // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8602  SourceLocation InsertLoc =
8603  getLocForEndOfToken(NameInfo.getLocEnd());
8604  Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8605  << 1 // typedef declaration
8606  << FixItHint::CreateReplacement(UsingLoc, "typedef")
8608  InsertLoc, " " + NameInfo.getName().getAsString());
8609  }
8610  } else if (R.getAsSingle<VarDecl>()) {
8611  // Don't provide a fixit outside C++11 mode; we don't want to suggest
8612  // repeating the type of the static data member here.
8613  FixItHint FixIt;
8614  if (getLangOpts().CPlusPlus11) {
8615  // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8617  UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8618  }
8619 
8620  Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8621  << 2 // reference declaration
8622  << FixIt;
8623  } else if (R.getAsSingle<EnumConstantDecl>()) {
8624  // Don't provide a fixit outside C++11 mode; we don't want to suggest
8625  // repeating the type of the enumeration here, and we can't do so if
8626  // the type is anonymous.
8627  FixItHint FixIt;
8628  if (getLangOpts().CPlusPlus11) {
8629  // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8631  UsingLoc, "constexpr auto " + NameInfo.getName().getAsString() + " = ");
8632  }
8633 
8634  Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8635  << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
8636  << FixIt;
8637  }
8638  return true;
8639  }
8640 
8641  // Otherwise, everything is known to be fine.
8642  return false;
8643  }
8644 
8645  // The current scope is a record.
8646 
8647  // If the named context is dependent, we can't decide much.
8648  if (!NamedContext) {
8649  // FIXME: in C++0x, we can diagnose if we can prove that the
8650  // nested-name-specifier does not refer to a base class, which is
8651  // still possible in some cases.
8652 
8653  // Otherwise we have to conservatively report that things might be
8654  // okay.
8655  return false;
8656  }
8657 
8658  if (!NamedContext->isRecord()) {
8659  // Ideally this would point at the last name in the specifier,
8660  // but we don't have that level of source info.
8661  Diag(SS.getRange().getBegin(),
8662  diag::err_using_decl_nested_name_specifier_is_not_class)
8663  << SS.getScopeRep() << SS.getRange();
8664  return true;
8665  }
8666 
8667  if (!NamedContext->isDependentContext() &&
8668  RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8669  return true;
8670 
8671  if (getLangOpts().CPlusPlus11) {
8672  // C++11 [namespace.udecl]p3:
8673  // In a using-declaration used as a member-declaration, the
8674  // nested-name-specifier shall name a base class of the class
8675  // being defined.
8676 
8677  if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8678  cast<CXXRecordDecl>(NamedContext))) {
8679  if (CurContext == NamedContext) {
8680  Diag(NameLoc,
8681  diag::err_using_decl_nested_name_specifier_is_current_class)
8682  << SS.getRange();
8683  return true;
8684  }
8685 
8686  Diag(SS.getRange().getBegin(),
8687  diag::err_using_decl_nested_name_specifier_is_not_base_class)
8688  << SS.getScopeRep()
8689  << cast<CXXRecordDecl>(CurContext)
8690  << SS.getRange();
8691  return true;
8692  }
8693 
8694  return false;
8695  }
8696 
8697  // C++03 [namespace.udecl]p4:
8698  // A using-declaration used as a member-declaration shall refer
8699  // to a member of a base class of the class being defined [etc.].
8700 
8701  // Salient point: SS doesn't have to name a base class as long as
8702  // lookup only finds members from base classes. Therefore we can
8703  // diagnose here only if we can prove that that can't happen,
8704  // i.e. if the class hierarchies provably don't intersect.
8705 
8706  // TODO: it would be nice if "definitely valid" results were cached
8707  // in the UsingDecl and UsingShadowDecl so that these checks didn't
8708  // need to be repeated.
8709 
8710  llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
8711  auto Collect = [&Bases](const CXXRecordDecl *Base) {
8712  Bases.insert(Base);
8713  return true;
8714  };
8715 
8716  // Collect all bases. Return false if we find a dependent base.
8717  if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
8718  return false;
8719 
8720  // Returns true if the base is dependent or is one of the accumulated base
8721  // classes.
8722  auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
8723  return !Bases.count(Base);
8724  };
8725 
8726  // Return false if the class has a dependent base or if it or one
8727  // of its bases is present in the base set of the current context.
8728  if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
8729  !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
8730  return false;
8731 
8732  Diag(SS.getRange().getBegin(),
8733  diag::err_using_decl_nested_name_specifier_is_not_base_class)
8734  << SS.getScopeRep()
8735  << cast<CXXRecordDecl>(CurContext)
8736  << SS.getRange();
8737 
8738  return true;
8739 }
8740 
8742  AccessSpecifier AS,
8743  MultiTemplateParamsArg TemplateParamLists,
8744  SourceLocation UsingLoc,
8745  UnqualifiedId &Name,
8746  AttributeList *AttrList,
8747  TypeResult Type,
8748  Decl *DeclFromDeclSpec) {
8749  // Skip up to the relevant declaration scope.
8750  while (S->isTemplateParamScope())
8751  S = S->getParent();
8752  assert((S->getFlags() & Scope::DeclScope) &&
8753  "got alias-declaration outside of declaration scope");
8754 
8755  if (Type.isInvalid())
8756  return nullptr;
8757 
8758  bool Invalid = false;
8760  TypeSourceInfo *TInfo = nullptr;
8761  GetTypeFromParser(Type.get(), &TInfo);
8762 
8763  if (DiagnoseClassNameShadow(CurContext, NameInfo))
8764  return nullptr;
8765 
8768  Invalid = true;
8770  TInfo->getTypeLoc().getBeginLoc());
8771  }
8772 
8774  LookupName(Previous, S);
8775 
8776  // Warn about shadowing the name of a template parameter.
8777  if (Previous.isSingleResult() &&
8778  Previous.getFoundDecl()->isTemplateParameter()) {
8780  Previous.clear();
8781  }
8782 
8783  assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8784  "name in alias declaration must be an identifier");
8786  Name.StartLocation,
8787  Name.Identifier, TInfo);
8788 
8789  NewTD->setAccess(AS);
8790 
8791  if (Invalid)
8792  NewTD->setInvalidDecl();
8793 
8794  ProcessDeclAttributeList(S, NewTD, AttrList);
8795 
8797  Invalid |= NewTD->isInvalidDecl();
8798 
8799  bool Redeclaration = false;
8800 
8801  NamedDecl *NewND;
8802  if (TemplateParamLists.size()) {
8803  TypeAliasTemplateDecl *OldDecl = nullptr;
8804  TemplateParameterList *OldTemplateParams = nullptr;
8805 
8806  if (TemplateParamLists.size() != 1) {
8807  Diag(UsingLoc, diag::err_alias_template_extra_headers)
8808  << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8809  TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
8810  }
8811  TemplateParameterList *TemplateParams = TemplateParamLists[0];
8812 
8813  // Check that we can declare a template here.
8814  if (CheckTemplateDeclScope(S, TemplateParams))
8815  return nullptr;
8816 
8817  // Only consider previous declarations in the same scope.
8818  FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8819  /*ExplicitInstantiationOrSpecialization*/false);
8820  if (!Previous.empty()) {
8821  Redeclaration = true;
8822 
8823  OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8824  if (!OldDecl && !Invalid) {
8825  Diag(UsingLoc, diag::err_redefinition_different_kind)
8826  << Name.Identifier;
8827 
8828  NamedDecl *OldD = Previous.getRepresentativeDecl();
8829  if (OldD->getLocation().isValid())
8830  Diag(OldD->getLocation(), diag::note_previous_definition);
8831 
8832  Invalid = true;
8833  }
8834 
8835  if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8836  if (TemplateParameterListsAreEqual(TemplateParams,
8837  OldDecl->getTemplateParameters(),
8838  /*Complain=*/true,
8840  OldTemplateParams = OldDecl->getTemplateParameters();
8841  else
8842  Invalid = true;
8843 
8844  TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8845  if (!Invalid &&
8847  NewTD->getUnderlyingType())) {
8848  // FIXME: The C++0x standard does not clearly say this is ill-formed,
8849  // but we can't reasonably accept it.
8850  Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8851  << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8852  if (OldTD->getLocation().isValid())
8853  Diag(OldTD->getLocation(), diag::note_previous_definition);
8854  Invalid = true;
8855  }
8856  }
8857  }
8858 
8859  // Merge any previous default template arguments into our parameters,
8860  // and check the parameter list.
8861  if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8863  return nullptr;
8864 
8865  TypeAliasTemplateDecl *NewDecl =
8867  Name.Identifier, TemplateParams,
8868  NewTD);
8869  NewTD->setDescribedAliasTemplate(NewDecl);
8870 
8871  NewDecl->setAccess(AS);
8872 
8873  if (Invalid)
8874  NewDecl->setInvalidDecl();
8875  else if (OldDecl)
8876  NewDecl->setPreviousDecl(OldDecl);
8877 
8878  NewND = NewDecl;
8879  } else {
8880  if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
8881  setTagNameForLinkagePurposes(TD, NewTD);
8882  handleTagNumbering(TD, S);
8883  }
8884  ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8885  NewND = NewTD;
8886  }
8887 
8888  PushOnScopeChains(NewND, S);
8889  ActOnDocumentableDecl(NewND);
8890  return NewND;
8891 }
8892 
8894  SourceLocation AliasLoc,
8895  IdentifierInfo *Alias, CXXScopeSpec &SS,
8896  SourceLocation IdentLoc,
8897  IdentifierInfo *Ident) {
8898 
8899  // Lookup the namespace name.
8900  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8901  LookupParsedName(R, S, &SS);
8902 
8903  if (R.isAmbiguous())
8904  return nullptr;
8905 
8906  if (R.empty()) {
8907  if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
8908  Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8909  return nullptr;
8910  }
8911  }
8912  assert(!R.isAmbiguous() && !R.empty());
8913  NamedDecl *ND = R.getRepresentativeDecl();
8914 
8915  // Check if we have a previous declaration with the same name.
8916  LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
8918  LookupName(PrevR, S);
8919 
8920  // Check we're not shadowing a template parameter.
8921  if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
8922  DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
8923  PrevR.clear();
8924  }
8925 
8926  // Filter out any other lookup result from an enclosing scope.
8927  FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
8928  /*AllowInlineNamespace*/false);
8929 
8930  // Find the previous declaration and check that we can redeclare it.
8931  NamespaceAliasDecl *Prev = nullptr;
8932  if (PrevR.isSingleResult()) {
8933  NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
8934  if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8935  // We already have an alias with the same name that points to the same
8936  // namespace; check that it matches.
8937  if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
8938  Prev = AD;
8939  } else if (isVisible(PrevDecl)) {
8940  Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8941  << Alias;
8942  Diag(AD->getLocation(), diag::note_previous_namespace_alias)
8943  << AD->getNamespace();
8944  return nullptr;
8945  }
8946  } else if (isVisible(PrevDecl)) {
8947  unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
8948  ? diag::err_redefinition
8949  : diag::err_redefinition_different_kind;
8950  Diag(AliasLoc, DiagID) << Alias;
8951  Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8952  return nullptr;
8953  }
8954  }
8955 
8956  // The use of a nested name specifier may trigger deprecation warnings.
8957  DiagnoseUseOfDecl(ND, IdentLoc);
8958 
8959  NamespaceAliasDecl *AliasDecl =
8960  NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
8961  Alias, SS.getWithLocInContext(Context),
8962  IdentLoc, ND);
8963  if (Prev)
8964  AliasDecl->setPreviousDecl(Prev);
8965 
8966  PushOnScopeChains(AliasDecl, S);
8967  return AliasDecl;
8968 }
8969 
8972  CXXMethodDecl *MD) {
8973  CXXRecordDecl *ClassDecl = MD->getParent();
8974 
8975  // C++ [except.spec]p14:
8976  // An implicitly declared special member function (Clause 12) shall have an
8977  // exception-specification. [...]
8978  ImplicitExceptionSpecification ExceptSpec(*this);
8979  if (ClassDecl->isInvalidDecl())
8980  return ExceptSpec;
8981 
8982  // Direct base-class constructors.
8983  for (const auto &B : ClassDecl->bases()) {
8984  if (B.isVirtual()) // Handled below.
8985  continue;
8986 
8987  if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8988  CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8989  CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8990  // If this is a deleted function, add it anyway. This might be conformant
8991  // with the standard. This might not. I'm not sure. It might not matter.
8992  if (Constructor)
8993  ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8994  }
8995  }
8996 
8997  // Virtual base-class constructors.
8998  for (const auto &B : ClassDecl->vbases()) {
8999  if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
9000  CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9001  CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
9002  // If this is a deleted function, add it anyway. This might be conformant
9003  // with the standard. This might not. I'm not sure. It might not matter.
9004  if (Constructor)
9005  ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
9006  }
9007  }
9008 
9009  // Field constructors.
9010  for (const auto *F : ClassDecl->fields()) {
9011  if (F->hasInClassInitializer()) {
9012  if (Expr *E = F->getInClassInitializer())
9013  ExceptSpec.CalledExpr(E);
9014  } else if (const RecordType *RecordTy
9015  = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
9016  CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9017  CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
9018  // If this is a deleted function, add it anyway. This might be conformant
9019  // with the standard. This might not. I'm not sure. It might not matter.
9020  // In particular, the problem is that this function never gets called. It
9021  // might just be ill-formed because this function attempts to refer to
9022  // a deleted function here.
9023  if (Constructor)
9024  ExceptSpec.CalledDecl(F->getLocation(), Constructor);
9025  }
9026  }
9027 
9028  return ExceptSpec;
9029 }
9030 
9033  CXXConstructorDecl *CD) {
9034  CXXRecordDecl *ClassDecl = CD->getParent();
9035 
9036  // C++ [except.spec]p14:
9037  // An inheriting constructor [...] shall have an exception-specification. [...]
9038  ImplicitExceptionSpecification ExceptSpec(*this);
9039  if (ClassDecl->isInvalidDecl())
9040  return ExceptSpec;
9041 
9042  auto Inherited = CD->getInheritedConstructor();
9043  InheritedConstructorInfo ICI(*this, Loc, Inherited.getShadowDecl());
9044 
9045  // Direct and virtual base-class constructors.
9046  for (bool VBase : {false, true}) {
9047  for (CXXBaseSpecifier &B :
9048  VBase ? ClassDecl->vbases() : ClassDecl->bases()) {
9049  // Don't visit direct vbases twice.
9050  if (B.isVirtual() != VBase)
9051  continue;
9052 
9053  CXXRecordDecl *BaseClass = B.getType()->getAsCXXRecordDecl();
9054  if (!BaseClass)
9055  continue;
9056 
9057  CXXConstructorDecl *Constructor =
9058  ICI.findConstructorForBase(BaseClass, Inherited.getConstructor())
9059  .first;
9060  if (!Constructor)
9061  Constructor = LookupDefaultConstructor(BaseClass);
9062  if (Constructor)
9063  ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
9064  }
9065  }
9066 
9067  // Field constructors.
9068  for (const auto *F : ClassDecl->fields()) {
9069  if (F->hasInClassInitializer()) {
9070  if (Expr *E = F->getInClassInitializer())
9071  ExceptSpec.CalledExpr(E);
9072  } else if (const RecordType *RecordTy
9073  = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
9074  CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9075  CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
9076  if (Constructor)
9077  ExceptSpec.CalledDecl(F->getLocation(), Constructor);
9078  }
9079  }
9080 
9081  return ExceptSpec;
9082 }
9083 
9084 namespace {
9085 /// RAII object to register a special member as being currently declared.
9086 struct DeclaringSpecialMember {
9087  Sema &S;
9089  Sema::ContextRAII SavedContext;
9090  bool WasAlreadyBeingDeclared;
9091 
9092  DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
9093  : S(S), D(RD, CSM), SavedContext(S, RD) {
9094  WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
9095  if (WasAlreadyBeingDeclared)
9096  // This almost never happens, but if it does, ensure that our cache
9097  // doesn't contain a stale result.
9098  S.SpecialMemberCache.clear();
9099 
9100  // FIXME: Register a note to be produced if we encounter an error while
9101  // declaring the special member.
9102  }
9103  ~DeclaringSpecialMember() {
9104  if (!WasAlreadyBeingDeclared)
9105  S.SpecialMembersBeingDeclared.erase(D);
9106  }
9107 
9108  /// \brief Are we already trying to declare this special member?
9109  bool isAlreadyBeingDeclared() const {
9110  return WasAlreadyBeingDeclared;
9111  }
9112 };
9113 }
9114 
9116  // Look up any existing declarations, but don't trigger declaration of all
9117  // implicit special members with this name.
9118  DeclarationName Name = FD->getDeclName();
9121  for (auto *D : FD->getParent()->lookup(Name))
9122  if (auto *Acceptable = R.getAcceptableDecl(D))
9123  R.addDecl(Acceptable);
9124  R.resolveKind();
9125  R.suppressDiagnostics();
9126 
9127  CheckFunctionDeclaration(S, FD, R, /*IsExplicitSpecialization*/false);
9128 }
9129 
9131  CXXRecordDecl *ClassDecl) {
9132  // C++ [class.ctor]p5:
9133  // A default constructor for a class X is a constructor of class X
9134  // that can be called without an argument. If there is no
9135  // user-declared constructor for class X, a default constructor is
9136  // implicitly declared. An implicitly-declared default constructor
9137  // is an inline public member of its class.
9138  assert(ClassDecl->needsImplicitDefaultConstructor() &&
9139  "Should not build implicit default constructor!");
9140 
9141  DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
9142  if (DSM.isAlreadyBeingDeclared())
9143  return nullptr;
9144 
9145  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9147  false);
9148 
9149  // Create the actual constructor declaration.
9150  CanQualType ClassType
9152  SourceLocation ClassLoc = ClassDecl->getLocation();
9153  DeclarationName Name
9155  DeclarationNameInfo NameInfo(Name, ClassLoc);
9157  Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
9158  /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
9159  /*isImplicitlyDeclared=*/true, Constexpr);
9160  DefaultCon->setAccess(AS_public);
9161  DefaultCon->setDefaulted();
9162 
9163  if (getLangOpts().CUDA) {
9165  DefaultCon,
9166  /* ConstRHS */ false,
9167  /* Diagnose */ false);
9168  }
9169 
9170  // Build an exception specification pointing back at this constructor.
9171  FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
9172  DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9173 
9174  // We don't need to use SpecialMemberIsTrivial here; triviality for default
9175  // constructors is easy to compute.
9176  DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
9177 
9178  // Note that we have declared this constructor.
9180 
9181  Scope *S = getScopeForContext(ClassDecl);
9183 
9185  SetDeclDeleted(DefaultCon, ClassLoc);
9186 
9187  if (S)
9188  PushOnScopeChains(DefaultCon, S, false);
9189  ClassDecl->addDecl(DefaultCon);
9190 
9191  return DefaultCon;
9192 }
9193 
9195  CXXConstructorDecl *Constructor) {
9196  assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
9197  !Constructor->doesThisDeclarationHaveABody() &&
9198  !Constructor->isDeleted()) &&
9199  "DefineImplicitDefaultConstructor - call it for implicit default ctor");
9200 
9201  CXXRecordDecl *ClassDecl = Constructor->getParent();
9202  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
9203 
9204  SynthesizedFunctionScope Scope(*this, Constructor);
9205  DiagnosticErrorTrap Trap(Diags);
9206  if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9207  Trap.hasErrorOccurred()) {
9208  Diag(CurrentLocation, diag::note_member_synthesized_at)
9209  << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
9210  Constructor->setInvalidDecl();
9211  return;
9212  }
9213 
9214  // The exception specification is needed because we are defining the
9215  // function.
9216  ResolveExceptionSpec(CurrentLocation,
9217  Constructor->getType()->castAs<FunctionProtoType>());
9218 
9219  SourceLocation Loc = Constructor->getLocEnd().isValid()
9220  ? Constructor->getLocEnd()
9221  : Constructor->getLocation();
9222  Constructor->setBody(new (Context) CompoundStmt(Loc));
9223 
9224  Constructor->markUsed(Context);
9225  MarkVTableUsed(CurrentLocation, ClassDecl);
9226 
9228  L->CompletedImplicitDefinition(Constructor);
9229  }
9230 
9231  DiagnoseUninitializedFields(*this, Constructor);
9232 }
9233 
9235  // Perform any delayed checks on exception specifications.
9237 }
9238 
9239 /// Find or create the fake constructor we synthesize to model constructing an
9240 /// object of a derived class via a constructor of a base class.
9243  CXXConstructorDecl *BaseCtor,
9244  ConstructorUsingShadowDecl *Shadow) {
9245  CXXRecordDecl *Derived = Shadow->getParent();
9246  SourceLocation UsingLoc = Shadow->getLocation();
9247 
9248  // FIXME: Add a new kind of DeclarationName for an inherited constructor.
9249  // For now we use the name of the base class constructor as a member of the
9250  // derived class to indicate a (fake) inherited constructor name.
9251  DeclarationName Name = BaseCtor->getDeclName();
9252 
9253  // Check to see if we already have a fake constructor for this inherited
9254  // constructor call.
9255  for (NamedDecl *Ctor : Derived->lookup(Name))
9256  if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
9257  ->getInheritedConstructor()
9258  .getConstructor(),
9259  BaseCtor))
9260  return cast<CXXConstructorDecl>(Ctor);
9261 
9262  DeclarationNameInfo NameInfo(Name, UsingLoc);
9263  TypeSourceInfo *TInfo =
9264  Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
9265  FunctionProtoTypeLoc ProtoLoc =
9267 
9268  // Check the inherited constructor is valid and find the list of base classes
9269  // from which it was inherited.
9270  InheritedConstructorInfo ICI(*this, Loc, Shadow);
9271 
9272  bool Constexpr =
9273  BaseCtor->isConstexpr() &&
9275  false, BaseCtor, &ICI);
9276 
9278  Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
9279  BaseCtor->isExplicit(), /*Inline=*/true,
9280  /*ImplicitlyDeclared=*/true, Constexpr,
9281  InheritedConstructor(Shadow, BaseCtor));
9282  if (Shadow->isInvalidDecl())
9283  DerivedCtor->setInvalidDecl();
9284 
9285  // Build an unevaluated exception specification for this fake constructor.
9286  const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
9289  EPI.ExceptionSpec.SourceDecl = DerivedCtor;
9290  DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
9291  FPT->getParamTypes(), EPI));
9292 
9293  // Build the parameter declarations.
9294  SmallVector<ParmVarDecl *, 16> ParamDecls;
9295  for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
9296  TypeSourceInfo *TInfo =
9299  Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
9300  FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
9301  PD->setScopeInfo(0, I);
9302  PD->setImplicit();
9303  // Ensure attributes are propagated onto parameters (this matters for
9304  // format, pass_object_size, ...).
9305  mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
9306  ParamDecls.push_back(PD);
9307  ProtoLoc.setParam(I, PD);
9308  }
9309 
9310  // Set up the new constructor.
9311  assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
9312  DerivedCtor->setAccess(BaseCtor->getAccess());
9313  DerivedCtor->setParams(ParamDecls);
9314  Derived->addDecl(DerivedCtor);
9315 
9316  if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
9317  SetDeclDeleted(DerivedCtor, UsingLoc);
9318 
9319  return DerivedCtor;
9320 }
9321 
9323  InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
9326  /*Diagnose*/true);
9327 }
9328 
9330  CXXConstructorDecl *Constructor) {
9331  CXXRecordDecl *ClassDecl = Constructor->getParent();
9332  assert(Constructor->getInheritedConstructor() &&
9333  !Constructor->doesThisDeclarationHaveABody() &&
9334  !Constructor->isDeleted());
9335  if (Constructor->isInvalidDecl())
9336  return;
9337 
9338  ConstructorUsingShadowDecl *Shadow =
9339  Constructor->getInheritedConstructor().getShadowDecl();
9340  CXXConstructorDecl *InheritedCtor =
9341  Constructor->getInheritedConstructor().getConstructor();
9342 
9343  // [class.inhctor.init]p1:
9344  // initialization proceeds as if a defaulted default constructor is used to
9345  // initialize the D object and each base class subobject from which the
9346  // constructor was inherited
9347 
9348  InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
9349  CXXRecordDecl *RD = Shadow->getParent();
9350  SourceLocation InitLoc = Shadow->getLocation();
9351 
9352  // Initializations are performed "as if by a defaulted default constructor",
9353  // so enter the appropriate scope.
9354  SynthesizedFunctionScope Scope(*this, Constructor);
9355  DiagnosticErrorTrap Trap(Diags);
9356 
9357  // Build explicit initializers for all base classes from which the
9358  // constructor was inherited.
9360  for (bool VBase : {false, true}) {
9361  for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
9362  if (B.isVirtual() != VBase)
9363  continue;
9364 
9365  auto *BaseRD = B.getType()->getAsCXXRecordDecl();
9366  if (!BaseRD)
9367  continue;
9368 
9369  auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
9370  if (!BaseCtor.first)
9371  continue;
9372 
9373  MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
9375  InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
9376 
9377  auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
9378  Inits.push_back(new (Context) CXXCtorInitializer(
9379  Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
9380  SourceLocation()));
9381  }
9382  }
9383 
9384  // We now proceed as if for a defaulted default constructor, with the relevant
9385  // initializers replaced.
9386 
9387  bool HadError = SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits);
9388  if (HadError || Trap.hasErrorOccurred()) {
9389  Diag(CurrentLocation, diag::note_inhctor_synthesized_at) << RD;
9390  Constructor->setInvalidDecl();
9391  return;
9392  }
9393 
9394  // The exception specification is needed because we are defining the
9395  // function.
9396  ResolveExceptionSpec(CurrentLocation,
9397  Constructor->getType()->castAs<FunctionProtoType>());
9398 
9399  Constructor->setBody(new (Context) CompoundStmt(InitLoc));
9400 
9401  Constructor->markUsed(Context);
9402  MarkVTableUsed(CurrentLocation, ClassDecl);
9403 
9405  L->CompletedImplicitDefinition(Constructor);
9406  }
9407 
9408  DiagnoseUninitializedFields(*this, Constructor);
9409 }
9410 
9413  CXXRecordDecl *ClassDecl = MD->getParent();
9414 
9415  // C++ [except.spec]p14:
9416  // An implicitly declared special member function (Clause 12) shall have
9417  // an exception-specification.
9418  ImplicitExceptionSpecification ExceptSpec(*this);
9419  if (ClassDecl->isInvalidDecl())
9420  return ExceptSpec;
9421 
9422  // Direct base-class destructors.
9423  for (const auto &B : ClassDecl->bases()) {
9424  if (B.isVirtual()) // Handled below.
9425  continue;
9426 
9427  if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9428  ExceptSpec.CalledDecl(B.getLocStart(),
9429  LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9430  }
9431 
9432  // Virtual base-class destructors.
9433  for (const auto &B : ClassDecl->vbases()) {
9434  if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9435  ExceptSpec.CalledDecl(B.getLocStart(),
9436  LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9437  }
9438 
9439  // Field destructors.
9440  for (const auto *F : ClassDecl->fields()) {
9441  if (const RecordType *RecordTy
9442  = Context.getBaseElementType(F->getType())->getAs<RecordType>())
9443  ExceptSpec.CalledDecl(F->getLocation(),
9444  LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
9445  }
9446 
9447  return ExceptSpec;
9448 }
9449 
9451  // C++ [class.dtor]p2:
9452  // If a class has no user-declared destructor, a destructor is
9453  // declared implicitly. An implicitly-declared destructor is an
9454  // inline public member of its class.
9455  assert(ClassDecl->needsImplicitDestructor());
9456 
9457  DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9458  if (DSM.isAlreadyBeingDeclared())
9459  return nullptr;
9460 
9461  // Create the actual destructor declaration.
9462  CanQualType ClassType
9464  SourceLocation ClassLoc = ClassDecl->getLocation();
9465  DeclarationName Name
9467  DeclarationNameInfo NameInfo(Name, ClassLoc);
9468  CXXDestructorDecl *Destructor
9469  = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
9470  QualType(), nullptr, /*isInline=*/true,
9471  /*isImplicitlyDeclared=*/true);
9472  Destructor->setAccess(AS_public);
9473  Destructor->setDefaulted();
9474 
9475  if (getLangOpts().CUDA) {
9477  Destructor,
9478  /* ConstRHS */ false,
9479  /* Diagnose */ false);
9480  }
9481 
9482  // Build an exception specification pointing back at this destructor.
9483  FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
9484  Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9485 
9486  // We don't need to use SpecialMemberIsTrivial here; triviality for
9487  // destructors is easy to compute.
9488  Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9489 
9490  // Note that we have declared this destructor.
9492 
9493  Scope *S = getScopeForContext(ClassDecl);
9495 
9496  if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
9497  SetDeclDeleted(Destructor, ClassLoc);
9498 
9499  // Introduce this destructor into its scope.
9500  if (S)
9501  PushOnScopeChains(Destructor, S, false);
9502  ClassDecl->addDecl(Destructor);
9503 
9504  return Destructor;
9505 }
9506 
9508  CXXDestructorDecl *Destructor) {
9509  assert((Destructor->isDefaulted() &&
9510  !Destructor->doesThisDeclarationHaveABody() &&
9511  !Destructor->isDeleted()) &&
9512  "DefineImplicitDestructor - call it for implicit default dtor");
9513  CXXRecordDecl *ClassDecl = Destructor->getParent();
9514  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
9515 
9516  if (Destructor->isInvalidDecl())
9517  return;
9518 
9519  SynthesizedFunctionScope Scope(*this, Destructor);
9520 
9521  DiagnosticErrorTrap Trap(Diags);
9522  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9523  Destructor->getParent());
9524 
9525  if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
9526  Diag(CurrentLocation, diag::note_member_synthesized_at)
9527  << CXXDestructor << Context.getTagDeclType(ClassDecl);
9528 
9529  Destructor->setInvalidDecl();
9530  return;
9531  }
9532 
9533  // The exception specification is needed because we are defining the
9534  // function.
9535  ResolveExceptionSpec(CurrentLocation,
9536  Destructor->getType()->castAs<FunctionProtoType>());
9537 
9538  SourceLocation Loc = Destructor->getLocEnd().isValid()
9539  ? Destructor->getLocEnd()
9540  : Destructor->getLocation();
9541  Destructor->setBody(new (Context) CompoundStmt(Loc));
9542  Destructor->markUsed(Context);
9543  MarkVTableUsed(CurrentLocation, ClassDecl);
9544 
9546  L->CompletedImplicitDefinition(Destructor);
9547  }
9548 }
9549 
9550 /// \brief Perform any semantic analysis which needs to be delayed until all
9551 /// pending class member declarations have been parsed.
9553  // If the context is an invalid C++ class, just suppress these checks.
9554  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9555  if (Record->isInvalidDecl()) {
9558  return;
9559  }
9560  }
9561 }
9562 
9564  // Don't do anything for template patterns.
9565  if (Class->getDescribedClassTemplate())
9566  return;
9567 
9568  CallingConv ExpectedCallingConv = S.Context.getDefaultCallingConvention(
9569  /*IsVariadic=*/false, /*IsCXXMethod=*/true);
9570 
9571  CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
9572  for (Decl *Member : Class->decls()) {
9573  auto *CD = dyn_cast<CXXConstructorDecl>(Member);
9574  if (!CD) {
9575  // Recurse on nested classes.
9576  if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
9577  getDefaultArgExprsForConstructors(S, NestedRD);
9578  continue;
9579  } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
9580  continue;
9581  }
9582 
9583  CallingConv ActualCallingConv =
9584  CD->getType()->getAs<FunctionProtoType>()->getCallConv();
9585 
9586  // Skip default constructors with typical calling conventions and no default
9587  // arguments.
9588  unsigned NumParams = CD->getNumParams();
9589  if (ExpectedCallingConv == ActualCallingConv && NumParams == 0)
9590  continue;
9591 
9592  if (LastExportedDefaultCtor) {
9593  S.Diag(LastExportedDefaultCtor->getLocation(),
9594  diag::err_attribute_dll_ambiguous_default_ctor) << Class;
9595  S.Diag(CD->getLocation(), diag::note_entity_declared_at)
9596  << CD->getDeclName();
9597  return;
9598  }
9599  LastExportedDefaultCtor = CD;
9600 
9601  for (unsigned I = 0; I != NumParams; ++I) {
9602  // Skip any default arguments that we've already instantiated.
9604  continue;
9605 
9606  Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD,
9607  CD->getParamDecl(I)).get();
9609  S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
9610  }
9611  }
9612 }
9613 
9615  auto *RD = dyn_cast<CXXRecordDecl>(D);
9616 
9617  // Default constructors that are annotated with __declspec(dllexport) which
9618  // have default arguments or don't use the standard calling convention are
9619  // wrapped with a thunk called the default constructor closure.
9620  if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
9622 
9624 }
9625 
9627  if (!DelayedDllExportClasses.empty()) {
9628  // Calling ReferenceDllExportedMethods might cause the current function to
9629  // be called again, so use a local copy of DelayedDllExportClasses.
9631  std::swap(DelayedDllExportClasses, WorkList);
9632  for (CXXRecordDecl *Class : WorkList)
9633  ReferenceDllExportedMethods(*this, Class);
9634  }
9635 }
9636 
9638  CXXDestructorDecl *Destructor) {
9639  assert(getLangOpts().CPlusPlus11 &&
9640  "adjusting dtor exception specs was introduced in c++11");
9641 
9642  // C++11 [class.dtor]p3:
9643  // A declaration of a destructor that does not have an exception-
9644  // specification is implicitly considered to have the same exception-
9645  // specification as an implicit declaration.
9646  const FunctionProtoType *DtorType = Destructor->getType()->
9647  getAs<FunctionProtoType>();
9648  if (DtorType->hasExceptionSpec())
9649  return;
9650 
9651  // Replace the destructor's type, building off the existing one. Fortunately,
9652  // the only thing of interest in the destructor type is its extended info.
9653  // The return and arguments are fixed.
9656  EPI.ExceptionSpec.SourceDecl = Destructor;
9657  Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9658 
9659  // FIXME: If the destructor has a body that could throw, and the newly created
9660  // spec doesn't allow exceptions, we should emit a warning, because this
9661  // change in behavior can break conforming C++03 programs at runtime.
9662  // However, we don't have a body or an exception specification yet, so it
9663  // needs to be done somewhere else.
9664 }
9665 
9666 namespace {
9667 /// \brief An abstract base class for all helper classes used in building the
9668 // copy/move operators. These classes serve as factory functions and help us
9669 // avoid using the same Expr* in the AST twice.
9670 class ExprBuilder {
9671  ExprBuilder(const ExprBuilder&) = delete;
9672  ExprBuilder &operator=(const ExprBuilder&) = delete;
9673 
9674 protected:
9675  static Expr *assertNotNull(Expr *E) {
9676  assert(E && "Expression construction must not fail.");
9677  return E;
9678  }
9679 
9680 public:
9681  ExprBuilder() {}
9682  virtual ~ExprBuilder() {}
9683 
9684  virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9685 };
9686 
9687 class RefBuilder: public ExprBuilder {
9688  VarDecl *Var;
9689  QualType VarType;
9690 
9691 public:
9692  Expr *build(Sema &S, SourceLocation Loc) const override {
9693  return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
9694  }
9695 
9696  RefBuilder(VarDecl *Var, QualType VarType)
9697  : Var(Var), VarType(VarType) {}
9698 };
9699 
9700 class ThisBuilder: public ExprBuilder {
9701 public:
9702  Expr *build(Sema &S, SourceLocation Loc) const override {
9703  return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
9704  }
9705 };
9706 
9707 class CastBuilder: public ExprBuilder {
9708  const ExprBuilder &Builder;
9709  QualType Type;
9711  const CXXCastPath &Path;
9712 
9713 public:
9714  Expr *build(Sema &S, SourceLocation Loc) const override {
9715  return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9716  CK_UncheckedDerivedToBase, Kind,
9717  &Path).get());
9718  }
9719 
9720  CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9721  const CXXCastPath &Path)
9722  : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9723 };
9724 
9725 class DerefBuilder: public ExprBuilder {
9726  const ExprBuilder &Builder;
9727 
9728 public:
9729  Expr *build(Sema &S, SourceLocation Loc) const override {
9730  return assertNotNull(
9731  S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
9732  }
9733 
9734  DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9735 };
9736 
9737 class MemberBuilder: public ExprBuilder {
9738  const ExprBuilder &Builder;
9739  QualType Type;
9740  CXXScopeSpec SS;
9741  bool IsArrow;
9742  LookupResult &MemberLookup;
9743 
9744 public:
9745  Expr *build(Sema &S, SourceLocation Loc) const override {
9746  return assertNotNull(S.BuildMemberReferenceExpr(
9747  Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
9748  nullptr, MemberLookup, nullptr, nullptr).get());
9749  }
9750 
9751  MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9752  LookupResult &MemberLookup)
9753  : Builder(Builder), Type(Type), IsArrow(IsArrow),
9754  MemberLookup(MemberLookup) {}
9755 };
9756 
9757 class MoveCastBuilder: public ExprBuilder {
9758  const ExprBuilder &Builder;
9759 
9760 public:
9761  Expr *build(Sema &S, SourceLocation Loc) const override {
9762  return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9763  }
9764 
9765  MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9766 };
9767 
9768 class LvalueConvBuilder: public ExprBuilder {
9769  const ExprBuilder &Builder;
9770 
9771 public:
9772  Expr *build(Sema &S, SourceLocation Loc) const override {
9773  return assertNotNull(
9774  S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
9775  }
9776 
9777  LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9778 };
9779 
9780 class SubscriptBuilder: public ExprBuilder {
9781  const ExprBuilder &Base;
9782  const ExprBuilder &Index;
9783 
9784 public:
9785  Expr *build(Sema &S, SourceLocation Loc) const override {
9786  return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
9787  Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
9788  }
9789 
9790  SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9791  : Base(Base), Index(Index) {}
9792 };
9793 
9794 } // end anonymous namespace
9795 
9796 /// When generating a defaulted copy or move assignment operator, if a field
9797 /// should be copied with __builtin_memcpy rather than via explicit assignments,
9798 /// do so. This optimization only applies for arrays of scalars, and for arrays
9799 /// of class type where the selected copy/move-assignment operator is trivial.
9800 static StmtResult
9802  const ExprBuilder &ToB, const ExprBuilder &FromB) {
9803  // Compute the size of the memory buffer to be copied.
9804  QualType SizeType = S.Context.getSizeType();
9805  llvm::APInt Size(S.Context.getTypeSize(SizeType),
9807 
9808  // Take the address of the field references for "from" and "to". We
9809  // directly construct UnaryOperators here because semantic analysis
9810  // does not permit us to take the address of an xvalue.
9811  Expr *From = FromB.build(S, Loc);
9812  From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9813  S.Context.getPointerType(From->getType()),
9814  VK_RValue, OK_Ordinary, Loc);
9815  Expr *To = ToB.build(S, Loc);
9816  To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9817  S.Context.getPointerType(To->getType()),
9818  VK_RValue, OK_Ordinary, Loc);
9819 
9820  const Type *E = T->getBaseElementTypeUnsafe();
9821  bool NeedsCollectableMemCpy =
9822  E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9823 
9824  // Create a reference to the __builtin_objc_memmove_collectable function
9825  StringRef MemCpyName = NeedsCollectableMemCpy ?
9826  "__builtin_objc_memmove_collectable" :
9827  "__builtin_memcpy";
9828  LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9830  S.LookupName(R, S.TUScope, true);
9831 
9832  FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9833  if (!MemCpy)
9834  // Something went horribly wrong earlier, and we will have complained
9835  // about it.
9836  return StmtError();
9837 
9838  ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
9839  VK_RValue, Loc, nullptr);
9840  assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9841 
9842  Expr *CallArgs[] = {
9843  To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9844  };
9845  ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
9846  Loc, CallArgs, Loc);
9847 
9848  assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
9849  return Call.getAs<Stmt>();
9850 }
9851 
9852 /// \brief Builds a statement that copies/moves the given entity from \p From to
9853 /// \c To.
9854 ///
9855 /// This routine is used to copy/move the members of a class with an
9856 /// implicitly-declared copy/move assignment operator. When the entities being
9857 /// copied are arrays, this routine builds for loops to copy them.
9858 ///
9859 /// \param S The Sema object used for type-checking.
9860 ///
9861 /// \param Loc The location where the implicit copy/move is being generated.
9862 ///
9863 /// \param T The type of the expressions being copied/moved. Both expressions
9864 /// must have this type.
9865 ///
9866 /// \param To The expression we are copying/moving to.
9867 ///
9868 /// \param From The expression we are copying/moving from.
9869 ///
9870 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
9871 /// Otherwise, it's a non-static member subobject.
9872 ///
9873 /// \param Copying Whether we're copying or moving.
9874 ///
9875 /// \param Depth Internal parameter recording the depth of the recursion.
9876 ///
9877 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9878 /// if a memcpy should be used instead.
9879 static StmtResult
9881  const ExprBuilder &To, const ExprBuilder &From,
9882  bool CopyingBaseSubobject, bool Copying,
9883  unsigned Depth = 0) {
9884  // C++11 [class.copy]p28:
9885  // Each subobject is assigned in the manner appropriate to its type:
9886  //
9887  // - if the subobject is of class type, as if by a call to operator= with
9888  // the subobject as the object expression and the corresponding
9889  // subobject of x as a single function argument (as if by explicit
9890  // qualification; that is, ignoring any possible virtual overriding
9891  // functions in more derived classes);
9892  //
9893  // C++03 [class.copy]p13:
9894  // - if the subobject is of class type, the copy assignment operator for
9895  // the class is used (as if by explicit qualification; that is,
9896  // ignoring any possible virtual overriding functions in more derived
9897  // classes);
9898  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9899  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9900 
9901  // Look for operator=.
9902  DeclarationName Name
9904  LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9905  S.LookupQualifiedName(OpLookup, ClassDecl, false);
9906 
9907  // Prior to C++11, filter out any result that isn't a copy/move-assignment
9908  // operator.
9909  if (!S.getLangOpts().CPlusPlus11) {
9910  LookupResult::Filter F = OpLookup.makeFilter();
9911  while (F.hasNext()) {
9912  NamedDecl *D = F.next();
9913  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9914  if (Method->isCopyAssignmentOperator() ||
9915  (!Copying && Method->isMoveAssignmentOperator()))
9916  continue;
9917 
9918  F.erase();
9919  }
9920  F.done();
9921  }
9922 
9923  // Suppress the protected check (C++ [class.protected]) for each of the
9924  // assignment operators we found. This strange dance is required when
9925  // we're assigning via a base classes's copy-assignment operator. To
9926  // ensure that we're getting the right base class subobject (without
9927  // ambiguities), we need to cast "this" to that subobject type; to
9928  // ensure that we don't go through the virtual call mechanism, we need
9929  // to qualify the operator= name with the base class (see below). However,
9930  // this means that if the base class has a protected copy assignment
9931  // operator, the protected member access check will fail. So, we
9932  // rewrite "protected" access to "public" access in this case, since we
9933  // know by construction that we're calling from a derived class.
9934  if (CopyingBaseSubobject) {
9935  for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9936  L != LEnd; ++L) {
9937  if (L.getAccess() == AS_protected)
9938  L.setAccess(AS_public);
9939  }
9940  }
9941 
9942  // Create the nested-name-specifier that will be used to qualify the
9943  // reference to operator=; this is required to suppress the virtual
9944  // call mechanism.
9945  CXXScopeSpec SS;
9946  const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
9947  SS.MakeTrivial(S.Context,
9948  NestedNameSpecifier::Create(S.Context, nullptr, false,
9949  CanonicalT),
9950  Loc);
9951 
9952  // Create the reference to operator=.
9953  ExprResult OpEqualRef
9954  = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9955  SS, /*TemplateKWLoc=*/SourceLocation(),
9956  /*FirstQualifierInScope=*/nullptr,
9957  OpLookup,
9958  /*TemplateArgs=*/nullptr, /*S*/nullptr,
9959  /*SuppressQualifierCheck=*/true);
9960  if (OpEqualRef.isInvalid())
9961  return StmtError();
9962 
9963  // Build the call to the assignment operator.
9964 
9965  Expr *FromInst = From.build(S, Loc);
9966  ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
9967  OpEqualRef.getAs<Expr>(),
9968  Loc, FromInst, Loc);
9969  if (Call.isInvalid())
9970  return StmtError();
9971 
9972  // If we built a call to a trivial 'operator=' while copying an array,
9973  // bail out. We'll replace the whole shebang with a memcpy.
9974  CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9975  if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9976  return StmtResult((Stmt*)nullptr);
9977 
9978  // Convert to an expression-statement, and clean up any produced
9979  // temporaries.
9980  return S.ActOnExprStmt(Call);
9981  }
9982 
9983  // - if the subobject is of scalar type, the built-in assignment
9984  // operator is used.
9985  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
9986  if (!ArrayTy) {
9988  Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
9989  if (Assignment.isInvalid())
9990  return StmtError();
9991  return S.ActOnExprStmt(Assignment);
9992  }
9993 
9994  // - if the subobject is an array, each element is assigned, in the
9995  // manner appropriate to the element type;
9996 
9997  // Construct a loop over the array bounds, e.g.,
9998  //
9999  // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
10000  //
10001  // that will copy each of the array elements.
10002  QualType SizeType = S.Context.getSizeType();
10003 
10004  // Create the iteration variable.
10005  IdentifierInfo *IterationVarName = nullptr;
10006  {
10007  SmallString<8> Str;
10008  llvm::raw_svector_ostream OS(Str);
10009  OS << "__i" << Depth;
10010  IterationVarName = &S.Context.Idents.get(OS.str());
10011  }
10012  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10013  IterationVarName, SizeType,
10014  S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10015  SC_None);
10016 
10017  // Initialize the iteration variable to zero.
10018  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
10019  IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
10020 
10021  // Creates a reference to the iteration variable.
10022  RefBuilder IterationVarRef(IterationVar, SizeType);
10023  LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
10024 
10025  // Create the DeclStmt that holds the iteration variable.
10026  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
10027 
10028  // Subscript the "from" and "to" expressions with the iteration variable.
10029  SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
10030  MoveCastBuilder FromIndexMove(FromIndexCopy);
10031  const ExprBuilder *FromIndex;
10032  if (Copying)
10033  FromIndex = &FromIndexCopy;
10034  else
10035  FromIndex = &FromIndexMove;
10036 
10037  SubscriptBuilder ToIndex(To, IterationVarRefRVal);
10038 
10039  // Build the copy/move for an individual element of the array.
10040  StmtResult Copy =
10042  ToIndex, *FromIndex, CopyingBaseSubobject,
10043  Copying, Depth + 1);
10044  // Bail out if copying fails or if we determined that we should use memcpy.
10045  if (Copy.isInvalid() || !Copy.get())
10046  return Copy;
10047 
10048  // Create the comparison against the array bound.
10049  llvm::APInt Upper
10050  = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
10051  Expr *Comparison
10052  = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
10053  IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
10054  BO_NE, S.Context.BoolTy,
10055  VK_RValue, OK_Ordinary, Loc, false);
10056 
10057  // Create the pre-increment of the iteration variable.
10058  Expr *Increment
10059  = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
10060  SizeType, VK_LValue, OK_Ordinary, Loc);
10061 
10062  // Construct the loop that copies all elements of this array.
10063  return S.ActOnForStmt(
10064  Loc, Loc, InitStmt,
10065  S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
10066  S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
10067 }
10068 
10069 static StmtResult
10071  const ExprBuilder &To, const ExprBuilder &From,
10072  bool CopyingBaseSubobject, bool Copying) {
10073  // Maybe we should use a memcpy?
10074  if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
10076  return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
10077 
10079  CopyingBaseSubobject,
10080  Copying, 0));
10081 
10082  // If we ended up picking a trivial assignment operator for an array of a
10083  // non-trivially-copyable class type, just emit a memcpy.
10084  if (!Result.isInvalid() && !Result.get())
10085  return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
10086 
10087  return Result;
10088 }
10089 
10092  CXXRecordDecl *ClassDecl = MD->getParent();
10093 
10094  ImplicitExceptionSpecification ExceptSpec(*this);
10095  if (ClassDecl->isInvalidDecl())
10096  return ExceptSpec;
10097 
10098  const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10099  assert(T->getNumParams() == 1 && "not a copy assignment op");
10100  unsigned ArgQuals =
10102 
10103  // C++ [except.spec]p14:
10104  // An implicitly declared special member function (Clause 12) shall have an
10105  // exception-specification. [...]
10106 
10107  // It is unspecified whether or not an implicit copy assignment operator
10108  // attempts to deduplicate calls to assignment operators of virtual bases are
10109  // made. As such, this exception specification is effectively unspecified.
10110  // Based on a similar decision made for constness in C++0x, we're erring on
10111  // the side of assuming such calls to be made regardless of whether they
10112  // actually happen.
10113  for (const auto &Base : ClassDecl->bases()) {
10114  if (Base.isVirtual())
10115  continue;
10116 
10117  CXXRecordDecl *BaseClassDecl
10118  = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10119  if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10120  ArgQuals, false, 0))
10121  ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
10122  }
10123 
10124  for (const auto &Base : ClassDecl->vbases()) {
10125  CXXRecordDecl *BaseClassDecl
10126  = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10127  if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10128  ArgQuals, false, 0))
10129  ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
10130  }
10131 
10132  for (const auto *Field : ClassDecl->fields()) {
10133  QualType FieldType = Context.getBaseElementType(Field->getType());
10134  if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10135  if (CXXMethodDecl *CopyAssign =
10136  LookupCopyingAssignment(FieldClassDecl,
10137  ArgQuals | FieldType.getCVRQualifiers(),
10138  false, 0))
10139  ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
10140  }
10141  }
10142 
10143  return ExceptSpec;
10144 }
10145 
10147  // Note: The following rules are largely analoguous to the copy
10148  // constructor rules. Note that virtual bases are not taken into account
10149  // for determining the argument type of the operator. Note also that
10150  // operators taking an object instead of a reference are allowed.
10151  assert(ClassDecl->needsImplicitCopyAssignment());
10152 
10153  DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
10154  if (DSM.isAlreadyBeingDeclared())
10155  return nullptr;
10156 
10157  QualType ArgType = Context.getTypeDeclType(ClassDecl);
10158  QualType RetType = Context.getLValueReferenceType(ArgType);
10159  bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
10160  if (Const)
10161  ArgType = ArgType.withConst();
10162  ArgType = Context.getLValueReferenceType(ArgType);
10163 
10164  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10166  Const);
10167 
10168  // An implicitly-declared copy assignment operator is an inline public
10169  // member of its class.
10171  SourceLocation ClassLoc = ClassDecl->getLocation();
10172  DeclarationNameInfo NameInfo(Name, ClassLoc);
10173  CXXMethodDecl *CopyAssignment =
10174  CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10175  /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10176  /*isInline=*/true, Constexpr, SourceLocation());
10177  CopyAssignment->setAccess(AS_public);
10178  CopyAssignment->setDefaulted();
10179  CopyAssignment->setImplicit();
10180 
10181  if (getLangOpts().CUDA) {
10183  CopyAssignment,
10184  /* ConstRHS */ Const,
10185  /* Diagnose */ false);
10186  }
10187 
10188  // Build an exception specification pointing back at this member.
10190  getImplicitMethodEPI(*this, CopyAssignment);
10191  CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10192 
10193  // Add the parameter to the operator.
10194  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
10195  ClassLoc, ClassLoc,
10196  /*Id=*/nullptr, ArgType,
10197  /*TInfo=*/nullptr, SC_None,
10198  nullptr);
10199  CopyAssignment->setParams(FromParam);
10200 
10201  CopyAssignment->setTrivial(
10203  ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
10204  : ClassDecl->hasTrivialCopyAssignment());
10205 
10206  // Note that we have added this copy-assignment operator.
10208 
10209  Scope *S = getScopeForContext(ClassDecl);
10210  CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
10211 
10212  if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
10213  SetDeclDeleted(CopyAssignment, ClassLoc);
10214 
10215  if (S)
10216  PushOnScopeChains(CopyAssignment, S, false);
10217  ClassDecl->addDecl(CopyAssignment);
10218 
10219  return CopyAssignment;
10220 }
10221 
10222 /// Diagnose an implicit copy operation for a class which is odr-used, but
10223 /// which is deprecated because the class has a user-declared copy constructor,
10224 /// copy assignment operator, or destructor.
10226  SourceLocation UseLoc) {
10227  assert(CopyOp->isImplicit());
10228 
10229  CXXRecordDecl *RD = CopyOp->getParent();
10230  CXXMethodDecl *UserDeclaredOperation = nullptr;
10231 
10232  // In Microsoft mode, assignment operations don't affect constructors and
10233  // vice versa.
10234  if (RD->hasUserDeclaredDestructor()) {
10235  UserDeclaredOperation = RD->getDestructor();
10236  } else if (!isa<CXXConstructorDecl>(CopyOp) &&
10237  RD->hasUserDeclaredCopyConstructor() &&
10238  !S.getLangOpts().MSVCCompat) {
10239  // Find any user-declared copy constructor.
10240  for (auto *I : RD->ctors()) {
10241  if (I->isCopyConstructor()) {
10242  UserDeclaredOperation = I;
10243  break;
10244  }
10245  }
10246  assert(UserDeclaredOperation);
10247  } else if (isa<CXXConstructorDecl>(CopyOp) &&
10248  RD->hasUserDeclaredCopyAssignment() &&
10249  !S.getLangOpts().MSVCCompat) {
10250  // Find any user-declared move assignment operator.
10251  for (auto *I : RD->methods()) {
10252  if (I->isCopyAssignmentOperator()) {
10253  UserDeclaredOperation = I;
10254  break;
10255  }
10256  }
10257  assert(UserDeclaredOperation);
10258  }
10259 
10260  if (UserDeclaredOperation) {
10261  S.Diag(UserDeclaredOperation->getLocation(),
10262  diag::warn_deprecated_copy_operation)
10263  << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
10264  << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
10265  S.Diag(UseLoc, diag::note_member_synthesized_at)
10266  << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
10268  << RD;
10269  }
10270 }
10271 
10273  CXXMethodDecl *CopyAssignOperator) {
10274  assert((CopyAssignOperator->isDefaulted() &&
10275  CopyAssignOperator->isOverloadedOperator() &&
10276  CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
10277  !CopyAssignOperator->doesThisDeclarationHaveABody() &&
10278  !CopyAssignOperator->isDeleted()) &&
10279  "DefineImplicitCopyAssignment called for wrong function");
10280 
10281  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
10282 
10283  if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
10284  CopyAssignOperator->setInvalidDecl();
10285  return;
10286  }
10287 
10288  // C++11 [class.copy]p18:
10289  // The [definition of an implicitly declared copy assignment operator] is
10290  // deprecated if the class has a user-declared copy constructor or a
10291  // user-declared destructor.
10292  if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
10293  diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
10294 
10295  CopyAssignOperator->markUsed(Context);
10296 
10297  SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
10298  DiagnosticErrorTrap Trap(Diags);
10299 
10300  // C++0x [class.copy]p30:
10301  // The implicitly-defined or explicitly-defaulted copy assignment operator
10302  // for a non-union class X performs memberwise copy assignment of its
10303  // subobjects. The direct base classes of X are assigned first, in the
10304  // order of their declaration in the base-specifier-list, and then the
10305  // immediate non-static data members of X are assigned, in the order in
10306  // which they were declared in the class definition.
10307 
10308  // The statements that form the synthesized function body.
10309  SmallVector<Stmt*, 8> Statements;
10310 
10311  // The parameter for the "other" object, which we are copying from.
10312  ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
10313  Qualifiers OtherQuals = Other->getType().getQualifiers();
10314  QualType OtherRefType = Other->getType();
10315  if (const LValueReferenceType *OtherRef
10316  = OtherRefType->getAs<LValueReferenceType>()) {
10317  OtherRefType = OtherRef->getPointeeType();
10318  OtherQuals = OtherRefType.getQualifiers();
10319  }
10320 
10321  // Our location for everything implicitly-generated.
10322  SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
10323  ? CopyAssignOperator->getLocEnd()
10324  : CopyAssignOperator->getLocation();
10325 
10326  // Builds a DeclRefExpr for the "other" object.
10327  RefBuilder OtherRef(Other, OtherRefType);
10328 
10329  // Builds the "this" pointer.
10330  ThisBuilder This;
10331 
10332  // Assign base classes.
10333  bool Invalid = false;
10334  for (auto &Base : ClassDecl->bases()) {
10335  // Form the assignment:
10336  // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
10337  QualType BaseType = Base.getType().getUnqualifiedType();
10338  if (!BaseType->isRecordType()) {
10339  Invalid = true;
10340  continue;
10341  }
10342 
10343  CXXCastPath BasePath;
10344  BasePath.push_back(&Base);
10345 
10346  // Construct the "from" expression, which is an implicit cast to the
10347  // appropriately-qualified base type.
10348  CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
10349  VK_LValue, BasePath);
10350 
10351  // Dereference "this".
10352  DerefBuilder DerefThis(This);
10353  CastBuilder To(DerefThis,
10355  BaseType, CopyAssignOperator->getTypeQualifiers()),
10356  VK_LValue, BasePath);
10357 
10358  // Build the copy.
10359  StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
10360  To, From,
10361  /*CopyingBaseSubobject=*/true,
10362  /*Copying=*/true);
10363  if (Copy.isInvalid()) {
10364  Diag(CurrentLocation, diag::note_member_synthesized_at)
10365  << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10366  CopyAssignOperator->setInvalidDecl();
10367  return;
10368  }
10369 
10370  // Success! Record the copy.
10371  Statements.push_back(Copy.getAs<Expr>());
10372  }
10373 
10374  // Assign non-static members.
10375  for (auto *Field : ClassDecl->fields()) {
10376  // FIXME: We should form some kind of AST representation for the implied
10377  // memcpy in a union copy operation.
10378  if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
10379  continue;
10380 
10381  if (Field->isInvalidDecl()) {
10382  Invalid = true;
10383  continue;
10384  }
10385 
10386  // Check for members of reference type; we can't copy those.
10387  if (Field->getType()->isReferenceType()) {
10388  Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10389  << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10390  Diag(Field->getLocation(), diag::note_declared_at);
10391  Diag(CurrentLocation, diag::note_member_synthesized_at)
10392  << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10393  Invalid = true;
10394  continue;
10395  }
10396 
10397  // Check for members of const-qualified, non-class type.
10398  QualType BaseType = Context.getBaseElementType(Field->getType());
10399  if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10400  Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10401  << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10402  Diag(Field->getLocation(), diag::note_declared_at);
10403  Diag(CurrentLocation, diag::note_member_synthesized_at)
10404  << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10405  Invalid = true;
10406  continue;
10407  }
10408 
10409  // Suppress assigning zero-width bitfields.
10410  if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10411  continue;
10412 
10413  QualType FieldType = Field->getType().getNonReferenceType();
10414  if (FieldType->isIncompleteArrayType()) {
10415  assert(ClassDecl->hasFlexibleArrayMember() &&
10416  "Incomplete array type is not valid");
10417  continue;
10418  }
10419 
10420  // Build references to the field in the object we're copying from and to.
10421  CXXScopeSpec SS; // Intentionally empty
10422  LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10424  MemberLookup.addDecl(Field);
10425  MemberLookup.resolveKind();
10426 
10427  MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10428 
10429  MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
10430 
10431  // Build the copy of this field.
10432  StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
10433  To, From,
10434  /*CopyingBaseSubobject=*/false,
10435  /*Copying=*/true);
10436  if (Copy.isInvalid()) {
10437  Diag(CurrentLocation, diag::note_member_synthesized_at)
10438  << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10439  CopyAssignOperator->setInvalidDecl();
10440  return;
10441  }
10442 
10443  // Success! Record the copy.
10444  Statements.push_back(Copy.getAs<Stmt>());
10445  }
10446 
10447  if (!Invalid) {
10448  // Add a "return *this;"
10449  ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10450 
10451  StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10452  if (Return.isInvalid())
10453  Invalid = true;
10454  else {
10455  Statements.push_back(Return.getAs<Stmt>());
10456 
10457  if (Trap.hasErrorOccurred()) {
10458  Diag(CurrentLocation, diag::note_member_synthesized_at)
10459  << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10460  Invalid = true;
10461  }
10462  }
10463  }
10464 
10465  // The exception specification is needed because we are defining the
10466  // function.
10467  ResolveExceptionSpec(CurrentLocation,
10468  CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10469 
10470  if (Invalid) {
10471  CopyAssignOperator->setInvalidDecl();
10472  return;
10473  }
10474 
10475  StmtResult Body;
10476  {
10477  CompoundScopeRAII CompoundScope(*this);
10478  Body = ActOnCompoundStmt(Loc, Loc, Statements,
10479  /*isStmtExpr=*/false);
10480  assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10481  }
10482  CopyAssignOperator->setBody(Body.getAs<Stmt>());
10483 
10485  L->CompletedImplicitDefinition(CopyAssignOperator);
10486  }
10487 }
10488 
10491  CXXRecordDecl *ClassDecl = MD->getParent();
10492 
10493  ImplicitExceptionSpecification ExceptSpec(*this);
10494  if (ClassDecl->isInvalidDecl())
10495  return ExceptSpec;
10496 
10497  // C++0x [except.spec]p14:
10498  // An implicitly declared special member function (Clause 12) shall have an
10499  // exception-specification. [...]
10500 
10501  // It is unspecified whether or not an implicit move assignment operator
10502  // attempts to deduplicate calls to assignment operators of virtual bases are
10503  // made. As such, this exception specification is effectively unspecified.
10504  // Based on a similar decision made for constness in C++0x, we're erring on
10505  // the side of assuming such calls to be made regardless of whether they
10506  // actually happen.
10507  // Note that a move constructor is not implicitly declared when there are
10508  // virtual bases, but it can still be user-declared and explicitly defaulted.
10509  for (const auto &Base : ClassDecl->bases()) {
10510  if (Base.isVirtual())
10511  continue;
10512 
10513  CXXRecordDecl *BaseClassDecl
10514  = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10515  if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10516  0, false, 0))
10517  ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10518  }
10519 
10520  for (const auto &Base : ClassDecl->vbases()) {
10521  CXXRecordDecl *BaseClassDecl
10522  = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10523  if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10524  0, false, 0))
10525  ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10526  }
10527 
10528  for (const auto *Field : ClassDecl->fields()) {
10529  QualType FieldType = Context.getBaseElementType(Field->getType());
10530  if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10531  if (CXXMethodDecl *MoveAssign =
10532  LookupMovingAssignment(FieldClassDecl,
10533  FieldType.getCVRQualifiers(),
10534  false, 0))
10535  ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
10536  }
10537  }
10538 
10539  return ExceptSpec;
10540 }
10541 
10543  assert(ClassDecl->needsImplicitMoveAssignment());
10544 
10545  DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10546  if (DSM.isAlreadyBeingDeclared())
10547  return nullptr;
10548 
10549  // Note: The following rules are largely analoguous to the move
10550  // constructor rules.
10551 
10552  QualType ArgType = Context.getTypeDeclType(ClassDecl);
10553  QualType RetType = Context.getLValueReferenceType(ArgType);
10554  ArgType = Context.getRValueReferenceType(ArgType);
10555 
10556  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10558  false);
10559 
10560  // An implicitly-declared move assignment operator is an inline public
10561  // member of its class.
10563  SourceLocation ClassLoc = ClassDecl->getLocation();
10564  DeclarationNameInfo NameInfo(Name, ClassLoc);
10565  CXXMethodDecl *MoveAssignment =
10566  CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10567  /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10568  /*isInline=*/true, Constexpr, SourceLocation());
10569  MoveAssignment->setAccess(AS_public);
10570  MoveAssignment->setDefaulted();
10571  MoveAssignment->setImplicit();
10572 
10573  if (getLangOpts().CUDA) {
10575  MoveAssignment,
10576  /* ConstRHS */ false,
10577  /* Diagnose */ false);
10578  }
10579 
10580  // Build an exception specification pointing back at this member.
10582  getImplicitMethodEPI(*this, MoveAssignment);
10583  MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10584 
10585  // Add the parameter to the operator.
10586  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
10587  ClassLoc, ClassLoc,
10588  /*Id=*/nullptr, ArgType,
10589  /*TInfo=*/nullptr, SC_None,
10590  nullptr);
10591  MoveAssignment->setParams(FromParam);
10592 
10593  MoveAssignment->setTrivial(
10595  ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10596  : ClassDecl->hasTrivialMoveAssignment());
10597 
10598  // Note that we have added this copy-assignment operator.
10600 
10601  Scope *S = getScopeForContext(ClassDecl);
10602  CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
10603 
10604  if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
10606  SetDeclDeleted(MoveAssignment, ClassLoc);
10607  }
10608 
10609  if (S)
10610  PushOnScopeChains(MoveAssignment, S, false);
10611  ClassDecl->addDecl(MoveAssignment);
10612 
10613  return MoveAssignment;
10614 }
10615 
10616 /// Check if we're implicitly defining a move assignment operator for a class
10617 /// with virtual bases. Such a move assignment might move-assign the virtual
10618 /// base multiple times.
10620  SourceLocation CurrentLocation) {
10621  assert(!Class->isDependentContext() && "should not define dependent move");
10622 
10623  // Only a virtual base could get implicitly move-assigned multiple times.
10624  // Only a non-trivial move assignment can observe this. We only want to
10625  // diagnose if we implicitly define an assignment operator that assigns
10626  // two base classes, both of which move-assign the same virtual base.
10627  if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10628  Class->getNumBases() < 2)
10629  return;
10630 
10632  typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10633  VBaseMap VBases;
10634 
10635  for (auto &BI : Class->bases()) {
10636  Worklist.push_back(&BI);
10637  while (!Worklist.empty()) {
10638  CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10639  CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10640 
10641  // If the base has no non-trivial move assignment operators,
10642  // we don't care about moves from it.
10643  if (!Base->hasNonTrivialMoveAssignment())
10644  continue;
10645 
10646  // If there's nothing virtual here, skip it.
10647  if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10648  continue;
10649 
10650  // If we're not actually going to call a move assignment for this base,
10651  // or the selected move assignment is trivial, skip it.
10654  /*ConstArg*/false, /*VolatileArg*/false,
10655  /*RValueThis*/true, /*ConstThis*/false,
10656  /*VolatileThis*/false);
10657  if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10658  !SMOR->getMethod()->isMoveAssignmentOperator())
10659  continue;
10660 
10661  if (BaseSpec->isVirtual()) {
10662  // We're going to move-assign this virtual base, and its move
10663  // assignment operator is not trivial. If this can happen for
10664  // multiple distinct direct bases of Class, diagnose it. (If it
10665  // only happens in one base, we'll diagnose it when synthesizing
10666  // that base class's move assignment operator.)
10667  CXXBaseSpecifier *&Existing =
10668  VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
10669  .first->second;
10670  if (Existing && Existing != &BI) {
10671  S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10672  << Class << Base;
10673  S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10674  << (Base->getCanonicalDecl() ==
10675  Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10676  << Base << Existing->getType() << Existing->getSourceRange();
10677  S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
10678  << (Base->getCanonicalDecl() ==
10679  BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10680  << Base << BI.getType() << BaseSpec->getSourceRange();
10681 
10682  // Only diagnose each vbase once.
10683  Existing = nullptr;
10684  }
10685  } else {
10686  // Only walk over bases that have defaulted move assignment operators.
10687  // We assume that any user-provided move assignment operator handles
10688  // the multiple-moves-of-vbase case itself somehow.
10689  if (!SMOR->getMethod()->isDefaulted())
10690  continue;
10691 
10692  // We're going to move the base classes of Base. Add them to the list.
10693  for (auto &BI : Base->bases())
10694  Worklist.push_back(&BI);
10695  }
10696  }
10697  }
10698 }
10699 
10701  CXXMethodDecl *MoveAssignOperator) {
10702  assert((MoveAssignOperator->isDefaulted() &&
10703  MoveAssignOperator->isOverloadedOperator() &&
10704  MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
10705  !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10706  !MoveAssignOperator->isDeleted()) &&
10707  "DefineImplicitMoveAssignment called for wrong function");
10708 
10709  CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10710 
10711  if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10712  MoveAssignOperator->setInvalidDecl();
10713  return;
10714  }
10715 
10716  MoveAssignOperator->markUsed(Context);
10717 
10718  SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
10719  DiagnosticErrorTrap Trap(Diags);
10720 
10721  // C++0x [class.copy]p28:
10722  // The implicitly-defined or move assignment operator for a non-union class
10723  // X performs memberwise move assignment of its subobjects. The direct base
10724  // classes of X are assigned first, in the order of their declaration in the
10725  // base-specifier-list, and then the immediate non-static data members of X
10726  // are assigned, in the order in which they were declared in the class
10727  // definition.
10728 
10729  // Issue a warning if our implicit move assignment operator will move
10730  // from a virtual base more than once.
10731  checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
10732 
10733  // The statements that form the synthesized function body.
10734  SmallVector<Stmt*, 8> Statements;
10735 
10736  // The parameter for the "other" object, which we are move from.
10737  ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10738  QualType OtherRefType = Other->getType()->
10739  getAs<RValueReferenceType>()->getPointeeType();
10740  assert(!OtherRefType.getQualifiers() &&
10741  "Bad argument type of defaulted move assignment");
10742 
10743  // Our location for everything implicitly-generated.
10744  SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10745  ? MoveAssignOperator->getLocEnd()
10746  : MoveAssignOperator->getLocation();
10747 
10748  // Builds a reference to the "other" object.
10749  RefBuilder OtherRef(Other, OtherRefType);
10750  // Cast to rvalue.
10751  MoveCastBuilder MoveOther(OtherRef);
10752 
10753  // Builds the "this" pointer.
10754  ThisBuilder This;
10755 
10756  // Assign base classes.
10757  bool Invalid = false;
10758  for (auto &Base : ClassDecl->bases()) {
10759  // C++11 [class.copy]p28:
10760  // It is unspecified whether subobjects representing virtual base classes
10761  // are assigned more than once by the implicitly-defined copy assignment
10762  // operator.
10763  // FIXME: Do not assign to a vbase that will be assigned by some other base
10764  // class. For a move-assignment, this can result in the vbase being moved
10765  // multiple times.
10766 
10767  // Form the assignment:
10768  // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
10769  QualType BaseType = Base.getType().getUnqualifiedType();
10770  if (!BaseType->isRecordType()) {
10771  Invalid = true;
10772  continue;
10773  }
10774 
10775  CXXCastPath BasePath;
10776  BasePath.push_back(&Base);
10777 
10778  // Construct the "from" expression, which is an implicit cast to the
10779  // appropriately-qualified base type.
10780  CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
10781 
10782  // Dereference "this".
10783  DerefBuilder DerefThis(This);
10784 
10785  // Implicitly cast "this" to the appropriately-qualified base type.
10786  CastBuilder To(DerefThis,
10788  BaseType, MoveAssignOperator->getTypeQualifiers()),
10789  VK_LValue, BasePath);
10790 
10791  // Build the move.
10792  StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
10793  To, From,
10794  /*CopyingBaseSubobject=*/true,
10795  /*Copying=*/false);
10796  if (Move.isInvalid()) {
10797  Diag(CurrentLocation, diag::note_member_synthesized_at)
10798  << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10799  MoveAssignOperator->setInvalidDecl();
10800  return;
10801  }
10802 
10803  // Success! Record the move.
10804  Statements.push_back(Move.getAs<Expr>());
10805  }
10806 
10807  // Assign non-static members.
10808  for (auto *Field : ClassDecl->fields()) {
10809  // FIXME: We should form some kind of AST representation for the implied
10810  // memcpy in a union copy operation.
10811  if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
10812  continue;
10813 
10814  if (Field->isInvalidDecl()) {
10815  Invalid = true;
10816  continue;
10817  }
10818 
10819  // Check for members of reference type; we can't move those.
10820  if (Field->getType()->isReferenceType()) {
10821  Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10822  << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10823  Diag(Field->getLocation(), diag::note_declared_at);
10824  Diag(CurrentLocation, diag::note_member_synthesized_at)
10825  << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10826  Invalid = true;
10827  continue;
10828  }
10829 
10830  // Check for members of const-qualified, non-class type.
10831  QualType BaseType = Context.getBaseElementType(Field->getType());
10832  if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10833  Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10834  << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10835  Diag(Field->getLocation(), diag::note_declared_at);
10836  Diag(CurrentLocation, diag::note_member_synthesized_at)
10837  << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10838  Invalid = true;
10839  continue;
10840  }
10841 
10842  // Suppress assigning zero-width bitfields.
10843  if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10844  continue;
10845 
10846  QualType FieldType = Field->getType().getNonReferenceType();
10847  if (FieldType->isIncompleteArrayType()) {
10848  assert(ClassDecl->hasFlexibleArrayMember() &&
10849  "Incomplete array type is not valid");
10850  continue;
10851  }
10852 
10853  // Build references to the field in the object we're copying from and to.
10854  LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10856  MemberLookup.addDecl(Field);
10857  MemberLookup.resolveKind();
10858  MemberBuilder From(MoveOther, OtherRefType,
10859  /*IsArrow=*/false, MemberLookup);
10860  MemberBuilder To(This, getCurrentThisType(),
10861  /*IsArrow=*/true, MemberLookup);
10862 
10863  assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
10864  "Member reference with rvalue base must be rvalue except for reference "
10865  "members, which aren't allowed for move assignment.");
10866 
10867  // Build the move of this field.
10868  StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
10869  To, From,
10870  /*CopyingBaseSubobject=*/false,
10871  /*Copying=*/false);
10872  if (Move.isInvalid()) {
10873  Diag(CurrentLocation, diag::note_member_synthesized_at)
10874  << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10875  MoveAssignOperator->setInvalidDecl();
10876  return;
10877  }
10878 
10879  // Success! Record the copy.
10880  Statements.push_back(Move.getAs<Stmt>());
10881  }
10882 
10883  if (!Invalid) {
10884  // Add a "return *this;"
10885  ExprResult ThisObj =
10886  CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10887 
10888  StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10889  if (Return.isInvalid())
10890  Invalid = true;
10891  else {
10892  Statements.push_back(Return.getAs<Stmt>());
10893 
10894  if (Trap.hasErrorOccurred()) {
10895  Diag(CurrentLocation, diag::note_member_synthesized_at)
10896  << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10897  Invalid = true;
10898  }
10899  }
10900  }
10901 
10902  // The exception specification is needed because we are defining the
10903  // function.
10904  ResolveExceptionSpec(CurrentLocation,
10905  MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10906 
10907  if (Invalid) {
10908  MoveAssignOperator->setInvalidDecl();
10909  return;
10910  }
10911 
10912  StmtResult Body;
10913  {
10914  CompoundScopeRAII CompoundScope(*this);
10915  Body = ActOnCompoundStmt(Loc, Loc, Statements,
10916  /*isStmtExpr=*/false);
10917  assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10918  }
10919  MoveAssignOperator->setBody(Body.getAs<Stmt>());
10920 
10922  L->CompletedImplicitDefinition(MoveAssignOperator);
10923  }
10924 }
10925 
10928  CXXRecordDecl *ClassDecl = MD->getParent();
10929 
10930  ImplicitExceptionSpecification ExceptSpec(*this);
10931  if (ClassDecl->isInvalidDecl())
10932  return ExceptSpec;
10933 
10934  const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10935  assert(T->getNumParams() >= 1 && "not a copy ctor");
10936  unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10937 
10938  // C++ [except.spec]p14:
10939  // An implicitly declared special member function (Clause 12) shall have an
10940  // exception-specification. [...]
10941  for (const auto &Base : ClassDecl->bases()) {
10942  // Virtual bases are handled below.
10943  if (Base.isVirtual())
10944  continue;
10945 
10946  CXXRecordDecl *BaseClassDecl
10947  = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10948  if (CXXConstructorDecl *CopyConstructor =
10949  LookupCopyingConstructor(BaseClassDecl, Quals))
10950  ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10951  }
10952  for (const auto &Base : ClassDecl->vbases()) {
10953  CXXRecordDecl *BaseClassDecl
10954  = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10955  if (CXXConstructorDecl *CopyConstructor =
10956  LookupCopyingConstructor(BaseClassDecl, Quals))
10957  ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10958  }
10959  for (const auto *Field : ClassDecl->fields()) {
10960  QualType FieldType = Context.getBaseElementType(Field->getType());
10961  if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10962  if (CXXConstructorDecl *CopyConstructor =
10963  LookupCopyingConstructor(FieldClassDecl,
10964  Quals | FieldType.getCVRQualifiers()))
10965  ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
10966  }
10967  }
10968 
10969  return ExceptSpec;
10970 }
10971 
10973  CXXRecordDecl *ClassDecl) {
10974  // C++ [class.copy]p4:
10975  // If the class definition does not explicitly declare a copy
10976  // constructor, one is declared implicitly.
10977  assert(ClassDecl->needsImplicitCopyConstructor());
10978 
10979  DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10980  if (DSM.isAlreadyBeingDeclared())
10981  return nullptr;
10982 
10983  QualType ClassType = Context.getTypeDeclType(ClassDecl);
10984  QualType ArgType = ClassType;
10985  bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
10986  if (Const)
10987  ArgType = ArgType.withConst();
10988  ArgType = Context.getLValueReferenceType(ArgType);
10989 
10990  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10992  Const);
10993 
10994  DeclarationName Name
10996  Context.getCanonicalType(ClassType));
10997  SourceLocation ClassLoc = ClassDecl->getLocation();
10998  DeclarationNameInfo NameInfo(Name, ClassLoc);
10999 
11000  // An implicitly-declared copy constructor is an inline public
11001  // member of its class.
11003  Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11004  /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11005  Constexpr);
11006  CopyConstructor->setAccess(AS_public);
11007  CopyConstructor->setDefaulted();
11008 
11009  if (getLangOpts().CUDA) {
11011  CopyConstructor,
11012  /* ConstRHS */ Const,
11013  /* Diagnose */ false);
11014  }
11015 
11016  // Build an exception specification pointing back at this member.
11018  getImplicitMethodEPI(*this, CopyConstructor);
11019  CopyConstructor->setType(
11020  Context.getFunctionType(Context.VoidTy, ArgType, EPI));
11021 
11022  // Add the parameter to the constructor.
11023  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
11024  ClassLoc, ClassLoc,
11025  /*IdentifierInfo=*/nullptr,
11026  ArgType, /*TInfo=*/nullptr,
11027  SC_None, nullptr);
11028  CopyConstructor->setParams(FromParam);
11029 
11030  CopyConstructor->setTrivial(
11032  ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
11033  : ClassDecl->hasTrivialCopyConstructor());
11034 
11035  // Note that we have declared this constructor.
11037 
11038  Scope *S = getScopeForContext(ClassDecl);
11039  CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
11040 
11041  if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
11042  SetDeclDeleted(CopyConstructor, ClassLoc);
11043 
11044  if (S)
11045  PushOnScopeChains(CopyConstructor, S, false);
11046  ClassDecl->addDecl(CopyConstructor);
11047 
11048  return CopyConstructor;
11049 }
11050 
11052  CXXConstructorDecl *CopyConstructor) {
11053  assert((CopyConstructor->isDefaulted() &&
11054  CopyConstructor->isCopyConstructor() &&
11055  !CopyConstructor->doesThisDeclarationHaveABody() &&
11056  !CopyConstructor->isDeleted()) &&
11057  "DefineImplicitCopyConstructor - call it for implicit copy ctor");
11058 
11059  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
11060  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
11061 
11062  // C++11 [class.copy]p7:
11063  // The [definition of an implicitly declared copy constructor] is
11064  // deprecated if the class has a user-declared copy assignment operator
11065  // or a user-declared destructor.
11066  if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
11067  diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
11068 
11069  SynthesizedFunctionScope Scope(*this, CopyConstructor);
11070  DiagnosticErrorTrap Trap(Diags);
11071 
11072  if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
11073  Trap.hasErrorOccurred()) {
11074  Diag(CurrentLocation, diag::note_member_synthesized_at)
11075  << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
11076  CopyConstructor->setInvalidDecl();
11077  } else {
11078  SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
11079  ? CopyConstructor->getLocEnd()
11080  : CopyConstructor->getLocation();
11081  Sema::CompoundScopeRAII CompoundScope(*this);
11082  CopyConstructor->setBody(
11083  ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
11084  }
11085 
11086  // The exception specification is needed because we are defining the
11087  // function.
11088  ResolveExceptionSpec(CurrentLocation,
11089  CopyConstructor->getType()->castAs<FunctionProtoType>());
11090 
11091  CopyConstructor->markUsed(Context);
11092  MarkVTableUsed(CurrentLocation, ClassDecl);
11093 
11095  L->CompletedImplicitDefinition(CopyConstructor);
11096  }
11097 }
11098 
11101  CXXRecordDecl *ClassDecl = MD->getParent();
11102 
11103  // C++ [except.spec]p14:
11104  // An implicitly declared special member function (Clause 12) shall have an
11105  // exception-specification. [...]
11106  ImplicitExceptionSpecification ExceptSpec(*this);
11107  if (ClassDecl->isInvalidDecl())
11108  return ExceptSpec;
11109 
11110  // Direct base-class constructors.
11111  for (const auto &B : ClassDecl->bases()) {
11112  if (B.isVirtual()) // Handled below.
11113  continue;
11114 
11115  if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
11116  CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
11117  CXXConstructorDecl *Constructor =
11118  LookupMovingConstructor(BaseClassDecl, 0);
11119  // If this is a deleted function, add it anyway. This might be conformant
11120  // with the standard. This might not. I'm not sure. It might not matter.
11121  if (Constructor)
11122  ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
11123  }
11124  }
11125 
11126  // Virtual base-class constructors.
11127  for (const auto &B : ClassDecl->vbases()) {
11128  if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
11129  CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
11130  CXXConstructorDecl *Constructor =
11131  LookupMovingConstructor(BaseClassDecl, 0);
11132  // If this is a deleted function, add it anyway. This might be conformant
11133  // with the standard. This might not. I'm not sure. It might not matter.
11134  if (Constructor)
11135  ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
11136  }
11137  }
11138 
11139  // Field constructors.
11140  for (const auto *F : ClassDecl->fields()) {
11141  QualType FieldType = Context.getBaseElementType(F->getType());
11142  if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
11143  CXXConstructorDecl *Constructor =
11144  LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
11145  // If this is a deleted function, add it anyway. This might be conformant
11146  // with the standard. This might not. I'm not sure. It might not matter.
11147  // In particular, the problem is that this function never gets called. It
11148  // might just be ill-formed because this function attempts to refer to
11149  // a deleted function here.
11150  if (Constructor)
11151  ExceptSpec.CalledDecl(F->getLocation(), Constructor);
11152  }
11153  }
11154 
11155  return ExceptSpec;
11156 }
11157 
11159  CXXRecordDecl *ClassDecl) {
11160  assert(ClassDecl->needsImplicitMoveConstructor());
11161 
11162  DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
11163  if (DSM.isAlreadyBeingDeclared())
11164  return nullptr;
11165 
11166  QualType ClassType = Context.getTypeDeclType(ClassDecl);
11167  QualType ArgType = Context.getRValueReferenceType(ClassType);
11168 
11169  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11171  false);
11172 
11173  DeclarationName Name
11175  Context.getCanonicalType(ClassType));
11176  SourceLocation ClassLoc = ClassDecl->getLocation();
11177  DeclarationNameInfo NameInfo(Name, ClassLoc);
11178 
11179  // C++11 [class.copy]p11:
11180  // An implicitly-declared copy/move constructor is an inline public
11181  // member of its class.
11183  Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11184  /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11185  Constexpr);
11186  MoveConstructor->setAccess(AS_public);
11187  MoveConstructor->setDefaulted();
11188 
11189  if (getLangOpts().CUDA) {
11191  MoveConstructor,
11192  /* ConstRHS */ false,
11193  /* Diagnose */ false);
11194  }
11195 
11196  // Build an exception specification pointing back at this member.
11198  getImplicitMethodEPI(*this, MoveConstructor);
11199  MoveConstructor->setType(
11200  Context.getFunctionType(Context.VoidTy, ArgType, EPI));
11201 
11202  // Add the parameter to the constructor.
11203  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
11204  ClassLoc, ClassLoc,
11205  /*IdentifierInfo=*/nullptr,
11206  ArgType, /*TInfo=*/nullptr,
11207  SC_None, nullptr);
11208  MoveConstructor->setParams(FromParam);
11209 
11210  MoveConstructor->setTrivial(
11212  ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
11213  : ClassDecl->hasTrivialMoveConstructor());
11214 
11215  // Note that we have declared this constructor.
11217 
11218  Scope *S = getScopeForContext(ClassDecl);
11219  CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
11220 
11221  if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
11223  SetDeclDeleted(MoveConstructor, ClassLoc);
11224  }
11225 
11226  if (S)
11227  PushOnScopeChains(MoveConstructor, S, false);
11228  ClassDecl->addDecl(MoveConstructor);
11229 
11230  return MoveConstructor;
11231 }
11232 
11234  CXXConstructorDecl *MoveConstructor) {
11235  assert((MoveConstructor->isDefaulted() &&
11236  MoveConstructor->isMoveConstructor() &&
11237  !MoveConstructor->doesThisDeclarationHaveABody() &&
11238  !MoveConstructor->isDeleted()) &&
11239  "DefineImplicitMoveConstructor - call it for implicit move ctor");
11240 
11241  CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
11242  assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
11243 
11244  SynthesizedFunctionScope Scope(*this, MoveConstructor);
11245  DiagnosticErrorTrap Trap(Diags);
11246 
11247  if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
11248  Trap.hasErrorOccurred()) {
11249  Diag(CurrentLocation, diag::note_member_synthesized_at)
11250  << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
11251  MoveConstructor->setInvalidDecl();
11252  } else {
11253  SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
11254  ? MoveConstructor->getLocEnd()
11255  : MoveConstructor->getLocation();
11256  Sema::CompoundScopeRAII CompoundScope(*this);
11257  MoveConstructor->setBody(ActOnCompoundStmt(
11258  Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
11259  }
11260 
11261  // The exception specification is needed because we are defining the
11262  // function.
11263  ResolveExceptionSpec(CurrentLocation,
11264  MoveConstructor->getType()->castAs<FunctionProtoType>());
11265 
11266  MoveConstructor->markUsed(Context);
11267  MarkVTableUsed(CurrentLocation, ClassDecl);
11268 
11270  L->CompletedImplicitDefinition(MoveConstructor);
11271  }
11272 }
11273 
11275  return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
11276 }
11277 
11279  SourceLocation CurrentLocation,
11280  CXXConversionDecl *Conv) {
11281  CXXRecordDecl *Lambda = Conv->getParent();
11282  CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
11283  // If we are defining a specialization of a conversion to function-ptr
11284  // cache the deduced template arguments for this specialization
11285  // so that we can use them to retrieve the corresponding call-operator
11286  // and static-invoker.
11287  const TemplateArgumentList *DeducedTemplateArgs = nullptr;
11288 
11289  // Retrieve the corresponding call-operator specialization.
11290  if (Lambda->isGenericLambda()) {
11291  assert(Conv->isFunctionTemplateSpecialization());
11292  FunctionTemplateDecl *CallOpTemplate =
11293  CallOp->getDescribedFunctionTemplate();
11294  DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
11295  void *InsertPos = nullptr;
11296  FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
11297  DeducedTemplateArgs->asArray(),
11298  InsertPos);
11299  assert(CallOpSpec &&
11300  "Conversion operator must have a corresponding call operator");
11301  CallOp = cast<CXXMethodDecl>(CallOpSpec);
11302  }
11303  // Mark the call operator referenced (and add to pending instantiations
11304  // if necessary).
11305  // For both the conversion and static-invoker template specializations
11306  // we construct their body's in this function, so no need to add them
11307  // to the PendingInstantiations.
11308  MarkFunctionReferenced(CurrentLocation, CallOp);
11309 
11310  SynthesizedFunctionScope Scope(*this, Conv);
11311  DiagnosticErrorTrap Trap(Diags);
11312 
11313  // Retrieve the static invoker...
11314  CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
11315  // ... and get the corresponding specialization for a generic lambda.
11316  if (Lambda->isGenericLambda()) {
11317  assert(DeducedTemplateArgs &&
11318  "Must have deduced template arguments from Conversion Operator");
11319  FunctionTemplateDecl *InvokeTemplate =
11320  Invoker->getDescribedFunctionTemplate();
11321  void *InsertPos = nullptr;
11322  FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
11323  DeducedTemplateArgs->asArray(),
11324  InsertPos);
11325  assert(InvokeSpec &&
11326  "Must have a corresponding static invoker specialization");
11327  Invoker = cast<CXXMethodDecl>(InvokeSpec);
11328  }
11329  // Construct the body of the conversion function { return __invoke; }.
11330  Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
11331  VK_LValue, Conv->getLocation()).get();
11332  assert(FunctionRef && "Can't refer to __invoke function?");
11333  Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
11334  Conv->setBody(new (Context) CompoundStmt(Context, Return,
11335  Conv->getLocation(),
11336  Conv->getLocation()));
11337 
11338  Conv->markUsed(Context);
11339  Conv->setReferenced();
11340 
11341  // Fill in the __invoke function with a dummy implementation. IR generation
11342  // will fill in the actual details.
11343  Invoker->markUsed(Context);
11344  Invoker->setReferenced();
11345  Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
11346 
11348  L->CompletedImplicitDefinition(Conv);
11349  L->CompletedImplicitDefinition(Invoker);
11350  }
11351 }
11352 
11353 
11354 
11356  SourceLocation CurrentLocation,
11357  CXXConversionDecl *Conv)
11358 {
11359  assert(!Conv->getParent()->isGenericLambda());
11360 
11361  Conv->markUsed(Context);
11362 
11363  SynthesizedFunctionScope Scope(*this, Conv);
11364  DiagnosticErrorTrap Trap(Diags);
11365 
11366  // Copy-initialize the lambda object as needed to capture it.
11367  Expr *This = ActOnCXXThis(CurrentLocation).get();
11368  Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
11369 
11370  ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
11371  Conv->getLocation(),
11372  Conv, DerefThis);
11373 
11374  // If we're not under ARC, make sure we still get the _Block_copy/autorelease
11375  // behavior. Note that only the general conversion function does this
11376  // (since it's unusable otherwise); in the case where we inline the
11377  // block literal, it has block literal lifetime semantics.
11378  if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
11379  BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
11380  CK_CopyAndAutoreleaseBlockObject,
11381  BuildBlock.get(), nullptr, VK_RValue);
11382 
11383  if (BuildBlock.isInvalid()) {
11384  Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11385  Conv->setInvalidDecl();
11386  return;
11387  }
11388 
11389  // Create the return statement that returns the block from the conversion
11390  // function.
11391  StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
11392  if (Return.isInvalid()) {
11393  Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11394  Conv->setInvalidDecl();
11395  return;
11396  }
11397 
11398  // Set the body of the conversion function.
11399  Stmt *ReturnS = Return.get();
11400  Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
11401  Conv->getLocation(),
11402  Conv->getLocation()));
11403 
11404  // We're done; notify the mutation listener, if any.
11406  L->CompletedImplicitDefinition(Conv);
11407  }
11408 }
11409 
11410 /// \brief Determine whether the given list arguments contains exactly one
11411 /// "real" (non-default) argument.
11413  switch (Args.size()) {
11414  case 0:
11415  return false;
11416 
11417  default:
11418  if (!Args[1]->isDefaultArgument())
11419  return false;
11420 
11421  // fall through
11422  case 1:
11423  return !Args[0]->isDefaultArgument();
11424  }
11425 
11426  return false;
11427 }
11428 
11429 ExprResult
11431  NamedDecl *FoundDecl,
11432  CXXConstructorDecl *Constructor,
11433  MultiExprArg ExprArgs,
11434  bool HadMultipleCandidates,
11435  bool IsListInitialization,
11436  bool IsStdInitListInitialization,
11437  bool RequiresZeroInit,
11438  unsigned ConstructKind,
11439  SourceRange ParenRange) {
11440  bool Elidable = false;
11441 
11442  // C++0x [class.copy]p34:
11443  // When certain criteria are met, an implementation is allowed to
11444  // omit the copy/move construction of a class object, even if the
11445  // copy/move constructor and/or destructor for the object have
11446  // side effects. [...]
11447  // - when a temporary class object that has not been bound to a
11448  // reference (12.2) would be copied/moved to a class object
11449  // with the same cv-unqualified type, the copy/move operation
11450  // can be omitted by constructing the temporary object
11451  // directly into the target of the omitted copy/move
11452  if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
11453  Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
11454  Expr *SubExpr = ExprArgs[0];
11455  Elidable = SubExpr->isTemporaryObject(
11456  Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
11457  }
11458 
11459  return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
11460  FoundDecl, Constructor,
11461  Elidable, ExprArgs, HadMultipleCandidates,
11462  IsListInitialization,
11463  IsStdInitListInitialization, RequiresZeroInit,
11464  ConstructKind, ParenRange);
11465 }
11466 
11467 ExprResult
11469  NamedDecl *FoundDecl,
11470  CXXConstructorDecl *Constructor,
11471  bool Elidable,
11472  MultiExprArg ExprArgs,
11473  bool HadMultipleCandidates,
11474  bool IsListInitialization,
11475  bool IsStdInitListInitialization,
11476  bool RequiresZeroInit,
11477  unsigned ConstructKind,
11478  SourceRange ParenRange) {
11479  if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
11480  Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
11481  if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
11482  return ExprError();
11483  }
11484 
11485  return BuildCXXConstructExpr(
11486  ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
11487  HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11488  RequiresZeroInit, ConstructKind, ParenRange);
11489 }
11490 
11491 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
11492 /// including handling of its default argument expressions.
11493 ExprResult
11495  CXXConstructorDecl *Constructor,
11496  bool Elidable,
11497  MultiExprArg ExprArgs,
11498  bool HadMultipleCandidates,
11499  bool IsListInitialization,
11500  bool IsStdInitListInitialization,
11501  bool RequiresZeroInit,
11502  unsigned ConstructKind,
11503  SourceRange ParenRange) {
11504  assert(declaresSameEntity(
11505  Constructor->getParent(),
11506  DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
11507  "given constructor for wrong type");
11508  MarkFunctionReferenced(ConstructLoc, Constructor);
11509 
11510  return CXXConstructExpr::Create(
11511  Context, DeclInitType, ConstructLoc, Constructor, Elidable,
11512  ExprArgs, HadMultipleCandidates, IsListInitialization,
11513  IsStdInitListInitialization, RequiresZeroInit,
11514  static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11515  ParenRange);
11516 }
11517 
11519  assert(Field->hasInClassInitializer());
11520 
11521  // If we already have the in-class initializer nothing needs to be done.
11522  if (Field->getInClassInitializer())
11523  return CXXDefaultInitExpr::Create(Context, Loc, Field);
11524 
11525  // Maybe we haven't instantiated the in-class initializer. Go check the
11526  // pattern FieldDecl to see if it has one.
11527  CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
11528 
11530  CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
11532  ClassPattern->lookup(Field->getDeclName());
11533 
11534  // Lookup can return at most two results: the pattern for the field, or the
11535  // injected class name of the parent record. No other member can have the
11536  // same name as the field.
11537  assert(!Lookup.empty() && Lookup.size() <= 2 &&
11538  "more than two lookup results for field name");
11539  FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
11540  if (!Pattern) {
11541  assert(isa<CXXRecordDecl>(Lookup[0]) &&
11542  "cannot have other non-field member with same name");
11543  Pattern = cast<FieldDecl>(Lookup[1]);
11544  }
11545 
11546  if (InstantiateInClassInitializer(Loc, Field, Pattern,
11548  return ExprError();
11549  return CXXDefaultInitExpr::Create(Context, Loc, Field);
11550  }
11551 
11552  // DR1351:
11553  // If the brace-or-equal-initializer of a non-static data member
11554  // invokes a defaulted default constructor of its class or of an
11555  // enclosing class in a potentially evaluated subexpression, the
11556  // program is ill-formed.
11557  //
11558  // This resolution is unworkable: the exception specification of the
11559  // default constructor can be needed in an unevaluated context, in
11560  // particular, in the operand of a noexcept-expression, and we can be
11561  // unable to compute an exception specification for an enclosed class.
11562  //
11563  // Any attempt to resolve the exception specification of a defaulted default
11564  // constructor before the initializer is lexically complete will ultimately
11565  // come here at which point we can diagnose it.
11566  RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
11567  if (OutermostClass == ParentRD) {
11568  Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
11569  << ParentRD << Field;
11570  } else {
11571  Diag(Field->getLocEnd(),
11572  diag::err_in_class_initializer_not_yet_parsed_outer_class)
11573  << ParentRD << OutermostClass << Field;
11574  }
11575 
11576  return ExprError();
11577 }
11578 
11580  if (VD->isInvalidDecl()) return;
11581 
11582  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
11583  if (ClassDecl->isInvalidDecl()) return;
11584  if (ClassDecl->hasIrrelevantDestructor()) return;
11585  if (ClassDecl->isDependentContext()) return;
11586 
11587  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11588  MarkFunctionReferenced(VD->getLocation(), Destructor);
11589  CheckDestructorAccess(VD->getLocation(), Destructor,
11590  PDiag(diag::err_access_dtor_var)
11591  << VD->getDeclName()
11592  << VD->getType());
11593  DiagnoseUseOfDecl(Destructor, VD->getLocation());
11594 
11595  if (Destructor->isTrivial()) return;
11596  if (!VD->hasGlobalStorage()) return;
11597 
11598  // Emit warning for non-trivial dtor in global scope (a real global,
11599  // class-static, function-static).
11600  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11601 
11602  // TODO: this should be re-enabled for static locals by !CXAAtExit
11603  if (!VD->isStaticLocal())
11604  Diag(VD->getLocation(), diag::warn_global_destructor);
11605 }
11606 
11607 /// \brief Given a constructor and the set of arguments provided for the
11608 /// constructor, convert the arguments and add any required default arguments
11609 /// to form a proper call to this constructor.
11610 ///
11611 /// \returns true if an error occurred, false otherwise.
11612 bool
11614  MultiExprArg ArgsPtr,
11615  SourceLocation Loc,
11616  SmallVectorImpl<Expr*> &ConvertedArgs,
11617  bool AllowExplicit,
11618  bool IsListInitialization) {
11619  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11620  unsigned NumArgs = ArgsPtr.size();
11621  Expr **Args = ArgsPtr.data();
11622 
11623  const FunctionProtoType *Proto
11624  = Constructor->getType()->getAs<FunctionProtoType>();
11625  assert(Proto && "Constructor without a prototype?");
11626  unsigned NumParams = Proto->getNumParams();
11627 
11628  // If too few arguments are available, we'll fill in the rest with defaults.
11629  if (NumArgs < NumParams)
11630  ConvertedArgs.reserve(NumParams);
11631  else
11632  ConvertedArgs.reserve(NumArgs);
11633 
11634  VariadicCallType CallType =
11636  SmallVector<Expr *, 8> AllArgs;
11637  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
11638  Proto, 0,
11639  llvm::makeArrayRef(Args, NumArgs),
11640  AllArgs,
11641  CallType, AllowExplicit,
11642  IsListInitialization);
11643  ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
11644 
11645  DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
11646 
11647  CheckConstructorCall(Constructor,
11648  llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
11649  Proto, Loc);
11650 
11651  return Invalid;
11652 }
11653 
11654 static inline bool
11656  const FunctionDecl *FnDecl) {
11657  const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
11658  if (isa<NamespaceDecl>(DC)) {
11659  return SemaRef.Diag(FnDecl->getLocation(),
11660  diag::err_operator_new_delete_declared_in_namespace)
11661  << FnDecl->getDeclName();
11662  }
11663 
11664  if (isa<TranslationUnitDecl>(DC) &&
11665  FnDecl->getStorageClass() == SC_Static) {
11666  return SemaRef.Diag(FnDecl->getLocation(),
11667  diag::err_operator_new_delete_declared_static)
11668  << FnDecl->getDeclName();
11669  }
11670 
11671  return false;
11672 }
11673 
11674 static inline bool
11676  CanQualType ExpectedResultType,
11677  CanQualType ExpectedFirstParamType,
11678  unsigned DependentParamTypeDiag,
11679  unsigned InvalidParamTypeDiag) {
11680  QualType ResultType =
11681  FnDecl->getType()->getAs<FunctionType>()->getReturnType();
11682 
11683  // Check that the result type is not dependent.
11684  if (ResultType->isDependentType())
11685  return SemaRef.Diag(FnDecl->getLocation(),
11686  diag::err_operator_new_delete_dependent_result_type)
11687  << FnDecl->getDeclName() << ExpectedResultType;
11688 
11689  // Check that the result type is what we expect.
11690  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11691  return SemaRef.Diag(FnDecl->getLocation(),
11692  diag::err_operator_new_delete_invalid_result_type)
11693  << FnDecl->getDeclName() << ExpectedResultType;
11694 
11695  // A function template must have at least 2 parameters.
11696  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11697  return SemaRef.Diag(FnDecl->getLocation(),
11698  diag::err_operator_new_delete_template_too_few_parameters)
11699  << FnDecl->getDeclName();
11700 
11701  // The function decl must have at least 1 parameter.
11702  if (FnDecl->getNumParams() == 0)
11703  return SemaRef.Diag(FnDecl->getLocation(),
11704  diag::err_operator_new_delete_too_few_parameters)
11705  << FnDecl->getDeclName();
11706 
11707  // Check the first parameter type is not dependent.
11708  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11709  if (FirstParamType->isDependentType())
11710  return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11711  << FnDecl->getDeclName() << ExpectedFirstParamType;
11712 
11713  // Check that the first parameter type is what we expect.
11714  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
11715  ExpectedFirstParamType)
11716  return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11717  << FnDecl->getDeclName() << ExpectedFirstParamType;
11718 
11719  return false;
11720 }
11721 
11722 static bool
11724  // C++ [basic.stc.dynamic.allocation]p1:
11725  // A program is ill-formed if an allocation function is declared in a
11726  // namespace scope other than global scope or declared static in global
11727  // scope.
11728  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11729  return true;
11730 
11731  CanQualType SizeTy =
11732  SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11733 
11734  // C++ [basic.stc.dynamic.allocation]p1:
11735  // The return type shall be void*. The first parameter shall have type
11736  // std::size_t.
11737  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11738  SizeTy,
11739  diag::err_operator_new_dependent_param_type,
11740  diag::err_operator_new_param_type))
11741  return true;
11742 
11743  // C++ [basic.stc.dynamic.allocation]p1:
11744  // The first parameter shall not have an associated default argument.
11745  if (FnDecl->getParamDecl(0)->hasDefaultArg())
11746  return SemaRef.Diag(FnDecl->getLocation(),
11747  diag::err_operator_new_default_arg)
11748  << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11749 
11750  return false;
11751 }
11752 
11753 static bool
11755  // C++ [basic.stc.dynamic.deallocation]p1:
11756  // A program is ill-formed if deallocation functions are declared in a
11757  // namespace scope other than global scope or declared static in global
11758  // scope.
11759  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11760  return true;
11761 
11762  // C++ [basic.stc.dynamic.deallocation]p2:
11763  // Each deallocation function shall return void and its first parameter
11764  // shall be void*.
11765  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11766  SemaRef.Context.VoidPtrTy,
11767  diag::err_operator_delete_dependent_param_type,
11768  diag::err_operator_delete_param_type))
11769  return true;
11770 
11771  return false;
11772 }
11773 
11774 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
11775 /// of this overloaded operator is well-formed. If so, returns false;
11776 /// otherwise, emits appropriate diagnostics and returns true.
11778  assert(FnDecl && FnDecl->isOverloadedOperator() &&
11779  "Expected an overloaded operator declaration");
11780 
11782 
11783  // C++ [over.oper]p5:
11784  // The allocation and deallocation functions, operator new,
11785  // operator new[], operator delete and operator delete[], are
11786  // described completely in 3.7.3. The attributes and restrictions
11787  // found in the rest of this subclause do not apply to them unless
11788  // explicitly stated in 3.7.3.
11789  if (Op == OO_Delete || Op == OO_Array_Delete)
11790  return CheckOperatorDeleteDeclaration(*this, FnDecl);
11791 
11792  if (Op == OO_New || Op == OO_Array_New)
11793  return CheckOperatorNewDeclaration(*this, FnDecl);
11794 
11795  // C++ [over.oper]p6:
11796  // An operator function shall either be a non-static member
11797  // function or be a non-member function and have at least one
11798  // parameter whose type is a class, a reference to a class, an
11799  // enumeration, or a reference to an enumeration.
11800  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11801  if (MethodDecl->isStatic())
11802  return Diag(FnDecl->getLocation(),
11803  diag::err_operator_overload_static) << FnDecl->getDeclName();
11804  } else {
11805  bool ClassOrEnumParam = false;
11806  for (auto Param : FnDecl->parameters()) {
11807  QualType ParamType = Param->getType().getNonReferenceType();
11808  if (ParamType->isDependentType() || ParamType->isRecordType() ||
11809  ParamType->isEnumeralType()) {
11810  ClassOrEnumParam = true;
11811  break;
11812  }
11813  }
11814 
11815  if (!ClassOrEnumParam)
11816  return Diag(FnDecl->getLocation(),
11817  diag::err_operator_overload_needs_class_or_enum)
11818  << FnDecl->getDeclName();
11819  }
11820 
11821  // C++ [over.oper]p8:
11822  // An operator function cannot have default arguments (8.3.6),
11823  // except where explicitly stated below.
11824  //
11825  // Only the function-call operator allows default arguments
11826  // (C++ [over.call]p1).
11827  if (Op != OO_Call) {
11828  for (auto Param : FnDecl->parameters()) {
11829  if (Param->hasDefaultArg())
11830  return Diag(Param->getLocation(),
11831  diag::err_operator_overload_default_arg)
11832  << FnDecl->getDeclName() << Param->getDefaultArgRange();
11833  }
11834  }
11835 
11836  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11837  { false, false, false }
11838 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11839  , { Unary, Binary, MemberOnly }
11840 #include "clang/Basic/OperatorKinds.def"
11841  };
11842 
11843  bool CanBeUnaryOperator = OperatorUses[Op][0];
11844  bool CanBeBinaryOperator = OperatorUses[Op][1];
11845  bool MustBeMemberOperator = OperatorUses[Op][2];
11846 
11847  // C++ [over.oper]p8:
11848  // [...] Operator functions cannot have more or fewer parameters
11849  // than the number required for the corresponding operator, as
11850  // described in the rest of this subclause.
11851  unsigned NumParams = FnDecl->getNumParams()
11852  + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
11853  if (Op != OO_Call &&
11854  ((NumParams == 1 && !CanBeUnaryOperator) ||
11855  (NumParams == 2 && !CanBeBinaryOperator) ||
11856  (NumParams < 1) || (NumParams > 2))) {
11857  // We have the wrong number of parameters.
11858  unsigned ErrorKind;
11859  if (CanBeUnaryOperator && CanBeBinaryOperator) {
11860  ErrorKind = 2; // 2 -> unary or binary.
11861  } else if (CanBeUnaryOperator) {
11862  ErrorKind = 0; // 0 -> unary
11863  } else {
11864  assert(CanBeBinaryOperator &&
11865  "All non-call overloaded operators are unary or binary!");
11866  ErrorKind = 1; // 1 -> binary
11867  }
11868 
11869  return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
11870  << FnDecl->getDeclName() << NumParams << ErrorKind;
11871  }
11872 
11873  // Overloaded operators other than operator() cannot be variadic.
11874  if (Op != OO_Call &&
11875  FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
11876  return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
11877  << FnDecl->getDeclName();
11878  }
11879 
11880  // Some operators must be non-static member functions.
11881  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11882  return Diag(FnDecl->getLocation(),
11883  diag::err_operator_overload_must_be_member)
11884  << FnDecl->getDeclName();
11885  }
11886 
11887  // C++ [over.inc]p1:
11888  // The user-defined function called operator++ implements the
11889  // prefix and postfix ++ operator. If this function is a member
11890  // function with no parameters, or a non-member function with one
11891  // parameter of class or enumeration type, it defines the prefix
11892  // increment operator ++ for objects of that type. If the function
11893  // is a member function with one parameter (which shall be of type
11894  // int) or a non-member function with two parameters (the second
11895  // of which shall be of type int), it defines the postfix
11896  // increment operator ++ for objects of that type.
11897  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11898  ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
11899  QualType ParamType = LastParam->getType();
11900 
11901  if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11902  !ParamType->isDependentType())
11903  return Diag(LastParam->getLocation(),
11904  diag::err_operator_overload_post_incdec_must_be_int)
11905  << LastParam->getType() << (Op == OO_MinusMinus);
11906  }
11907 
11908  return false;
11909 }
11910 
11911 static bool
11913  FunctionTemplateDecl *TpDecl) {
11914  TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
11915 
11916  // Must have one or two template parameters.
11917  if (TemplateParams->size() == 1) {
11918  NonTypeTemplateParmDecl *PmDecl =
11919  dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
11920 
11921  // The template parameter must be a char parameter pack.
11922  if (PmDecl && PmDecl->isTemplateParameterPack() &&
11923  SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
11924  return false;
11925 
11926  } else if (TemplateParams->size() == 2) {
11927  TemplateTypeParmDecl *PmType =
11928  dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
11929  NonTypeTemplateParmDecl *PmArgs =
11930  dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
11931 
11932  // The second template parameter must be a parameter pack with the
11933  // first template parameter as its type.
11934  if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
11935  PmArgs->isTemplateParameterPack()) {
11936  const TemplateTypeParmType *TArgs =
11937  PmArgs->getType()->getAs<TemplateTypeParmType>();
11938  if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11939  TArgs->getIndex() == PmType->getIndex()) {
11940  if (SemaRef.ActiveTemplateInstantiations.empty())
11941  SemaRef.Diag(TpDecl->getLocation(),
11942  diag::ext_string_literal_operator_template);
11943  return false;
11944  }
11945  }
11946  }
11947 
11948  SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
11949  diag::err_literal_operator_template)
11950  << TpDecl->getTemplateParameters()->getSourceRange();
11951  return true;
11952 }
11953 
11954 /// CheckLiteralOperatorDeclaration - Check whether the declaration
11955 /// of this literal operator function is well-formed. If so, returns
11956 /// false; otherwise, emits appropriate diagnostics and returns true.
11958  if (isa<CXXMethodDecl>(FnDecl)) {
11959  Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11960  << FnDecl->getDeclName();
11961  return true;
11962  }
11963 
11964  if (FnDecl->isExternC()) {
11965  Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11966  return true;
11967  }
11968 
11969  // This might be the definition of a literal operator template.
11971 
11972  // This might be a specialization of a literal operator template.
11973  if (!TpDecl)
11974  TpDecl = FnDecl->getPrimaryTemplate();
11975 
11976  // template <char...> type operator "" name() and
11977  // template <class T, T...> type operator "" name() are the only valid
11978  // template signatures, and the only valid signatures with no parameters.
11979  if (TpDecl) {
11980  if (FnDecl->param_size() != 0) {
11981  Diag(FnDecl->getLocation(),
11982  diag::err_literal_operator_template_with_params);
11983  return true;
11984  }
11985 
11986  if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
11987  return true;
11988 
11989  } else if (FnDecl->param_size() == 1) {
11990  const ParmVarDecl *Param = FnDecl->getParamDecl(0);
11991 
11992  QualType ParamType = Param->getType().getUnqualifiedType();
11993 
11994  // Only unsigned long long int, long double, any character type, and const
11995  // char * are allowed as the only parameters.
11996  if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
11997  ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
11998  Context.hasSameType(ParamType, Context.CharTy) ||
11999  Context.hasSameType(ParamType, Context.WideCharTy) ||
12000  Context.hasSameType(ParamType, Context.Char16Ty) ||
12001  Context.hasSameType(ParamType, Context.Char32Ty)) {
12002  } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
12003  QualType InnerType = Ptr->getPointeeType();
12004 
12005  // Pointer parameter must be a const char *.
12006  if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
12007  Context.CharTy) &&
12008  InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
12009  Diag(Param->getSourceRange().getBegin(),
12010  diag::err_literal_operator_param)
12011  << ParamType << "'const char *'" << Param->getSourceRange();
12012  return true;
12013  }
12014 
12015  } else if (ParamType->isRealFloatingType()) {
12016  Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12017  << ParamType << Context.LongDoubleTy << Param->getSourceRange();
12018  return true;
12019 
12020  } else if (ParamType->isIntegerType()) {
12021  Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12022  << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
12023  return true;
12024 
12025  } else {
12026  Diag(Param->getSourceRange().getBegin(),
12027  diag::err_literal_operator_invalid_param)
12028  << ParamType << Param->getSourceRange();
12029  return true;
12030  }
12031 
12032  } else if (FnDecl->param_size() == 2) {
12033  FunctionDecl::param_iterator Param = FnDecl->param_begin();
12034 
12035  // First, verify that the first parameter is correct.
12036 
12037  QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
12038 
12039  // Two parameter function must have a pointer to const as a
12040  // first parameter; let's strip those qualifiers.
12041  const PointerType *PT = FirstParamType->getAs<PointerType>();
12042 
12043  if (!PT) {
12044  Diag((*Param)->getSourceRange().getBegin(),
12045  diag::err_literal_operator_param)
12046  << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12047  return true;
12048  }
12049 
12050  QualType PointeeType = PT->getPointeeType();
12051  // First parameter must be const
12052  if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
12053  Diag((*Param)->getSourceRange().getBegin(),
12054  diag::err_literal_operator_param)
12055  << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12056  return true;
12057  }
12058 
12059  QualType InnerType = PointeeType.getUnqualifiedType();
12060  // Only const char *, const wchar_t*, const char16_t*, and const char32_t*
12061  // are allowed as the first parameter to a two-parameter function
12062  if (!(Context.hasSameType(InnerType, Context.CharTy) ||
12063  Context.hasSameType(InnerType, Context.WideCharTy) ||
12064  Context.hasSameType(InnerType, Context.Char16Ty) ||
12065  Context.hasSameType(InnerType, Context.Char32Ty))) {
12066  Diag((*Param)->getSourceRange().getBegin(),
12067  diag::err_literal_operator_param)
12068  << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12069  return true;
12070  }
12071 
12072  // Move on to the second and final parameter.
12073  ++Param;
12074 
12075  // The second parameter must be a std::size_t.
12076  QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
12077  if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
12078  Diag((*Param)->getSourceRange().getBegin(),
12079  diag::err_literal_operator_param)
12080  << SecondParamType << Context.getSizeType()
12081  << (*Param)->getSourceRange();
12082  return true;
12083  }
12084  } else {
12085  Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
12086  return true;
12087  }
12088 
12089  // Parameters are good.
12090 
12091  // A parameter-declaration-clause containing a default argument is not
12092  // equivalent to any of the permitted forms.
12093  for (auto Param : FnDecl->parameters()) {
12094  if (Param->hasDefaultArg()) {
12095  Diag(Param->getDefaultArgRange().getBegin(),
12096  diag::err_literal_operator_default_argument)
12097  << Param->getDefaultArgRange();
12098  break;
12099  }
12100  }
12101 
12102  StringRef LiteralName
12103  = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
12104  if (LiteralName[0] != '_') {
12105  // C++11 [usrlit.suffix]p1:
12106  // Literal suffix identifiers that do not start with an underscore
12107  // are reserved for future standardization.
12108  Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
12110  }
12111 
12112  return false;
12113 }
12114 
12115 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
12116 /// linkage specification, including the language and (if present)
12117 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
12118 /// language string literal. LBraceLoc, if valid, provides the location of
12119 /// the '{' brace. Otherwise, this linkage specification does not
12120 /// have any braces.
12122  Expr *LangStr,
12123  SourceLocation LBraceLoc) {
12124  StringLiteral *Lit = cast<StringLiteral>(LangStr);
12125  if (!Lit->isAscii()) {
12126  Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
12127  << LangStr->getSourceRange();
12128  return nullptr;
12129  }
12130 
12131  StringRef Lang = Lit->getString();
12133  if (Lang == "C")
12134  Language = LinkageSpecDecl::lang_c;
12135  else if (Lang == "C++")
12136  Language = LinkageSpecDecl::lang_cxx;
12137  else {
12138  Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
12139  << LangStr->getSourceRange();
12140  return nullptr;
12141  }
12142 
12143  // FIXME: Add all the various semantics of linkage specifications
12144 
12146  LangStr->getExprLoc(), Language,
12147  LBraceLoc.isValid());
12148  CurContext->addDecl(D);
12149  PushDeclContext(S, D);
12150  return D;
12151 }
12152 
12153 /// ActOnFinishLinkageSpecification - Complete the definition of
12154 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
12155 /// valid, it's the position of the closing '}' brace in a linkage
12156 /// specification that uses braces.
12158  Decl *LinkageSpec,
12159  SourceLocation RBraceLoc) {
12160  if (RBraceLoc.isValid()) {
12161  LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
12162  LSDecl->setRBraceLoc(RBraceLoc);
12163  }
12164  PopDeclContext();
12165  return LinkageSpec;
12166 }
12167 
12169  AttributeList *AttrList,
12170  SourceLocation SemiLoc) {
12171  Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
12172  // Attribute declarations appertain to empty declaration so we handle
12173  // them here.
12174  if (AttrList)
12175  ProcessDeclAttributeList(S, ED, AttrList);
12176 
12177  CurContext->addDecl(ED);
12178  return ED;
12179 }
12180 
12181 /// \brief Perform semantic analysis for the variable declaration that
12182 /// occurs within a C++ catch clause, returning the newly-created
12183 /// variable.
12185  TypeSourceInfo *TInfo,
12186  SourceLocation StartLoc,
12187  SourceLocation Loc,
12188  IdentifierInfo *Name) {
12189  bool Invalid = false;
12190  QualType ExDeclType = TInfo->getType();
12191 
12192  // Arrays and functions decay.
12193  if (ExDeclType->isArrayType())
12194  ExDeclType = Context.getArrayDecayedType(ExDeclType);
12195  else if (ExDeclType->isFunctionType())
12196  ExDeclType = Context.getPointerType(ExDeclType);
12197 
12198  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
12199  // The exception-declaration shall not denote a pointer or reference to an
12200  // incomplete type, other than [cv] void*.
12201  // N2844 forbids rvalue references.
12202  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
12203  Diag(Loc, diag::err_catch_rvalue_ref);
12204  Invalid = true;
12205  }
12206 
12207  if (ExDeclType->isVariablyModifiedType()) {
12208  Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
12209  Invalid = true;
12210  }
12211 
12212  QualType BaseType = ExDeclType;
12213  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
12214  unsigned DK = diag::err_catch_incomplete;
12215  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
12216  BaseType = Ptr->getPointeeType();
12217  Mode = 1;
12218  DK = diag::err_catch_incomplete_ptr;
12219  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
12220  // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
12221  BaseType = Ref->getPointeeType();
12222  Mode = 2;
12223  DK = diag::err_catch_incomplete_ref;
12224  }
12225  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
12226  !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
12227  Invalid = true;
12228 
12229  if (!Invalid && !ExDeclType->isDependentType() &&
12230  RequireNonAbstractType(Loc, ExDeclType,
12231  diag::err_abstract_type_in_decl,
12233  Invalid = true;
12234 
12235  // Only the non-fragile NeXT runtime currently supports C++ catches
12236  // of ObjC types, and no runtime supports catching ObjC types by value.
12237  if (!Invalid && getLangOpts().ObjC1) {
12238  QualType T = ExDeclType;
12239  if (const ReferenceType *RT = T->getAs<ReferenceType>())
12240  T = RT->getPointeeType();
12241 
12242  if (T->isObjCObjectType()) {
12243  Diag(Loc, diag::err_objc_object_catch);
12244  Invalid = true;
12245  } else if (T->isObjCObjectPointerType()) {
12246  // FIXME: should this be a test for macosx-fragile specifically?
12248  Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
12249  }
12250  }
12251 
12252  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
12253  ExDeclType, TInfo, SC_None);
12254  ExDecl->setExceptionVariable(true);
12255 
12256  // In ARC, infer 'retaining' for variables of retainable type.
12257  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
12258  Invalid = true;
12259 
12260  if (!Invalid && !ExDeclType->isDependentType()) {
12261  if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
12262  // Insulate this from anything else we might currently be parsing.
12264 
12265  // C++ [except.handle]p16:
12266  // The object declared in an exception-declaration or, if the
12267  // exception-declaration does not specify a name, a temporary (12.2) is
12268  // copy-initialized (8.5) from the exception object. [...]
12269  // The object is destroyed when the handler exits, after the destruction
12270  // of any automatic objects initialized within the handler.
12271  //
12272  // We just pretend to initialize the object with itself, then make sure
12273  // it can be destroyed later.
12274  QualType initType = Context.getExceptionObjectType(ExDeclType);
12275 
12276  InitializedEntity entity =
12278  InitializationKind initKind =
12280 
12281  Expr *opaqueValue =
12282  new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
12283  InitializationSequence sequence(*this, entity, initKind, opaqueValue);
12284  ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
12285  if (result.isInvalid())
12286  Invalid = true;
12287  else {
12288  // If the constructor used was non-trivial, set this as the
12289  // "initializer".
12290  CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
12291  if (!construct->getConstructor()->isTrivial()) {
12292  Expr *init = MaybeCreateExprWithCleanups(construct);
12293  ExDecl->setInit(init);
12294  }
12295 
12296  // And make sure it's destructable.
12297  FinalizeVarWithDestructor(ExDecl, recordType);
12298  }
12299  }
12300  }
12301 
12302  if (Invalid)
12303  ExDecl->setInvalidDecl();
12304 
12305  return ExDecl;
12306 }
12307 
12308 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
12309 /// handler.
12311  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12312  bool Invalid = D.isInvalidType();
12313 
12314  // Check for unexpanded parameter packs.
12316  UPPC_ExceptionType)) {
12318  D.getIdentifierLoc());
12319  Invalid = true;
12320  }
12321 
12322  IdentifierInfo *II = D.getIdentifier();
12323  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
12325  ForRedeclaration)) {
12326  // The scope should be freshly made just for us. There is just no way
12327  // it contains any previous declaration, except for function parameters in
12328  // a function-try-block's catch statement.
12329  assert(!S->isDeclScope(PrevDecl));
12330  if (isDeclInScope(PrevDecl, CurContext, S)) {
12331  Diag(D.getIdentifierLoc(), diag::err_redefinition)
12332  << D.getIdentifier();
12333  Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12334  Invalid = true;
12335  } else if (PrevDecl->isTemplateParameter())
12336  // Maybe we will complain about the shadowed template parameter.
12338  }
12339 
12340  if (D.getCXXScopeSpec().isSet() && !Invalid) {
12341  Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
12342  << D.getCXXScopeSpec().getRange();
12343  Invalid = true;
12344  }
12345 
12346  VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
12347  D.getLocStart(),
12348  D.getIdentifierLoc(),
12349  D.getIdentifier());
12350  if (Invalid)
12351  ExDecl->setInvalidDecl();
12352 
12353  // Add the exception declaration into this scope.
12354  if (II)
12355  PushOnScopeChains(ExDecl, S);
12356  else
12357  CurContext->addDecl(ExDecl);
12358 
12359  ProcessDeclAttributes(S, ExDecl, D);
12360  return ExDecl;
12361 }
12362 
12364  Expr *AssertExpr,
12365  Expr *AssertMessageExpr,
12366  SourceLocation RParenLoc) {
12367  StringLiteral *AssertMessage =
12368  AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
12369 
12371  return nullptr;
12372 
12373  return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
12374  AssertMessage, RParenLoc, false);
12375 }
12376 
12378  Expr *AssertExpr,
12379  StringLiteral *AssertMessage,
12380  SourceLocation RParenLoc,
12381  bool Failed) {
12382  assert(AssertExpr != nullptr && "Expected non-null condition");
12383  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
12384  !Failed) {
12385  // In a static_assert-declaration, the constant-expression shall be a
12386  // constant expression that can be contextually converted to bool.
12387  ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
12388  if (Converted.isInvalid())
12389  Failed = true;
12390 
12391  llvm::APSInt Cond;
12392  if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
12393  diag::err_static_assert_expression_is_not_constant,
12394  /*AllowFold=*/false).isInvalid())
12395  Failed = true;
12396 
12397  if (!Failed && !Cond) {
12398  SmallString<256> MsgBuffer;
12399  llvm::raw_svector_ostream Msg(MsgBuffer);
12400  if (AssertMessage)
12401  AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
12402  Diag(StaticAssertLoc, diag::err_static_assert_failed)
12403  << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
12404  Failed = true;
12405  }
12406  }
12407 
12408  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
12409  AssertExpr, AssertMessage, RParenLoc,
12410  Failed);
12411 
12412  CurContext->addDecl(Decl);
12413  return Decl;
12414 }
12415 
12416 /// \brief Perform semantic analysis of the given friend type declaration.
12417 ///
12418 /// \returns A friend declaration that.
12420  SourceLocation FriendLoc,
12421  TypeSourceInfo *TSInfo) {
12422  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
12423 
12424  QualType T = TSInfo->getType();
12425  SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
12426 
12427  // C++03 [class.friend]p2:
12428  // An elaborated-type-specifier shall be used in a friend declaration
12429  // for a class.*
12430  //
12431  // * The class-key of the elaborated-type-specifier is required.
12432  if (!ActiveTemplateInstantiations.empty()) {
12433  // Do not complain about the form of friend template types during
12434  // template instantiation; we will already have complained when the
12435  // template was declared.
12436  } else {
12437  if (!T->isElaboratedTypeSpecifier()) {
12438  // If we evaluated the type to a record type, suggest putting
12439  // a tag in front.
12440  if (const RecordType *RT = T->getAs<RecordType>()) {
12441  RecordDecl *RD = RT->getDecl();
12442 
12443  SmallString<16> InsertionText(" ");
12444  InsertionText += RD->getKindName();
12445 
12446  Diag(TypeRange.getBegin(),
12447  getLangOpts().CPlusPlus11 ?
12448  diag::warn_cxx98_compat_unelaborated_friend_type :
12449  diag::ext_unelaborated_friend_type)
12450  << (unsigned) RD->getTagKind()
12451  << T
12453  InsertionText);
12454  } else {
12455  Diag(FriendLoc,
12457  diag::warn_cxx98_compat_nonclass_type_friend :
12458  diag::ext_nonclass_type_friend)
12459  << T
12460  << TypeRange;
12461  }
12462  } else if (T->getAs<EnumType>()) {
12463  Diag(FriendLoc,
12465  diag::warn_cxx98_compat_enum_friend :
12466  diag::ext_enum_friend)
12467  << T
12468  << TypeRange;
12469  }
12470 
12471  // C++11 [class.friend]p3:
12472  // A friend declaration that does not declare a function shall have one
12473  // of the following forms:
12474  // friend elaborated-type-specifier ;
12475  // friend simple-type-specifier ;
12476  // friend typename-specifier ;
12477  if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
12478  Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
12479  }
12480 
12481  // If the type specifier in a friend declaration designates a (possibly
12482  // cv-qualified) class type, that class is declared as a friend; otherwise,
12483  // the friend declaration is ignored.
12485  TSInfo->getTypeLoc().getLocStart(), TSInfo,
12486  FriendLoc);
12487 }
12488 
12489 /// Handle a friend tag declaration where the scope specifier was
12490 /// templated.
12492  unsigned TagSpec, SourceLocation TagLoc,
12493  CXXScopeSpec &SS,
12494  IdentifierInfo *Name,
12495  SourceLocation NameLoc,
12497  MultiTemplateParamsArg TempParamLists) {
12499 
12500  bool isExplicitSpecialization = false;
12501  bool Invalid = false;
12502 
12503  if (TemplateParameterList *TemplateParams =
12505  TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
12506  isExplicitSpecialization, Invalid)) {
12507  if (TemplateParams->size() > 0) {
12508  // This is a declaration of a class template.
12509  if (Invalid)
12510  return nullptr;
12511 
12512  return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
12513  NameLoc, Attr, TemplateParams, AS_public,
12514  /*ModulePrivateLoc=*/SourceLocation(),
12515  FriendLoc, TempParamLists.size() - 1,
12516  TempParamLists.data()).get();
12517  } else {
12518  // The "template<>" header is extraneous.
12519  Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12521  isExplicitSpecialization = true;
12522  }
12523  }
12524 
12525  if (Invalid) return nullptr;
12526 
12527  bool isAllExplicitSpecializations = true;
12528  for (unsigned I = TempParamLists.size(); I-- > 0; ) {
12529  if (TempParamLists[I]->size()) {
12530  isAllExplicitSpecializations = false;
12531  break;
12532  }
12533  }
12534 
12535  // FIXME: don't ignore attributes.
12536 
12537  // If it's explicit specializations all the way down, just forget
12538  // about the template header and build an appropriate non-templated
12539  // friend. TODO: for source fidelity, remember the headers.
12540  if (isAllExplicitSpecializations) {
12541  if (SS.isEmpty()) {
12542  bool Owned = false;
12543  bool IsDependent = false;
12544  return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
12545  Attr, AS_public,
12546  /*ModulePrivateLoc=*/SourceLocation(),
12547  MultiTemplateParamsArg(), Owned, IsDependent,
12548  /*ScopedEnumKWLoc=*/SourceLocation(),
12549  /*ScopedEnumUsesClassTag=*/false,
12550  /*UnderlyingType=*/TypeResult(),
12551  /*IsTypeSpecifier=*/false);
12552  }
12553 
12555  ElaboratedTypeKeyword Keyword
12557  QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
12558  *Name, NameLoc);
12559  if (T.isNull())
12560  return nullptr;
12561 
12563  if (isa<DependentNameType>(T)) {
12566  TL.setElaboratedKeywordLoc(TagLoc);
12567  TL.setQualifierLoc(QualifierLoc);
12568  TL.setNameLoc(NameLoc);
12569  } else {
12571  TL.setElaboratedKeywordLoc(TagLoc);
12572  TL.setQualifierLoc(QualifierLoc);
12573  TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
12574  }
12575 
12576  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12577  TSI, FriendLoc, TempParamLists);
12578  Friend->setAccess(AS_public);
12579  CurContext->addDecl(Friend);
12580  return Friend;
12581  }
12582 
12583  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12584 
12585 
12586 
12587  // Handle the case of a templated-scope friend class. e.g.
12588  // template <class T> class A<T>::B;
12589  // FIXME: we don't support these right now.
12590  Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12591  << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
12596  TL.setElaboratedKeywordLoc(TagLoc);
12598  TL.setNameLoc(NameLoc);
12599 
12600  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12601  TSI, FriendLoc, TempParamLists);
12602  Friend->setAccess(AS_public);
12603  Friend->setUnsupportedFriend(true);
12604  CurContext->addDecl(Friend);
12605  return Friend;
12606 }
12607 
12608 
12609 /// Handle a friend type declaration. This works in tandem with
12610 /// ActOnTag.
12611 ///
12612 /// Notes on friend class templates:
12613 ///
12614 /// We generally treat friend class declarations as if they were
12615 /// declaring a class. So, for example, the elaborated type specifier
12616 /// in a friend declaration is required to obey the restrictions of a
12617 /// class-head (i.e. no typedefs in the scope chain), template
12618 /// parameters are required to match up with simple template-ids, &c.
12619 /// However, unlike when declaring a template specialization, it's
12620 /// okay to refer to a template specialization without an empty
12621 /// template parameter declaration, e.g.
12622 /// friend class A<T>::B<unsigned>;
12623 /// We permit this as a special case; if there are any template
12624 /// parameters present at all, require proper matching, i.e.
12625 /// template <> template <class T> friend class A<int>::B;
12627  MultiTemplateParamsArg TempParams) {
12628  SourceLocation Loc = DS.getLocStart();
12629 
12630  assert(DS.isFriendSpecified());
12632 
12633  // Try to convert the decl specifier to a type. This works for
12634  // friend templates because ActOnTag never produces a ClassTemplateDecl
12635  // for a TUK_Friend.
12636  Declarator TheDeclarator(DS, Declarator::MemberContext);
12637  TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12638  QualType T = TSI->getType();
12639  if (TheDeclarator.isInvalidType())
12640  return nullptr;
12641 
12643  return nullptr;
12644 
12645  // This is definitely an error in C++98. It's probably meant to
12646  // be forbidden in C++0x, too, but the specification is just
12647  // poorly written.
12648  //
12649  // The problem is with declarations like the following:
12650  // template <T> friend A<T>::foo;
12651  // where deciding whether a class C is a friend or not now hinges
12652  // on whether there exists an instantiation of A that causes
12653  // 'foo' to equal C. There are restrictions on class-heads
12654  // (which we declare (by fiat) elaborated friend declarations to
12655  // be) that makes this tractable.
12656  //
12657  // FIXME: handle "template <> friend class A<T>;", which
12658  // is possibly well-formed? Who even knows?
12659  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
12660  Diag(Loc, diag::err_tagless_friend_type_template)
12661  << DS.getSourceRange();
12662  return nullptr;
12663  }
12664 
12665  // C++98 [class.friend]p1: A friend of a class is a function
12666  // or class that is not a member of the class . . .
12667  // This is fixed in DR77, which just barely didn't make the C++03
12668  // deadline. It's also a very silly restriction that seriously
12669  // affects inner classes and which nobody else seems to implement;
12670  // thus we never diagnose it, not even in -pedantic.
12671  //
12672  // But note that we could warn about it: it's always useless to
12673  // friend one of your own members (it's not, however, worthless to
12674  // friend a member of an arbitrary specialization of your template).
12675 
12676  Decl *D;
12677  if (!TempParams.empty())
12679  TempParams,
12680  TSI,
12681  DS.getFriendSpecLoc());
12682  else
12683  D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
12684 
12685  if (!D)
12686  return nullptr;
12687 
12688  D->setAccess(AS_public);
12689  CurContext->addDecl(D);
12690 
12691  return D;
12692 }
12693 
12695  MultiTemplateParamsArg TemplateParams) {
12696  const DeclSpec &DS = D.getDeclSpec();
12697 
12698  assert(DS.isFriendSpecified());
12700 
12701  SourceLocation Loc = D.getIdentifierLoc();
12702  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12703 
12704  // C++ [class.friend]p1
12705  // A friend of a class is a function or class....
12706  // Note that this sees through typedefs, which is intended.
12707  // It *doesn't* see through dependent types, which is correct
12708  // according to [temp.arg.type]p3:
12709  // If a declaration acquires a function type through a
12710  // type dependent on a template-parameter and this causes
12711  // a declaration that does not use the syntactic form of a
12712  // function declarator to have a function type, the program
12713  // is ill-formed.
12714  if (!TInfo->getType()->isFunctionType()) {
12715  Diag(Loc, diag::err_unexpected_friend);
12716 
12717  // It might be worthwhile to try to recover by creating an
12718  // appropriate declaration.
12719  return nullptr;
12720  }
12721 
12722  // C++ [namespace.memdef]p3
12723  // - If a friend declaration in a non-local class first declares a
12724  // class or function, the friend class or function is a member
12725  // of the innermost enclosing namespace.
12726  // - The name of the friend is not found by simple name lookup
12727  // until a matching declaration is provided in that namespace
12728  // scope (either before or after the class declaration granting
12729  // friendship).
12730  // - If a friend function is called, its name may be found by the
12731  // name lookup that considers functions from namespaces and
12732  // classes associated with the types of the function arguments.
12733  // - When looking for a prior declaration of a class or a function
12734  // declared as a friend, scopes outside the innermost enclosing
12735  // namespace scope are not considered.
12736 
12737  CXXScopeSpec &SS = D.getCXXScopeSpec();
12739  DeclarationName Name = NameInfo.getName();
12740  assert(Name);
12741 
12742  // Check for unexpanded parameter packs.
12746  return nullptr;
12747 
12748  // The context we found the declaration in, or in which we should
12749  // create the declaration.
12750  DeclContext *DC;
12751  Scope *DCScope = S;
12752  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12754 
12755  // There are five cases here.
12756  // - There's no scope specifier and we're in a local class. Only look
12757  // for functions declared in the immediately-enclosing block scope.
12758  // We recover from invalid scope qualifiers as if they just weren't there.
12759  FunctionDecl *FunctionContainingLocalClass = nullptr;
12760  if ((SS.isInvalid() || !SS.isSet()) &&
12761  (FunctionContainingLocalClass =
12762  cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12763  // C++11 [class.friend]p11:
12764  // If a friend declaration appears in a local class and the name
12765  // specified is an unqualified name, a prior declaration is
12766  // looked up without considering scopes that are outside the
12767  // innermost enclosing non-class scope. For a friend function
12768  // declaration, if there is no prior declaration, the program is
12769  // ill-formed.
12770 
12771  // Find the innermost enclosing non-class scope. This is the block
12772  // scope containing the local class definition (or for a nested class,
12773  // the outer local class).
12774  DCScope = S->getFnParent();
12775 
12776  // Look up the function name in the scope.
12777  Previous.clear(LookupLocalFriendName);
12778  LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12779 
12780  if (!Previous.empty()) {
12781  // All possible previous declarations must have the same context:
12782  // either they were declared at block scope or they are members of
12783  // one of the enclosing local classes.
12784  DC = Previous.getRepresentativeDecl()->getDeclContext();
12785  } else {
12786  // This is ill-formed, but provide the context that we would have
12787  // declared the function in, if we were permitted to, for error recovery.
12788  DC = FunctionContainingLocalClass;
12789  }
12791 
12792  // C++ [class.friend]p6:
12793  // A function can be defined in a friend declaration of a class if and
12794  // only if the class is a non-local class (9.8), the function name is
12795  // unqualified, and the function has namespace scope.
12796  if (D.isFunctionDefinition()) {
12797  Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12798  }
12799 
12800  // - There's no scope specifier, in which case we just go to the
12801  // appropriate scope and look for a function or function template
12802  // there as appropriate.
12803  } else if (SS.isInvalid() || !SS.isSet()) {
12804  // C++11 [namespace.memdef]p3:
12805  // If the name in a friend declaration is neither qualified nor
12806  // a template-id and the declaration is a function or an
12807  // elaborated-type-specifier, the lookup to determine whether
12808  // the entity has been previously declared shall not consider
12809  // any scopes outside the innermost enclosing namespace.
12810  bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
12811 
12812  // Find the appropriate context according to the above.
12813  DC = CurContext;
12814 
12815  // Skip class contexts. If someone can cite chapter and verse
12816  // for this behavior, that would be nice --- it's what GCC and
12817  // EDG do, and it seems like a reasonable intent, but the spec
12818  // really only says that checks for unqualified existing
12819  // declarations should stop at the nearest enclosing namespace,
12820  // not that they should only consider the nearest enclosing
12821  // namespace.
12822  while (DC->isRecord())
12823  DC = DC->getParent();
12824 
12825  DeclContext *LookupDC = DC;
12826  while (LookupDC->isTransparentContext())
12827  LookupDC = LookupDC->getParent();
12828 
12829  while (true) {
12830  LookupQualifiedName(Previous, LookupDC);
12831 
12832  if (!Previous.empty()) {
12833  DC = LookupDC;
12834  break;
12835  }
12836 
12837  if (isTemplateId) {
12838  if (isa<TranslationUnitDecl>(LookupDC)) break;
12839  } else {
12840  if (LookupDC->isFileContext()) break;
12841  }
12842  LookupDC = LookupDC->getParent();
12843  }
12844 
12845  DCScope = getScopeForDeclContext(S, DC);
12846 
12847  // - There's a non-dependent scope specifier, in which case we
12848  // compute it and do a previous lookup there for a function
12849  // or function template.
12850  } else if (!SS.getScopeRep()->isDependent()) {
12851  DC = computeDeclContext(SS);
12852  if (!DC) return nullptr;
12853 
12854  if (RequireCompleteDeclContext(SS, DC)) return nullptr;
12855 
12856  LookupQualifiedName(Previous, DC);
12857 
12858  // Ignore things found implicitly in the wrong scope.
12859  // TODO: better diagnostics for this case. Suggesting the right
12860  // qualified scope would be nice...
12861  LookupResult::Filter F = Previous.makeFilter();
12862  while (F.hasNext()) {
12863  NamedDecl *D = F.next();
12864  if (!DC->InEnclosingNamespaceSetOf(
12865  D->getDeclContext()->getRedeclContext()))
12866  F.erase();
12867  }
12868  F.done();
12869 
12870  if (Previous.empty()) {
12871  D.setInvalidType();
12872  Diag(Loc, diag::err_qualified_friend_not_found)
12873  << Name << TInfo->getType();
12874  return nullptr;
12875  }
12876 
12877  // C++ [class.friend]p1: A friend of a class is a function or
12878  // class that is not a member of the class . . .
12879  if (DC->Equals(CurContext))
12880  Diag(DS.getFriendSpecLoc(),
12881  getLangOpts().CPlusPlus11 ?
12882  diag::warn_cxx98_compat_friend_is_member :
12883  diag::err_friend_is_member);
12884 
12885  if (D.isFunctionDefinition()) {
12886  // C++ [class.friend]p6:
12887  // A function can be defined in a friend declaration of a class if and
12888  // only if the class is a non-local class (9.8), the function name is
12889  // unqualified, and the function has namespace scope.
12891  = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12892 
12893  DB << SS.getScopeRep();
12894  if (DC->isFileContext())
12895  DB << FixItHint::CreateRemoval(SS.getRange());
12896  SS.clear();
12897  }
12898 
12899  // - There's a scope specifier that does not match any template
12900  // parameter lists, in which case we use some arbitrary context,
12901  // create a method or method template, and wait for instantiation.
12902  // - There's a scope specifier that does match some template
12903  // parameter lists, which we don't handle right now.
12904  } else {
12905  if (D.isFunctionDefinition()) {
12906  // C++ [class.friend]p6:
12907  // A function can be defined in a friend declaration of a class if and
12908  // only if the class is a non-local class (9.8), the function name is
12909  // unqualified, and the function has namespace scope.
12910  Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12911  << SS.getScopeRep();
12912  }
12913 
12914  DC = CurContext;
12915  assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
12916  }
12917 
12918  if (!DC->isRecord()) {
12919  int DiagArg = -1;
12920  switch (D.getName().getKind()) {
12923  DiagArg = 0;
12924  break;
12926  DiagArg = 1;
12927  break;
12929  DiagArg = 2;
12930  break;
12936  break;
12937  }
12938  // This implies that it has to be an operator or function.
12939  if (DiagArg >= 0) {
12940  Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
12941  return nullptr;
12942  }
12943  }
12944 
12945  // FIXME: This is an egregious hack to cope with cases where the scope stack
12946  // does not contain the declaration context, i.e., in an out-of-line
12947  // definition of a class.
12948  Scope FakeDCScope(S, Scope::DeclScope, Diags);
12949  if (!DCScope) {
12950  FakeDCScope.setEntity(DC);
12951  DCScope = &FakeDCScope;
12952  }
12953 
12954  bool AddToScope = true;
12955  NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
12956  TemplateParams, AddToScope);
12957  if (!ND) return nullptr;
12958 
12959  assert(ND->getLexicalDeclContext() == CurContext);
12960 
12961  // If we performed typo correction, we might have added a scope specifier
12962  // and changed the decl context.
12963  DC = ND->getDeclContext();
12964 
12965  // Add the function declaration to the appropriate lookup tables,
12966  // adjusting the redeclarations list as necessary. We don't
12967  // want to do this yet if the friending class is dependent.
12968  //
12969  // Also update the scope-based lookup if the target context's
12970  // lookup context is in lexical scope.
12971  if (!CurContext->isDependentContext()) {
12972  DC = DC->getRedeclContext();
12973  DC->makeDeclVisibleInContext(ND);
12974  if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12975  PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
12976  }
12977 
12979  D.getIdentifierLoc(), ND,
12980  DS.getFriendSpecLoc());
12981  FrD->setAccess(AS_public);
12982  CurContext->addDecl(FrD);
12983 
12984  if (ND->isInvalidDecl()) {
12985  FrD->setInvalidDecl();
12986  } else {
12987  if (DC->isRecord()) CheckFriendAccess(ND);
12988 
12989  FunctionDecl *FD;
12990  if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12991  FD = FTD->getTemplatedDecl();
12992  else
12993  FD = cast<FunctionDecl>(ND);
12994 
12995  // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12996  // default argument expression, that declaration shall be a definition
12997  // and shall be the only declaration of the function or function
12998  // template in the translation unit.
13000  if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
13001  Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
13002  Diag(OldFD->getLocation(), diag::note_previous_declaration);
13003  } else if (!D.isFunctionDefinition())
13004  Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
13005  }
13006 
13007  // Mark templated-scope function declarations as unsupported.
13008  if (FD->getNumTemplateParameterLists() && SS.isValid()) {
13009  Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
13010  << SS.getScopeRep() << SS.getRange()
13011  << cast<CXXRecordDecl>(CurContext);
13012  FrD->setUnsupportedFriend(true);
13013  }
13014  }
13015 
13016  return ND;
13017 }
13018 
13019 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
13020  AdjustDeclIfTemplate(Dcl);
13021 
13022  FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
13023  if (!Fn) {
13024  Diag(DelLoc, diag::err_deleted_non_function);
13025  return;
13026  }
13027 
13028  if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
13029  // Don't consider the implicit declaration we generate for explicit
13030  // specializations. FIXME: Do not generate these implicit declarations.
13031  if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
13032  Prev->getPreviousDecl()) &&
13033  !Prev->isDefined()) {
13034  Diag(DelLoc, diag::err_deleted_decl_not_first);
13035  Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
13036  Prev->isImplicit() ? diag::note_previous_implicit_declaration
13037  : diag::note_previous_declaration);
13038  }
13039  // If the declaration wasn't the first, we delete the function anyway for
13040  // recovery.
13041  Fn = Fn->getCanonicalDecl();
13042  }
13043 
13044  // dllimport/dllexport cannot be deleted.
13045  if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
13046  Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
13047  Fn->setInvalidDecl();
13048  }
13049 
13050  if (Fn->isDeleted())
13051  return;
13052 
13053  // See if we're deleting a function which is already known to override a
13054  // non-deleted virtual function.
13055  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
13056  bool IssuedDiagnostic = false;
13058  E = MD->end_overridden_methods();
13059  I != E; ++I) {
13060  if (!(*MD->begin_overridden_methods())->isDeleted()) {
13061  if (!IssuedDiagnostic) {
13062  Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
13063  IssuedDiagnostic = true;
13064  }
13065  Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
13066  }
13067  }
13068  }
13069 
13070  // C++11 [basic.start.main]p3:
13071  // A program that defines main as deleted [...] is ill-formed.
13072  if (Fn->isMain())
13073  Diag(DelLoc, diag::err_deleted_main);
13074 
13075  Fn->setDeletedAsWritten();
13076 }
13077 
13078 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
13079  CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
13080 
13081  if (MD) {
13082  if (MD->getParent()->isDependentType()) {
13083  MD->setDefaulted();
13084  MD->setExplicitlyDefaulted();
13085  return;
13086  }
13087 
13088  CXXSpecialMember Member = getSpecialMember(MD);
13089  if (Member == CXXInvalid) {
13090  if (!MD->isInvalidDecl())
13091  Diag(DefaultLoc, diag::err_default_special_members);
13092  return;
13093  }
13094 
13095  MD->setDefaulted();
13096  MD->setExplicitlyDefaulted();
13097 
13098  // If this definition appears within the record, do the checking when
13099  // the record is complete.
13100  const FunctionDecl *Primary = MD;
13101  if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
13102  // Ask the template instantiation pattern that actually had the
13103  // '= default' on it.
13104  Primary = Pattern;
13105 
13106  // If the method was defaulted on its first declaration, we will have
13107  // already performed the checking in CheckCompletedCXXClass. Such a
13108  // declaration doesn't trigger an implicit definition.
13109  if (Primary->getCanonicalDecl()->isDefaulted())
13110  return;
13111 
13113 
13114  if (!MD->isInvalidDecl())
13115  DefineImplicitSpecialMember(*this, MD, DefaultLoc);
13116  } else {
13117  Diag(DefaultLoc, diag::err_default_special_members);
13118  }
13119 }
13120 
13121 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
13122  for (Stmt *SubStmt : S->children()) {
13123  if (!SubStmt)
13124  continue;
13125  if (isa<ReturnStmt>(SubStmt))
13126  Self.Diag(SubStmt->getLocStart(),
13127  diag::err_return_in_constructor_handler);
13128  if (!isa<Expr>(SubStmt))
13129  SearchForReturnInStmt(Self, SubStmt);
13130  }
13131 }
13132 
13134  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
13135  CXXCatchStmt *Handler = TryBlock->getHandler(I);
13136  SearchForReturnInStmt(*this, Handler);
13137  }
13138 }
13139 
13141  const CXXMethodDecl *Old) {
13142  const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
13143  const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
13144 
13145  CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
13146 
13147  // If the calling conventions match, everything is fine
13148  if (NewCC == OldCC)
13149  return false;
13150 
13151  // If the calling conventions mismatch because the new function is static,
13152  // suppress the calling convention mismatch error; the error about static
13153  // function override (err_static_overrides_virtual from
13154  // Sema::CheckFunctionDeclaration) is more clear.
13155  if (New->getStorageClass() == SC_Static)
13156  return false;
13157 
13158  Diag(New->getLocation(),
13159  diag::err_conflicting_overriding_cc_attributes)
13160  << New->getDeclName() << New->getType() << Old->getType();
13161  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
13162  return true;
13163 }
13164 
13166  const CXXMethodDecl *Old) {
13167  QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
13168  QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
13169 
13170  if (Context.hasSameType(NewTy, OldTy) ||
13171  NewTy->isDependentType() || OldTy->isDependentType())
13172  return false;
13173 
13174  // Check if the return types are covariant
13175  QualType NewClassTy, OldClassTy;
13176 
13177  /// Both types must be pointers or references to classes.
13178  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
13179  if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
13180  NewClassTy = NewPT->getPointeeType();
13181  OldClassTy = OldPT->getPointeeType();
13182  }
13183  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
13184  if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
13185  if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
13186  NewClassTy = NewRT->getPointeeType();
13187  OldClassTy = OldRT->getPointeeType();
13188  }
13189  }
13190  }
13191 
13192  // The return types aren't either both pointers or references to a class type.
13193  if (NewClassTy.isNull()) {
13194  Diag(New->getLocation(),
13195  diag::err_different_return_type_for_overriding_virtual_function)
13196  << New->getDeclName() << NewTy << OldTy
13197  << New->getReturnTypeSourceRange();
13198  Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13199  << Old->getReturnTypeSourceRange();
13200 
13201  return true;
13202  }
13203 
13204  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
13205  // C++14 [class.virtual]p8:
13206  // If the class type in the covariant return type of D::f differs from
13207  // that of B::f, the class type in the return type of D::f shall be
13208  // complete at the point of declaration of D::f or shall be the class
13209  // type D.
13210  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
13211  if (!RT->isBeingDefined() &&
13212  RequireCompleteType(New->getLocation(), NewClassTy,
13213  diag::err_covariant_return_incomplete,
13214  New->getDeclName()))
13215  return true;
13216  }
13217 
13218  // Check if the new class derives from the old class.
13219  if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
13220  Diag(New->getLocation(), diag::err_covariant_return_not_derived)
13221  << New->getDeclName() << NewTy << OldTy
13222  << New->getReturnTypeSourceRange();
13223  Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13224  << Old->getReturnTypeSourceRange();
13225  return true;
13226  }
13227 
13228  // Check if we the conversion from derived to base is valid.
13230  NewClassTy, OldClassTy,
13231  diag::err_covariant_return_inaccessible_base,
13232  diag::err_covariant_return_ambiguous_derived_to_base_conv,
13233  New->getLocation(), New->getReturnTypeSourceRange(),
13234  New->getDeclName(), nullptr)) {
13235  // FIXME: this note won't trigger for delayed access control
13236  // diagnostics, and it's impossible to get an undelayed error
13237  // here from access control during the original parse because
13238  // the ParsingDeclSpec/ParsingDeclarator are still in scope.
13239  Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13240  << Old->getReturnTypeSourceRange();
13241  return true;
13242  }
13243  }
13244 
13245  // The qualifiers of the return types must be the same.
13246  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
13247  Diag(New->getLocation(),
13248  diag::err_covariant_return_type_different_qualifications)
13249  << New->getDeclName() << NewTy << OldTy
13250  << New->getReturnTypeSourceRange();
13251  Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13252  << Old->getReturnTypeSourceRange();
13253  return true;
13254  }
13255 
13256 
13257  // The new class type must have the same or less qualifiers as the old type.
13258  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
13259  Diag(New->getLocation(),
13260  diag::err_covariant_return_type_class_type_more_qualified)
13261  << New->getDeclName() << NewTy << OldTy
13262  << New->getReturnTypeSourceRange();
13263  Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13264  << Old->getReturnTypeSourceRange();
13265  return true;
13266  }
13267 
13268  return false;
13269 }
13270 
13271 /// \brief Mark the given method pure.
13272 ///
13273 /// \param Method the method to be marked pure.
13274 ///
13275 /// \param InitRange the source range that covers the "0" initializer.
13277  SourceLocation EndLoc = InitRange.getEnd();
13278  if (EndLoc.isValid())
13279  Method->setRangeEnd(EndLoc);
13280 
13281  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
13282  Method->setPure();
13283  return false;
13284  }
13285 
13286  if (!Method->isInvalidDecl())
13287  Diag(Method->getLocation(), diag::err_non_virtual_pure)
13288  << Method->getDeclName() << InitRange;
13289  return true;
13290 }
13291 
13293  if (D->getFriendObjectKind())
13294  Diag(D->getLocation(), diag::err_pure_friend);
13295  else if (auto *M = dyn_cast<CXXMethodDecl>(D))
13296  CheckPureMethod(M, ZeroLoc);
13297  else
13298  Diag(D->getLocation(), diag::err_illegal_initializer);
13299 }
13300 
13301 /// \brief Determine whether the given declaration is a static data member.
13302 static bool isStaticDataMember(const Decl *D) {
13303  if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
13304  return Var->isStaticDataMember();
13305 
13306  return false;
13307 }
13308 
13309 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
13310 /// an initializer for the out-of-line declaration 'Dcl'. The scope
13311 /// is a fresh scope pushed for just this purpose.
13312 ///
13313 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
13314 /// static data member of class X, names should be looked up in the scope of
13315 /// class X.
13317  // If there is no declaration, there was an error parsing it.
13318  if (!D || D->isInvalidDecl())
13319  return;
13320 
13321  // We will always have a nested name specifier here, but this declaration
13322  // might not be out of line if the specifier names the current namespace:
13323  // extern int n;
13324  // int ::n = 0;
13325  if (D->isOutOfLine())
13326  EnterDeclaratorContext(S, D->getDeclContext());
13327 
13328  // If we are parsing the initializer for a static data member, push a
13329  // new expression evaluation context that is associated with this static
13330  // data member.
13331  if (isStaticDataMember(D))
13333 }
13334 
13335 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
13336 /// initializer for the out-of-line declaration 'D'.
13338  // If there is no declaration, there was an error parsing it.
13339  if (!D || D->isInvalidDecl())
13340  return;
13341 
13342  if (isStaticDataMember(D))
13344 
13345  if (D->isOutOfLine())
13347 }
13348 
13349 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
13350 /// C++ if/switch/while/for statement.
13351 /// e.g: "if (int x = f()) {...}"
13353  // C++ 6.4p2:
13354  // The declarator shall not specify a function or an array.
13355  // The type-specifier-seq shall not contain typedef and shall not declare a
13356  // new class or enumeration.
13358  "Parser allowed 'typedef' as storage class of condition decl.");
13359 
13360  Decl *Dcl = ActOnDeclarator(S, D);
13361  if (!Dcl)
13362  return true;
13363 
13364  if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
13365  Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
13366  << D.getSourceRange();
13367  return true;
13368  }
13369 
13370  return Dcl;
13371 }
13372 
13374  if (!ExternalSource)
13375  return;
13376 
13378  ExternalSource->ReadUsedVTables(VTables);
13379  SmallVector<VTableUse, 4> NewUses;
13380  for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
13382  = VTablesUsed.find(VTables[I].Record);
13383  // Even if a definition wasn't required before, it may be required now.
13384  if (Pos != VTablesUsed.end()) {
13385  if (!Pos->second && VTables[I].DefinitionRequired)
13386  Pos->second = true;
13387  continue;
13388  }
13389 
13390  VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
13391  NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
13392  }
13393 
13394  VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
13395 }
13396 
13398  bool DefinitionRequired) {
13399  // Ignore any vtable uses in unevaluated operands or for classes that do
13400  // not have a vtable.
13401  if (!Class->isDynamicClass() || Class->isDependentContext() ||
13403  return;
13404 
13405  // Try to insert this class into the map.
13407  Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13409  Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
13410  if (!Pos.second) {
13411  // If we already had an entry, check to see if we are promoting this vtable
13412  // to require a definition. If so, we need to reappend to the VTableUses
13413  // list, since we may have already processed the first entry.
13414  if (DefinitionRequired && !Pos.first->second) {
13415  Pos.first->second = true;
13416  } else {
13417  // Otherwise, we can early exit.
13418  return;
13419  }
13420  } else {
13421  // The Microsoft ABI requires that we perform the destructor body
13422  // checks (i.e. operator delete() lookup) when the vtable is marked used, as
13423  // the deleting destructor is emitted with the vtable, not with the
13424  // destructor definition as in the Itanium ABI.
13426  CXXDestructorDecl *DD = Class->getDestructor();
13427  if (DD && DD->isVirtual() && !DD->isDeleted()) {
13428  if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
13429  // If this is an out-of-line declaration, marking it referenced will
13430  // not do anything. Manually call CheckDestructor to look up operator
13431  // delete().
13432  ContextRAII SavedContext(*this, DD);
13433  CheckDestructor(DD);
13434  } else {
13435  MarkFunctionReferenced(Loc, Class->getDestructor());
13436  }
13437  }
13438  }
13439  }
13440 
13441  // Local classes need to have their virtual members marked
13442  // immediately. For all other classes, we mark their virtual members
13443  // at the end of the translation unit.
13444  if (Class->isLocalClass())
13445  MarkVirtualMembersReferenced(Loc, Class);
13446  else
13447  VTableUses.push_back(std::make_pair(Class, Loc));
13448 }
13449 
13452  if (VTableUses.empty())
13453  return false;
13454 
13455  // Note: The VTableUses vector could grow as a result of marking
13456  // the members of a class as "used", so we check the size each
13457  // time through the loop and prefer indices (which are stable) to
13458  // iterators (which are not).
13459  bool DefinedAnything = false;
13460  for (unsigned I = 0; I != VTableUses.size(); ++I) {
13461  CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
13462  if (!Class)
13463  continue;
13464 
13465  SourceLocation Loc = VTableUses[I].second;
13466 
13467  bool DefineVTable = true;
13468 
13469  // If this class has a key function, but that key function is
13470  // defined in another translation unit, we don't need to emit the
13471  // vtable even though we're using it.
13472  const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
13473  if (KeyFunction && !KeyFunction->hasBody()) {
13474  // The key function is in another translation unit.
13475  DefineVTable = false;
13477  KeyFunction->getTemplateSpecializationKind();
13478  assert(TSK != TSK_ExplicitInstantiationDefinition &&
13479  TSK != TSK_ImplicitInstantiation &&
13480  "Instantiations don't have key functions");
13481  (void)TSK;
13482  } else if (!KeyFunction) {
13483  // If we have a class with no key function that is the subject
13484  // of an explicit instantiation declaration, suppress the
13485  // vtable; it will live with the explicit instantiation
13486  // definition.
13487  bool IsExplicitInstantiationDeclaration
13490  for (auto R : Class->redecls()) {
13492  = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
13494  IsExplicitInstantiationDeclaration = true;
13495  else if (TSK == TSK_ExplicitInstantiationDefinition) {
13496  IsExplicitInstantiationDeclaration = false;
13497  break;
13498  }
13499  }
13500 
13501  if (IsExplicitInstantiationDeclaration)
13502  DefineVTable = false;
13503  }
13504 
13505  // The exception specifications for all virtual members may be needed even
13506  // if we are not providing an authoritative form of the vtable in this TU.
13507  // We may choose to emit it available_externally anyway.
13508  if (!DefineVTable) {
13510  continue;
13511  }
13512 
13513  // Mark all of the virtual members of this class as referenced, so
13514  // that we can build a vtable. Then, tell the AST consumer that a
13515  // vtable for this class is required.
13516  DefinedAnything = true;
13517  MarkVirtualMembersReferenced(Loc, Class);
13518  CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13519  if (VTablesUsed[Canonical])
13520  Consumer.HandleVTable(Class);
13521 
13522  // Optionally warn if we're emitting a weak vtable.
13523  if (Class->isExternallyVisible() &&
13525  const FunctionDecl *KeyFunctionDef = nullptr;
13526  if (!KeyFunction ||
13527  (KeyFunction->hasBody(KeyFunctionDef) &&
13528  KeyFunctionDef->isInlined()))
13529  Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
13531  ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
13532  << Class;
13533  }
13534  }
13535  VTableUses.clear();
13536 
13537  return DefinedAnything;
13538 }
13539 
13541  const CXXRecordDecl *RD) {
13542  for (const auto *I : RD->methods())
13543  if (I->isVirtual() && !I->isPure())
13544  ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
13545 }
13546 
13548  const CXXRecordDecl *RD) {
13549  // Mark all functions which will appear in RD's vtable as used.
13550  CXXFinalOverriderMap FinalOverriders;
13551  RD->getFinalOverriders(FinalOverriders);
13552  for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
13553  E = FinalOverriders.end();
13554  I != E; ++I) {
13555  for (OverridingMethods::const_iterator OI = I->second.begin(),
13556  OE = I->second.end();
13557  OI != OE; ++OI) {
13558  assert(OI->second.size() > 0 && "no final overrider");
13559  CXXMethodDecl *Overrider = OI->second.front().Method;
13560 
13561  // C++ [basic.def.odr]p2:
13562  // [...] A virtual member function is used if it is not pure. [...]
13563  if (!Overrider->isPure())
13564  MarkFunctionReferenced(Loc, Overrider);
13565  }
13566  }
13567 
13568  // Only classes that have virtual bases need a VTT.
13569  if (RD->getNumVBases() == 0)
13570  return;
13571 
13572  for (const auto &I : RD->bases()) {
13573  const CXXRecordDecl *Base =
13574  cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
13575  if (Base->getNumVBases() == 0)
13576  continue;
13577  MarkVirtualMembersReferenced(Loc, Base);
13578  }
13579 }
13580 
13581 /// SetIvarInitializers - This routine builds initialization ASTs for the
13582 /// Objective-C implementation whose ivars need be initialized.
13584  if (!getLangOpts().CPlusPlus)
13585  return;
13586  if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
13589  if (ivars.empty())
13590  return;
13592  for (unsigned i = 0; i < ivars.size(); i++) {
13593  FieldDecl *Field = ivars[i];
13594  if (Field->isInvalidDecl())
13595  continue;
13596 
13597  CXXCtorInitializer *Member;
13599  InitializationKind InitKind =
13600  InitializationKind::CreateDefault(ObjCImplementation->getLocation());
13601 
13602  InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13603  ExprResult MemberInit =
13604  InitSeq.Perform(*this, InitEntity, InitKind, None);
13605  MemberInit = MaybeCreateExprWithCleanups(MemberInit);
13606  // Note, MemberInit could actually come back empty if no initialization
13607  // is required (e.g., because it would call a trivial default constructor)
13608  if (!MemberInit.get() || MemberInit.isInvalid())
13609  continue;
13610 
13611  Member =
13613  SourceLocation(),
13614  MemberInit.getAs<Expr>(),
13615  SourceLocation());
13616  AllToInit.push_back(Member);
13617 
13618  // Be sure that the destructor is accessible and is marked as referenced.
13619  if (const RecordType *RecordTy =
13621  ->getAs<RecordType>()) {
13622  CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
13623  if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
13624  MarkFunctionReferenced(Field->getLocation(), Destructor);
13625  CheckDestructorAccess(Field->getLocation(), Destructor,
13626  PDiag(diag::err_access_dtor_ivar)
13627  << Context.getBaseElementType(Field->getType()));
13628  }
13629  }
13630  }
13631  ObjCImplementation->setIvarInitializers(Context,
13632  AllToInit.data(), AllToInit.size());
13633  }
13634 }
13635 
13636 static
13638  llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13639  llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13640  llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13641  Sema &S) {
13642  if (Ctor->isInvalidDecl())
13643  return;
13644 
13645  CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13646 
13647  // Target may not be determinable yet, for instance if this is a dependent
13648  // call in an uninstantiated template.
13649  if (Target) {
13650  const FunctionDecl *FNTarget = nullptr;
13651  (void)Target->hasBody(FNTarget);
13652  Target = const_cast<CXXConstructorDecl*>(
13653  cast_or_null<CXXConstructorDecl>(FNTarget));
13654  }
13655 
13656  CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13657  // Avoid dereferencing a null pointer here.
13658  *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
13659 
13660  if (!Current.insert(Canonical).second)
13661  return;
13662 
13663  // We know that beyond here, we aren't chaining into a cycle.
13664  if (!Target || !Target->isDelegatingConstructor() ||
13665  Target->isInvalidDecl() || Valid.count(TCanonical)) {
13666  Valid.insert(Current.begin(), Current.end());
13667  Current.clear();
13668  // We've hit a cycle.
13669  } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13670  Current.count(TCanonical)) {
13671  // If we haven't diagnosed this cycle yet, do so now.
13672  if (!Invalid.count(TCanonical)) {
13673  S.Diag((*Ctor->init_begin())->getSourceLocation(),
13674  diag::warn_delegating_ctor_cycle)
13675  << Ctor;
13676 
13677  // Don't add a note for a function delegating directly to itself.
13678  if (TCanonical != Canonical)
13679  S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13680 
13681  CXXConstructorDecl *C = Target;
13682  while (C->getCanonicalDecl() != Canonical) {
13683  const FunctionDecl *FNTarget = nullptr;
13684  (void)C->getTargetConstructor()->hasBody(FNTarget);
13685  assert(FNTarget && "Ctor cycle through bodiless function");
13686 
13687  C = const_cast<CXXConstructorDecl*>(
13688  cast<CXXConstructorDecl>(FNTarget));
13689  S.Diag(C->getLocation(), diag::note_which_delegates_to);
13690  }
13691  }
13692 
13693  Invalid.insert(Current.begin(), Current.end());
13694  Current.clear();
13695  } else {
13696  DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13697  }
13698 }
13699 
13700 
13702  llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13703 
13705  I = DelegatingCtorDecls.begin(ExternalSource),
13706  E = DelegatingCtorDecls.end();
13707  I != E; ++I)
13708  DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
13709 
13710  for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13711  CE = Invalid.end();
13712  CI != CE; ++CI)
13713  (*CI)->setInvalidDecl();
13714 }
13715 
13716 namespace {
13717  /// \brief AST visitor that finds references to the 'this' expression.
13718  class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13719  Sema &S;
13720 
13721  public:
13722  explicit FindCXXThisExpr(Sema &S) : S(S) { }
13723 
13724  bool VisitCXXThisExpr(CXXThisExpr *E) {
13725  S.Diag(E->getLocation(), diag::err_this_static_member_func)
13726  << E->isImplicit();
13727  return false;
13728  }
13729  };
13730 }
13731 
13733  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13734  if (!TSInfo)
13735  return false;
13736 
13737  TypeLoc TL = TSInfo->getTypeLoc();
13739  if (!ProtoTL)
13740  return false;
13741 
13742  // C++11 [expr.prim.general]p3:
13743  // [The expression this] shall not appear before the optional
13744  // cv-qualifier-seq and it shall not appear within the declaration of a
13745  // static member function (although its type and value category are defined
13746  // within a static member function as they are within a non-static member
13747  // function). [ Note: this is because declaration matching does not occur
13748  // until the complete declarator is known. - end note ]
13749  const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13750  FindCXXThisExpr Finder(*this);
13751 
13752  // If the return type came after the cv-qualifier-seq, check it now.
13753  if (Proto->hasTrailingReturn() &&
13754  !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
13755  return true;
13756 
13757  // Check the exception specification.
13759  return true;
13760 
13762 }
13763 
13765  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13766  if (!TSInfo)
13767  return false;
13768 
13769  TypeLoc TL = TSInfo->getTypeLoc();
13771  if (!ProtoTL)
13772  return false;
13773 
13774  const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13775  FindCXXThisExpr Finder(*this);
13776 
13777  switch (Proto->getExceptionSpecType()) {
13778  case EST_Unparsed:
13779  case EST_Uninstantiated:
13780  case EST_Unevaluated:
13781  case EST_BasicNoexcept:
13782  case EST_DynamicNone:
13783  case EST_MSAny:
13784  case EST_None:
13785  break;
13786 
13787  case EST_ComputedNoexcept:
13788  if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13789  return true;
13790 
13791  case EST_Dynamic:
13792  for (const auto &E : Proto->exceptions()) {
13793  if (!Finder.TraverseType(E))
13794  return true;
13795  }
13796  break;
13797  }
13798 
13799  return false;
13800 }
13801 
13803  FindCXXThisExpr Finder(*this);
13804 
13805  // Check attributes.
13806  for (const auto *A : Method->attrs()) {
13807  // FIXME: This should be emitted by tblgen.
13808  Expr *Arg = nullptr;
13809  ArrayRef<Expr *> Args;
13810  if (const auto *G = dyn_cast<GuardedByAttr>(A))
13811  Arg = G->getArg();
13812  else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
13813  Arg = G->getArg();
13814  else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
13815  Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
13816  else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
13817  Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
13818  else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
13819  Arg = ETLF->getSuccessValue();
13820  Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
13821  } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
13822  Arg = STLF->getSuccessValue();
13823  Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
13824  } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
13825  Arg = LR->getArg();
13826  else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
13827  Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
13828  else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
13829  Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13830  else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
13831  Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13832  else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
13833  Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13834  else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
13835  Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13836 
13837  if (Arg && !Finder.TraverseStmt(Arg))
13838  return true;
13839 
13840  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13841  if (!Finder.TraverseStmt(Args[I]))
13842  return true;
13843  }
13844  }
13845 
13846  return false;
13847 }
13848 
13850  bool IsTopLevel, ExceptionSpecificationType EST,
13851  ArrayRef<ParsedType> DynamicExceptions,
13852  ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
13853  SmallVectorImpl<QualType> &Exceptions,
13855  Exceptions.clear();
13856  ESI.Type = EST;
13857  if (EST == EST_Dynamic) {
13858  Exceptions.reserve(DynamicExceptions.size());
13859  for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13860  // FIXME: Preserve type source info.
13861  QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13862 
13863  if (IsTopLevel) {
13865  collectUnexpandedParameterPacks(ET, Unexpanded);
13866  if (!Unexpanded.empty()) {
13868  DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
13869  Unexpanded);
13870  continue;
13871  }
13872  }
13873 
13874  // Check that the type is valid for an exception spec, and
13875  // drop it if not.
13876  if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13877  Exceptions.push_back(ET);
13878  }
13879  ESI.Exceptions = Exceptions;
13880  return;
13881  }
13882 
13883  if (EST == EST_ComputedNoexcept) {
13884  // If an error occurred, there's no expression here.
13885  if (NoexceptExpr) {
13886  assert((NoexceptExpr->isTypeDependent() ||
13887  NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13888  Context.BoolTy) &&
13889  "Parser should have made sure that the expression is boolean");
13890  if (IsTopLevel && NoexceptExpr &&
13891  DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
13892  ESI.Type = EST_BasicNoexcept;
13893  return;
13894  }
13895 
13896  if (!NoexceptExpr->isValueDependent())
13897  NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
13898  diag::err_noexcept_needs_constant_expression,
13899  /*AllowFold*/ false).get();
13900  ESI.NoexceptExpr = NoexceptExpr;
13901  }
13902  return;
13903  }
13904 }
13905 
13908  SourceRange SpecificationRange,
13909  ArrayRef<ParsedType> DynamicExceptions,
13910  ArrayRef<SourceRange> DynamicExceptionRanges,
13911  Expr *NoexceptExpr) {
13912  if (!MethodD)
13913  return;
13914 
13915  // Dig out the method we're referring to.
13916  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
13917  MethodD = FunTmpl->getTemplatedDecl();
13918 
13919  CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
13920  if (!Method)
13921  return;
13922 
13923  // Check the exception specification.
13924  llvm::SmallVector<QualType, 4> Exceptions;
13926  checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
13927  DynamicExceptionRanges, NoexceptExpr, Exceptions,
13928  ESI);
13929 
13930  // Update the exception specification on the function type.
13931  Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
13932 
13933  if (Method->isStatic())
13935 
13936  if (Method->isVirtual()) {
13937  // Check overrides, which we previously had to delay.
13939  OEnd = Method->end_overridden_methods();
13940  O != OEnd; ++O)
13942  }
13943 }
13944 
13945 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13946 ///
13948  SourceLocation DeclStart,
13949  Declarator &D, Expr *BitWidth,
13950  InClassInitStyle InitStyle,
13951  AccessSpecifier AS,
13952  AttributeList *MSPropertyAttr) {
13953  IdentifierInfo *II = D.getIdentifier();
13954  if (!II) {
13955  Diag(DeclStart, diag::err_anonymous_property);
13956  return nullptr;
13957  }
13958  SourceLocation Loc = D.getIdentifierLoc();
13959 
13960  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13961  QualType T = TInfo->getType();
13962  if (getLangOpts().CPlusPlus) {
13964 
13967  D.setInvalidType();
13968  T = Context.IntTy;
13969  TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13970  }
13971  }
13972 
13974 
13975  if (D.getDeclSpec().isInlineSpecified())
13976  Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
13977  << getLangOpts().CPlusPlus1z;
13980  diag::err_invalid_thread)
13981  << DeclSpec::getSpecifierName(TSCS);
13982 
13983  // Check to see if this name was declared as a member previously
13984  NamedDecl *PrevDecl = nullptr;
13986  LookupName(Previous, S);
13987  switch (Previous.getResultKind()) {
13988  case LookupResult::Found:
13990  PrevDecl = Previous.getAsSingle<NamedDecl>();
13991  break;
13992 
13994  PrevDecl = Previous.getRepresentativeDecl();
13995  break;
13996 
14000  break;
14001  }
14002 
14003  if (PrevDecl && PrevDecl->isTemplateParameter()) {
14004  // Maybe we will complain about the shadowed template parameter.
14006  // Just pretend that we didn't see the previous declaration.
14007  PrevDecl = nullptr;
14008  }
14009 
14010  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14011  PrevDecl = nullptr;
14012 
14013  SourceLocation TSSL = D.getLocStart();
14014  const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
14016  Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
14017  ProcessDeclAttributes(TUScope, NewPD, D);
14018  NewPD->setAccess(AS);
14019 
14020  if (NewPD->isInvalidDecl())
14021  Record->setInvalidDecl();
14022 
14024  NewPD->setModulePrivate();
14025 
14026  if (NewPD->isInvalidDecl() && PrevDecl) {
14027  // Don't introduce NewFD into scope; there's already something
14028  // with the same name in the same scope.
14029  } else if (II) {
14030  PushOnScopeChains(NewPD, S);
14031  } else
14032  Record->addDecl(NewPD);
14033 
14034  return NewPD;
14035 }
QualType BuildStdInitializerList(QualType Element, SourceLocation Loc)
Looks for the std::initializer_list template and instantiates it with Element, or emits an error if i...
Abstract class used to diagnose incomplete types.
Definition: Sema.h:1341
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:266
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition: Scope.h:210
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:52
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:457
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl)
Definition: DeclCXX.cpp:2082
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:2411
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType) const
Defines the clang::ASTContext interface.
void ActOnFinishDelayedMemberInitializers(Decl *Record)
unsigned getNumInits() const
Definition: Expr.h:3776
VariadicCallType
Definition: Sema.h:8558
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1410
SourceLocation getEnd() const
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:64
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK)
Definition: SemaExpr.cpp:14402
CastKind getCastKind() const
Definition: Expr.h:2680
IdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:981
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1561
static StmtResult buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &To, const ExprBuilder &From, bool CopyingBaseSubobject, bool Copying, unsigned Depth=0)
Builds a statement that copies/moves the given entity from From to To.
static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, Expr *Init, SourceLocation IdLoc)
Checks a member initializer expression for cases where reference (or pointer) members are bound to by...
bool isVariadic() const
Definition: Type.h:3366
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl *&Operator, bool Diagnose=true)
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
Name lookup found a set of overloaded functions that met the criteria.
Definition: Sema/Lookup.h:47
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2097
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context, meaning that the members declared in this context are semantically declared in the nearest enclosing non-transparent (opaque) context but are lexically declared in this context.
Definition: DeclBase.cpp:954
bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef< CXXBaseSpecifier * > Bases)
Performs the actual work of attaching the given base class specifiers to a C++ class.
bool needsImplicitMoveConstructor() const
Determine whether this class should get an implicit move constructor or if any existing special membe...
Definition: DeclCXX.h:920
iterator begin() const
Definition: DeclBase.h:1103
unsigned RefQualifierIsLValueRef
Whether the ref-qualifier (if any) is an lvalue reference.
Definition: DeclSpec.h:1220
unsigned getDepth() const
Definition: Type.h:3945
StringRef getName() const
getName - Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:237
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
void CheckConstructor(CXXConstructorDecl *Constructor)
CheckConstructor - Checks a fully-formed constructor for well-formedness, issuing any diagnostics req...
no exception specification
bool needsOverloadResolutionForDestructor() const
Determine whether we need to eagerly declare a destructor for this class.
Definition: DeclCXX.h:1022
bool TemplateParameterListsAreEqual(TemplateParameterList *New, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2179
EvaluatedExprVisitor - This class visits 'Expr *'s.
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:542
CanQualType VoidPtrTy
Definition: ASTContext.h:908
A (possibly-)qualified type.
Definition: Type.h:598
ASTConsumer & Consumer
Definition: Sema.h:300
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition: DeclCXX.h:208
Simple class containing the result of Sema::CorrectTypo.
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:1967
base_class_range bases()
Definition: DeclCXX.h:718
bool isInvalid() const
Definition: Ownership.h:160
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:5647
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:541
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2217
bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B)
Determine if A and B are equivalent internal linkage declarations from different modules, and thus an ambiguity error can be downgraded to an extension warning.
NestedNameSpecifier * getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:571
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:2986
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2501
static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM, bool ConstArg, bool Diagnose)
Check whether the members of a class type allow a special member to be trivial.
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition: DeclSpec.h:1087
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:2361
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1269
void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace)
ActOnFinishNamespaceDef - This callback is called after a namespace is exited.
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
Definition: SemaDecl.cpp:5354
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:254
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition: DeclSpec.h:958
void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, FunctionDecl *Function)
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
static unsigned NumImplicitMoveAssignmentOperatorsDeclared
The number of implicitly-declared move assignment operators for which declarations were built...
Definition: ASTContext.h:2478
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
static TypeAliasTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
FunctionDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
std::unique_ptr< RecordDeclSetTy > PureVirtualClassDiagSet
PureVirtualClassDiagSet - a set of class declarations which we have emitted a list of pure virtual fu...
Definition: Sema.h:504
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc...
Definition: Sema.h:2705
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
Definition: Decl.h:232
DeclarationName getCXXConstructorName(CanQualType Ty)
getCXXConstructorName - Returns the name of a C++ constructor for the given Type. ...
method_range methods() const
Definition: DeclCXX.h:760
CanQualType Char32Ty
Definition: ASTContext.h:900
The subobject is a base class.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:1693
const LangOptions & getLangOpts() const
Definition: Sema.h:1062
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Sema/Lookup.h:252
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false)
Perform unqualified name lookup starting from a given scope.
const Scope * getFnParent() const
getFnParent - Return the closest scope that is a function body.
Definition: Scope.h:223
An initializer.
Definition: Sema.h:6112
static unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
Definition: ASTContext.h:2446
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
DeclClass * getAsSingle() const
Definition: Sema/Lookup.h:491
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration...
Definition: DeclCXX.h:1821
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID. ...
bool hasDefaultArg() const
hasDefaultArg - Determines whether this parameter has a default argument, either parsed or not...
Definition: Decl.cpp:2414
Expr *const * semantics_iterator
Definition: Expr.h:4745
static ClassTemplateDecl * LookupStdInitializerList(Sema &S, SourceLocation Loc)
IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId, the identifier suffix.
Definition: DeclSpec.h:931
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Sema/Lookup.h:508
Filter makeFilter()
Create a filter for this result set.
Definition: Sema/Lookup.h:665
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:1453
We are matching the template parameter lists of two templates that might be redeclarations.
Definition: Sema.h:5971
CXXMethodDecl * LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals)
Look up the moving assignment operator for the given class.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:3818
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:2879
CXXCatchStmt * getHandler(unsigned i)
Definition: StmtCXX.h:104
TypeLoc getNamedTypeLoc() const
Definition: TypeLoc.h:1759
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program...
Definition: Decl.cpp:2520
IfStmt - This represents an if/then/else.
Definition: Stmt.h:881
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type...
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD)
Check a completed declaration of an implicit special member.
IdentifierInfo * getCXXLiteralIdentifier() const
getCXXLiteralIdentifier - If this name is the name of a literal operator, retrieve the identifier ass...
CachedTokens * DefaultArgTokens
DefaultArgTokens - When the parameter's default argument cannot be parsed immediately (because it occ...
Definition: DeclSpec.h:1189
EnumConstantDecl - An instance of this object exists for each enum constant that is defined...
Definition: Decl.h:2481
StmtResult ActOnExprStmt(ExprResult Arg)
Definition: SemaStmt.cpp:44
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:218
void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnStartDelayedCXXMethodDeclaration - We have completed parsing a top-level (non-nested) C++ class...
static CharSourceRange getTokenRange(SourceRange R)
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
Definition: SemaDecl.cpp:10748
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:761
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed...
Definition: SemaExpr.cpp:4499
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition: Sema.h:819
static unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
Definition: ASTContext.h:2474
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:179
bool needsOverloadResolutionForCopyConstructor() const
Determine whether we need to eagerly declare a defaulted copy constructor for this class...
Definition: DeclCXX.h:869
void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class)
Force the declaration of any implicitly-declared members of this class.
Definition: SemaLookup.cpp:726
Expr * get() const
Definition: Sema.h:3312
A conversion function name, e.g., operator int.
Definition: DeclSpec.h:897
ctor_range ctors() const
Definition: DeclCXX.h:779
DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D)
ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a C++ if/switch/while/for statem...
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsExplicitSpecialization)
Perform semantic checking of a new function declaration.
Definition: SemaDecl.cpp:8637
void erase()
Erase the last element returned from this iterator.
Definition: Sema/Lookup.h:637
static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D)
Determine what kind of template specialization the given declaration is.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
bool isRecordType() const
Definition: Type.h:5539
QualType getUnderlyingType() const
Definition: Decl.h:2649
void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD)
Mark the exception specifications of all virtual member functions in the given class as needed...
StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef< Stmt * > Elts, bool isStmtExpr)
Definition: SemaStmt.cpp:332
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1139
void setRangeEnd(SourceLocation E)
Definition: Decl.h:1753
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr * > Args, SmallVectorImpl< Expr * > &AllArgs, VariadicCallType CallType=VariadicDoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
Definition: SemaExpr.cpp:4801
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc)
BuildCallToMemberFunction - Build a call to a member function.
static bool FindBaseInitializer(Sema &SemaRef, CXXRecordDecl *ClassDecl, QualType BaseType, const CXXBaseSpecifier *&DirectBaseSpec, const CXXBaseSpecifier *&VirtualBaseSpec)
Find the direct and/or virtual base specifiers that correspond to the given base type, for use in base initialization within a constructor.
void addDefaultArgExprForConstructor(const CXXConstructorDecl *CD, unsigned ParmIdx, Expr *DAE)
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl, bool ConsiderCudaAttrs=true)
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function...
Definition: SemaDecl.cpp:5292
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
StringRef P
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:713
void setPure(bool P=true)
Definition: Decl.cpp:2507
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src)
bool hasFlexibleArrayMember() const
Definition: Decl.h:3305
void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD)
MarkVirtualMembersReferenced - Will mark all members of the given CXXRecordDecl referenced.
bool isEnumeralType() const
Definition: Type.h:5542
SCS getStorageClassSpec() const
Definition: DeclSpec.h:447
void FindHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl< CXXMethodDecl * > &OverloadedMethods)
Check if a method overloads virtual methods in a base class without overriding any.
void AddDecl(Decl *D)
Definition: Scope.h:275
static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base)
Determine whether a direct base class is a virtual base class.
void ActOnBaseSpecifiers(Decl *ClassDecl, MutableArrayRef< CXXBaseSpecifier * > Bases)
ActOnBaseSpecifiers - Attach the given base specifiers to the class, after checking whether there are...
void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD)
Evaluate the implicit exception specification for a defaulted special member function.
PtrTy get() const
Definition: Ownership.h:164
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:4357
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type...
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition: Type.cpp:2404
IdentifierInfo * getAsIdentifierInfo() const
getAsIdentifierInfo - Retrieve the IdentifierInfo * stored in this declaration name, or NULL if this declaration name isn't a simple identifier.
The base class of the type hierarchy.
Definition: Type.h:1281
CXXRecordDecl * getAsRecordDecl() const
Retrieve the record declaration stored in this nested name specifier.
bool isElaboratedTypeSpecifier() const
Determine wither this type is a C++ elaborated-type-specifier.
Definition: Type.cpp:2494
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:922
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition: DeclCXX.h:1421
iterator begin() const
Definition: Sema/Lookup.h:319
void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnFinishDelayedCXXMethodDeclaration - We have finished processing the delayed method declaration f...
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:5292
unsigned getLength() const
Efficiently return the length of this identifier info.
MapType::iterator iterator
QualType getRecordType(const RecordDecl *Decl) const
One instance of this struct is used for each type in a declarator that is parsed. ...
Definition: DeclSpec.h:1101
bool isCopyConstructor(unsigned &TypeQuals) const
Whether this constructor is a copy constructor (C++ [class.copy]p2, which can be used to copy the cla...
Definition: DeclCXX.cpp:1872
Declaration of a variable template.
const Expr * getInit() const
Definition: Decl.h:1139
void MarkDeclRefReferenced(DeclRefExpr *E)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:14024
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
NamespaceDecl - Represent a C++ namespace.
Definition: Decl.h:471
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:46
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1162
static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc, CharSourceRange FromRange, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code from FromRange at a specific location...
Definition: Diagnostic.h:91
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition: DeclSpec.cpp:447
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:101
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:563
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:93
A container of type source information.
Definition: Decl.h:62
bool defaultedDefaultConstructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition: DeclCXX.h:1199
unsigned getIndex() const
Definition: Type.h:3946
const Stmt * getElse() const
Definition: Stmt.h:921
bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMember CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose)
Given a implicit special member, infer its CUDA target from the calls it needs to make to underlying ...
Definition: SemaCUDA.cpp:225
void PopDeclContext()
Definition: SemaDecl.cpp:1120
bool needsImplicitDestructor() const
Determine whether this class needs an implicit destructor to be lazily declared.
Definition: DeclCXX.h:1016
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, ArrayRef< TemplateParameterList * > FriendTypeTPLists=None)
Definition: DeclFriend.cpp:27
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2187
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition: Expr.cpp:2802
CanQualType WideCharTy
Definition: ASTContext.h:897
bool hasErrorOccurred() const
Determine whether any errors have occurred since this object instance was created.
Definition: Diagnostic.h:840
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2, C99 6.9p3)
Definition: SemaExpr.cpp:12949
Expr * getInClassInitializer() const
getInClassInitializer - Get the C++11 in-class initializer for this member, or null if one has not be...
Definition: Decl.h:2416
capture_iterator capture_begin() const
Retrieve an iterator pointing to the first lambda capture.
Definition: ExprCXX.cpp:944
InClassInitStyle getInClassInitStyle() const
getInClassInitStyle - Get the kind of (C++11) in-class initializer which this field has...
Definition: Decl.h:2400
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S)
MergeCXXFunctionDecl - Merge two declarations of the same C++ function, once we already know that the...
const llvm::APInt & getSize() const
Definition: Type.h:2527
void CheckCXXDefaultArguments(FunctionDecl *FD)
CheckCXXDefaultArguments - Verify that the default arguments for a function declaration are well-form...
RAII object to handle the state changes required to synthesize a function body.
Definition: Sema.h:668
Look up a namespace name within a C++ using directive or namespace alias definition, ignoring non-namespace names (C++ [basic.lookup.udir]p1).
Definition: Sema.h:2725
static InitializedEntity InitializeBase(ASTContext &Context, const CXXBaseSpecifier *Base, bool IsInheritedVirtualBase, const InitializedEntity *Parent=nullptr)
Create the initialization entity for a base class subobject.
Definition: SemaInit.cpp:2874
CXXMethodDecl * DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit move assignment operator for the given class.
static CXXConstructExpr * Create(const ASTContext &C, QualType T, SourceLocation Loc, CXXConstructorDecl *Ctor, bool Elidable, ArrayRef< Expr * > Args, bool HadMultipleCandidates, bool ListInitialization, bool StdInitListInitialization, bool ZeroInitialization, ConstructionKind ConstructKind, SourceRange ParenOrBraceRange)
Definition: ExprCXX.cpp:751
void ActOnFinishCXXNonNestedClass(Decl *D)
static void DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, const CXXConstructorDecl *Constructor, ArrayRef< CXXCtorInitializer * > Inits)
This file provides some common utility functions for processing Lambda related AST Constructs...
CXXConstructorDecl * LookupMovingConstructor(CXXRecordDecl *Class, unsigned Quals)
Look up the moving constructor for the given class.
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class, then each of the following shall have a name different from T:
Definition: SemaDecl.cpp:4806
bool isImplicit() const
Definition: ExprCXX.h:895
void ActOnDefaultCtorInitializers(Decl *CDtorDecl)
DeclContext::lookup_result Decls
The set of declarations found inside this base class subobject.
FriendDecl - Represents the declaration of a friend entity, which can be a function, a type, or a templated function or type.
Definition: DeclFriend.h:40
RAII object that enters a new expression evaluation context.
Definition: Sema.h:9606
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record)
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:768
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:25
CXXMethodDecl * LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals)
Look up the copying assignment operator for the given class.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
std::pair< CXXRecordDecl *, CXXSpecialMember > SpecialMemberDecl
Definition: Sema.h:1017
Expr * getInit() const
Get the initializer.
Definition: DeclCXX.h:2155
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1624
DiagnosticsEngine & Diags
Definition: Sema.h:301
Wrapper for source info for member pointers.
Definition: TypeLoc.h:1163
const Expr * getCallee() const
Definition: Expr.h:2188
void finishedDefaultedOrDeletedMember(CXXMethodDecl *MD)
Indicates that the declaration of a defaulted or deleted special member function is now complete...
Definition: DeclCXX.cpp:1000
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool IsForUsingDecl)
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
Extra information about a function prototype.
Definition: Type.h:3167
void clear()
Clear the base-paths results.
CallingConv getCallConv() const
Definition: Type.h:3017
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
field_iterator field_begin() const
Definition: Decl.cpp:3767
static MSPropertyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, IdentifierInfo *Getter, IdentifierInfo *Setter)
Definition: DeclCXX.cpp:2320
MapType::const_iterator const_iterator
The "__interface" keyword.
Definition: Type.h:4346
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:1813
RAII class that determines when any errors have occurred between the time the instance was created an...
Definition: Diagnostic.h:829
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:387
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition: Sema.h:9602
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:998
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition: DeclCXX.cpp:1883
Like System, but searched after the system directories.
SpecialMemberOverloadResult * LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMember SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis)
static StmtResult buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &ToB, const ExprBuilder &FromB)
When generating a defaulted copy or move assignment operator, if a field should be copied with __buil...
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:49
void setBegin(SourceLocation b)
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition: Type.h:4414
static InitializationKind CreateDirectList(SourceLocation InitLoc)
decl_iterator decls_end() const
Definition: DeclBase.h:1455
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
Definition: SemaDecl.cpp:7661
bool hasNonTrivialMoveAssignment() const
Determine whether this class has a non-trivial move assignment operator (C++11 [class.copy]p25)
Definition: DeclCXX.h:1261
void DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a function pointer.
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:1553
Decl * ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams)
Handle a friend type declaration.
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, bool Diagnose=false)
Determine whether a defaulted or deleted special member function is trivial, as specified in C++11 [c...
static AccessSpecDecl * Create(ASTContext &C, AccessSpecifier AS, DeclContext *DC, SourceLocation ASLoc, SourceLocation ColonLoc)
Definition: DeclCXX.h:130
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1377
bool isObjCRetainableType() const
Definition: Type.cpp:3699
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:1620
type_object_range type_objects() const
Returns the range of type objects, from the identifier outwards.
Definition: DeclSpec.h:2021
Defines the clang::Expr interface and subclasses for C++ expressions.
Parse and apply any fixits to the source.
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:1337
bool isUnionType() const
Definition: Type.cpp:391
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:189
iterator begin(Source *source, bool LocalOnly=false)
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:1739
bool isVoidType() const
Definition: Type.h:5680
bool isBaseInitializer() const
Determine whether this initializer is initializing a base class.
Definition: DeclCXX.h:2002
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
Definition: SemaDecl.cpp:3759
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old)
Merge the exception specifications of two variable declarations.
A reasonable base class for TypeLocs that correspond to types that are written as a type-specifier...
Definition: TypeLoc.h:485
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:2889
The collection of all-type qualifiers we support.
Definition: Type.h:117
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:5115
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitMoveConstructor - Checks for feasibility of defining this constructor as the move const...
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
FieldDecl * HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS)
HandleField - Analyze a field of a C struct or a C++ data member.
Definition: SemaDecl.cpp:13344
bool hasTrivialCopyConstructor() const
Determine whether this class has a trivial copy constructor (C++ [class.copy]p6, C++11 [class...
Definition: DeclCXX.h:1213
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:37
QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckConstructorDeclarator - Called by ActOnDeclarator to check the well-formedness of the constructo...
static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T)
Determine whether the given type is an incomplete or zero-lenfgth array type.
void CheckDelayedMemberExceptionSpecs()
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:40
unsigned getNumParams() const
Definition: Type.h:3271
AccessResult CheckFriendAccess(NamedDecl *D)
Checks access to the target of a friend declaration.
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3253
Decl * ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, AttributeList *AttrList, TypeResult Type, Decl *DeclFromDeclSpec)
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, InheritedConstructorInfo *ICI=nullptr, bool Diagnose=false)
Determine if a special member function should have a deleted definition when it is defaulted...
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body (definition).
Definition: Decl.cpp:2454
void LoadExternalVTableUses()
Load any externally-stored vtable uses.
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.h:2157
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2161
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1492
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:2623
static bool IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2)
Determine whether a using declaration considers the given declarations as "equivalent", e.g., if they are redeclarations of the same entity or are both typedefs of the same type.
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:952
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
DeclarationName getName() const
getName - Returns the embedded declaration name.
FunctionType::ExtInfo ExtInfo
Definition: Type.h:3182
Represents a class template specialization, which refers to a class template with a given set of temp...
One of these records is kept for each identifier that is lexed.
iterator end() const
Definition: Sema/Lookup.h:320
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Sema/Lookup.h:57
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1150
static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext)
Determine whether a using statement is in a context where it will be apply in all contexts...
Decl * ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident)
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:4567
void setRecordingPaths(bool RP)
Specify whether we should be recording paths or not.
method_iterator end_overridden_methods() const
Definition: DeclCXX.cpp:1655
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition: Decl.h:2466
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
Decl * ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, bool HasUsingKeyword, SourceLocation UsingLoc, CXXScopeSpec &SS, UnqualifiedId &Name, AttributeList *AttrList, bool HasTypenameKeyword, SourceLocation TypenameLoc)
class LLVM_ALIGNAS(8) DependentTemplateSpecializationType const IdentifierInfo * Name
Represents a template specialization type whose template cannot be resolved, e.g. ...
Definition: Type.h:4549
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition: DeclSpec.h:939
AttributeList * getList() const
void setUninstantiatedDefaultArg(Expr *arg)
Definition: Decl.cpp:2403
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:1789
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:3189
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:92
static unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
Definition: ASTContext.h:2464
A C++ nested-name-specifier augmented with source location information.
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1067
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:3276
bool isDelegatingConstructor() const
Determine whether this constructor is a delegating constructor.
Definition: DeclCXX.h:2306
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef< CXXCtorInitializer * > Initializers=None)
ImplicitInitializerKind
ImplicitInitializerKind - How an implicit base or member initializer should initialize its base or me...
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:1744
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
static void AddMostOverridenMethods(const CXXMethodDecl *MD, llvm::SmallPtrSetImpl< const CXXMethodDecl * > &Methods)
Add the most overriden methods from MD to Methods.
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclCXX.h:204
bool isRecordingPaths() const
Whether we are recording paths.
bool isReferenceType() const
Definition: Type.h:5491
BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, ParsedAttributes &Attrs, bool Virtual, AccessSpecifier Access, ParsedType basetype, SourceLocation BaseLoc, SourceLocation EllipsisLoc)
ActOnBaseSpecifier - Parsed a base specifier.
static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, FieldDecl *Field, IndirectFieldDecl *Indirect=nullptr)
QualType getReturnType() const
Definition: Decl.h:2034
void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl< QualType > &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI)
Check the given exception-specification and update the exception specification information with the r...
VarDecl * BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id)
Perform semantic analysis for the variable declaration that occurs within a C++ catch clause...
FieldDecl - An instance of this class is created by Sema::ActOnField to represent a member of a struc...
Definition: Decl.h:2293
bool hasInheritedConstructor() const
Determine whether this class has a using-declaration that names a user-declared base class constructo...
Definition: DeclCXX.h:1304
CXXConstructorDecl * getTargetConstructor() const
When this constructor delegates to another, retrieve the target.
Definition: DeclCXX.cpp:1854
bool needsOverloadResolutionForMoveConstructor() const
Determine whether we need to eagerly declare a defaulted move constructor for this class...
Definition: DeclCXX.h:930
NoexceptResult
Result type of getNoexceptSpec().
Definition: Type.h:3322
bool isAbstractType(SourceLocation Loc, QualType T)
static bool isIncrementDecrementOp(Opcode Op)
Definition: Expr.h:1729
unsigned TypeQuals
The type qualifiers: const/volatile/restrict/__unaligned The qualifier bitmask values are the same as...
Definition: DeclSpec.h:1224
void Deallocate(void *Ptr) const
Definition: ASTContext.h:574
ImplicitExceptionSpecification ComputeInheritingCtorExceptionSpec(SourceLocation Loc, CXXConstructorDecl *CD)
Determine what sort of exception specification an inheriting constructor of a class will have...
ParmVarDecl * getParam(unsigned i) const
Definition: TypeLoc.h:1306
CXXMethodDecl * getCanonicalDecl() override
Definition: DeclCXX.h:1804
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:2521
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
This is not an overload because the signature exactly matches an existing declaration.
Definition: Sema.h:2242
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:678
static CXXCtorInitializer * Create(ASTContext &Context, FieldDecl *Member, SourceLocation MemberLoc, SourceLocation L, Expr *Init, SourceLocation R, VarDecl **Indices, unsigned NumIndices)
Creates a new member initializer that optionally contains array indices used to describe an elementwi...
Definition: DeclCXX.cpp:1768
bool isTranslationUnit() const
Definition: DeclBase.h:1283
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1788
TagKind getTagKind() const
Definition: Decl.h:2930
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:28
SourceRange getLocalSourceRange() const
Get the local source range.
Definition: TypeLoc.h:134
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:1982
static void extendLeft(SourceRange &R, SourceRange Before)
DeclarationName getCXXDestructorName(CanQualType Ty)
getCXXDestructorName - Returns the name of a C++ destructor for the given Type.
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr)
Definition: Expr.cpp:368
std::pair< CXXConstructorDecl *, bool > findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const
Find the constructor to use for inherited construction of a base class, and whether that base class c...
bool isMoveConstructor(unsigned &TypeQuals) const
Determine whether this constructor is a move constructor (C++11 [class.copy]p3), which can be used to...
Definition: DeclCXX.cpp:1877
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition: DeclCXX.h:1112
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:509
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclSpec.h:1761
unsigned size() const
Definition: DeclTemplate.h:92
static bool CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, SmallVectorImpl< SourceLocation > &ReturnStmts, SourceLocation &Cxx1yLoc)
Check the provided statement is allowed in a constexpr function definition.
bool DefineUsedVTables()
Define all of the vtables that have been used in this translation unit and reference any virtual memb...
Expr * getSubExpr()
Definition: Expr.h:2684
Represents an access specifier followed by colon ':'.
Definition: DeclCXX.h:103
void ClearStorageClassSpecs()
Definition: DeclSpec.h:461
bool needsImplicitCopyAssignment() const
Determine whether this class needs an implicit copy assignment operator to be lazily declared...
Definition: DeclCXX.h:944
void addShadowDecl(UsingShadowDecl *S)
Definition: DeclCXX.cpp:2206
TypeSourceInfo * getTypeSourceInfo() const
Definition: TemplateBase.h:478
Decl * ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, AttributeList *Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see 'struct foo' or 'struct {'.
Definition: SemaDecl.cpp:12260
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1199
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:12840
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2007
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator, which is not a function declaration or definition and therefore is not permitted to have default arguments.
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Sema/Lookup.h:39
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Definition: SemaDecl.cpp:5816
IdentifierTable & Idents
Definition: ASTContext.h:459
SpecialMemberOverloadResult - The overloading result for a special member function.
Definition: Sema.h:917
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:205
The type of an exception.
Definition: Sema.h:6121
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:105
Expr * getLHS() const
Definition: Expr.h:2943
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted per C++0x.
Definition: Decl.h:1858
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:170
static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, DeclStmt *DS, SourceLocation &Cxx1yLoc)
Check the given declaration statement is legal within a constexpr function body.
UnionParsedType DestructorName
When Kind == IK_DestructorName, the type referred to by the class-name.
Definition: DeclSpec.h:947
Describes an C or C++ initializer list.
Definition: Expr.h:3746
Represents a C++ using-declaration.
Definition: DeclCXX.h:3039
bool implicitCopyConstructorHasConstParam() const
Determine whether an implicit copy constructor for this type would have a parameter with a const-qual...
Definition: DeclCXX.h:875
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:884
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2383
bool isCompleteType(SourceLocation Loc, QualType T)
Definition: Sema.h:1452
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Definition: SemaLookup.cpp:470
NamespaceDecl * getOrCreateStdNamespace()
Retrieve the special "std" namespace, which may require us to implicitly define the namespace...
Represents the results of name lookup.
Definition: Sema/Lookup.h:30
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:588
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:2427
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef< UnexpandedParameterPack > Unexpanded)
Diagnose unexpanded parameter packs.
bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics...
Definition: SemaExpr.cpp:317
void CalledExpr(Expr *E)
Integrate an invoked expression into the collected data.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:604
bool isLastDiagnosticIgnored() const
Determine whether the previous diagnostic was ignored.
Definition: Diagnostic.h:514
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2004
static InitializedEntity InitializeDelegation(QualType Type)
Create the initialization entity for a delegated constructor.
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition: Decl.h:526
IndirectFieldDecl * getIndirectMember() const
Definition: DeclCXX.h:2082
Microsoft throw(...) extension.
A convenient class for passing around template argument information.
Definition: TemplateBase.h:523
bool isFunctionDeclarationContext() const
Return true if this declaration appears in a context where a function declarator would be a function ...
Definition: DeclSpec.h:2120
static bool isStaticDataMember(const Decl *D)
Determine whether the given declaration is a static data member.
virtual void HandleVTable(CXXRecordDecl *RD)
Callback involved at the end of a translation unit to notify the consumer that a vtable for the given...
Definition: ASTConsumer.h:121
CXXConstructorDecl * DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit move constructor for the given class.
bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl, AccessSpecifier access, QualType objectType)
Is the given special member function accessible for the purposes of deciding whether to define a spec...
The base type of a class type.
Definition: Sema.h:6082
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method)
Check whether 'this' shows up in the type of a static member function after the (naturally empty) cv-...
QualType getReturnType() const
Definition: Type.h:3009
Look up all declarations in a scope with the given name, including resolved using declarations...
Definition: Sema.h:2729
bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow)
Determines whether to create a using shadow decl for a particular decl, given the set of decls existi...
unsigned getMinRequiredArguments() const
getMinRequiredArguments - Returns the minimum number of arguments needed to call this function...
Definition: Decl.cpp:2785
bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS)
Determine whether the identifier II is a typo for the name of the class type currently being defined...
bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionExceptionSpec - Checks whether the exception spec is a subset of base spec...
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:1838
bool isDefaulted() const
Whether this function is defaulted per C++0x.
Definition: Decl.h:1853
bool CheckConstexprFunctionDecl(const FunctionDecl *FD)
void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor)
Define the specified inheriting constructor.
An x-value expression is a reference to an object with independent storage but which can be "moved"...
Definition: Specifiers.h:114
field_range fields() const
Definition: Decl.h:3382
void RemoveDecl(NamedDecl *D)
RemoveDecl - Unlink the decl from its shadowed decl chain.
static bool BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, FieldDecl *Field, IndirectFieldDecl *Indirect, CXXCtorInitializer *&CXXMemberInit)
StmtResult StmtError()
Definition: Ownership.h:269
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc)
Diagnose a declaration whose declarator-id has the given nested-name-specifier.
Definition: SemaDecl.cpp:4834
static void NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, const QualType &Type)
Recursively add the bases of Type. Don't add Type itself.
NamedDecl * BuildUsingDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, AttributeList *AttrList, bool IsInstantiation, bool HasTypenameKeyword, SourceLocation TypenameLoc)
Builds a using declaration.
static bool isValidUDSuffix(const LangOptions &LangOpts, StringRef Suffix)
Determine whether a suffix is a valid ud-suffix.
capture_iterator capture_end() const
Retrieve an iterator pointing past the end of the sequence of lambda captures.
Definition: ExprCXX.cpp:948
semantics_iterator semantics_end()
Definition: Expr.h:4753
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclSpec.h:1090
TypeDecl - Represents a declaration of a type.
Definition: Decl.h:2569
Expr * getNoexceptExpr() const
Definition: Type.h:3336
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:2897
An implicit 'self' parameter.
Definition: DeclSpec.h:909
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:147
RecordDecl * getDecl() const
Definition: Type.h:3716
FunctionDecl * getTemplateInstantiationPattern() const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition: Decl.cpp:3128
void CheckDelegatingCtorCycles()
QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckDestructorDeclarator - Called by ActOnDeclarator to check the well-formednes of the destructor d...
ImplicitExceptionSpecification ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD)
Determine what sort of exception specification a defaulted destructor of a class will have...
static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class)
static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, SourceLocation CurrentLocation)
Check if we're implicitly defining a move assignment operator for a class with virtual bases...
child_range children()
Definition: Expr.h:3908
void setExceptionVariable(bool EV)
Definition: Decl.h:1212
bool isOverloadedOperator() const
isOverloadedOperator - Whether this function declaration represents an C++ overloaded operator...
Definition: Decl.h:2093
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:720
CanQualType LongDoubleTy
Definition: ASTContext.h:904
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:2448
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:39
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence...
Definition: SemaInit.cpp:6208
The type of a data member.
Definition: Sema.h:6088
bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
CXXRecordDecl * getCanonicalDecl() override
Definition: DeclCXX.h:654
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1039
const Type * getBaseClass() const
If this is a base class initializer, returns the type of the base class.
Definition: DeclCXX.cpp:1788
CXXBaseSpecifier * CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
ActOnBaseSpecifier - Parsed a base specifier.
void setTrivial(bool IT)
Definition: Decl.h:1849
bool isDelegatingInitializer() const
Determine whether this initializer is creating a delegating constructor.
Definition: DeclCXX.h:2030
ExprResult ActOnCXXThis(SourceLocation loc)
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:63
static unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built...
Definition: ASTContext.h:2450
void setNumCtorInitializers(unsigned numCtorInitializers)
Definition: DeclCXX.h:2297
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context...
static UnresolvedUsingValueDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo)
Definition: DeclCXX.cpp:2259
std::string getAsString() const
getNameAsString - Retrieve the human-readable string for this name.
SourceLocation getLocation() const
Definition: Attr.h:94
SourceLocation getLocStart() const LLVM_READONLY
Definition: ExprCXX.h:892
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1503
bool isStaticLocal() const
isStaticLocal - Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:980
Preprocessor & PP
Definition: Sema.h:298
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:1800
static NamespaceAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Namespace)
Definition: DeclCXX.cpp:2133
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:720
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
static bool findCircularInheritance(const CXXRecordDecl *Class, const CXXRecordDecl *Current)
Determine whether the given class is a base class of the given class, including looking at dependent ...
static void DelegatingCycleHelper(CXXConstructorDecl *Ctor, llvm::SmallSet< CXXConstructorDecl *, 4 > &Valid, llvm::SmallSet< CXXConstructorDecl *, 4 > &Invalid, llvm::SmallSet< CXXConstructorDecl *, 4 > &Current, Sema &S)
An ordinary object is located at an address in memory.
Definition: Specifiers.h:121
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:3068
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
A class that does preordor or postorder depth-first traversal on the entire Clang AST and visits each...
Decl * ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, Expr *LangStr, SourceLocation LBraceLoc)
ActOnStartLinkageSpecification - Parsed the beginning of a C++ linkage specification, including the language and (if present) the '{'.
Represents an ObjC class declaration.
Definition: DeclObjC.h:1091
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, AttributeList *Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
Represents a linkage specification.
Definition: DeclCXX.h:2523
ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs=nullptr)
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclSpec.h:503
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Sema/Lookup.h:410
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:2713
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1206
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:502
detail::InMemoryDirectory::const_iterator I
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition: Type.h:3160
unsigned getNumParams() const
Definition: TypeLoc.h:1301
QualType getCanonicalTypeInternal() const
Definition: Type.h:2001
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2098
init_iterator init_begin()
Retrieve an iterator to the first initializer.
Definition: DeclCXX.h:2257
QualType getType() const
Definition: Decl.h:599
bool isInvalid() const
const LangOptions & LangOpts
Definition: Sema.h:297
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type...
Definition: TypeLoc.h:53
bool isUnnamedBitfield() const
Determines whether this is an unnamed bitfield.
Definition: Decl.h:2367
void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL, bool IncludeCXX11Attributes=true)
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
Definition: Sema.h:2756
void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc)
PopPragmaVisibility - Pop the top element of the visibility stack; used for '#pragma GCC visibility' ...
Definition: SemaAttr.cpp:473
This object can be modified without requiring retains or releases.
Definition: Type.h:138
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5...
Definition: Sema.h:6946
SourceRange getRange() const
Definition: DeclSpec.h:68
bool isDefined(const FunctionDecl *&Definition) const
isDefined - Returns true if the function is defined at all, including a deleted definition.
Definition: Decl.cpp:2479
param_iterator param_begin()
Definition: Decl.h:2000
Represents the this expression in C++.
Definition: ExprCXX.h:873
UsingShadowDecl * BuildUsingShadowDecl(Scope *S, UsingDecl *UD, NamedDecl *Target, UsingShadowDecl *PrevDecl)
Builds a shadow declaration corresponding to a 'using' declaration.
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition: DeclCXX.h:1161
SourceLocation getUsingLoc() const
Return the source location of the 'using' keyword.
Definition: DeclCXX.h:3069
field_iterator field_end() const
Definition: Decl.h:3385
Class that aids in the construction of nested-name-specifiers along with source-location information ...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
static StmtResult buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &To, const ExprBuilder &From, bool CopyingBaseSubobject, bool Copying)
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
CXXConstructorDecl * getConstructor() const
Definition: DeclCXX.h:2174
void removeInClassInitializer()
removeInClassInitializer - Remove the C++11 in-class initializer from this member.
Definition: Decl.h:2433
CXXMethodDecl * getMethod() const
Definition: Sema.h:933
void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an initializer for the declaratio...
CXXSpecialMember
Kinds of C++ special members.
Definition: Sema.h:1007
QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *Init, SourceLocation EllipsisLoc)
Handle a C++ member initializer.
CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow)
Given a derived-class using shadow declaration for a constructor and the correspnding base class cons...
bool isStatic() const
Definition: DeclCXX.cpp:1475
bool isUnion() const
Definition: Decl.h:2939
void setBases(CXXBaseSpecifier const *const *Bases, unsigned NumBases)
Sets the base classes of this struct or class.
Definition: DeclCXX.cpp:137
CXXConstructorDecl * getCanonicalDecl() override
Definition: DeclCXX.h:2388
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:3170
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition: DeclSpec.h:1736
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:263
Decl * ActOnEmptyDeclaration(Scope *S, AttributeList *AttrList, SourceLocation SemiLoc)
Handle a C++11 empty-declaration and attribute-declaration.
TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x alias-declaration.
Definition: Decl.h:2701
CanQualType getCanonicalTypeUnqualified() const
TST getTypeSpecType() const
Definition: DeclSpec.h:479
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:551
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Sema/Lookup.h:237
QualType getParamType(unsigned i) const
Definition: Type.h:3272
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3073
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:119
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
Definition: DeclCXX.h:1292
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:3304
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:14058
void ClearConstexprSpec()
Definition: DeclSpec.h:712
CXXMethodDecl * getMethodDecl() const
Retrieves the declaration of the called method.
Definition: ExprCXX.cpp:471
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc...
Definition: SemaExpr.cpp:10772
void ActOnFinishCXXMemberDecls()
Perform any semantic analysis which needs to be delayed until all pending class member declarations h...
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1009
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared copy assignment operator.
bool isParameterPack() const
Determine whether this parameter is actually a function parameter pack.
Definition: Decl.cpp:2422
static unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
Definition: ASTContext.h:2453
A RAII object to enter scope of a compound statement.
Definition: Sema.h:3353
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL...
bool inferObjCARCLifetime(ValueDecl *decl)
Definition: SemaDecl.cpp:5487
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:646
bool needsImplicitMoveAssignment() const
Determine whether this class should get an implicit move assignment operator or if any existing speci...
Definition: DeclCXX.h:993
static InitializedEntity InitializeMember(FieldDecl *Member, const InitializedEntity *Parent=nullptr)
Create the initialization entity for a member subobject.
param_type_iterator param_type_begin() const
Definition: Type.h:3392
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat)
Definition: Expr.cpp:1652
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp)
Definition: SemaStmt.cpp:3176
ImplicitExceptionSpecification ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD)
Determine what sort of exception specification a defaulted default constructor of a class will have...
SourceLocation getFriendSpecLoc() const
Definition: DeclSpec.h:701
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:462
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1247
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition: DeclCXX.cpp:1046
static EmptyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:4202
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:225
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
static StaticAssertDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StaticAssertLoc, Expr *AssertExpr, StringLiteral *Message, SourceLocation RParenLoc, bool Failed)
Definition: DeclCXX.cpp:2304
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2063
bool isMoreQualifiedThan(QualType Other) const
Determine whether this type is more qualified than the other given type, requiring exact equality for...
Definition: Type.h:5403
const CXXMethodDecl *const * method_iterator
Definition: DeclCXX.h:1828
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:415
void setInClassInitializer(Expr *Init)
setInClassInitializer - Set the C++11 in-class initializer for this member.
Definition: Decl.h:2424
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:315
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param)
This is used to implement the constant expression evaluation part of the attribute enable_if extensio...
MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc)
NameKind getNameKind() const
getNameKind - Determine what kind of name this is.
bool InstantiateInClassInitializer(SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the definition of a field from the given pattern.
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:540
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:1799
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool isInline, bool isImplicitlyDeclared)
Definition: DeclCXX.cpp:1972
int * Depth
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
InheritedConstructor getInheritedConstructor() const
Get the constructor that this inheriting constructor is based on.
Definition: DeclCXX.h:2383
Allows QualTypes to be sorted and hence used in maps and sets.
Decl * ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc)
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:1909
bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method)
Whether this' shows up in the exception specification of a static member function.
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:155
const Type * getTypeForDecl() const
Definition: Decl.h:2590
Represents a shadow constructor declaration introduced into a class by a C++11 using-declaration that...
Definition: DeclCXX.h:2927
unsigned getTypeQualifiers() const
Definition: DeclCXX.h:1854
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D, const TemplateArgumentList *Innermost=nullptr, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Definition: Decl.h:590
Expr - This represents one expression.
Definition: Expr.h:105
StringRef getName() const
Return the actual identifier string.
void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitCopyConstructor - Checks for feasibility of defining this constructor as the copy const...
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:102
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:544
bool isDeclarationOfFunction() const
Determine whether the declaration that will be produced from this declaration will be a function...
Definition: DeclSpec.cpp:261
bool isInstance() const
Definition: DeclCXX.h:1763
ImplicitExceptionSpecification ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD)
Determine what sort of exception specification a defaulted move constructor of a class will have...
bool isDeclScope(Decl *D)
isDeclScope - Return true if this is the scope that the specified decl is declared in...
Definition: Scope.h:309
Helper class that collects exception specifications for implicitly-declared special member functions...
Definition: Sema.h:4338
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath)
StateNode * Previous
Declaration of a template type parameter.
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
bool isFunctionDefinition() const
Definition: DeclSpec.h:2241
void setHideTags(bool Hide)
Sets whether tag declarations should be hidden by non-tag declarations during resolution.
Definition: Sema/Lookup.h:281
static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class)
This file defines the classes used to store parsed information about declaration-specifiers and decla...
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:981
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:4357
bool isVirtual() const
Definition: DeclCXX.h:1780
ArrayRef< NamedDecl * > chain() const
Definition: Decl.h:2540
void setRBraceLoc(SourceLocation L)
Definition: Decl.h:571
Inits[]
Definition: OpenMPClause.h:312
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2414
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition: Sema.h:716
void freeParams()
Reset the parameter list to having zero parameters.
Definition: DeclSpec.h:1310
void setInit(Expr *I)
Definition: Decl.cpp:2081
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:886
static unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
Definition: ASTContext.h:2460
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Sema/Lookup.h:501
llvm::SmallSet< SpecialMemberDecl, 4 > SpecialMembersBeingDeclared
The C++ special members which we are currently in the process of declaring.
Definition: Sema.h:1022
bool isLiteral() const
Determine whether this class is a literal type.
Definition: DeclCXX.h:1342
void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir)
void setRBraceLoc(SourceLocation L)
Definition: DeclCXX.h:2578
Defines the clang::Preprocessor interface.
bool CheckInheritingConstructorUsingDecl(UsingDecl *UD)
Additional checks for a using declaration referring to a constructor name.
bool isInherited() const
Definition: Attr.h:98
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, bool AllowFold=true)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:12635
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:216
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2011
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:3280
bool isInitListConstructor(const CXXConstructorDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init.list]p2.
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:543
void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD)
bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, SourceLocation ColonLoc, AttributeList *Attrs=nullptr)
ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
void PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, const BlockExpr *blkExpr=nullptr)
Definition: Sema.cpp:1152
FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const
Overwrite an EPI's exception specification with this computed exception specification.
Definition: Sema.h:4384
ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens)
Definition: SemaCast.cpp:237
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:2391
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, Expr *Init)
This is invoked after parsing an in-class initializer for a non-static C++ class member, and after instantiating an in-class initializer in a class template.
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
CXXTryStmt - A C++ try block, including all handlers.
Definition: StmtCXX.h:65
static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, SourceLocation DefaultLoc)
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param)
ActOnDelayedCXXMethodParameter - We've already started a delayed C++ method declaration.
Represents a C++ template name within the type system.
Definition: TemplateName.h:176
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
enum clang::DeclaratorChunk::@185 Kind
bool hasUserDeclaredMoveConstructor() const
Determine whether this class has had a move constructor declared by the user.
Definition: DeclCXX.h:899
NamedDecl * ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration)
ActOnTypedefNameDecl - Perform semantic checking for a declaration which declares a typedef-name...
Definition: SemaDecl.cpp:5394
bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:6826
Defines the clang::TypeLoc interface and its subclasses.
There is no noexcept specifier.
Definition: Type.h:3323
SourceLocation getLocStart() const LLVM_READONLY
Definition: ExprCXX.h:1747
SourceLocation getLastLocation() const
Definition: DeclSpec.h:2304
SourceRange getDefaultArgRange() const
Retrieve the source range that covers the entire default argument.
Definition: Decl.cpp:2383
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:1409
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2083
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:12898
bool isConstexprSpecified() const
Definition: DeclSpec.h:706
void propagateDLLAttrToBaseClassTemplate(CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc)
Perform propagation of DLL attributes from a derived class to a templated base class for MS compatibi...
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:317
bool isExplicit() const
Determine whether this constructor was marked "explicit" or not.
Definition: DeclCXX.h:2238
void setInheritConstructors(bool Inherit=true)
Set that this base class's constructors should be inherited.
Definition: DeclCXX.h:221
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:107
SourceLocation getLocEnd() const LLVM_READONLY
SmallVector< VTableUse, 16 > VTableUses
The list of vtables that are required but have not yet been materialized.
Definition: Sema.h:5371
static bool isPotentialConstantExpr(const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExpr - Return true if this function's definition might be usable in a constant exp...
StorageClass
Storage classes.
Definition: Specifiers.h:201
Expr * getSubExpr() const
Definition: Expr.h:1695
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition: DeclSpec.h:590
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared move assignment operator.
void CheckCompletedCXXClass(CXXRecordDecl *Record)
Perform semantic checks on a class definition that has been completing, introducing implicitly-declar...
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:1774
void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don't have one.
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
bool hasTrailingReturn() const
Definition: Type.h:3376
bool isFunctionOrMethod() const
Definition: DeclBase.h:1263
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:93
InClassInitStyle
In-class initialization styles for non-static data members.
Definition: Specifiers.h:224
NamedDecl * getAcceptableDecl(NamedDecl *D) const
Retrieve the accepted (re)declaration of the given declaration, if there is one.
Definition: Sema/Lookup.h:345
Declaration of an alias template.
static unsigned getRecordDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for record diagnostic message.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1214
const TemplateArgument * data() const
Retrieve a pointer to the template argument list.
Definition: DeclTemplate.h:234
A boolean condition, from 'if', 'while', 'for', or 'do'.
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc)
static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, unsigned Quals, bool ConstRHS, CXXConstructorDecl *InheritedCtor=nullptr, Sema::InheritedConstructorInfo *Inherited=nullptr)
Is the special member function which would be selected to perform the specified operation on the spec...
bool isExternallyVisible() const
Definition: Decl.h:348
UnaryOperator - This represents the unary-expression's (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:1668
void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method)
Integrate another called method into the collected data.
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.h:2019
DeclContextLookupResult slice(size_t N) const
Definition: DeclBase.h:1114
SmallVector< ActiveTemplateInstantiation, 16 > ActiveTemplateInstantiations
List of active template instantiations.
Definition: Sema.h:6732
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
Definition: SemaType.cpp:7130
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1051
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2366
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
Definition: Decl.h:258
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:1066
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
CXXRecordDecl * getStdBadAlloc() const
class LLVM_ALIGNAS(8) TemplateSpecializationType unsigned NumArgs
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:4154
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:712
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1244
void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an initializer for the declaration ...
ValueDecl * getDecl()
Definition: Expr.h:1017
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2461
QualType getCVRQualifiedType(QualType T, unsigned CVR) const
Return a type with additional const, volatile, or restrict qualifiers.
Definition: ASTContext.h:1688
The result type of a method or function.
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:147
llvm::FoldingSet< SpecialMemberOverloadResult > SpecialMemberCache
A cache of special member function overload resolution results for C++ records.
Definition: Sema.h:942
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=NotForRedeclaration)
Look up a name, looking for a single declaration.
SourceLocation getLocEnd() const LLVM_READONLY
Definition: TypeLoc.h:131
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:1797
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:456
RecordDecl * getDefinition() const
getDefinition - Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:3372
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition: Type.h:727
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM)
Diagnose why the specified class does not have a trivial special member of the given kind...
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:165
bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, const CXXMethodDecl *Old)
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitDefaultConstructor - Checks for feasibility of defining this constructor as the default...
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:671
bool isVirtualSpecified() const
Definition: DeclSpec.h:567
bool needsOverloadResolutionForCopyAssignment() const
Determine whether we need to eagerly declare a defaulted copy assignment operator for this class...
Definition: DeclCXX.h:950
CXXConstructorDecl * LookupCopyingConstructor(CXXRecordDecl *Class, unsigned Quals)
Look up the copying constructor for the given class.
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:231
static bool RefersToRValueRef(Expr *MemRef)
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:553
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:1883
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition: Sema.h:2238
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, SourceLocation RBrac, AttributeList *AttrList)
void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl< CXXMethodDecl * > &OverloadedMethods)
static FriendTemplateDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc, MutableArrayRef< TemplateParameterList * > Params, FriendUnion Friend, SourceLocation FriendLoc)
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
ExprResult ActOnFinishFullExpr(Expr *Expr)
Definition: Sema.h:4903
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:473
bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body)
Check the body for the given constexpr function declaration only contains the permitted types of stat...
#define CheckPolymorphic(Type)
DeclarationNameInfo getNameInfo() const
Definition: DeclCXX.h:3083
DelegatingCtorDeclsType DelegatingCtorDecls
All the delegating constructors seen so far in the file, used for cycle detection at the end of the T...
Definition: Sema.h:534
bool isAmbiguous() const
Definition: Sema/Lookup.h:285
void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow)
Hides a using shadow declaration.
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:76
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
static void SearchForReturnInStmt(Sema &Self, Stmt *S)
Wrapper for source info for arrays.
Definition: TypeLoc.h:1358
ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange)
BuildCXXConstructExpr - Creates a complete call to a constructor, including handling of its default a...
bool doesThisDeclarationHaveABody() const
doesThisDeclarationHaveABody - Returns whether this specific declaration of the function has a body -...
Definition: Decl.h:1821
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:1479
There is no lifetime qualification on this type.
Definition: Type.h:134
void ActOnStartCXXInClassMemberInitializer()
Enter a new C++ default initializer scope.
DeclContext * getEntity() const
Definition: Scope.h:313
static bool CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, const FunctionDecl *FnDecl)
void setSourceOrder(int pos)
Set the source order of this initializer.
Definition: DeclCXX.h:2115
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type. ...
Definition: Decl.cpp:2911
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:215
ASTMatchFinder *const Finder
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class...
Definition: Expr.h:848
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:236
static unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
Definition: ASTContext.h:2485
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1579
#define false
Definition: stdbool.h:33
CanQualType BuiltinFnTy
Definition: ASTContext.h:910
The "struct" keyword.
Definition: Type.h:4344
Kind
static CXXConstructorDecl * findUserDeclaredCtor(CXXRecordDecl *RD)
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition: ExprCXX.h:1325
bool CheckUsingDeclQualifier(SourceLocation UsingLoc, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc)
Checks that the given nested-name qualifier used in a using decl in the current context is appropriat...
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:3153
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:4679
SourceRange getSourceRange() const override LLVM_READONLY
Definition: Decl.cpp:2351
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:144
SmallVectorImpl< AnnotatedLine * >::const_iterator Next
SourceRange getSourceRange() const LLVM_READONLY
Determine the source range covering the entire initializer.
Definition: DeclCXX.cpp:1808
bool isInterface() const
Definition: Decl.h:2937
llvm::SmallPtrSet< QualType, 4 > IndirectBaseSet
Use small set to collect indirect bases.
This is not an overload because the lookup results contain a non-function.
Definition: Sema.h:2246
Encodes a location in the source.
void setOperatorDelete(FunctionDecl *OD)
Definition: DeclCXX.cpp:1984
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record)
bool isAnonymousStructOrUnion() const
isAnonymousStructOrUnion - Determines whether this field is a representative for an anonymous struct ...
Definition: Decl.cpp:3458
body_range body()
Definition: Stmt.h:581
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any...
Definition: ASTContext.h:943
unsigned getNumParams() const
getNumParams - Return the number of parameters this function must have based on its FunctionType...
Definition: Decl.cpp:2742
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:3733
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:5259
bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange)
Mark the given method pure.
Decl * ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, SourceLocation RBraceLoc)
ActOnFinishLinkageSpecification - Complete the definition of the C++ linkage specification LinkageSpe...
const TemplateArgument * iterator
Definition: Type.h:4233
bool InEnclosingNamespaceSetOf(const DeclContext *NS) const
Test if this context is part of the enclosing namespace set of the context NS, as defined in C++0x [n...
Definition: DeclBase.cpp:1561
unsigned getBitWidthValue(const ASTContext &Ctx) const
Definition: Decl.cpp:3468
method_iterator begin_overridden_methods() const
Definition: DeclCXX.cpp:1650
Decl * BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, StringLiteral *AssertMessageExpr, SourceLocation RParenLoc, bool Failed)
FieldDecl * getAnyMember() const
Definition: DeclCXX.h:2074
An overloaded operator name, e.g., operator+.
Definition: DeclSpec.h:895
Expr * getRepAsExpr() const
Definition: DeclSpec.h:495
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition: DeclSpec.h:1748
static void CheckConstexprCtorInitializer(Sema &SemaRef, const FunctionDecl *Dcl, FieldDecl *Field, llvm::SmallSet< Decl *, 16 > &Inits, bool &Diagnosed)
Check that the given field is initialized within a constexpr constructor.
bool isValid() const
Return true if this is a valid SourceLocation object.
static unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built...
Definition: ASTContext.h:2471
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
const std::string ID
reference front() const
Definition: DeclBase.h:1109
void ExitDeclaratorContext(Scope *S)
Definition: SemaDecl.cpp:1177
TagDecl - Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:2727
void referenceDLLExportedClassMethods()
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context...
Definition: DeclSpec.cpp:143
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc)
Build the type that describes a C++ typename specifier, e.g., "typename T::type". ...
Represents a call to a member function that may be written either with member call syntax (e...
Definition: ExprCXX.h:121
SourceLocation getBeginLoc() const
Retrieve the location of the beginning of this nested-name-specifier.
bool isValid() const
unsigned size_overridden_methods() const
Definition: DeclCXX.cpp:1660
FunctionTypeInfo Fun
Definition: DeclSpec.h:1447
InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, ConstructorUsingShadowDecl *Shadow)
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location, which defaults to the empty location.
ASTContext & getASTContext() const
Definition: Sema.h:1069
static bool CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, CanQualType ExpectedResultType, CanQualType ExpectedFirstParamType, unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag)
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:93
DeclStmt - Adaptor class for mixing declarations with statements and expressions. ...
Definition: Stmt.h:443
IdentifierTable & getIdentifierTable()
Definition: Preprocessor.h:697
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec and return false if there was no error...
Definition: DeclSpec.cpp:502
void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor)
DefineImplicitDestructor - Checks for feasibility of defining this destructor as the default destruct...
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3185
TagDecl * getCanonicalDecl() override
Definition: Decl.cpp:3533
TypeAliasDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
static InitializedEntity InitializeElement(ASTContext &Context, unsigned Index, const InitializedEntity &Parent)
Create the initialization entity for an array element.
QualType withConst() const
Definition: Type.h:764
void removeShadowDecl(UsingShadowDecl *S)
Definition: DeclCXX.cpp:2216
void setCtorInitializers(CXXCtorInitializer **Initializers)
Definition: DeclCXX.h:2301
ClassTemplateDecl * StdInitializerList
The C++ "std::initializer_list" template, which is defined in <initializer_list>. ...
Definition: Sema.h:724
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1736
unsigned getDepth() const
Retrieve the depth of the template parameter.
void setDefaulted(bool D=true)
Definition: Decl.h:1854
bool needsOverloadResolutionForMoveAssignment() const
Determine whether we need to eagerly declare a move assignment operator for this class.
Definition: DeclCXX.h:1003
paths_iterator begin()
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:178
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc)
SourceLocation getSourceLocation() const
Determine the source location of the initializer.
Definition: DeclCXX.cpp:1795
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:630
No ref-qualifier was provided.
Definition: Type.h:1238
void setEntity(DeclContext *E)
Definition: Scope.h:314
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckForFunctionMarkedFinal - Checks whether a virtual member function overrides a virtual member fun...
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:1989
bool hasUserProvidedDefaultConstructor() const
Whether this class has a user-provided default constructor per C++11.
Definition: DeclCXX.h:850
llvm::SmallPtrSet< const CXXRecordDecl *, 8 > RecordDeclSetTy
Definition: Sema.h:499
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:194
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths)
Builds a string representing ambiguous paths from a specific derived class to different subobjects of...
void setImplicitMoveConstructorIsDeleted()
Set that we attempted to declare an implicitly move constructor, but overload resolution failed so we...
Definition: DeclCXX.h:911
SourceRange getSourceRange() const override LLVM_READONLY
Definition: Decl.cpp:3527
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2114
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Sema/Lookup.h:52
const ObjCInterfaceDecl * getClassInterface() const
Definition: DeclObjC.h:2325
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:707
bool isTemplateParamScope() const
isTemplateParamScope - Return true if this scope is a C++ template parameter scope.
Definition: Scope.h:365
void push_back(const T &LocalValue)
static CXXBaseSpecifier * findDirectBaseWithType(CXXRecordDecl *Derived, QualType DesiredBase, bool &AnyDependentBases)
Find the base specifier for a base class with the given type.
CanQualType VoidTy
Definition: ASTContext.h:893
void actOnDelayedExceptionSpecification(Decl *Method, ExceptionSpecificationType EST, SourceRange SpecificationRange, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr)
Add an exception-specification to the given member function (or member function template).
Decl * ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, AttributeList *Attr, MultiTemplateParamsArg TempParamLists)
Handle a friend tag declaration where the scope specifier was templated.
Describes the kind of initialization being performed, along with location information for tokens rela...
static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident)
A friend declaration.
Definition: Sema.h:6106
AbstractDiagSelID
Definition: Sema.h:5623
arg_range arguments()
Definition: Expr.h:2242
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:5774
A class for iterating through a result set and possibly filtering out results.
Definition: Sema/Lookup.h:600
Direct list-initialization.
Definition: Specifiers.h:227
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
Represents a C++11 virt-specifier-seq.
Definition: DeclSpec.h:2276
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:568
static CXXDefaultInitExpr * Create(const ASTContext &C, SourceLocation Loc, FieldDecl *Field)
Field is the non-static data member whose default initializer is used by this expression.
Definition: ExprCXX.h:1052
static ConstructorUsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, UsingDecl *Using, NamedDecl *Target, bool IsVirtual)
Definition: DeclCXX.cpp:2188
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:2734
TypeLocClass getTypeLocClass() const
Definition: TypeLoc.h:90
bool isFinalSpelledSealed() const
Definition: DeclSpec.h:2296
void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD, const FunctionProtoType *T)
Check whether the exception specification provided for an explicitly-defaulted special member matches...
void setIsParsingBaseSpecifiers()
Definition: DeclCXX.h:702
SourceLocation getBegin() const
bool isTypeDependent() const
isTypeDependent - Determines whether this expression is type-dependent (C++ [temp.dep.expr]), which means that its type could change from one template instantiation to the next.
Definition: Expr.h:165
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:5849
T * get(ExternalASTSource *Source) const
Retrieve the pointer to the AST node that this lazy pointer.
TypeLoc getReturnLoc() const
Definition: TypeLoc.h:1309
A default argument.
Definition: Sema.h:6115
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:72
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1407
static bool BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, CXXBaseSpecifier *BaseSpec, bool IsInheritedVirtualBase, CXXCtorInitializer *&CXXBaseInit)
No entity found met the criteria.
Definition: Sema/Lookup.h:34
NoexceptResult getNoexceptSpec(const ASTContext &Ctx) const
Get the meaning of the noexcept spec on this function, if any.
Definition: Type.cpp:2752
static bool CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl)
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
bool isAscii() const
Definition: Expr.h:1557
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:159
This template specialization was formed from a template-id but has not yet been declared, defined, or instantiated.
Definition: Specifiers.h:144
bool isFileContext() const
Definition: DeclBase.h:1279
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition: Sema.h:479
bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous)
Checks that the given using declaration is not an invalid redeclaration.
bool SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const LangOptions &Lang)
Definition: DeclSpec.cpp:780
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
Definition: SemaType.cpp:1984
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition: Decl.h:2901
void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef< CXXCtorInitializer * > MemInits, bool AnyErrors)
ActOnMemInitializers - Handle the member initializers for a constructor.
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
Definition: SemaDecl.cpp:11087
Attr * clone(ASTContext &C) const
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:5329
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, AttributeList *AttrList)
Definition: SemaDecl.cpp:13854
ConstructorUsingShadowDecl * getShadowDecl() const
Definition: DeclCXX.h:2173
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.cpp:427
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:652
void setExplicitlyDefaulted(bool ED=true)
Definition: Decl.h:1859
unsigned TypeAlias
Whether this template specialization type is a substituted type alias.
Definition: Type.h:4171
void setHasInheritedDefaultArg(bool I=true)
Definition: Decl.h:1509
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:262
static Sema::ImplicitExceptionSpecification computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD)
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:70
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:563
bool isDynamicClass() const
Definition: DeclCXX.h:698
Opcode getOpcode() const
Definition: Expr.h:1692
CXXMethodDecl * getLambdaStaticInvoker() const
Retrieve the lambda static invoker, the address of which is returned by the conversion operator...
Definition: DeclCXX.cpp:1068
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:193
bool isFunctionProtoType() const
Definition: Type.h:1662
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1302
QualType getPointeeType() const
Definition: Type.h:2193
bool hasTrivialCopyAssignment() const
Determine whether this class has a trivial copy assignment operator (C++ [class.copy]p11, C++11 [class.copy]p25)
Definition: DeclCXX.h:1241
Decl * ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, AttributeList *AttrList)
A constructor named via a template-id.
Definition: DeclSpec.h:903
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD)
getSpecialMember - get the special member enum for a method.
Definition: SemaDecl.cpp:2600
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
CXXDestructorDecl * DeclareImplicitDestructor(CXXRecordDecl *ClassDecl)
Declare the implicit destructor for the given class.
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:4157
The expression in a static assertion.
Definition: Sema.h:6094
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl)
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:1760
static AttributeList * getMSPropertyAttr(AttributeList *list)
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
Decl * ActOnExceptionDeclarator(Scope *S, Declarator &D)
ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch handler.
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:2609
attr::Kind getKind() const
Definition: Attr.h:87
ast_type_traits::DynTypedNode Node
QualType getType() const
Definition: Expr.h:126
bool isAnonymousStructOrUnion() const
isAnonymousStructOrUnion - Whether this is an anonymous struct or union.
Definition: Decl.h:3320
CanQualType CharTy
Definition: ASTContext.h:895
TLS with a dynamic initializer.
Definition: Decl.h:787
Represents a template argument.
Definition: TemplateBase.h:40
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1310
void setBody(Stmt *B)
Definition: Decl.cpp:2501
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:238
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument. ...
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
TagTypeKind
The kind of a tag type.
Definition: Type.h:4342
TypeSourceInfo * getTypeSourceInfo() const
Returns the declarator information for a base class or delegating initializer.
Definition: DeclCXX.h:2063
static bool isInvalid(LocType Loc, bool *Invalid)
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:3169
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:448
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2328
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LanguageIDs Lang, bool HasBraces)
Definition: DeclCXX.cpp:2025
SourceLocation getLocStart() const LLVM_READONLY
Definition: Stmt.h:473
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition: Decl.h:2719
CXXConstructorDecl * DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit copy constructor for the given class.
bool hasTypename() const
Return true if the using declaration has 'typename'.
Definition: DeclCXX.h:3091
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3030
not evaluated yet, for special member function
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1135
AccessSpecifier getAccessSpecifier() const
Returns the access specifier for this base specifier.
Definition: DeclCXX.h:235
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:330
void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc=SourceLocation(), SourceLocation VolatileQualLoc=SourceLocation(), SourceLocation RestrictQualLoc=SourceLocation(), SourceLocation AtomicQualLoc=SourceLocation(), SourceLocation UnalignedQualLoc=SourceLocation())
Definition: SemaType.cpp:2654
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator's nested name ...
Definition: SemaDecl.cpp:1148
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Sema/Lookup.h:257
bool hasUnparsedDefaultArg() const
hasUnparsedDefaultArg - Determines whether this parameter has a default argument that has not yet bee...
Definition: Decl.h:1488
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:22
bool isFriendSpecified() const
Definition: DeclSpec.h:700
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return 0.
Definition: Expr.cpp:1209
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1375
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_RValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:368
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type...
Definition: Expr.cpp:2520
StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body)
Definition: SemaStmt.cpp:1627
SourceLocation getLocStart() const LLVM_READONLY
Definition: TypeLoc.h:130
unsigned isVariadic
isVariadic - If this function has a prototype, and if that proto ends with ',...)', this is true.
Definition: DeclSpec.h:1213
SourceRange getSourceRange(const SourceRange &Range)
Returns the SourceRange of a SourceRange.
Definition: FixIt.h:34
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
static bool InitializationHasSideEffects(const FieldDecl &FD)
bool hasVariantMembers() const
Determine whether this class has any variant members.
Definition: DeclCXX.h:1172
ImplicitExceptionSpecification ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD)
Determine what sort of exception specification a defautled copy assignment operator of a class will h...
IndirectFieldDecl - An instance of this class is created to represent a field injected from an anonym...
Definition: Decl.h:2521
void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, Expr *defarg)
ActOnParamDefaultArgument - Check whether the default argument provided for a function parameter is w...
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types...
SourceLocation getFinalLoc() const
Definition: DeclSpec.h:2297
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1056
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:903
bool isFinalSpecified() const
Definition: DeclSpec.h:2295
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:104
static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl< const void * > &IdealInits)
std::pair< SourceLocation, SourceLocation > getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:1550
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:155
static NamespaceDecl * getNamespaceDecl(NamedDecl *D)
getNamespaceDecl - Returns the namespace a decl represents.
QualType getExceptionObjectType(QualType T) const
Represents a dependent using declaration which was marked with typename.
Definition: DeclCXX.h:3268
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
static UsingDirectiveDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation NamespaceLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Nominated, DeclContext *CommonAncestor)
Definition: DeclCXX.cpp:2042
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1176
DeclarationName - The name of a declaration.
Expr * getDefaultArg()
Definition: Decl.cpp:2366
ImplicitExceptionSpecification ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD)
Determine what sort of exception specification a defaulted copy constructor of a class will have...
unsigned getNumHandlers() const
Definition: StmtCXX.h:103
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
Definition: SemaDecl.cpp:3732
bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
static UnresolvedUsingTypenameDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TargetNameLoc, DeclarationName TargetName)
Definition: DeclCXX.cpp:2284
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1113
std::pair< CXXRecordDecl *, SourceLocation > VTableUse
The list of classes whose vtables have been used within this translation unit, and the source locatio...
Definition: Sema.h:5367
param_type_iterator param_type_end() const
Definition: Type.h:3395
A mapping from each virtual member function to its set of final overriders.
StringRef getString() const
Definition: Expr.h:1514
SourceLocation getLocStart() const LLVM_READONLY
Definition: Decl.h:693
size_t param_size() const
Definition: Decl.h:2004
bool hasTrivialMoveConstructor() const
Determine whether this class has a trivial move constructor (C++11 [class.copy]p12) ...
Definition: DeclCXX.h:1226
detail::InMemoryDirectory::const_iterator E
bool isAmbiguous(CanQualType BaseType)
Determine whether the path from the most-derived type to the given base type is ambiguous (i...
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2401
bool hasUserDeclaredMoveAssignment() const
Determine whether this class has had a move assignment declared by the user.
Definition: DeclCXX.h:971
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:141
IdentifierResolver IdResolver
Definition: Sema.h:708
semantics_iterator semantics_begin()
Definition: Expr.h:4747
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2205
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Sema/Lookup.h:292
SourceLocation getLocation() const
Definition: ExprCXX.h:889
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:1966
bool isMsStruct(const ASTContext &C) const
isMsStrust - Get whether or not this is an ms_struct which can be turned on with an attribute...
Definition: Decl.cpp:3784
FieldDecl * getMember() const
If this is a member initializer, returns the declaration of the non-static data member being initiali...
Definition: DeclCXX.h:2069
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation...
Definition: DeclCXX.cpp:406
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
static Sema::SpecialMemberOverloadResult * lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, unsigned FieldQuals, bool ConstRHS)
Look up the special member function that would be called by a special member function for a subobject...
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to form a template specialization. ...
MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc)
bool field_empty() const
Definition: Decl.h:3391
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1027
DeclClass * getCorrectionDeclAs() const
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext, providing only those that are of type SpecificDecl (or a class derived from it).
Definition: DeclBase.h:1473
static unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
Definition: ASTContext.h:2467
Expr * IgnoreParenImpCasts() LLVM_READONLY
IgnoreParenImpCasts - Ignore parentheses and implicit casts.
Definition: Expr.cpp:2413
void PushUsingDirective(UsingDirectiveDecl *UDir)
Definition: Scope.h:442
CXXConstructorDecl * DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit default constructor for the given class.
bool isRValueReferenceType() const
Definition: Type.h:5497
const Stmt * getThen() const
Definition: Stmt.h:919
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:5432
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1807
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:127
static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, CXXMethodDecl *MD)
bool hasInheritedDefaultArg() const
Definition: Decl.h:1505
void RemoveDecl(Decl *D)
Definition: Scope.h:279
Name lookup found a single declaration that met the criteria.
Definition: Sema/Lookup.h:43
bool empty() const
Return true if no decls were found.
Definition: Sema/Lookup.h:323
bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS=nullptr)
isCurrentClassName - Determine whether the identifier II is the name of the class type currently bein...
bool isObjCObjectType() const
Definition: Type.h:5557
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2461
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
static AccessSpecifier MergeAccess(AccessSpecifier PathAccess, AccessSpecifier DeclAccess)
Calculates the access of a decl that is reached along a path.
Definition: DeclCXX.h:1616
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:831
Decl * ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, SourceLocation NamespaceLoc, SourceLocation IdentLoc, IdentifierInfo *Ident, SourceLocation LBrace, AttributeList *AttrList, UsingDirectiveDecl *&UsingDecl)
ActOnStartNamespaceDef - This is called at the start of a namespace definition.
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:191
bool hasTrivialMoveAssignment() const
Determine whether this class has a trivial move assignment operator (C++11 [class.copy]p25)
Definition: DeclCXX.h:1254
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:3707
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:427
static bool CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl)
void setUnparsedDefaultArg()
setUnparsedDefaultArg - Specify that this parameter has an unparsed default argument.
Definition: Decl.h:1501
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:2408
static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, SourceLocation UseLoc)
Diagnose an implicit copy operation for a class which is odr-used, but which is deprecated because th...
SourceManager & getSourceManager() const
Definition: Sema.h:1067
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl)
CheckLiteralOperatorDeclaration - Check whether the declaration of this literal operator function is ...
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:5818
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy.
Definition: Sema.h:1912
static void extendRight(SourceRange &R, SourceRange After)
unsigned getTypeQuals() const
Definition: Type.h:3378
Decl::Kind getDeclKind() const
Definition: DeclBase.h:1208
bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const AttributeList *AttrList)
UsingDecl * getUsingDecl() const
Gets the using declaration to which this declaration is tied.
Definition: DeclCXX.cpp:2177
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, bool IsDecltype=false)
Definition: SemaExpr.cpp:12822
Represents a C++ base or member initializer.
Definition: DeclCXX.h:1922
LanguageIDs
Represents the language in a linkage specification.
Definition: DeclCXX.h:2532
This template specialization was declared or defined by an explicit specialization (C++ [temp...
Definition: Specifiers.h:151
SourceRange getSourceRange() const LLVM_READONLY
getSourceRange - The range of the declaration name.
void AddDecl(NamedDecl *D)
AddDecl - Link the decl to its shadowed decl chain.
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:3273
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false)
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S'...
Definition: SemaDecl.cpp:1309
CXXRecordDecl * getOrigin() const
Retrieve the type from which this base-paths search began.
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope...
Definition: SemaDecl.cpp:1314
TrivialSubobjectKind
The kind of subobject we are checking for triviality.
NamedDecl * ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle)
ActOnCXXMemberDeclarator - This is invoked when a C++ class member declarator is parsed.
bool isFunctionType() const
Definition: Type.h:5479
static const void * GetKeyForBase(ASTContext &Context, QualType BaseType)
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations
A mapping from parameters with unparsed default arguments to the set of instantiations of each parame...
Definition: Sema.h:972
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsExplicitSpecialization, bool &Invalid)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
ClassTemplateDecl * getCanonicalDecl() override
CXXBasePath & front()
QualType BuildDecltypeType(Expr *E, SourceLocation Loc, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
Definition: SemaType.cpp:7312
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1288
bool isImplicitlyDeleted(FunctionDecl *FD)
Determine whether the given function is an implicitly-deleted special member function.
The noexcept specifier evaluates to false.
Definition: Type.h:3326
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2319
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1534
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1225
ActionResult< Stmt * > StmtResult
Definition: Ownership.h:254
decl_range decls()
Definition: Stmt.h:491
static UsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, UsingDecl *Using, NamedDecl *Target)
Definition: DeclCXX.h:2863
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier that qualifies the name, with source-location information.
Definition: DeclCXX.h:3076
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1528
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:1848
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr)
Definition: SemaExpr.cpp:11302
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool isInline, bool isConstexpr, SourceLocation EndLocation)
Definition: DeclCXX.cpp:1540
The template argument is a type.
Definition: TemplateBase.h:48
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:255
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:78
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1296
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream...
bool isInlineSpecified() const
Definition: DeclSpec.h:560
bool isInvalid() const
The "class" keyword.
Definition: Type.h:4350
A template-id, e.g., f<int>.
Definition: DeclSpec.h:907
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
Represents a base class of a C++ class.
Definition: DeclCXX.h:159
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2533
bool isAnyMemberInitializer() const
Definition: DeclCXX.h:2010
void setNamedTypeInfo(TypeSourceInfo *TInfo)
setNamedTypeInfo - Sets the source type info associated to the name.
void checkClassLevelDLLAttribute(CXXRecordDecl *Class)
Check class-level dllimport/dllexport attribute.
bool isUsable() const
Definition: Ownership.h:161
void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, ArrayRef< Expr * > Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition: SemaExpr.cpp:408
QualType getPointeeType() const
Definition: Type.h:2340
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:3155
This is a scope that can contain a declaration.
Definition: Scope.h:58
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:147
IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:1972
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:1863
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
Definition: SemaDecl.cpp:4916
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:1101
static const void * GetKeyForMember(ASTContext &Context, CXXCtorInitializer *Member)
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1037
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name.
Definition: DeclCXX.h:3079
Expr * getBase() const
Definition: Expr.h:2405
A template argument list.
Definition: DeclTemplate.h:173
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1013
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the class template specialization.
void setInvalidType(bool Val=true)
Definition: DeclSpec.h:2221
Expr * NoexceptExpr
Noexcept expression, if this is EST_ComputedNoexcept.
Definition: Type.h:3157
void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc)
PushNamespaceVisibilityAttr - Note that we've entered a namespace with a visibility attribute...
Definition: SemaAttr.cpp:464
void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc)
ActOnParamDefaultArgumentError - Parsing or semantic analysis of the default argument for the paramet...
void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a block pointer.
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups, surround it with a ExprWithCleanups node.
ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:1724
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record)
MarkBaseAndMemberDestructorsReferenced - Given a record decl, mark all the non-trivial destructors of...
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2315
static bool functionDeclHasDefaultArgument(const FunctionDecl *FD)
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
void CheckOverrideControl(NamedDecl *D)
CheckOverrideControl - Check C++11 override control semantics.
ThreadStorageClassSpecifier
Thread storage-class-specifier.
Definition: Specifiers.h:188
void setImplicitMoveAssignmentIsDeleted()
Set that we attempted to declare an implicit move assignment operator, but overload resolution failed...
Definition: DeclCXX.h:983
Describes the sequence of initializations required to initialize a given object or reference with a s...
Captures information about "declaration specifiers".
Definition: DeclSpec.h:228
FormatToken * Current
bool isAggregate() const
Determine whether this class is an aggregate (C++ [dcl.init.aggr]), which is a class with no user-dec...
Definition: DeclCXX.h:1107
bool isExplicitSpecified() const
Definition: DeclSpec.h:570
static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD)
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:5339
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:1978
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D...
void setDefaultArg(Expr *defarg)
Definition: Decl.cpp:2378
void setEnd(SourceLocation e)
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or NULL if there isn't one...
Represents a C++ struct/union/class.
Definition: DeclCXX.h:263
BoundNodesTreeBuilder *const Builder
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
static bool isCompoundAssignmentOp(Opcode Opc)
Definition: Expr.h:3027
bool hasUserDeclaredDestructor() const
Determine whether this class has a user-declared destructor.
Definition: DeclCXX.h:1010
void setIvarInitializers(ASTContext &C, CXXCtorInitializer **initializers, unsigned numInitializers)
Definition: DeclObjC.cpp:2110
A user-defined literal name, e.g., operator "" _i.
Definition: DeclSpec.h:899
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc)
bool isObjCObjectPointerType() const
Definition: Type.h:5554
bool implicitCopyAssignmentHasConstParam() const
Determine whether an implicit copy assignment operator for this type would have a parameter with a co...
Definition: DeclCXX.h:956
Opcode getOpcode() const
Definition: Expr.h:2940
Look up a friend of a local class.
Definition: Sema.h:2737
bool needsImplicitDefaultConstructor() const
Determine if we need to declare a default constructor for this class.
Definition: DeclCXX.h:832
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:3240
CXXCatchStmt - This represents a C++ catch block.
Definition: StmtCXX.h:29
void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD)
void setConstexpr(bool IC)
Definition: Decl.h:1884
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
FunctionDecl * FindUsualDeallocationFunction(SourceLocation StartLoc, bool CanProvideSize, DeclarationName Name)
void addHiddenDecl(Decl *D)
Add the declaration D to this context without modifying any lookup tables.
Definition: DeclBase.cpp:1270
void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc)
ActOnParamUnparsedDefaultArgument - We've seen a default argument for a function parameter, but we can't parse it yet because we're inside a class definition.
The parameter type of a method or function.
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1307
bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range)
CheckSpecifiedExceptionType - Check if the given type is valid in an exception specification.
CallingConv getDefaultCallingConvention(bool isVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current target.
CanQualType Char16Ty
Definition: ASTContext.h:899
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult{return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
TypeLoc getElementLoc() const
Definition: TypeLoc.h:1388
static bool hasOneRealArgument(MultiExprArg Args)
Determine whether the given list arguments contains exactly one "real" (non-default) argument...
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck=false, bool ForceUnprivileged=false)
Checks access for a hierarchy conversion.
static unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
Definition: ASTContext.h:2457
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:311
SourceLocation getOverrideLoc() const
Definition: DeclSpec.h:2293
void setUnsupportedFriend(bool Unsupported)
Definition: DeclFriend.h:159
static UsingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
Definition: DeclCXX.cpp:2237
Declaration of a class template.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
Definition: Diagnostic.h:115
MutableArrayRef< ParmVarDecl * >::iterator param_iterator
Definition: Decl.h:1997
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:353
const PropertyData & getPropertyData() const
bool isOverrideSpecified() const
Definition: DeclSpec.h:2292
LookupResultKind getResultKind() const
Definition: Sema/Lookup.h:305
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:70
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionReturnType - Checks whether the return types are covariant, according to C++ [class.virtual]p5.
static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, QualType SubType, bool ConstRHS, Sema::CXXSpecialMember CSM, TrivialSubobjectKind Kind, bool Diagnose)
Check whether the special member selected for a given type would be trivial.
unsigned getIndex() const
Retrieve the index of the template parameter.
bool isArrayType() const
Definition: Type.h:5521
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1466
Defines the clang::TargetInfo interface.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2148
bool needsImplicitCopyConstructor() const
Determine whether this class needs an implicit copy constructor to be lazily declared.
Definition: DeclCXX.h:863
Expr * getRHS() const
Definition: Expr.h:2945
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC...
Definition: DeclBase.h:1330
static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, bool ConstArg, CXXConstructorDecl *InheritedCtor=nullptr, Sema::InheritedConstructorInfo *Inherited=nullptr)
Determine whether the specified special member function would be constexpr if it were implicitly defi...
SourceRange getSourceRange() const override LLVM_READONLY
Definition: Decl.cpp:3346
const FunctionDecl * getOperatorDelete() const
Definition: DeclCXX.h:2439
void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, SmallVectorImpl< ObjCIvarDecl * > &Ivars)
CollectIvarsToConstructOrDestruct - Collect those ivars which require initialization.
ExprResult ExprError()
Definition: Ownership.h:268
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated, or computed.
FriendDecl * CheckFriendTypeDecl(SourceLocation LocStart, SourceLocation FriendLoc, TypeSourceInfo *TSInfo)
Perform semantic analysis of the given friend type declaration.
MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, SourceLocation LParenLoc, ArrayRef< Expr * > Args, SourceLocation RParenLoc, SourceLocation EllipsisLoc)
Handle a C++ member initializer using parentheses syntax.
static void CheckAbstractClassUsage(AbstractUsageInfo &Info, CXXMethodDecl *MD)
Check for invalid uses of an abstract type in a method declaration.
bool isIncompleteArrayType() const
Definition: Type.h:5527
CanQualType IntTy
Definition: ASTContext.h:901
A using declaration.
Definition: Sema.h:6103
bool isRecord() const
Definition: DeclBase.h:1287
bool isFragile() const
The inverse of isNonFragile(): does this runtime follow the set of implied behaviors for a "fragile" ...
Definition: ObjCRuntime.h:95
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:166
TranslationUnitDecl - The top declaration context.
Definition: Decl.h:80
NamespaceDecl * getAnonymousNamespace() const
Retrieve the anonymous namespace nested inside this namespace, if any.
Definition: Decl.h:548
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:196
ImplicitExceptionSpecification ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD)
Determine what sort of exception specification a defaulted move assignment operator of a class will h...
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:932
void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC)
CheckConversionDeclarator - Called by ActOnDeclarator to check the well-formednes of the conversion f...
bool isSet() const
Deprecated.
Definition: DeclSpec.h:209
NamedDecl * getMostRecentDecl()
Definition: Decl.h:401
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:133
void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD)
Diagnose methods which overload virtual methods in a base class without overriding any...
CXXMethodDecl * DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit copy assignment operator for the given class.
bool isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is provably not derived from the type Base.
CXXConstructorDecl * LookupDefaultConstructor(CXXRecordDecl *Class)
Look up the default constructor for the given class.
QualType getElementType() const
Definition: Type.h:2490
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Expr * getDefaultArgExprForConstructor(const CXXConstructorDecl *CD, unsigned ParmIdx)
llvm::DenseMap< CXXRecordDecl *, bool > VTablesUsed
The set of classes whose vtables have been used within this translation unit, and a bit that will be ...
Definition: Sema.h:5377
SourceManager & SourceMgr
Definition: Sema.h:302
bool hasRefQualifier() const
Determine whether this function declaration contains a ref-qualifier.
Definition: DeclSpec.h:1387
SourceLocation getRefQualifierLoc() const
Retrieve the location of the ref-qualifier, if any.
Definition: DeclSpec.h:1361
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:19
void setBaseObjectType(QualType T)
Sets the base object type for this lookup.
Definition: Sema/Lookup.h:404
static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM, unsigned Quals, bool ConstRHS, CXXMethodDecl **Selected)
Perform lookup for a special member of the specified kind, and determine whether it is trivial...
const Expr * getInit(unsigned Init) const
Definition: Expr.h:3785
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:52
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:3308
bool CheckDestructor(CXXDestructorDecl *Destructor)
CheckDestructor - Checks a fully-formed destructor definition for well-formedness, issuing any diagnostics required.
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Sema/Lookup.h:566
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2008
An instance of this class represents the declaration of a property member.
Definition: DeclCXX.h:3394
AttributeList * getNext() const
#define true
Definition: stdbool.h:32
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:109
StringRef getKindName() const
Definition: Decl.h:2926
A trivial tuple used to represent a source range.
bool CompleteConstructorCall(CXXConstructorDecl *Constructor, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl< Expr * > &ConvertedArgs, bool AllowExplicit=false, bool IsListInitialization=false)
Given a constructor and the set of arguments provided for the constructor, convert the arguments and ...
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:733
ASTContext & Context
Definition: Sema.h:299
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, std::unique_ptr< CorrectionCandidateCallback > CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
FunctionDecl * getCanonicalDecl() override
Definition: Decl.cpp:2676
paths_iterator end()
NamedDecl - This represents a decl with a name.
Definition: Decl.h:213
bool isInvalidType() const
Definition: DeclSpec.h:2222
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T)=0
bool isModulePrivateSpecified() const
Definition: DeclSpec.h:703
const CXXRecordDecl * getParent() const
Returns the parent of this using shadow declaration, which is the class in which this is declared...
Definition: DeclCXX.h:2980
CanQualType BoolTy
Definition: ASTContext.h:894
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID...
Represents a C++ namespace alias.
Definition: DeclCXX.h:2718
No keyword precedes the qualified type name.
Definition: Type.h:4372
SourceRange getSourceRange() const LLVM_READONLY
Retrieves the source range that contains the entire base specifier.
Definition: DeclCXX.h:203
void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const
Retrieve the final overriders for each virtual member function in the class hierarchy where this clas...
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:5318
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg)
Definition: Sema.h:3334
Represents C++ using-directive.
Definition: DeclCXX.h:2615
SmallVector< std::pair< const CXXMethodDecl *, const CXXMethodDecl * >, 2 > DelayedExceptionSpecChecks
All the overriding functions seen during a class definition that had their exception spec checks dela...
Definition: Sema.h:540
void DiagnoseAbstractType(const CXXRecordDecl *RD)
static Expr * CastForMoving(Sema &SemaRef, Expr *E, QualType T=QualType())
bool hasConstexprDefaultConstructor() const
Determine whether this class has a constexpr default constructor.
Definition: DeclCXX.h:1205
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:665
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition: DeclCXX.h:1154
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
virtual void ReadUsedVTables(SmallVectorImpl< ExternalVTableUse > &VTables)
Read the set of used vtables known to the external Sema source.
The global specifier '::'. There is no stored value.
The noexcept specifier is dependent.
Definition: Type.h:3325
The type of an arbitrary declaration.
Definition: Sema.h:6085
NamespaceDecl * getStdNamespace() const
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
The object is actually the complete object.
void setType(QualType newType)
Definition: Decl.h:600
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool isExplicit, bool isInline, bool isImplicitlyDeclared, bool isConstexpr, InheritedConstructor Inherited=InheritedConstructor())
Definition: DeclCXX.cpp:1833
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:470
Wrapper for source info for pointers.
Definition: TypeLoc.h:1134
ParsedAttributes - A collection of parsed attributes.
SourceLocation ColonLoc
Location of ':'.
Definition: OpenMPClause.h:266
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:135
void WillReplaceSpecifier(bool ForceReplacement)
Wrapper for source info for block pointers.
Definition: TypeLoc.h:1147
void setDeletedAsWritten(bool D=true)
Definition: Decl.h:1911
void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl)
AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared special functions, such as the default constructor, copy constructor, or destructor, to the given C++ class (C++ [special]p1).
bool hasInheritedAssignment() const
Determine whether this class has a using-declaration that names a base class assignment operator...
Definition: DeclCXX.h:1310
TemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args, QualType Canon, QualType Aliased)
void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation)
SetIvarInitializers - This routine builds initialization ASTs for the Objective-C implementation whos...
No in-class initializer.
Definition: Specifiers.h:225
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:4561
SmallVector< std::pair< CXXMethodDecl *, const FunctionProtoType * >, 2 > DelayedDefaultedMemberExceptionSpecs
All the members seen during a class definition which were both explicitly defaulted and had explicitl...
Definition: Sema.h:550
ArrayRef< QualType > exceptions() const
Definition: Type.h:3401
bool isBeingDefined() const
isBeingDefined - Return true if this decl is currently being defined.
Definition: Decl.h:2882
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2512
base_class_range vbases()
Definition: DeclCXX.h:735
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:3187
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
enum clang::UnqualifiedId::IdKind Kind
Declaration of a template function.
Definition: DeclTemplate.h:838
void clear()
Clears out any current state.
Definition: Sema/Lookup.h:538
std::list< CXXBasePath >::iterator paths_iterator
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:4315
MSPropertyDecl * HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, AttributeList *MSPropertyAttr)
HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer)
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:1120
void DiagnoseAbsenceOfOverrideControl(NamedDecl *D)
DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was not used in the declaration of ...
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition: DeclSpec.h:1286
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1730
Comparison
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition: Sema.h:484
static bool checkLiteralOperatorTemplateParameterList(Sema &SemaRef, FunctionTemplateDecl *TpDecl)
Attr - This represents one attribute.
Definition: Attr.h:45
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:749
Represents a shadow declaration introduced into a scope by a (resolved) using declaration.
Definition: DeclCXX.h:2835
TypeSourceInfo * GetTypeForDeclarator(Declarator &D, Scope *S)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:4581
bool hasUserDeclaredConstructor() const
Determine whether this class has any user-declared constructors.
Definition: DeclCXX.h:844
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:5702
const RecordDecl * getParent() const
getParent - Returns the parent of this field declaration, which is the struct in which this method is...
Definition: Decl.h:2455
Helper class that creates diagnostics with optional template instantiation stacks.
Definition: Sema.h:1092
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Definition: Expr.cpp:2295
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:1729
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:4788
AttributeList - Represents a syntactic attribute.
Definition: AttributeList.h:94
Decl * ActOnConversionDeclarator(CXXConversionDecl *Conversion)
ActOnConversionDeclarator - Called by ActOnDeclarator to complete the declaration of the given C++ co...
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:5286
bool isMutable() const
isMutable - Determines whether this field is mutable (C++ only).
Definition: Decl.h:2358
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope...
Definition: SemaDecl.cpp:1331
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition: Sema.h:976
bool hasInClassInitializer() const
hasInClassInitializer - Determine whether this member has a C++11 in-class initializer.
Definition: Decl.h:2408
bool isPointerType() const
Definition: Type.h:5482
static unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
Definition: ASTContext.h:2481
static bool isVisible(Sema &SemaRef, NamedDecl *D)
Determine whether the given declaration is visible to the program.
Definition: Sema/Lookup.h:333
unsigned getNumTemplateParameterLists() const
Definition: Decl.h:714
NamedDecl * ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams)
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
getCXXOperatorName - Get the name of the overloadable C++ operator corresponding to Op...
unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template)
static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, SourceLocation Loc, IdentifierInfo *II, bool *IsInline, NamespaceDecl *PrevNS)
Diagnose a mismatch in 'inline' qualifiers when a namespace is reopened.
A RAII object to temporarily push a declaration context.
Definition: Sema.h:634
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any...
Definition: Decl.cpp:3014
The subobject is a non-static data member.
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:131