clang API Documentation

SemaDeclCXX.cpp
Go to the documentation of this file.
00001 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file implements semantic analysis for C++ declarations.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/Sema/SemaInternal.h"
00015 #include "clang/Sema/CXXFieldCollector.h"
00016 #include "clang/Sema/Scope.h"
00017 #include "clang/Sema/Initialization.h"
00018 #include "clang/Sema/Lookup.h"
00019 #include "clang/Sema/ScopeInfo.h"
00020 #include "clang/AST/ASTConsumer.h"
00021 #include "clang/AST/ASTContext.h"
00022 #include "clang/AST/ASTMutationListener.h"
00023 #include "clang/AST/CharUnits.h"
00024 #include "clang/AST/CXXInheritance.h"
00025 #include "clang/AST/DeclVisitor.h"
00026 #include "clang/AST/ExprCXX.h"
00027 #include "clang/AST/RecordLayout.h"
00028 #include "clang/AST/RecursiveASTVisitor.h"
00029 #include "clang/AST/StmtVisitor.h"
00030 #include "clang/AST/TypeLoc.h"
00031 #include "clang/AST/TypeOrdering.h"
00032 #include "clang/Sema/DeclSpec.h"
00033 #include "clang/Sema/ParsedTemplate.h"
00034 #include "clang/Basic/PartialDiagnostic.h"
00035 #include "clang/Lex/Preprocessor.h"
00036 #include "llvm/ADT/SmallString.h"
00037 #include "llvm/ADT/STLExtras.h"
00038 #include <map>
00039 #include <set>
00040 
00041 using namespace clang;
00042 
00043 //===----------------------------------------------------------------------===//
00044 // CheckDefaultArgumentVisitor
00045 //===----------------------------------------------------------------------===//
00046 
00047 namespace {
00048   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
00049   /// the default argument of a parameter to determine whether it
00050   /// contains any ill-formed subexpressions. For example, this will
00051   /// diagnose the use of local variables or parameters within the
00052   /// default argument expression.
00053   class CheckDefaultArgumentVisitor
00054     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
00055     Expr *DefaultArg;
00056     Sema *S;
00057 
00058   public:
00059     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
00060       : DefaultArg(defarg), S(s) {}
00061 
00062     bool VisitExpr(Expr *Node);
00063     bool VisitDeclRefExpr(DeclRefExpr *DRE);
00064     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
00065     bool VisitLambdaExpr(LambdaExpr *Lambda);
00066   };
00067 
00068   /// VisitExpr - Visit all of the children of this expression.
00069   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
00070     bool IsInvalid = false;
00071     for (Stmt::child_range I = Node->children(); I; ++I)
00072       IsInvalid |= Visit(*I);
00073     return IsInvalid;
00074   }
00075 
00076   /// VisitDeclRefExpr - Visit a reference to a declaration, to
00077   /// determine whether this declaration can be used in the default
00078   /// argument expression.
00079   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
00080     NamedDecl *Decl = DRE->getDecl();
00081     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
00082       // C++ [dcl.fct.default]p9
00083       //   Default arguments are evaluated each time the function is
00084       //   called. The order of evaluation of function arguments is
00085       //   unspecified. Consequently, parameters of a function shall not
00086       //   be used in default argument expressions, even if they are not
00087       //   evaluated. Parameters of a function declared before a default
00088       //   argument expression are in scope and can hide namespace and
00089       //   class member names.
00090       return S->Diag(DRE->getLocStart(),
00091                      diag::err_param_default_argument_references_param)
00092          << Param->getDeclName() << DefaultArg->getSourceRange();
00093     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
00094       // C++ [dcl.fct.default]p7
00095       //   Local variables shall not be used in default argument
00096       //   expressions.
00097       if (VDecl->isLocalVarDecl())
00098         return S->Diag(DRE->getLocStart(),
00099                        diag::err_param_default_argument_references_local)
00100           << VDecl->getDeclName() << DefaultArg->getSourceRange();
00101     }
00102 
00103     return false;
00104   }
00105 
00106   /// VisitCXXThisExpr - Visit a C++ "this" expression.
00107   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
00108     // C++ [dcl.fct.default]p8:
00109     //   The keyword this shall not be used in a default argument of a
00110     //   member function.
00111     return S->Diag(ThisE->getLocStart(),
00112                    diag::err_param_default_argument_references_this)
00113                << ThisE->getSourceRange();
00114   }
00115 
00116   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
00117     // C++11 [expr.lambda.prim]p13:
00118     //   A lambda-expression appearing in a default argument shall not
00119     //   implicitly or explicitly capture any entity.
00120     if (Lambda->capture_begin() == Lambda->capture_end())
00121       return false;
00122 
00123     return S->Diag(Lambda->getLocStart(), 
00124                    diag::err_lambda_capture_default_arg);
00125   }
00126 }
00127 
00128 void Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
00129                                                       CXXMethodDecl *Method) {
00130   // If we have an MSAny or unknown spec already, don't bother.
00131   if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
00132     return;
00133 
00134   const FunctionProtoType *Proto
00135     = Method->getType()->getAs<FunctionProtoType>();
00136   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
00137   if (!Proto)
00138     return;
00139 
00140   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
00141 
00142   // If this function can throw any exceptions, make a note of that.
00143   if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
00144     ClearExceptions();
00145     ComputedEST = EST;
00146     return;
00147   }
00148 
00149   // FIXME: If the call to this decl is using any of its default arguments, we
00150   // need to search them for potentially-throwing calls.
00151 
00152   // If this function has a basic noexcept, it doesn't affect the outcome.
00153   if (EST == EST_BasicNoexcept)
00154     return;
00155 
00156   // If we have a throw-all spec at this point, ignore the function.
00157   if (ComputedEST == EST_None)
00158     return;
00159 
00160   // If we're still at noexcept(true) and there's a nothrow() callee,
00161   // change to that specification.
00162   if (EST == EST_DynamicNone) {
00163     if (ComputedEST == EST_BasicNoexcept)
00164       ComputedEST = EST_DynamicNone;
00165     return;
00166   }
00167 
00168   // Check out noexcept specs.
00169   if (EST == EST_ComputedNoexcept) {
00170     FunctionProtoType::NoexceptResult NR =
00171         Proto->getNoexceptSpec(Self->Context);
00172     assert(NR != FunctionProtoType::NR_NoNoexcept &&
00173            "Must have noexcept result for EST_ComputedNoexcept.");
00174     assert(NR != FunctionProtoType::NR_Dependent &&
00175            "Should not generate implicit declarations for dependent cases, "
00176            "and don't know how to handle them anyway.");
00177 
00178     // noexcept(false) -> no spec on the new function
00179     if (NR == FunctionProtoType::NR_Throw) {
00180       ClearExceptions();
00181       ComputedEST = EST_None;
00182     }
00183     // noexcept(true) won't change anything either.
00184     return;
00185   }
00186 
00187   assert(EST == EST_Dynamic && "EST case not considered earlier.");
00188   assert(ComputedEST != EST_None &&
00189          "Shouldn't collect exceptions when throw-all is guaranteed.");
00190   ComputedEST = EST_Dynamic;
00191   // Record the exceptions in this function's exception specification.
00192   for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
00193                                           EEnd = Proto->exception_end();
00194        E != EEnd; ++E)
00195     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
00196       Exceptions.push_back(*E);
00197 }
00198 
00199 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
00200   if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
00201     return;
00202 
00203   // FIXME:
00204   //
00205   // C++0x [except.spec]p14:
00206   //   [An] implicit exception-specification specifies the type-id T if and
00207   // only if T is allowed by the exception-specification of a function directly
00208   // invoked by f's implicit definition; f shall allow all exceptions if any
00209   // function it directly invokes allows all exceptions, and f shall allow no
00210   // exceptions if every function it directly invokes allows no exceptions.
00211   //
00212   // Note in particular that if an implicit exception-specification is generated
00213   // for a function containing a throw-expression, that specification can still
00214   // be noexcept(true).
00215   //
00216   // Note also that 'directly invoked' is not defined in the standard, and there
00217   // is no indication that we should only consider potentially-evaluated calls.
00218   //
00219   // Ultimately we should implement the intent of the standard: the exception
00220   // specification should be the set of exceptions which can be thrown by the
00221   // implicit definition. For now, we assume that any non-nothrow expression can
00222   // throw any exception.
00223 
00224   if (Self->canThrow(E))
00225     ComputedEST = EST_None;
00226 }
00227 
00228 bool
00229 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
00230                               SourceLocation EqualLoc) {
00231   if (RequireCompleteType(Param->getLocation(), Param->getType(),
00232                           diag::err_typecheck_decl_incomplete_type)) {
00233     Param->setInvalidDecl();
00234     return true;
00235   }
00236 
00237   // C++ [dcl.fct.default]p5
00238   //   A default argument expression is implicitly converted (clause
00239   //   4) to the parameter type. The default argument expression has
00240   //   the same semantic constraints as the initializer expression in
00241   //   a declaration of a variable of the parameter type, using the
00242   //   copy-initialization semantics (8.5).
00243   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
00244                                                                     Param);
00245   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
00246                                                            EqualLoc);
00247   InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
00248   ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
00249                                       MultiExprArg(*this, &Arg, 1));
00250   if (Result.isInvalid())
00251     return true;
00252   Arg = Result.takeAs<Expr>();
00253 
00254   CheckImplicitConversions(Arg, EqualLoc);
00255   Arg = MaybeCreateExprWithCleanups(Arg);
00256 
00257   // Okay: add the default argument to the parameter
00258   Param->setDefaultArg(Arg);
00259 
00260   // We have already instantiated this parameter; provide each of the 
00261   // instantiations with the uninstantiated default argument.
00262   UnparsedDefaultArgInstantiationsMap::iterator InstPos
00263     = UnparsedDefaultArgInstantiations.find(Param);
00264   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
00265     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
00266       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
00267     
00268     // We're done tracking this parameter's instantiations.
00269     UnparsedDefaultArgInstantiations.erase(InstPos);
00270   }
00271   
00272   return false;
00273 }
00274 
00275 /// ActOnParamDefaultArgument - Check whether the default argument
00276 /// provided for a function parameter is well-formed. If so, attach it
00277 /// to the parameter declaration.
00278 void
00279 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
00280                                 Expr *DefaultArg) {
00281   if (!param || !DefaultArg)
00282     return;
00283 
00284   ParmVarDecl *Param = cast<ParmVarDecl>(param);
00285   UnparsedDefaultArgLocs.erase(Param);
00286 
00287   // Default arguments are only permitted in C++
00288   if (!getLangOpts().CPlusPlus) {
00289     Diag(EqualLoc, diag::err_param_default_argument)
00290       << DefaultArg->getSourceRange();
00291     Param->setInvalidDecl();
00292     return;
00293   }
00294 
00295   // Check for unexpanded parameter packs.
00296   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
00297     Param->setInvalidDecl();
00298     return;
00299   }    
00300       
00301   // Check that the default argument is well-formed
00302   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
00303   if (DefaultArgChecker.Visit(DefaultArg)) {
00304     Param->setInvalidDecl();
00305     return;
00306   }
00307 
00308   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
00309 }
00310 
00311 /// ActOnParamUnparsedDefaultArgument - We've seen a default
00312 /// argument for a function parameter, but we can't parse it yet
00313 /// because we're inside a class definition. Note that this default
00314 /// argument will be parsed later.
00315 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
00316                                              SourceLocation EqualLoc,
00317                                              SourceLocation ArgLoc) {
00318   if (!param)
00319     return;
00320 
00321   ParmVarDecl *Param = cast<ParmVarDecl>(param);
00322   if (Param)
00323     Param->setUnparsedDefaultArg();
00324 
00325   UnparsedDefaultArgLocs[Param] = ArgLoc;
00326 }
00327 
00328 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
00329 /// the default argument for the parameter param failed.
00330 void Sema::ActOnParamDefaultArgumentError(Decl *param) {
00331   if (!param)
00332     return;
00333 
00334   ParmVarDecl *Param = cast<ParmVarDecl>(param);
00335 
00336   Param->setInvalidDecl();
00337 
00338   UnparsedDefaultArgLocs.erase(Param);
00339 }
00340 
00341 /// CheckExtraCXXDefaultArguments - Check for any extra default
00342 /// arguments in the declarator, which is not a function declaration
00343 /// or definition and therefore is not permitted to have default
00344 /// arguments. This routine should be invoked for every declarator
00345 /// that is not a function declaration or definition.
00346 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
00347   // C++ [dcl.fct.default]p3
00348   //   A default argument expression shall be specified only in the
00349   //   parameter-declaration-clause of a function declaration or in a
00350   //   template-parameter (14.1). It shall not be specified for a
00351   //   parameter pack. If it is specified in a
00352   //   parameter-declaration-clause, it shall not occur within a
00353   //   declarator or abstract-declarator of a parameter-declaration.
00354   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
00355     DeclaratorChunk &chunk = D.getTypeObject(i);
00356     if (chunk.Kind == DeclaratorChunk::Function) {
00357       for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
00358         ParmVarDecl *Param =
00359           cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
00360         if (Param->hasUnparsedDefaultArg()) {
00361           CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
00362           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
00363             << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
00364           delete Toks;
00365           chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
00366         } else if (Param->getDefaultArg()) {
00367           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
00368             << Param->getDefaultArg()->getSourceRange();
00369           Param->setDefaultArg(0);
00370         }
00371       }
00372     }
00373   }
00374 }
00375 
00376 // MergeCXXFunctionDecl - Merge two declarations of the same C++
00377 // function, once we already know that they have the same
00378 // type. Subroutine of MergeFunctionDecl. Returns true if there was an
00379 // error, false otherwise.
00380 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
00381                                 Scope *S) {
00382   bool Invalid = false;
00383 
00384   // C++ [dcl.fct.default]p4:
00385   //   For non-template functions, default arguments can be added in
00386   //   later declarations of a function in the same
00387   //   scope. Declarations in different scopes have completely
00388   //   distinct sets of default arguments. That is, declarations in
00389   //   inner scopes do not acquire default arguments from
00390   //   declarations in outer scopes, and vice versa. In a given
00391   //   function declaration, all parameters subsequent to a
00392   //   parameter with a default argument shall have default
00393   //   arguments supplied in this or previous declarations. A
00394   //   default argument shall not be redefined by a later
00395   //   declaration (not even to the same value).
00396   //
00397   // C++ [dcl.fct.default]p6:
00398   //   Except for member functions of class templates, the default arguments 
00399   //   in a member function definition that appears outside of the class 
00400   //   definition are added to the set of default arguments provided by the 
00401   //   member function declaration in the class definition.
00402   for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
00403     ParmVarDecl *OldParam = Old->getParamDecl(p);
00404     ParmVarDecl *NewParam = New->getParamDecl(p);
00405 
00406     bool OldParamHasDfl = OldParam->hasDefaultArg();
00407     bool NewParamHasDfl = NewParam->hasDefaultArg();
00408 
00409     NamedDecl *ND = Old;
00410     if (S && !isDeclInScope(ND, New->getDeclContext(), S))
00411       // Ignore default parameters of old decl if they are not in
00412       // the same scope.
00413       OldParamHasDfl = false;
00414 
00415     if (OldParamHasDfl && NewParamHasDfl) {
00416 
00417       unsigned DiagDefaultParamID =
00418         diag::err_param_default_argument_redefinition;
00419 
00420       // MSVC accepts that default parameters be redefined for member functions
00421       // of template class. The new default parameter's value is ignored.
00422       Invalid = true;
00423       if (getLangOpts().MicrosoftExt) {
00424         CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
00425         if (MD && MD->getParent()->getDescribedClassTemplate()) {
00426           // Merge the old default argument into the new parameter.
00427           NewParam->setHasInheritedDefaultArg();
00428           if (OldParam->hasUninstantiatedDefaultArg())
00429             NewParam->setUninstantiatedDefaultArg(
00430                                       OldParam->getUninstantiatedDefaultArg());
00431           else
00432             NewParam->setDefaultArg(OldParam->getInit());
00433           DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
00434           Invalid = false;
00435         }
00436       }
00437       
00438       // FIXME: If we knew where the '=' was, we could easily provide a fix-it 
00439       // hint here. Alternatively, we could walk the type-source information
00440       // for NewParam to find the last source location in the type... but it
00441       // isn't worth the effort right now. This is the kind of test case that
00442       // is hard to get right:
00443       //   int f(int);
00444       //   void g(int (*fp)(int) = f);
00445       //   void g(int (*fp)(int) = &f);
00446       Diag(NewParam->getLocation(), DiagDefaultParamID)
00447         << NewParam->getDefaultArgRange();
00448       
00449       // Look for the function declaration where the default argument was
00450       // actually written, which may be a declaration prior to Old.
00451       for (FunctionDecl *Older = Old->getPreviousDecl();
00452            Older; Older = Older->getPreviousDecl()) {
00453         if (!Older->getParamDecl(p)->hasDefaultArg())
00454           break;
00455         
00456         OldParam = Older->getParamDecl(p);
00457       }        
00458       
00459       Diag(OldParam->getLocation(), diag::note_previous_definition)
00460         << OldParam->getDefaultArgRange();
00461     } else if (OldParamHasDfl) {
00462       // Merge the old default argument into the new parameter.
00463       // It's important to use getInit() here;  getDefaultArg()
00464       // strips off any top-level ExprWithCleanups.
00465       NewParam->setHasInheritedDefaultArg();
00466       if (OldParam->hasUninstantiatedDefaultArg())
00467         NewParam->setUninstantiatedDefaultArg(
00468                                       OldParam->getUninstantiatedDefaultArg());
00469       else
00470         NewParam->setDefaultArg(OldParam->getInit());
00471     } else if (NewParamHasDfl) {
00472       if (New->getDescribedFunctionTemplate()) {
00473         // Paragraph 4, quoted above, only applies to non-template functions.
00474         Diag(NewParam->getLocation(),
00475              diag::err_param_default_argument_template_redecl)
00476           << NewParam->getDefaultArgRange();
00477         Diag(Old->getLocation(), diag::note_template_prev_declaration)
00478           << false;
00479       } else if (New->getTemplateSpecializationKind()
00480                    != TSK_ImplicitInstantiation &&
00481                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
00482         // C++ [temp.expr.spec]p21:
00483         //   Default function arguments shall not be specified in a declaration
00484         //   or a definition for one of the following explicit specializations:
00485         //     - the explicit specialization of a function template;
00486         //     - the explicit specialization of a member function template;
00487         //     - the explicit specialization of a member function of a class 
00488         //       template where the class template specialization to which the
00489         //       member function specialization belongs is implicitly 
00490         //       instantiated.
00491         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
00492           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
00493           << New->getDeclName()
00494           << NewParam->getDefaultArgRange();
00495       } else if (New->getDeclContext()->isDependentContext()) {
00496         // C++ [dcl.fct.default]p6 (DR217):
00497         //   Default arguments for a member function of a class template shall 
00498         //   be specified on the initial declaration of the member function 
00499         //   within the class template.
00500         //
00501         // Reading the tea leaves a bit in DR217 and its reference to DR205 
00502         // leads me to the conclusion that one cannot add default function 
00503         // arguments for an out-of-line definition of a member function of a 
00504         // dependent type.
00505         int WhichKind = 2;
00506         if (CXXRecordDecl *Record 
00507               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
00508           if (Record->getDescribedClassTemplate())
00509             WhichKind = 0;
00510           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
00511             WhichKind = 1;
00512           else
00513             WhichKind = 2;
00514         }
00515         
00516         Diag(NewParam->getLocation(), 
00517              diag::err_param_default_argument_member_template_redecl)
00518           << WhichKind
00519           << NewParam->getDefaultArgRange();
00520       } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
00521         CXXSpecialMember NewSM = getSpecialMember(Ctor),
00522                          OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
00523         if (NewSM != OldSM) {
00524           Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
00525             << NewParam->getDefaultArgRange() << NewSM;
00526           Diag(Old->getLocation(), diag::note_previous_declaration_special)
00527             << OldSM;
00528         }
00529       }
00530     }
00531   }
00532 
00533   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
00534   // template has a constexpr specifier then all its declarations shall
00535   // contain the constexpr specifier.
00536   if (New->isConstexpr() != Old->isConstexpr()) {
00537     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
00538       << New << New->isConstexpr();
00539     Diag(Old->getLocation(), diag::note_previous_declaration);
00540     Invalid = true;
00541   }
00542 
00543   if (CheckEquivalentExceptionSpec(Old, New))
00544     Invalid = true;
00545 
00546   return Invalid;
00547 }
00548 
00549 /// \brief Merge the exception specifications of two variable declarations.
00550 ///
00551 /// This is called when there's a redeclaration of a VarDecl. The function
00552 /// checks if the redeclaration might have an exception specification and
00553 /// validates compatibility and merges the specs if necessary.
00554 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
00555   // Shortcut if exceptions are disabled.
00556   if (!getLangOpts().CXXExceptions)
00557     return;
00558 
00559   assert(Context.hasSameType(New->getType(), Old->getType()) &&
00560          "Should only be called if types are otherwise the same.");
00561 
00562   QualType NewType = New->getType();
00563   QualType OldType = Old->getType();
00564 
00565   // We're only interested in pointers and references to functions, as well
00566   // as pointers to member functions.
00567   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
00568     NewType = R->getPointeeType();
00569     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
00570   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
00571     NewType = P->getPointeeType();
00572     OldType = OldType->getAs<PointerType>()->getPointeeType();
00573   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
00574     NewType = M->getPointeeType();
00575     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
00576   }
00577 
00578   if (!NewType->isFunctionProtoType())
00579     return;
00580 
00581   // There's lots of special cases for functions. For function pointers, system
00582   // libraries are hopefully not as broken so that we don't need these
00583   // workarounds.
00584   if (CheckEquivalentExceptionSpec(
00585         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
00586         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
00587     New->setInvalidDecl();
00588   }
00589 }
00590 
00591 /// CheckCXXDefaultArguments - Verify that the default arguments for a
00592 /// function declaration are well-formed according to C++
00593 /// [dcl.fct.default].
00594 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
00595   unsigned NumParams = FD->getNumParams();
00596   unsigned p;
00597 
00598   bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
00599                   isa<CXXMethodDecl>(FD) &&
00600                   cast<CXXMethodDecl>(FD)->getParent()->isLambda();
00601               
00602   // Find first parameter with a default argument
00603   for (p = 0; p < NumParams; ++p) {
00604     ParmVarDecl *Param = FD->getParamDecl(p);
00605     if (Param->hasDefaultArg()) {
00606       // C++11 [expr.prim.lambda]p5:
00607       //   [...] Default arguments (8.3.6) shall not be specified in the 
00608       //   parameter-declaration-clause of a lambda-declarator.
00609       //
00610       // FIXME: Core issue 974 strikes this sentence, we only provide an
00611       // extension warning.
00612       if (IsLambda)
00613         Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
00614           << Param->getDefaultArgRange();
00615       break;
00616     }
00617   }
00618 
00619   // C++ [dcl.fct.default]p4:
00620   //   In a given function declaration, all parameters
00621   //   subsequent to a parameter with a default argument shall
00622   //   have default arguments supplied in this or previous
00623   //   declarations. A default argument shall not be redefined
00624   //   by a later declaration (not even to the same value).
00625   unsigned LastMissingDefaultArg = 0;
00626   for (; p < NumParams; ++p) {
00627     ParmVarDecl *Param = FD->getParamDecl(p);
00628     if (!Param->hasDefaultArg()) {
00629       if (Param->isInvalidDecl())
00630         /* We already complained about this parameter. */;
00631       else if (Param->getIdentifier())
00632         Diag(Param->getLocation(),
00633              diag::err_param_default_argument_missing_name)
00634           << Param->getIdentifier();
00635       else
00636         Diag(Param->getLocation(),
00637              diag::err_param_default_argument_missing);
00638 
00639       LastMissingDefaultArg = p;
00640     }
00641   }
00642 
00643   if (LastMissingDefaultArg > 0) {
00644     // Some default arguments were missing. Clear out all of the
00645     // default arguments up to (and including) the last missing
00646     // default argument, so that we leave the function parameters
00647     // in a semantically valid state.
00648     for (p = 0; p <= LastMissingDefaultArg; ++p) {
00649       ParmVarDecl *Param = FD->getParamDecl(p);
00650       if (Param->hasDefaultArg()) {
00651         Param->setDefaultArg(0);
00652       }
00653     }
00654   }
00655 }
00656 
00657 // CheckConstexprParameterTypes - Check whether a function's parameter types
00658 // are all literal types. If so, return true. If not, produce a suitable
00659 // diagnostic and return false.
00660 static bool CheckConstexprParameterTypes(Sema &SemaRef,
00661                                          const FunctionDecl *FD) {
00662   unsigned ArgIndex = 0;
00663   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
00664   for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
00665        e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
00666     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
00667     SourceLocation ParamLoc = PD->getLocation();
00668     if (!(*i)->isDependentType() &&
00669         SemaRef.RequireLiteralType(ParamLoc, *i,
00670                                    diag::err_constexpr_non_literal_param,
00671                                    ArgIndex+1, PD->getSourceRange(),
00672                                    isa<CXXConstructorDecl>(FD)))
00673       return false;
00674   }
00675   return true;
00676 }
00677 
00678 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
00679 // the requirements of a constexpr function definition or a constexpr
00680 // constructor definition. If so, return true. If not, produce appropriate
00681 // diagnostics and return false.
00682 //
00683 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
00684 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
00685   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
00686   if (MD && MD->isInstance()) {
00687     // C++11 [dcl.constexpr]p4:
00688     //  The definition of a constexpr constructor shall satisfy the following
00689     //  constraints:
00690     //  - the class shall not have any virtual base classes;
00691     const CXXRecordDecl *RD = MD->getParent();
00692     if (RD->getNumVBases()) {
00693       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
00694         << isa<CXXConstructorDecl>(NewFD) << RD->isStruct()
00695         << RD->getNumVBases();
00696       for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
00697              E = RD->vbases_end(); I != E; ++I)
00698         Diag(I->getLocStart(),
00699              diag::note_constexpr_virtual_base_here) << I->getSourceRange();
00700       return false;
00701     }
00702   }
00703 
00704   if (!isa<CXXConstructorDecl>(NewFD)) {
00705     // C++11 [dcl.constexpr]p3:
00706     //  The definition of a constexpr function shall satisfy the following
00707     //  constraints:
00708     // - it shall not be virtual;
00709     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
00710     if (Method && Method->isVirtual()) {
00711       Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
00712 
00713       // If it's not obvious why this function is virtual, find an overridden
00714       // function which uses the 'virtual' keyword.
00715       const CXXMethodDecl *WrittenVirtual = Method;
00716       while (!WrittenVirtual->isVirtualAsWritten())
00717         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
00718       if (WrittenVirtual != Method)
00719         Diag(WrittenVirtual->getLocation(),
00720              diag::note_overridden_virtual_function);
00721       return false;
00722     }
00723 
00724     // - its return type shall be a literal type;
00725     QualType RT = NewFD->getResultType();
00726     if (!RT->isDependentType() &&
00727         RequireLiteralType(NewFD->getLocation(), RT,
00728                            diag::err_constexpr_non_literal_return))
00729       return false;
00730   }
00731 
00732   // - each of its parameter types shall be a literal type;
00733   if (!CheckConstexprParameterTypes(*this, NewFD))
00734     return false;
00735 
00736   return true;
00737 }
00738 
00739 /// Check the given declaration statement is legal within a constexpr function
00740 /// body. C++0x [dcl.constexpr]p3,p4.
00741 ///
00742 /// \return true if the body is OK, false if we have diagnosed a problem.
00743 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
00744                                    DeclStmt *DS) {
00745   // C++0x [dcl.constexpr]p3 and p4:
00746   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
00747   //  contain only
00748   for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
00749          DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
00750     switch ((*DclIt)->getKind()) {
00751     case Decl::StaticAssert:
00752     case Decl::Using:
00753     case Decl::UsingShadow:
00754     case Decl::UsingDirective:
00755     case Decl::UnresolvedUsingTypename:
00756       //   - static_assert-declarations
00757       //   - using-declarations,
00758       //   - using-directives,
00759       continue;
00760 
00761     case Decl::Typedef:
00762     case Decl::TypeAlias: {
00763       //   - typedef declarations and alias-declarations that do not define
00764       //     classes or enumerations,
00765       TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
00766       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
00767         // Don't allow variably-modified types in constexpr functions.
00768         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
00769         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
00770           << TL.getSourceRange() << TL.getType()
00771           << isa<CXXConstructorDecl>(Dcl);
00772         return false;
00773       }
00774       continue;
00775     }
00776 
00777     case Decl::Enum:
00778     case Decl::CXXRecord:
00779       // As an extension, we allow the declaration (but not the definition) of
00780       // classes and enumerations in all declarations, not just in typedef and
00781       // alias declarations.
00782       if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
00783         SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
00784           << isa<CXXConstructorDecl>(Dcl);
00785         return false;
00786       }
00787       continue;
00788 
00789     case Decl::Var:
00790       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
00791         << isa<CXXConstructorDecl>(Dcl);
00792       return false;
00793 
00794     default:
00795       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
00796         << isa<CXXConstructorDecl>(Dcl);
00797       return false;
00798     }
00799   }
00800 
00801   return true;
00802 }
00803 
00804 /// Check that the given field is initialized within a constexpr constructor.
00805 ///
00806 /// \param Dcl The constexpr constructor being checked.
00807 /// \param Field The field being checked. This may be a member of an anonymous
00808 ///        struct or union nested within the class being checked.
00809 /// \param Inits All declarations, including anonymous struct/union members and
00810 ///        indirect members, for which any initialization was provided.
00811 /// \param Diagnosed Set to true if an error is produced.
00812 static void CheckConstexprCtorInitializer(Sema &SemaRef,
00813                                           const FunctionDecl *Dcl,
00814                                           FieldDecl *Field,
00815                                           llvm::SmallSet<Decl*, 16> &Inits,
00816                                           bool &Diagnosed) {
00817   if (Field->isUnnamedBitfield())
00818     return;
00819 
00820   if (Field->isAnonymousStructOrUnion() &&
00821       Field->getType()->getAsCXXRecordDecl()->isEmpty())
00822     return;
00823 
00824   if (!Inits.count(Field)) {
00825     if (!Diagnosed) {
00826       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
00827       Diagnosed = true;
00828     }
00829     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
00830   } else if (Field->isAnonymousStructOrUnion()) {
00831     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
00832     for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
00833          I != E; ++I)
00834       // If an anonymous union contains an anonymous struct of which any member
00835       // is initialized, all members must be initialized.
00836       if (!RD->isUnion() || Inits.count(&*I))
00837         CheckConstexprCtorInitializer(SemaRef, Dcl, &*I, Inits, Diagnosed);
00838   }
00839 }
00840 
00841 /// Check the body for the given constexpr function declaration only contains
00842 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
00843 ///
00844 /// \return true if the body is OK, false if we have diagnosed a problem.
00845 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
00846   if (isa<CXXTryStmt>(Body)) {
00847     // C++11 [dcl.constexpr]p3:
00848     //  The definition of a constexpr function shall satisfy the following
00849     //  constraints: [...]
00850     // - its function-body shall be = delete, = default, or a
00851     //   compound-statement
00852     //
00853     // C++11 [dcl.constexpr]p4:
00854     //  In the definition of a constexpr constructor, [...]
00855     // - its function-body shall not be a function-try-block;
00856     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
00857       << isa<CXXConstructorDecl>(Dcl);
00858     return false;
00859   }
00860 
00861   // - its function-body shall be [...] a compound-statement that contains only
00862   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
00863 
00864   llvm::SmallVector<SourceLocation, 4> ReturnStmts;
00865   for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
00866          BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
00867     switch ((*BodyIt)->getStmtClass()) {
00868     case Stmt::NullStmtClass:
00869       //   - null statements,
00870       continue;
00871 
00872     case Stmt::DeclStmtClass:
00873       //   - static_assert-declarations
00874       //   - using-declarations,
00875       //   - using-directives,
00876       //   - typedef declarations and alias-declarations that do not define
00877       //     classes or enumerations,
00878       if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
00879         return false;
00880       continue;
00881 
00882     case Stmt::ReturnStmtClass:
00883       //   - and exactly one return statement;
00884       if (isa<CXXConstructorDecl>(Dcl))
00885         break;
00886 
00887       ReturnStmts.push_back((*BodyIt)->getLocStart());
00888       continue;
00889 
00890     default:
00891       break;
00892     }
00893 
00894     Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
00895       << isa<CXXConstructorDecl>(Dcl);
00896     return false;
00897   }
00898 
00899   if (const CXXConstructorDecl *Constructor
00900         = dyn_cast<CXXConstructorDecl>(Dcl)) {
00901     const CXXRecordDecl *RD = Constructor->getParent();
00902     // DR1359:
00903     // - every non-variant non-static data member and base class sub-object
00904     //   shall be initialized;
00905     // - if the class is a non-empty union, or for each non-empty anonymous
00906     //   union member of a non-union class, exactly one non-static data member
00907     //   shall be initialized;
00908     if (RD->isUnion()) {
00909       if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
00910         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
00911         return false;
00912       }
00913     } else if (!Constructor->isDependentContext() &&
00914                !Constructor->isDelegatingConstructor()) {
00915       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
00916 
00917       // Skip detailed checking if we have enough initializers, and we would
00918       // allow at most one initializer per member.
00919       bool AnyAnonStructUnionMembers = false;
00920       unsigned Fields = 0;
00921       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
00922            E = RD->field_end(); I != E; ++I, ++Fields) {
00923         if (I->isAnonymousStructOrUnion()) {
00924           AnyAnonStructUnionMembers = true;
00925           break;
00926         }
00927       }
00928       if (AnyAnonStructUnionMembers ||
00929           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
00930         // Check initialization of non-static data members. Base classes are
00931         // always initialized so do not need to be checked. Dependent bases
00932         // might not have initializers in the member initializer list.
00933         llvm::SmallSet<Decl*, 16> Inits;
00934         for (CXXConstructorDecl::init_const_iterator
00935                I = Constructor->init_begin(), E = Constructor->init_end();
00936              I != E; ++I) {
00937           if (FieldDecl *FD = (*I)->getMember())
00938             Inits.insert(FD);
00939           else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
00940             Inits.insert(ID->chain_begin(), ID->chain_end());
00941         }
00942 
00943         bool Diagnosed = false;
00944         for (CXXRecordDecl::field_iterator I = RD->field_begin(),
00945              E = RD->field_end(); I != E; ++I)
00946           CheckConstexprCtorInitializer(*this, Dcl, &*I, Inits, Diagnosed);
00947         if (Diagnosed)
00948           return false;
00949       }
00950     }
00951   } else {
00952     if (ReturnStmts.empty()) {
00953       Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
00954       return false;
00955     }
00956     if (ReturnStmts.size() > 1) {
00957       Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
00958       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
00959         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
00960       return false;
00961     }
00962   }
00963 
00964   // C++11 [dcl.constexpr]p5:
00965   //   if no function argument values exist such that the function invocation
00966   //   substitution would produce a constant expression, the program is
00967   //   ill-formed; no diagnostic required.
00968   // C++11 [dcl.constexpr]p3:
00969   //   - every constructor call and implicit conversion used in initializing the
00970   //     return value shall be one of those allowed in a constant expression.
00971   // C++11 [dcl.constexpr]p4:
00972   //   - every constructor involved in initializing non-static data members and
00973   //     base class sub-objects shall be a constexpr constructor.
00974   llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
00975   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
00976     Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
00977       << isa<CXXConstructorDecl>(Dcl);
00978     for (size_t I = 0, N = Diags.size(); I != N; ++I)
00979       Diag(Diags[I].first, Diags[I].second);
00980     return false;
00981   }
00982 
00983   return true;
00984 }
00985 
00986 /// isCurrentClassName - Determine whether the identifier II is the
00987 /// name of the class type currently being defined. In the case of
00988 /// nested classes, this will only return true if II is the name of
00989 /// the innermost class.
00990 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
00991                               const CXXScopeSpec *SS) {
00992   assert(getLangOpts().CPlusPlus && "No class names in C!");
00993 
00994   CXXRecordDecl *CurDecl;
00995   if (SS && SS->isSet() && !SS->isInvalid()) {
00996     DeclContext *DC = computeDeclContext(*SS, true);
00997     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
00998   } else
00999     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
01000 
01001   if (CurDecl && CurDecl->getIdentifier())
01002     return &II == CurDecl->getIdentifier();
01003   else
01004     return false;
01005 }
01006 
01007 /// \brief Check the validity of a C++ base class specifier.
01008 ///
01009 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
01010 /// and returns NULL otherwise.
01011 CXXBaseSpecifier *
01012 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
01013                          SourceRange SpecifierRange,
01014                          bool Virtual, AccessSpecifier Access,
01015                          TypeSourceInfo *TInfo,
01016                          SourceLocation EllipsisLoc) {
01017   QualType BaseType = TInfo->getType();
01018 
01019   // C++ [class.union]p1:
01020   //   A union shall not have base classes.
01021   if (Class->isUnion()) {
01022     Diag(Class->getLocation(), diag::err_base_clause_on_union)
01023       << SpecifierRange;
01024     return 0;
01025   }
01026 
01027   if (EllipsisLoc.isValid() && 
01028       !TInfo->getType()->containsUnexpandedParameterPack()) {
01029     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
01030       << TInfo->getTypeLoc().getSourceRange();
01031     EllipsisLoc = SourceLocation();
01032   }
01033   
01034   if (BaseType->isDependentType())
01035     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
01036                                           Class->getTagKind() == TTK_Class,
01037                                           Access, TInfo, EllipsisLoc);
01038 
01039   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
01040 
01041   // Base specifiers must be record types.
01042   if (!BaseType->isRecordType()) {
01043     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
01044     return 0;
01045   }
01046 
01047   // C++ [class.union]p1:
01048   //   A union shall not be used as a base class.
01049   if (BaseType->isUnionType()) {
01050     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
01051     return 0;
01052   }
01053 
01054   // C++ [class.derived]p2:
01055   //   The class-name in a base-specifier shall not be an incompletely
01056   //   defined class.
01057   if (RequireCompleteType(BaseLoc, BaseType,
01058                           diag::err_incomplete_base_class, SpecifierRange)) {
01059     Class->setInvalidDecl();
01060     return 0;
01061   }
01062 
01063   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
01064   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
01065   assert(BaseDecl && "Record type has no declaration");
01066   BaseDecl = BaseDecl->getDefinition();
01067   assert(BaseDecl && "Base type is not incomplete, but has no definition");
01068   CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
01069   assert(CXXBaseDecl && "Base type is not a C++ type");
01070 
01071   // C++ [class]p3:
01072   //   If a class is marked final and it appears as a base-type-specifier in 
01073   //   base-clause, the program is ill-formed.
01074   if (CXXBaseDecl->hasAttr<FinalAttr>()) {
01075     Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 
01076       << CXXBaseDecl->getDeclName();
01077     Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
01078       << CXXBaseDecl->getDeclName();
01079     return 0;
01080   }
01081 
01082   if (BaseDecl->isInvalidDecl())
01083     Class->setInvalidDecl();
01084   
01085   // Create the base specifier.
01086   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
01087                                         Class->getTagKind() == TTK_Class,
01088                                         Access, TInfo, EllipsisLoc);
01089 }
01090 
01091 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
01092 /// one entry in the base class list of a class specifier, for
01093 /// example:
01094 ///    class foo : public bar, virtual private baz {
01095 /// 'public bar' and 'virtual private baz' are each base-specifiers.
01096 BaseResult
01097 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
01098                          bool Virtual, AccessSpecifier Access,
01099                          ParsedType basetype, SourceLocation BaseLoc,
01100                          SourceLocation EllipsisLoc) {
01101   if (!classdecl)
01102     return true;
01103 
01104   AdjustDeclIfTemplate(classdecl);
01105   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
01106   if (!Class)
01107     return true;
01108 
01109   TypeSourceInfo *TInfo = 0;
01110   GetTypeFromParser(basetype, &TInfo);
01111 
01112   if (EllipsisLoc.isInvalid() &&
01113       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 
01114                                       UPPC_BaseType))
01115     return true;
01116   
01117   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
01118                                                       Virtual, Access, TInfo,
01119                                                       EllipsisLoc))
01120     return BaseSpec;
01121 
01122   return true;
01123 }
01124 
01125 /// \brief Performs the actual work of attaching the given base class
01126 /// specifiers to a C++ class.
01127 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
01128                                 unsigned NumBases) {
01129  if (NumBases == 0)
01130     return false;
01131 
01132   // Used to keep track of which base types we have already seen, so
01133   // that we can properly diagnose redundant direct base types. Note
01134   // that the key is always the unqualified canonical type of the base
01135   // class.
01136   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
01137 
01138   // Copy non-redundant base specifiers into permanent storage.
01139   unsigned NumGoodBases = 0;
01140   bool Invalid = false;
01141   for (unsigned idx = 0; idx < NumBases; ++idx) {
01142     QualType NewBaseType
01143       = Context.getCanonicalType(Bases[idx]->getType());
01144     NewBaseType = NewBaseType.getLocalUnqualifiedType();
01145 
01146     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
01147     if (KnownBase) {
01148       // C++ [class.mi]p3:
01149       //   A class shall not be specified as a direct base class of a
01150       //   derived class more than once.
01151       Diag(Bases[idx]->getLocStart(),
01152            diag::err_duplicate_base_class)
01153         << KnownBase->getType()
01154         << Bases[idx]->getSourceRange();
01155 
01156       // Delete the duplicate base class specifier; we're going to
01157       // overwrite its pointer later.
01158       Context.Deallocate(Bases[idx]);
01159 
01160       Invalid = true;
01161     } else {
01162       // Okay, add this new base class.
01163       KnownBase = Bases[idx];
01164       Bases[NumGoodBases++] = Bases[idx];
01165       if (const RecordType *Record = NewBaseType->getAs<RecordType>())
01166         if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
01167           if (RD->hasAttr<WeakAttr>())
01168             Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
01169     }
01170   }
01171 
01172   // Attach the remaining base class specifiers to the derived class.
01173   Class->setBases(Bases, NumGoodBases);
01174 
01175   // Delete the remaining (good) base class specifiers, since their
01176   // data has been copied into the CXXRecordDecl.
01177   for (unsigned idx = 0; idx < NumGoodBases; ++idx)
01178     Context.Deallocate(Bases[idx]);
01179 
01180   return Invalid;
01181 }
01182 
01183 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
01184 /// class, after checking whether there are any duplicate base
01185 /// classes.
01186 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
01187                                unsigned NumBases) {
01188   if (!ClassDecl || !Bases || !NumBases)
01189     return;
01190 
01191   AdjustDeclIfTemplate(ClassDecl);
01192   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
01193                        (CXXBaseSpecifier**)(Bases), NumBases);
01194 }
01195 
01196 static CXXRecordDecl *GetClassForType(QualType T) {
01197   if (const RecordType *RT = T->getAs<RecordType>())
01198     return cast<CXXRecordDecl>(RT->getDecl());
01199   else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
01200     return ICT->getDecl();
01201   else
01202     return 0;
01203 }
01204 
01205 /// \brief Determine whether the type \p Derived is a C++ class that is
01206 /// derived from the type \p Base.
01207 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
01208   if (!getLangOpts().CPlusPlus)
01209     return false;
01210   
01211   CXXRecordDecl *DerivedRD = GetClassForType(Derived);
01212   if (!DerivedRD)
01213     return false;
01214   
01215   CXXRecordDecl *BaseRD = GetClassForType(Base);
01216   if (!BaseRD)
01217     return false;
01218   
01219   // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
01220   return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
01221 }
01222 
01223 /// \brief Determine whether the type \p Derived is a C++ class that is
01224 /// derived from the type \p Base.
01225 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
01226   if (!getLangOpts().CPlusPlus)
01227     return false;
01228   
01229   CXXRecordDecl *DerivedRD = GetClassForType(Derived);
01230   if (!DerivedRD)
01231     return false;
01232   
01233   CXXRecordDecl *BaseRD = GetClassForType(Base);
01234   if (!BaseRD)
01235     return false;
01236   
01237   return DerivedRD->isDerivedFrom(BaseRD, Paths);
01238 }
01239 
01240 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 
01241                               CXXCastPath &BasePathArray) {
01242   assert(BasePathArray.empty() && "Base path array must be empty!");
01243   assert(Paths.isRecordingPaths() && "Must record paths!");
01244   
01245   const CXXBasePath &Path = Paths.front();
01246        
01247   // We first go backward and check if we have a virtual base.
01248   // FIXME: It would be better if CXXBasePath had the base specifier for
01249   // the nearest virtual base.
01250   unsigned Start = 0;
01251   for (unsigned I = Path.size(); I != 0; --I) {
01252     if (Path[I - 1].Base->isVirtual()) {
01253       Start = I - 1;
01254       break;
01255     }
01256   }
01257 
01258   // Now add all bases.
01259   for (unsigned I = Start, E = Path.size(); I != E; ++I)
01260     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
01261 }
01262 
01263 /// \brief Determine whether the given base path includes a virtual
01264 /// base class.
01265 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
01266   for (CXXCastPath::const_iterator B = BasePath.begin(), 
01267                                 BEnd = BasePath.end();
01268        B != BEnd; ++B)
01269     if ((*B)->isVirtual())
01270       return true;
01271 
01272   return false;
01273 }
01274 
01275 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
01276 /// conversion (where Derived and Base are class types) is
01277 /// well-formed, meaning that the conversion is unambiguous (and
01278 /// that all of the base classes are accessible). Returns true
01279 /// and emits a diagnostic if the code is ill-formed, returns false
01280 /// otherwise. Loc is the location where this routine should point to
01281 /// if there is an error, and Range is the source range to highlight
01282 /// if there is an error.
01283 bool
01284 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
01285                                    unsigned InaccessibleBaseID,
01286                                    unsigned AmbigiousBaseConvID,
01287                                    SourceLocation Loc, SourceRange Range,
01288                                    DeclarationName Name,
01289                                    CXXCastPath *BasePath) {
01290   // First, determine whether the path from Derived to Base is
01291   // ambiguous. This is slightly more expensive than checking whether
01292   // the Derived to Base conversion exists, because here we need to
01293   // explore multiple paths to determine if there is an ambiguity.
01294   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
01295                      /*DetectVirtual=*/false);
01296   bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
01297   assert(DerivationOkay &&
01298          "Can only be used with a derived-to-base conversion");
01299   (void)DerivationOkay;
01300   
01301   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
01302     if (InaccessibleBaseID) {
01303       // Check that the base class can be accessed.
01304       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
01305                                    InaccessibleBaseID)) {
01306         case AR_inaccessible: 
01307           return true;
01308         case AR_accessible: 
01309         case AR_dependent:
01310         case AR_delayed:
01311           break;
01312       }
01313     }
01314     
01315     // Build a base path if necessary.
01316     if (BasePath)
01317       BuildBasePathArray(Paths, *BasePath);
01318     return false;
01319   }
01320   
01321   // We know that the derived-to-base conversion is ambiguous, and
01322   // we're going to produce a diagnostic. Perform the derived-to-base
01323   // search just one more time to compute all of the possible paths so
01324   // that we can print them out. This is more expensive than any of
01325   // the previous derived-to-base checks we've done, but at this point
01326   // performance isn't as much of an issue.
01327   Paths.clear();
01328   Paths.setRecordingPaths(true);
01329   bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
01330   assert(StillOkay && "Can only be used with a derived-to-base conversion");
01331   (void)StillOkay;
01332   
01333   // Build up a textual representation of the ambiguous paths, e.g.,
01334   // D -> B -> A, that will be used to illustrate the ambiguous
01335   // conversions in the diagnostic. We only print one of the paths
01336   // to each base class subobject.
01337   std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
01338   
01339   Diag(Loc, AmbigiousBaseConvID)
01340   << Derived << Base << PathDisplayStr << Range << Name;
01341   return true;
01342 }
01343 
01344 bool
01345 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
01346                                    SourceLocation Loc, SourceRange Range,
01347                                    CXXCastPath *BasePath,
01348                                    bool IgnoreAccess) {
01349   return CheckDerivedToBaseConversion(Derived, Base,
01350                                       IgnoreAccess ? 0
01351                                        : diag::err_upcast_to_inaccessible_base,
01352                                       diag::err_ambiguous_derived_to_base_conv,
01353                                       Loc, Range, DeclarationName(), 
01354                                       BasePath);
01355 }
01356 
01357 
01358 /// @brief Builds a string representing ambiguous paths from a
01359 /// specific derived class to different subobjects of the same base
01360 /// class.
01361 ///
01362 /// This function builds a string that can be used in error messages
01363 /// to show the different paths that one can take through the
01364 /// inheritance hierarchy to go from the derived class to different
01365 /// subobjects of a base class. The result looks something like this:
01366 /// @code
01367 /// struct D -> struct B -> struct A
01368 /// struct D -> struct C -> struct A
01369 /// @endcode
01370 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
01371   std::string PathDisplayStr;
01372   std::set<unsigned> DisplayedPaths;
01373   for (CXXBasePaths::paths_iterator Path = Paths.begin();
01374        Path != Paths.end(); ++Path) {
01375     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
01376       // We haven't displayed a path to this particular base
01377       // class subobject yet.
01378       PathDisplayStr += "\n    ";
01379       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
01380       for (CXXBasePath::const_iterator Element = Path->begin();
01381            Element != Path->end(); ++Element)
01382         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
01383     }
01384   }
01385   
01386   return PathDisplayStr;
01387 }
01388 
01389 //===----------------------------------------------------------------------===//
01390 // C++ class member Handling
01391 //===----------------------------------------------------------------------===//
01392 
01393 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
01394 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
01395                                 SourceLocation ASLoc,
01396                                 SourceLocation ColonLoc,
01397                                 AttributeList *Attrs) {
01398   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
01399   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
01400                                                   ASLoc, ColonLoc);
01401   CurContext->addHiddenDecl(ASDecl);
01402   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
01403 }
01404 
01405 /// CheckOverrideControl - Check C++0x override control semantics.
01406 void Sema::CheckOverrideControl(const Decl *D) {
01407   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
01408   if (!MD || !MD->isVirtual())
01409     return;
01410 
01411   if (MD->isDependentContext())
01412     return;
01413 
01414   // C++0x [class.virtual]p3:
01415   //   If a virtual function is marked with the virt-specifier override and does
01416   //   not override a member function of a base class, 
01417   //   the program is ill-formed.
01418   bool HasOverriddenMethods = 
01419     MD->begin_overridden_methods() != MD->end_overridden_methods();
01420   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
01421     Diag(MD->getLocation(), 
01422                  diag::err_function_marked_override_not_overriding)
01423       << MD->getDeclName();
01424     return;
01425   }
01426 }
01427 
01428 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 
01429 /// function overrides a virtual member function marked 'final', according to
01430 /// C++0x [class.virtual]p3.
01431 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
01432                                                   const CXXMethodDecl *Old) {
01433   if (!Old->hasAttr<FinalAttr>())
01434     return false;
01435 
01436   Diag(New->getLocation(), diag::err_final_function_overridden)
01437     << New->getDeclName();
01438   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
01439   return true;
01440 }
01441 
01442 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
01443 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
01444 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
01445 /// one has been parsed, and 'HasDeferredInit' is true if an initializer is
01446 /// present but parsing it has been deferred.
01447 Decl *
01448 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
01449                                MultiTemplateParamsArg TemplateParameterLists,
01450                                Expr *BW, const VirtSpecifiers &VS,
01451                                bool HasDeferredInit) {
01452   const DeclSpec &DS = D.getDeclSpec();
01453   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
01454   DeclarationName Name = NameInfo.getName();
01455   SourceLocation Loc = NameInfo.getLoc();
01456 
01457   // For anonymous bitfields, the location should point to the type.
01458   if (Loc.isInvalid())
01459     Loc = D.getLocStart();
01460 
01461   Expr *BitWidth = static_cast<Expr*>(BW);
01462 
01463   assert(isa<CXXRecordDecl>(CurContext));
01464   assert(!DS.isFriendSpecified());
01465 
01466   bool isFunc = D.isDeclarationOfFunction();
01467 
01468   // C++ 9.2p6: A member shall not be declared to have automatic storage
01469   // duration (auto, register) or with the extern storage-class-specifier.
01470   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
01471   // data members and cannot be applied to names declared const or static,
01472   // and cannot be applied to reference members.
01473   switch (DS.getStorageClassSpec()) {
01474     case DeclSpec::SCS_unspecified:
01475     case DeclSpec::SCS_typedef:
01476     case DeclSpec::SCS_static:
01477       // FALL THROUGH.
01478       break;
01479     case DeclSpec::SCS_mutable:
01480       if (isFunc) {
01481         if (DS.getStorageClassSpecLoc().isValid())
01482           Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
01483         else
01484           Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
01485 
01486         // FIXME: It would be nicer if the keyword was ignored only for this
01487         // declarator. Otherwise we could get follow-up errors.
01488         D.getMutableDeclSpec().ClearStorageClassSpecs();
01489       }
01490       break;
01491     default:
01492       if (DS.getStorageClassSpecLoc().isValid())
01493         Diag(DS.getStorageClassSpecLoc(),
01494              diag::err_storageclass_invalid_for_member);
01495       else
01496         Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
01497       D.getMutableDeclSpec().ClearStorageClassSpecs();
01498   }
01499 
01500   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
01501                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
01502                       !isFunc);
01503 
01504   Decl *Member;
01505   if (isInstField) {
01506     CXXScopeSpec &SS = D.getCXXScopeSpec();
01507 
01508     // Data members must have identifiers for names.
01509     if (!Name.isIdentifier()) {
01510       Diag(Loc, diag::err_bad_variable_name)
01511         << Name;
01512       return 0;
01513     }
01514 
01515     IdentifierInfo *II = Name.getAsIdentifierInfo();
01516 
01517     // Member field could not be with "template" keyword.
01518     // So TemplateParameterLists should be empty in this case.
01519     if (TemplateParameterLists.size()) {
01520       TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
01521       if (TemplateParams->size()) {
01522         // There is no such thing as a member field template.
01523         Diag(D.getIdentifierLoc(), diag::err_template_member)
01524             << II
01525             << SourceRange(TemplateParams->getTemplateLoc(),
01526                 TemplateParams->getRAngleLoc());
01527       } else {
01528         // There is an extraneous 'template<>' for this member.
01529         Diag(TemplateParams->getTemplateLoc(),
01530             diag::err_template_member_noparams)
01531             << II
01532             << SourceRange(TemplateParams->getTemplateLoc(),
01533                 TemplateParams->getRAngleLoc());
01534       }
01535       return 0;
01536     }
01537 
01538     if (SS.isSet() && !SS.isInvalid()) {
01539       // The user provided a superfluous scope specifier inside a class
01540       // definition:
01541       //
01542       // class X {
01543       //   int X::member;
01544       // };
01545       if (DeclContext *DC = computeDeclContext(SS, false))
01546         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
01547       else
01548         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
01549           << Name << SS.getRange();
01550       
01551       SS.clear();
01552     }
01553 
01554     Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
01555                          HasDeferredInit, AS);
01556     assert(Member && "HandleField never returns null");
01557   } else {
01558     assert(!HasDeferredInit);
01559 
01560     Member = HandleDeclarator(S, D, move(TemplateParameterLists));
01561     if (!Member) {
01562       return 0;
01563     }
01564 
01565     // Non-instance-fields can't have a bitfield.
01566     if (BitWidth) {
01567       if (Member->isInvalidDecl()) {
01568         // don't emit another diagnostic.
01569       } else if (isa<VarDecl>(Member)) {
01570         // C++ 9.6p3: A bit-field shall not be a static member.
01571         // "static member 'A' cannot be a bit-field"
01572         Diag(Loc, diag::err_static_not_bitfield)
01573           << Name << BitWidth->getSourceRange();
01574       } else if (isa<TypedefDecl>(Member)) {
01575         // "typedef member 'x' cannot be a bit-field"
01576         Diag(Loc, diag::err_typedef_not_bitfield)
01577           << Name << BitWidth->getSourceRange();
01578       } else {
01579         // A function typedef ("typedef int f(); f a;").
01580         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
01581         Diag(Loc, diag::err_not_integral_type_bitfield)
01582           << Name << cast<ValueDecl>(Member)->getType()
01583           << BitWidth->getSourceRange();
01584       }
01585 
01586       BitWidth = 0;
01587       Member->setInvalidDecl();
01588     }
01589 
01590     Member->setAccess(AS);
01591 
01592     // If we have declared a member function template, set the access of the
01593     // templated declaration as well.
01594     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
01595       FunTmpl->getTemplatedDecl()->setAccess(AS);
01596   }
01597 
01598   if (VS.isOverrideSpecified()) {
01599     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
01600     if (!MD || !MD->isVirtual()) {
01601       Diag(Member->getLocStart(), 
01602            diag::override_keyword_only_allowed_on_virtual_member_functions)
01603         << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
01604     } else
01605       MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
01606   }
01607   if (VS.isFinalSpecified()) {
01608     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
01609     if (!MD || !MD->isVirtual()) {
01610       Diag(Member->getLocStart(), 
01611            diag::override_keyword_only_allowed_on_virtual_member_functions)
01612       << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
01613     } else
01614       MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
01615   }
01616 
01617   if (VS.getLastLocation().isValid()) {
01618     // Update the end location of a method that has a virt-specifiers.
01619     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
01620       MD->setRangeEnd(VS.getLastLocation());
01621   }
01622       
01623   CheckOverrideControl(Member);
01624 
01625   assert((Name || isInstField) && "No identifier for non-field ?");
01626 
01627   if (isInstField)
01628     FieldCollector->Add(cast<FieldDecl>(Member));
01629   return Member;
01630 }
01631 
01632 /// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
01633 /// in-class initializer for a non-static C++ class member, and after
01634 /// instantiating an in-class initializer in a class template. Such actions
01635 /// are deferred until the class is complete.
01636 void
01637 Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
01638                                        Expr *InitExpr) {
01639   FieldDecl *FD = cast<FieldDecl>(D);
01640 
01641   if (!InitExpr) {
01642     FD->setInvalidDecl();
01643     FD->removeInClassInitializer();
01644     return;
01645   }
01646 
01647   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
01648     FD->setInvalidDecl();
01649     FD->removeInClassInitializer();
01650     return;
01651   }
01652 
01653   ExprResult Init = InitExpr;
01654   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
01655     if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
01656       Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
01657         << /*at end of ctor*/1 << InitExpr->getSourceRange();
01658     }
01659     Expr **Inits = &InitExpr;
01660     unsigned NumInits = 1;
01661     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
01662     InitializationKind Kind = EqualLoc.isInvalid()
01663         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
01664         : InitializationKind::CreateCopy(InitExpr->getLocStart(), EqualLoc);
01665     InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
01666     Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
01667     if (Init.isInvalid()) {
01668       FD->setInvalidDecl();
01669       return;
01670     }
01671 
01672     CheckImplicitConversions(Init.get(), EqualLoc);
01673   }
01674 
01675   // C++0x [class.base.init]p7:
01676   //   The initialization of each base and member constitutes a
01677   //   full-expression.
01678   Init = MaybeCreateExprWithCleanups(Init);
01679   if (Init.isInvalid()) {
01680     FD->setInvalidDecl();
01681     return;
01682   }
01683 
01684   InitExpr = Init.release();
01685 
01686   FD->setInClassInitializer(InitExpr);
01687 }
01688 
01689 /// \brief Find the direct and/or virtual base specifiers that
01690 /// correspond to the given base type, for use in base initialization
01691 /// within a constructor.
01692 static bool FindBaseInitializer(Sema &SemaRef, 
01693                                 CXXRecordDecl *ClassDecl,
01694                                 QualType BaseType,
01695                                 const CXXBaseSpecifier *&DirectBaseSpec,
01696                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
01697   // First, check for a direct base class.
01698   DirectBaseSpec = 0;
01699   for (CXXRecordDecl::base_class_const_iterator Base
01700          = ClassDecl->bases_begin(); 
01701        Base != ClassDecl->bases_end(); ++Base) {
01702     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
01703       // We found a direct base of this type. That's what we're
01704       // initializing.
01705       DirectBaseSpec = &*Base;
01706       break;
01707     }
01708   }
01709 
01710   // Check for a virtual base class.
01711   // FIXME: We might be able to short-circuit this if we know in advance that
01712   // there are no virtual bases.
01713   VirtualBaseSpec = 0;
01714   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
01715     // We haven't found a base yet; search the class hierarchy for a
01716     // virtual base class.
01717     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
01718                        /*DetectVirtual=*/false);
01719     if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 
01720                               BaseType, Paths)) {
01721       for (CXXBasePaths::paths_iterator Path = Paths.begin();
01722            Path != Paths.end(); ++Path) {
01723         if (Path->back().Base->isVirtual()) {
01724           VirtualBaseSpec = Path->back().Base;
01725           break;
01726         }
01727       }
01728     }
01729   }
01730 
01731   return DirectBaseSpec || VirtualBaseSpec;
01732 }
01733 
01734 /// \brief Handle a C++ member initializer using braced-init-list syntax.
01735 MemInitResult
01736 Sema::ActOnMemInitializer(Decl *ConstructorD,
01737                           Scope *S,
01738                           CXXScopeSpec &SS,
01739                           IdentifierInfo *MemberOrBase,
01740                           ParsedType TemplateTypeTy,
01741                           const DeclSpec &DS,
01742                           SourceLocation IdLoc,
01743                           Expr *InitList,
01744                           SourceLocation EllipsisLoc) {
01745   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
01746                              DS, IdLoc, InitList,
01747                              EllipsisLoc);
01748 }
01749 
01750 /// \brief Handle a C++ member initializer using parentheses syntax.
01751 MemInitResult
01752 Sema::ActOnMemInitializer(Decl *ConstructorD,
01753                           Scope *S,
01754                           CXXScopeSpec &SS,
01755                           IdentifierInfo *MemberOrBase,
01756                           ParsedType TemplateTypeTy,
01757                           const DeclSpec &DS,
01758                           SourceLocation IdLoc,
01759                           SourceLocation LParenLoc,
01760                           Expr **Args, unsigned NumArgs,
01761                           SourceLocation RParenLoc,
01762                           SourceLocation EllipsisLoc) {
01763   Expr *List = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
01764                                            RParenLoc);
01765   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
01766                              DS, IdLoc, List, EllipsisLoc);
01767 }
01768 
01769 namespace {
01770 
01771 // Callback to only accept typo corrections that can be a valid C++ member
01772 // intializer: either a non-static field member or a base class.
01773 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
01774  public:
01775   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
01776       : ClassDecl(ClassDecl) {}
01777 
01778   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
01779     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
01780       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
01781         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
01782       else
01783         return isa<TypeDecl>(ND);
01784     }
01785     return false;
01786   }
01787 
01788  private:
01789   CXXRecordDecl *ClassDecl;
01790 };
01791 
01792 }
01793 
01794 /// \brief Handle a C++ member initializer.
01795 MemInitResult
01796 Sema::BuildMemInitializer(Decl *ConstructorD,
01797                           Scope *S,
01798                           CXXScopeSpec &SS,
01799                           IdentifierInfo *MemberOrBase,
01800                           ParsedType TemplateTypeTy,
01801                           const DeclSpec &DS,
01802                           SourceLocation IdLoc,
01803                           Expr *Init,
01804                           SourceLocation EllipsisLoc) {
01805   if (!ConstructorD)
01806     return true;
01807 
01808   AdjustDeclIfTemplate(ConstructorD);
01809 
01810   CXXConstructorDecl *Constructor
01811     = dyn_cast<CXXConstructorDecl>(ConstructorD);
01812   if (!Constructor) {
01813     // The user wrote a constructor initializer on a function that is
01814     // not a C++ constructor. Ignore the error for now, because we may
01815     // have more member initializers coming; we'll diagnose it just
01816     // once in ActOnMemInitializers.
01817     return true;
01818   }
01819 
01820   CXXRecordDecl *ClassDecl = Constructor->getParent();
01821 
01822   // C++ [class.base.init]p2:
01823   //   Names in a mem-initializer-id are looked up in the scope of the
01824   //   constructor's class and, if not found in that scope, are looked
01825   //   up in the scope containing the constructor's definition.
01826   //   [Note: if the constructor's class contains a member with the
01827   //   same name as a direct or virtual base class of the class, a
01828   //   mem-initializer-id naming the member or base class and composed
01829   //   of a single identifier refers to the class member. A
01830   //   mem-initializer-id for the hidden base class may be specified
01831   //   using a qualified name. ]
01832   if (!SS.getScopeRep() && !TemplateTypeTy) {
01833     // Look for a member, first.
01834     DeclContext::lookup_result Result
01835       = ClassDecl->lookup(MemberOrBase);
01836     if (Result.first != Result.second) {
01837       ValueDecl *Member;
01838       if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
01839           (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
01840         if (EllipsisLoc.isValid())
01841           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
01842             << MemberOrBase
01843             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
01844 
01845         return BuildMemberInitializer(Member, Init, IdLoc);
01846       }
01847     }
01848   }
01849   // It didn't name a member, so see if it names a class.
01850   QualType BaseType;
01851   TypeSourceInfo *TInfo = 0;
01852 
01853   if (TemplateTypeTy) {
01854     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
01855   } else if (DS.getTypeSpecType() == TST_decltype) {
01856     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
01857   } else {
01858     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
01859     LookupParsedName(R, S, &SS);
01860 
01861     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
01862     if (!TyD) {
01863       if (R.isAmbiguous()) return true;
01864 
01865       // We don't want access-control diagnostics here.
01866       R.suppressDiagnostics();
01867 
01868       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
01869         bool NotUnknownSpecialization = false;
01870         DeclContext *DC = computeDeclContext(SS, false);
01871         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 
01872           NotUnknownSpecialization = !Record->hasAnyDependentBases();
01873 
01874         if (!NotUnknownSpecialization) {
01875           // When the scope specifier can refer to a member of an unknown
01876           // specialization, we take it as a type name.
01877           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
01878                                        SS.getWithLocInContext(Context),
01879                                        *MemberOrBase, IdLoc);
01880           if (BaseType.isNull())
01881             return true;
01882 
01883           R.clear();
01884           R.setLookupName(MemberOrBase);
01885         }
01886       }
01887 
01888       // If no results were found, try to correct typos.
01889       TypoCorrection Corr;
01890       MemInitializerValidatorCCC Validator(ClassDecl);
01891       if (R.empty() && BaseType.isNull() &&
01892           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
01893                               Validator, ClassDecl))) {
01894         std::string CorrectedStr(Corr.getAsString(getLangOpts()));
01895         std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
01896         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
01897           // We have found a non-static data member with a similar
01898           // name to what was typed; complain and initialize that
01899           // member.
01900           Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
01901             << MemberOrBase << true << CorrectedQuotedStr
01902             << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
01903           Diag(Member->getLocation(), diag::note_previous_decl)
01904             << CorrectedQuotedStr;
01905 
01906           return BuildMemberInitializer(Member, Init, IdLoc);
01907         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
01908           const CXXBaseSpecifier *DirectBaseSpec;
01909           const CXXBaseSpecifier *VirtualBaseSpec;
01910           if (FindBaseInitializer(*this, ClassDecl, 
01911                                   Context.getTypeDeclType(Type),
01912                                   DirectBaseSpec, VirtualBaseSpec)) {
01913             // We have found a direct or virtual base class with a
01914             // similar name to what was typed; complain and initialize
01915             // that base class.
01916             Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
01917               << MemberOrBase << false << CorrectedQuotedStr
01918               << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
01919 
01920             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 
01921                                                              : VirtualBaseSpec;
01922             Diag(BaseSpec->getLocStart(),
01923                  diag::note_base_class_specified_here)
01924               << BaseSpec->getType()
01925               << BaseSpec->getSourceRange();
01926 
01927             TyD = Type;
01928           }
01929         }
01930       }
01931 
01932       if (!TyD && BaseType.isNull()) {
01933         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
01934           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
01935         return true;
01936       }
01937     }
01938 
01939     if (BaseType.isNull()) {
01940       BaseType = Context.getTypeDeclType(TyD);
01941       if (SS.isSet()) {
01942         NestedNameSpecifier *Qualifier =
01943           static_cast<NestedNameSpecifier*>(SS.getScopeRep());
01944 
01945         // FIXME: preserve source range information
01946         BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
01947       }
01948     }
01949   }
01950 
01951   if (!TInfo)
01952     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
01953 
01954   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
01955 }
01956 
01957 /// Checks a member initializer expression for cases where reference (or
01958 /// pointer) members are bound to by-value parameters (or their addresses).
01959 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
01960                                                Expr *Init,
01961                                                SourceLocation IdLoc) {
01962   QualType MemberTy = Member->getType();
01963 
01964   // We only handle pointers and references currently.
01965   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
01966   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
01967     return;
01968 
01969   const bool IsPointer = MemberTy->isPointerType();
01970   if (IsPointer) {
01971     if (const UnaryOperator *Op
01972           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
01973       // The only case we're worried about with pointers requires taking the
01974       // address.
01975       if (Op->getOpcode() != UO_AddrOf)
01976         return;
01977 
01978       Init = Op->getSubExpr();
01979     } else {
01980       // We only handle address-of expression initializers for pointers.
01981       return;
01982     }
01983   }
01984 
01985   if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
01986     // Taking the address of a temporary will be diagnosed as a hard error.
01987     if (IsPointer)
01988       return;
01989 
01990     S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
01991       << Member << Init->getSourceRange();
01992   } else if (const DeclRefExpr *DRE
01993                = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
01994     // We only warn when referring to a non-reference parameter declaration.
01995     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
01996     if (!Parameter || Parameter->getType()->isReferenceType())
01997       return;
01998 
01999     S.Diag(Init->getExprLoc(),
02000            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
02001                      : diag::warn_bind_ref_member_to_parameter)
02002       << Member << Parameter << Init->getSourceRange();
02003   } else {
02004     // Other initializers are fine.
02005     return;
02006   }
02007 
02008   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
02009     << (unsigned)IsPointer;
02010 }
02011 
02012 /// Checks an initializer expression for use of uninitialized fields, such as
02013 /// containing the field that is being initialized. Returns true if there is an
02014 /// uninitialized field was used an updates the SourceLocation parameter; false
02015 /// otherwise.
02016 static bool InitExprContainsUninitializedFields(const Stmt *S,
02017                                                 const ValueDecl *LhsField,
02018                                                 SourceLocation *L) {
02019   assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
02020 
02021   if (isa<CallExpr>(S)) {
02022     // Do not descend into function calls or constructors, as the use
02023     // of an uninitialized field may be valid. One would have to inspect
02024     // the contents of the function/ctor to determine if it is safe or not.
02025     // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
02026     // may be safe, depending on what the function/ctor does.
02027     return false;
02028   }
02029   if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
02030     const NamedDecl *RhsField = ME->getMemberDecl();
02031 
02032     if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
02033       // The member expression points to a static data member.
02034       assert(VD->isStaticDataMember() && 
02035              "Member points to non-static data member!");
02036       (void)VD;
02037       return false;
02038     }
02039     
02040     if (isa<EnumConstantDecl>(RhsField)) {
02041       // The member expression points to an enum.
02042       return false;
02043     }
02044 
02045     if (RhsField == LhsField) {
02046       // Initializing a field with itself. Throw a warning.
02047       // But wait; there are exceptions!
02048       // Exception #1:  The field may not belong to this record.
02049       // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
02050       const Expr *base = ME->getBase();
02051       if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
02052         // Even though the field matches, it does not belong to this record.
02053         return false;
02054       }
02055       // None of the exceptions triggered; return true to indicate an
02056       // uninitialized field was used.
02057       *L = ME->getMemberLoc();
02058       return true;
02059     }
02060   } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
02061     // sizeof/alignof doesn't reference contents, do not warn.
02062     return false;
02063   } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
02064     // address-of doesn't reference contents (the pointer may be dereferenced
02065     // in the same expression but it would be rare; and weird).
02066     if (UOE->getOpcode() == UO_AddrOf)
02067       return false;
02068   }
02069   for (Stmt::const_child_range it = S->children(); it; ++it) {
02070     if (!*it) {
02071       // An expression such as 'member(arg ?: "")' may trigger this.
02072       continue;
02073     }
02074     if (InitExprContainsUninitializedFields(*it, LhsField, L))
02075       return true;
02076   }
02077   return false;
02078 }
02079 
02080 MemInitResult
02081 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
02082                              SourceLocation IdLoc) {
02083   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
02084   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
02085   assert((DirectMember || IndirectMember) &&
02086          "Member must be a FieldDecl or IndirectFieldDecl");
02087 
02088   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
02089     return true;
02090 
02091   if (Member->isInvalidDecl())
02092     return true;
02093 
02094   // Diagnose value-uses of fields to initialize themselves, e.g.
02095   //   foo(foo)
02096   // where foo is not also a parameter to the constructor.
02097   // TODO: implement -Wuninitialized and fold this into that framework.
02098   Expr **Args;
02099   unsigned NumArgs;
02100   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
02101     Args = ParenList->getExprs();
02102     NumArgs = ParenList->getNumExprs();
02103   } else {
02104     InitListExpr *InitList = cast<InitListExpr>(Init);
02105     Args = InitList->getInits();
02106     NumArgs = InitList->getNumInits();
02107   }
02108   for (unsigned i = 0; i < NumArgs; ++i) {
02109     SourceLocation L;
02110     if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
02111       // FIXME: Return true in the case when other fields are used before being
02112       // uninitialized. For example, let this field be the i'th field. When
02113       // initializing the i'th field, throw a warning if any of the >= i'th
02114       // fields are used, as they are not yet initialized.
02115       // Right now we are only handling the case where the i'th field uses
02116       // itself in its initializer.
02117       Diag(L, diag::warn_field_is_uninit);
02118     }
02119   }
02120 
02121   SourceRange InitRange = Init->getSourceRange();
02122 
02123   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
02124     // Can't check initialization for a member of dependent type or when
02125     // any of the arguments are type-dependent expressions.
02126     DiscardCleanupsInEvaluationContext();
02127   } else {
02128     bool InitList = false;
02129     if (isa<InitListExpr>(Init)) {
02130       InitList = true;
02131       Args = &Init;
02132       NumArgs = 1;
02133 
02134       if (isStdInitializerList(Member->getType(), 0)) {
02135         Diag(IdLoc, diag::warn_dangling_std_initializer_list)
02136             << /*at end of ctor*/1 << InitRange;
02137       }
02138     }
02139 
02140     // Initialize the member.
02141     InitializedEntity MemberEntity =
02142       DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
02143                    : InitializedEntity::InitializeMember(IndirectMember, 0);
02144     InitializationKind Kind =
02145       InitList ? InitializationKind::CreateDirectList(IdLoc)
02146                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
02147                                                   InitRange.getEnd());
02148 
02149     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
02150     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
02151                                             MultiExprArg(*this, Args, NumArgs),
02152                                             0);
02153     if (MemberInit.isInvalid())
02154       return true;
02155 
02156     CheckImplicitConversions(MemberInit.get(),
02157                              InitRange.getBegin());
02158 
02159     // C++0x [class.base.init]p7:
02160     //   The initialization of each base and member constitutes a
02161     //   full-expression.
02162     MemberInit = MaybeCreateExprWithCleanups(MemberInit);
02163     if (MemberInit.isInvalid())
02164       return true;
02165 
02166     // If we are in a dependent context, template instantiation will
02167     // perform this type-checking again. Just save the arguments that we
02168     // received.
02169     // FIXME: This isn't quite ideal, since our ASTs don't capture all
02170     // of the information that we have about the member
02171     // initializer. However, deconstructing the ASTs is a dicey process,
02172     // and this approach is far more likely to get the corner cases right.
02173     if (CurContext->isDependentContext()) {
02174       // The existing Init will do fine.
02175     } else {
02176       Init = MemberInit.get();
02177       CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
02178     }
02179   }
02180 
02181   if (DirectMember) {
02182     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
02183                                             InitRange.getBegin(), Init,
02184                                             InitRange.getEnd());
02185   } else {
02186     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
02187                                             InitRange.getBegin(), Init,
02188                                             InitRange.getEnd());
02189   }
02190 }
02191 
02192 MemInitResult
02193 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
02194                                  CXXRecordDecl *ClassDecl) {
02195   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
02196   if (!LangOpts.CPlusPlus0x)
02197     return Diag(NameLoc, diag::err_delegating_ctor)
02198       << TInfo->getTypeLoc().getLocalSourceRange();
02199   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
02200 
02201   bool InitList = true;
02202   Expr **Args = &Init;
02203   unsigned NumArgs = 1;
02204   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
02205     InitList = false;
02206     Args = ParenList->getExprs();
02207     NumArgs = ParenList->getNumExprs();
02208   }
02209 
02210   SourceRange InitRange = Init->getSourceRange();
02211   // Initialize the object.
02212   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
02213                                      QualType(ClassDecl->getTypeForDecl(), 0));
02214   InitializationKind Kind =
02215     InitList ? InitializationKind::CreateDirectList(NameLoc)
02216              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
02217                                                 InitRange.getEnd());
02218   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
02219   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
02220                                               MultiExprArg(*this, Args,NumArgs),
02221                                               0);
02222   if (DelegationInit.isInvalid())
02223     return true;
02224 
02225   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
02226          "Delegating constructor with no target?");
02227 
02228   CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
02229 
02230   // C++0x [class.base.init]p7:
02231   //   The initialization of each base and member constitutes a
02232   //   full-expression.
02233   DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
02234   if (DelegationInit.isInvalid())
02235     return true;
02236 
02237   // If we are in a dependent context, template instantiation will
02238   // perform this type-checking again. Just save the arguments that we
02239   // received in a ParenListExpr.
02240   // FIXME: This isn't quite ideal, since our ASTs don't capture all
02241   // of the information that we have about the base
02242   // initializer. However, deconstructing the ASTs is a dicey process,
02243   // and this approach is far more likely to get the corner cases right.
02244   if (CurContext->isDependentContext())
02245     DelegationInit = Owned(Init);
02246 
02247   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 
02248                                           DelegationInit.takeAs<Expr>(),
02249                                           InitRange.getEnd());
02250 }
02251 
02252 MemInitResult
02253 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
02254                            Expr *Init, CXXRecordDecl *ClassDecl,
02255                            SourceLocation EllipsisLoc) {
02256   SourceLocation BaseLoc
02257     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
02258 
02259   if (!BaseType->isDependentType() && !BaseType->isRecordType())
02260     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
02261              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
02262 
02263   // C++ [class.base.init]p2:
02264   //   [...] Unless the mem-initializer-id names a nonstatic data
02265   //   member of the constructor's class or a direct or virtual base
02266   //   of that class, the mem-initializer is ill-formed. A
02267   //   mem-initializer-list can initialize a base class using any
02268   //   name that denotes that base class type.
02269   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
02270 
02271   SourceRange InitRange = Init->getSourceRange();
02272   if (EllipsisLoc.isValid()) {
02273     // This is a pack expansion.
02274     if (!BaseType->containsUnexpandedParameterPack())  {
02275       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
02276         << SourceRange(BaseLoc, InitRange.getEnd());
02277 
02278       EllipsisLoc = SourceLocation();
02279     }
02280   } else {
02281     // Check for any unexpanded parameter packs.
02282     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
02283       return true;
02284 
02285     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
02286       return true;
02287   }
02288 
02289   // Check for direct and virtual base classes.
02290   const CXXBaseSpecifier *DirectBaseSpec = 0;
02291   const CXXBaseSpecifier *VirtualBaseSpec = 0;
02292   if (!Dependent) { 
02293     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
02294                                        BaseType))
02295       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
02296 
02297     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 
02298                         VirtualBaseSpec);
02299 
02300     // C++ [base.class.init]p2:
02301     // Unless the mem-initializer-id names a nonstatic data member of the
02302     // constructor's class or a direct or virtual base of that class, the
02303     // mem-initializer is ill-formed.
02304     if (!DirectBaseSpec && !VirtualBaseSpec) {
02305       // If the class has any dependent bases, then it's possible that
02306       // one of those types will resolve to the same type as
02307       // BaseType. Therefore, just treat this as a dependent base
02308       // class initialization.  FIXME: Should we try to check the
02309       // initialization anyway? It seems odd.
02310       if (ClassDecl->hasAnyDependentBases())
02311         Dependent = true;
02312       else
02313         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
02314           << BaseType << Context.getTypeDeclType(ClassDecl)
02315           << BaseTInfo->getTypeLoc().getLocalSourceRange();
02316     }
02317   }
02318 
02319   if (Dependent) {
02320     DiscardCleanupsInEvaluationContext();
02321 
02322     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
02323                                             /*IsVirtual=*/false,
02324                                             InitRange.getBegin(), Init,
02325                                             InitRange.getEnd(), EllipsisLoc);
02326   }
02327 
02328   // C++ [base.class.init]p2:
02329   //   If a mem-initializer-id is ambiguous because it designates both
02330   //   a direct non-virtual base class and an inherited virtual base
02331   //   class, the mem-initializer is ill-formed.
02332   if (DirectBaseSpec && VirtualBaseSpec)
02333     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
02334       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
02335 
02336   CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
02337   if (!BaseSpec)
02338     BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
02339 
02340   // Initialize the base.
02341   bool InitList = true;
02342   Expr **Args = &Init;
02343   unsigned NumArgs = 1;
02344   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
02345     InitList = false;
02346     Args = ParenList->getExprs();
02347     NumArgs = ParenList->getNumExprs();
02348   }
02349 
02350   InitializedEntity BaseEntity =
02351     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
02352   InitializationKind Kind =
02353     InitList ? InitializationKind::CreateDirectList(BaseLoc)
02354              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
02355                                                 InitRange.getEnd());
02356   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
02357   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
02358                                           MultiExprArg(*this, Args, NumArgs),
02359                                           0);
02360   if (BaseInit.isInvalid())
02361     return true;
02362 
02363   CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
02364 
02365   // C++0x [class.base.init]p7:
02366   //   The initialization of each base and member constitutes a 
02367   //   full-expression.
02368   BaseInit = MaybeCreateExprWithCleanups(BaseInit);
02369   if (BaseInit.isInvalid())
02370     return true;
02371 
02372   // If we are in a dependent context, template instantiation will
02373   // perform this type-checking again. Just save the arguments that we
02374   // received in a ParenListExpr.
02375   // FIXME: This isn't quite ideal, since our ASTs don't capture all
02376   // of the information that we have about the base
02377   // initializer. However, deconstructing the ASTs is a dicey process,
02378   // and this approach is far more likely to get the corner cases right.
02379   if (CurContext->isDependentContext())
02380     BaseInit = Owned(Init);
02381 
02382   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
02383                                           BaseSpec->isVirtual(),
02384                                           InitRange.getBegin(),
02385                                           BaseInit.takeAs<Expr>(),
02386                                           InitRange.getEnd(), EllipsisLoc);
02387 }
02388 
02389 // Create a static_cast<T&&>(expr).
02390 static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
02391   QualType ExprType = E->getType();
02392   QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
02393   SourceLocation ExprLoc = E->getLocStart();
02394   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
02395       TargetType, ExprLoc);
02396 
02397   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
02398                                    SourceRange(ExprLoc, ExprLoc),
02399                                    E->getSourceRange()).take();
02400 }
02401 
02402 /// ImplicitInitializerKind - How an implicit base or member initializer should
02403 /// initialize its base or member.
02404 enum ImplicitInitializerKind {
02405   IIK_Default,
02406   IIK_Copy,
02407   IIK_Move
02408 };
02409 
02410 static bool
02411 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
02412                              ImplicitInitializerKind ImplicitInitKind,
02413                              CXXBaseSpecifier *BaseSpec,
02414                              bool IsInheritedVirtualBase,
02415                              CXXCtorInitializer *&CXXBaseInit) {
02416   InitializedEntity InitEntity
02417     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
02418                                         IsInheritedVirtualBase);
02419 
02420   ExprResult BaseInit;
02421   
02422   switch (ImplicitInitKind) {
02423   case IIK_Default: {
02424     InitializationKind InitKind
02425       = InitializationKind::CreateDefault(Constructor->getLocation());
02426     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
02427     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
02428                                MultiExprArg(SemaRef, 0, 0));
02429     break;
02430   }
02431 
02432   case IIK_Move:
02433   case IIK_Copy: {
02434     bool Moving = ImplicitInitKind == IIK_Move;
02435     ParmVarDecl *Param = Constructor->getParamDecl(0);
02436     QualType ParamType = Param->getType().getNonReferenceType();
02437 
02438     Expr *CopyCtorArg = 
02439       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
02440                           SourceLocation(), Param, false,
02441                           Constructor->getLocation(), ParamType,
02442                           VK_LValue, 0);
02443 
02444     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
02445 
02446     // Cast to the base class to avoid ambiguities.
02447     QualType ArgTy = 
02448       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 
02449                                        ParamType.getQualifiers());
02450 
02451     if (Moving) {
02452       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
02453     }
02454 
02455     CXXCastPath BasePath;
02456     BasePath.push_back(BaseSpec);
02457     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
02458                                             CK_UncheckedDerivedToBase,
02459                                             Moving ? VK_XValue : VK_LValue,
02460                                             &BasePath).take();
02461 
02462     InitializationKind InitKind
02463       = InitializationKind::CreateDirect(Constructor->getLocation(),
02464                                          SourceLocation(), SourceLocation());
02465     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 
02466                                    &CopyCtorArg, 1);
02467     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
02468                                MultiExprArg(&CopyCtorArg, 1));
02469     break;
02470   }
02471   }
02472 
02473   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
02474   if (BaseInit.isInvalid())
02475     return true;
02476         
02477   CXXBaseInit =
02478     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
02479                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 
02480                                                         SourceLocation()),
02481                                              BaseSpec->isVirtual(),
02482                                              SourceLocation(),
02483                                              BaseInit.takeAs<Expr>(),
02484                                              SourceLocation(),
02485                                              SourceLocation());
02486 
02487   return false;
02488 }
02489 
02490 static bool RefersToRValueRef(Expr *MemRef) {
02491   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
02492   return Referenced->getType()->isRValueReferenceType();
02493 }
02494 
02495 static bool
02496 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
02497                                ImplicitInitializerKind ImplicitInitKind,
02498                                FieldDecl *Field, IndirectFieldDecl *Indirect,
02499                                CXXCtorInitializer *&CXXMemberInit) {
02500   if (Field->isInvalidDecl())
02501     return true;
02502 
02503   SourceLocation Loc = Constructor->getLocation();
02504 
02505   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
02506     bool Moving = ImplicitInitKind == IIK_Move;
02507     ParmVarDecl *Param = Constructor->getParamDecl(0);
02508     QualType ParamType = Param->getType().getNonReferenceType();
02509 
02510     // Suppress copying zero-width bitfields.
02511     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
02512       return false;
02513         
02514     Expr *MemberExprBase = 
02515       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
02516                           SourceLocation(), Param, false,
02517                           Loc, ParamType, VK_LValue, 0);
02518 
02519     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
02520 
02521     if (Moving) {
02522       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
02523     }
02524 
02525     // Build a reference to this field within the parameter.
02526     CXXScopeSpec SS;
02527     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
02528                               Sema::LookupMemberName);
02529     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
02530                                   : cast<ValueDecl>(Field), AS_public);
02531     MemberLookup.resolveKind();
02532     ExprResult CtorArg 
02533       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
02534                                          ParamType, Loc,
02535                                          /*IsArrow=*/false,
02536                                          SS,
02537                                          /*TemplateKWLoc=*/SourceLocation(),
02538                                          /*FirstQualifierInScope=*/0,
02539                                          MemberLookup,
02540                                          /*TemplateArgs=*/0);    
02541     if (CtorArg.isInvalid())
02542       return true;
02543 
02544     // C++11 [class.copy]p15:
02545     //   - if a member m has rvalue reference type T&&, it is direct-initialized
02546     //     with static_cast<T&&>(x.m);
02547     if (RefersToRValueRef(CtorArg.get())) {
02548       CtorArg = CastForMoving(SemaRef, CtorArg.take());
02549     }
02550 
02551     // When the field we are copying is an array, create index variables for 
02552     // each dimension of the array. We use these index variables to subscript
02553     // the source array, and other clients (e.g., CodeGen) will perform the
02554     // necessary iteration with these index variables.
02555     SmallVector<VarDecl *, 4> IndexVariables;
02556     QualType BaseType = Field->getType();
02557     QualType SizeType = SemaRef.Context.getSizeType();
02558     bool InitializingArray = false;
02559     while (const ConstantArrayType *Array
02560                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
02561       InitializingArray = true;
02562       // Create the iteration variable for this array index.
02563       IdentifierInfo *IterationVarName = 0;
02564       {
02565         SmallString<8> Str;
02566         llvm::raw_svector_ostream OS(Str);
02567         OS << "__i" << IndexVariables.size();
02568         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
02569       }
02570       VarDecl *IterationVar
02571         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
02572                           IterationVarName, SizeType,
02573                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
02574                           SC_None, SC_None);
02575       IndexVariables.push_back(IterationVar);
02576       
02577       // Create a reference to the iteration variable.
02578       ExprResult IterationVarRef
02579         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
02580       assert(!IterationVarRef.isInvalid() &&
02581              "Reference to invented variable cannot fail!");
02582       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
02583       assert(!IterationVarRef.isInvalid() &&
02584              "Conversion of invented variable cannot fail!");
02585 
02586       // Subscript the array with this iteration variable.
02587       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
02588                                                         IterationVarRef.take(),
02589                                                         Loc);
02590       if (CtorArg.isInvalid())
02591         return true;
02592 
02593       BaseType = Array->getElementType();
02594     }
02595 
02596     // The array subscript expression is an lvalue, which is wrong for moving.
02597     if (Moving && InitializingArray)
02598       CtorArg = CastForMoving(SemaRef, CtorArg.take());
02599 
02600     // Construct the entity that we will be initializing. For an array, this
02601     // will be first element in the array, which may require several levels
02602     // of array-subscript entities. 
02603     SmallVector<InitializedEntity, 4> Entities;
02604     Entities.reserve(1 + IndexVariables.size());
02605     if (Indirect)
02606       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
02607     else
02608       Entities.push_back(InitializedEntity::InitializeMember(Field));
02609     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
02610       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
02611                                                               0,
02612                                                               Entities.back()));
02613     
02614     // Direct-initialize to use the copy constructor.
02615     InitializationKind InitKind =
02616       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
02617     
02618     Expr *CtorArgE = CtorArg.takeAs<Expr>();
02619     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
02620                                    &CtorArgE, 1);
02621     
02622     ExprResult MemberInit
02623       = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 
02624                         MultiExprArg(&CtorArgE, 1));
02625     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
02626     if (MemberInit.isInvalid())
02627       return true;
02628 
02629     if (Indirect) {
02630       assert(IndexVariables.size() == 0 && 
02631              "Indirect field improperly initialized");
02632       CXXMemberInit
02633         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 
02634                                                    Loc, Loc, 
02635                                                    MemberInit.takeAs<Expr>(), 
02636                                                    Loc);
02637     } else
02638       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 
02639                                                  Loc, MemberInit.takeAs<Expr>(), 
02640                                                  Loc,
02641                                                  IndexVariables.data(),
02642                                                  IndexVariables.size());
02643     return false;
02644   }
02645 
02646   assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
02647 
02648   QualType FieldBaseElementType = 
02649     SemaRef.Context.getBaseElementType(Field->getType());
02650   
02651   if (FieldBaseElementType->isRecordType()) {
02652     InitializedEntity InitEntity 
02653       = Indirect? InitializedEntity::InitializeMember(Indirect)
02654                 : InitializedEntity::InitializeMember(Field);
02655     InitializationKind InitKind = 
02656       InitializationKind::CreateDefault(Loc);
02657     
02658     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
02659     ExprResult MemberInit = 
02660       InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
02661 
02662     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
02663     if (MemberInit.isInvalid())
02664       return true;
02665     
02666     if (Indirect)
02667       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
02668                                                                Indirect, Loc, 
02669                                                                Loc,
02670                                                                MemberInit.get(),
02671                                                                Loc);
02672     else
02673       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
02674                                                                Field, Loc, Loc,
02675                                                                MemberInit.get(),
02676                                                                Loc);
02677     return false;
02678   }
02679 
02680   if (!Field->getParent()->isUnion()) {
02681     if (FieldBaseElementType->isReferenceType()) {
02682       SemaRef.Diag(Constructor->getLocation(), 
02683                    diag::err_uninitialized_member_in_ctor)
02684       << (int)Constructor->isImplicit() 
02685       << SemaRef.Context.getTagDeclType(Constructor->getParent())
02686       << 0 << Field->getDeclName();
02687       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
02688       return true;
02689     }
02690 
02691     if (FieldBaseElementType.isConstQualified()) {
02692       SemaRef.Diag(Constructor->getLocation(), 
02693                    diag::err_uninitialized_member_in_ctor)
02694       << (int)Constructor->isImplicit() 
02695       << SemaRef.Context.getTagDeclType(Constructor->getParent())
02696       << 1 << Field->getDeclName();
02697       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
02698       return true;
02699     }
02700   }
02701   
02702   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
02703       FieldBaseElementType->isObjCRetainableType() &&
02704       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
02705       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
02706     // Instant objects:
02707     //   Default-initialize Objective-C pointers to NULL.
02708     CXXMemberInit
02709       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 
02710                                                  Loc, Loc, 
02711                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 
02712                                                  Loc);
02713     return false;
02714   }
02715       
02716   // Nothing to initialize.
02717   CXXMemberInit = 0;
02718   return false;
02719 }
02720 
02721 namespace {
02722 struct BaseAndFieldInfo {
02723   Sema &S;
02724   CXXConstructorDecl *Ctor;
02725   bool AnyErrorsInInits;
02726   ImplicitInitializerKind IIK;
02727   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
02728   SmallVector<CXXCtorInitializer*, 8> AllToInit;
02729 
02730   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
02731     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
02732     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
02733     if (Generated && Ctor->isCopyConstructor())
02734       IIK = IIK_Copy;
02735     else if (Generated && Ctor->isMoveConstructor())
02736       IIK = IIK_Move;
02737     else
02738       IIK = IIK_Default;
02739   }
02740   
02741   bool isImplicitCopyOrMove() const {
02742     switch (IIK) {
02743     case IIK_Copy:
02744     case IIK_Move:
02745       return true;
02746       
02747     case IIK_Default:
02748       return false;
02749     }
02750 
02751     llvm_unreachable("Invalid ImplicitInitializerKind!");
02752   }
02753 };
02754 }
02755 
02756 /// \brief Determine whether the given indirect field declaration is somewhere
02757 /// within an anonymous union.
02758 static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
02759   for (IndirectFieldDecl::chain_iterator C = F->chain_begin(), 
02760                                       CEnd = F->chain_end();
02761        C != CEnd; ++C)
02762     if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
02763       if (Record->isUnion())
02764         return true;
02765         
02766   return false;
02767 }
02768 
02769 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
02770 /// array type.
02771 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
02772   if (T->isIncompleteArrayType())
02773     return true;
02774   
02775   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
02776     if (!ArrayT->getSize())
02777       return true;
02778     
02779     T = ArrayT->getElementType();
02780   }
02781   
02782   return false;
02783 }
02784 
02785 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
02786                                     FieldDecl *Field, 
02787                                     IndirectFieldDecl *Indirect = 0) {
02788 
02789   // Overwhelmingly common case: we have a direct initializer for this field.
02790   if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
02791     Info.AllToInit.push_back(Init);
02792     return false;
02793   }
02794 
02795   // C++0x [class.base.init]p8: if the entity is a non-static data member that
02796   // has a brace-or-equal-initializer, the entity is initialized as specified
02797   // in [dcl.init].
02798   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
02799     CXXCtorInitializer *Init;
02800     if (Indirect)
02801       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
02802                                                       SourceLocation(),
02803                                                       SourceLocation(), 0,
02804                                                       SourceLocation());
02805     else
02806       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
02807                                                       SourceLocation(),
02808                                                       SourceLocation(), 0,
02809                                                       SourceLocation());
02810     Info.AllToInit.push_back(Init);
02811     return false;
02812   }
02813 
02814   // Don't build an implicit initializer for union members if none was
02815   // explicitly specified.
02816   if (Field->getParent()->isUnion() ||
02817       (Indirect && isWithinAnonymousUnion(Indirect)))
02818     return false;
02819 
02820   // Don't initialize incomplete or zero-length arrays.
02821   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
02822     return false;
02823 
02824   // Don't try to build an implicit initializer if there were semantic
02825   // errors in any of the initializers (and therefore we might be
02826   // missing some that the user actually wrote).
02827   if (Info.AnyErrorsInInits || Field->isInvalidDecl())
02828     return false;
02829 
02830   CXXCtorInitializer *Init = 0;
02831   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
02832                                      Indirect, Init))
02833     return true;
02834 
02835   if (Init)
02836     Info.AllToInit.push_back(Init);
02837 
02838   return false;
02839 }
02840 
02841 bool
02842 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
02843                                CXXCtorInitializer *Initializer) {
02844   assert(Initializer->isDelegatingInitializer());
02845   Constructor->setNumCtorInitializers(1);
02846   CXXCtorInitializer **initializer =
02847     new (Context) CXXCtorInitializer*[1];
02848   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
02849   Constructor->setCtorInitializers(initializer);
02850 
02851   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
02852     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
02853     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
02854   }
02855 
02856   DelegatingCtorDecls.push_back(Constructor);
02857 
02858   return false;
02859 }
02860 
02861 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
02862                                CXXCtorInitializer **Initializers,
02863                                unsigned NumInitializers,
02864                                bool AnyErrors) {
02865   if (Constructor->isDependentContext()) {
02866     // Just store the initializers as written, they will be checked during
02867     // instantiation.
02868     if (NumInitializers > 0) {
02869       Constructor->setNumCtorInitializers(NumInitializers);
02870       CXXCtorInitializer **baseOrMemberInitializers =
02871         new (Context) CXXCtorInitializer*[NumInitializers];
02872       memcpy(baseOrMemberInitializers, Initializers,
02873              NumInitializers * sizeof(CXXCtorInitializer*));
02874       Constructor->setCtorInitializers(baseOrMemberInitializers);
02875     }
02876     
02877     return false;
02878   }
02879 
02880   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
02881 
02882   // We need to build the initializer AST according to order of construction
02883   // and not what user specified in the Initializers list.
02884   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
02885   if (!ClassDecl)
02886     return true;
02887   
02888   bool HadError = false;
02889 
02890   for (unsigned i = 0; i < NumInitializers; i++) {
02891     CXXCtorInitializer *Member = Initializers[i];
02892     
02893     if (Member->isBaseInitializer())
02894       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
02895     else
02896       Info.AllBaseFields[Member->getAnyMember()] = Member;
02897   }
02898 
02899   // Keep track of the direct virtual bases.
02900   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
02901   for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
02902        E = ClassDecl->bases_end(); I != E; ++I) {
02903     if (I->isVirtual())
02904       DirectVBases.insert(I);
02905   }
02906 
02907   // Push virtual bases before others.
02908   for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
02909        E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
02910 
02911     if (CXXCtorInitializer *Value
02912         = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
02913       Info.AllToInit.push_back(Value);
02914     } else if (!AnyErrors) {
02915       bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
02916       CXXCtorInitializer *CXXBaseInit;
02917       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
02918                                        VBase, IsInheritedVirtualBase, 
02919                                        CXXBaseInit)) {
02920         HadError = true;
02921         continue;
02922       }
02923 
02924       Info.AllToInit.push_back(CXXBaseInit);
02925     }
02926   }
02927 
02928   // Non-virtual bases.
02929   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
02930        E = ClassDecl->bases_end(); Base != E; ++Base) {
02931     // Virtuals are in the virtual base list and already constructed.
02932     if (Base->isVirtual())
02933       continue;
02934 
02935     if (CXXCtorInitializer *Value
02936           = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
02937       Info.AllToInit.push_back(Value);
02938     } else if (!AnyErrors) {
02939       CXXCtorInitializer *CXXBaseInit;
02940       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
02941                                        Base, /*IsInheritedVirtualBase=*/false,
02942                                        CXXBaseInit)) {
02943         HadError = true;
02944         continue;
02945       }
02946 
02947       Info.AllToInit.push_back(CXXBaseInit);
02948     }
02949   }
02950 
02951   // Fields.
02952   for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
02953                                MemEnd = ClassDecl->decls_end();
02954        Mem != MemEnd; ++Mem) {
02955     if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
02956       // C++ [class.bit]p2:
02957       //   A declaration for a bit-field that omits the identifier declares an
02958       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
02959       //   initialized.
02960       if (F->isUnnamedBitfield())
02961         continue;
02962             
02963       // If we're not generating the implicit copy/move constructor, then we'll
02964       // handle anonymous struct/union fields based on their individual
02965       // indirect fields.
02966       if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
02967         continue;
02968           
02969       if (CollectFieldInitializer(*this, Info, F))
02970         HadError = true;
02971       continue;
02972     }
02973     
02974     // Beyond this point, we only consider default initialization.
02975     if (Info.IIK != IIK_Default)
02976       continue;
02977     
02978     if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
02979       if (F->getType()->isIncompleteArrayType()) {
02980         assert(ClassDecl->hasFlexibleArrayMember() &&
02981                "Incomplete array type is not valid");
02982         continue;
02983       }
02984       
02985       // Initialize each field of an anonymous struct individually.
02986       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
02987         HadError = true;
02988       
02989       continue;        
02990     }
02991   }
02992 
02993   NumInitializers = Info.AllToInit.size();
02994   if (NumInitializers > 0) {
02995     Constructor->setNumCtorInitializers(NumInitializers);
02996     CXXCtorInitializer **baseOrMemberInitializers =
02997       new (Context) CXXCtorInitializer*[NumInitializers];
02998     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
02999            NumInitializers * sizeof(CXXCtorInitializer*));
03000     Constructor->setCtorInitializers(baseOrMemberInitializers);
03001 
03002     // Constructors implicitly reference the base and member
03003     // destructors.
03004     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
03005                                            Constructor->getParent());
03006   }
03007 
03008   return HadError;
03009 }
03010 
03011 static void *GetKeyForTopLevelField(FieldDecl *Field) {
03012   // For anonymous unions, use the class declaration as the key.
03013   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
03014     if (RT->getDecl()->isAnonymousStructOrUnion())
03015       return static_cast<void *>(RT->getDecl());
03016   }
03017   return static_cast<void *>(Field);
03018 }
03019 
03020 static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
03021   return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
03022 }
03023 
03024 static void *GetKeyForMember(ASTContext &Context,
03025                              CXXCtorInitializer *Member) {
03026   if (!Member->isAnyMemberInitializer())
03027     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
03028     
03029   // For fields injected into the class via declaration of an anonymous union,
03030   // use its anonymous union class declaration as the unique key.
03031   FieldDecl *Field = Member->getAnyMember();
03032  
03033   // If the field is a member of an anonymous struct or union, our key
03034   // is the anonymous record decl that's a direct child of the class.
03035   RecordDecl *RD = Field->getParent();
03036   if (RD->isAnonymousStructOrUnion()) {
03037     while (true) {
03038       RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
03039       if (Parent->isAnonymousStructOrUnion())
03040         RD = Parent;
03041       else
03042         break;
03043     }
03044       
03045     return static_cast<void *>(RD);
03046   }
03047 
03048   return static_cast<void *>(Field);
03049 }
03050 
03051 static void
03052 DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
03053                                   const CXXConstructorDecl *Constructor,
03054                                   CXXCtorInitializer **Inits,
03055                                   unsigned NumInits) {
03056   if (Constructor->getDeclContext()->isDependentContext())
03057     return;
03058 
03059   // Don't check initializers order unless the warning is enabled at the
03060   // location of at least one initializer. 
03061   bool ShouldCheckOrder = false;
03062   for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
03063     CXXCtorInitializer *Init = Inits[InitIndex];
03064     if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
03065                                          Init->getSourceLocation())
03066           != DiagnosticsEngine::Ignored) {
03067       ShouldCheckOrder = true;
03068       break;
03069     }
03070   }
03071   if (!ShouldCheckOrder)
03072     return;
03073   
03074   // Build the list of bases and members in the order that they'll
03075   // actually be initialized.  The explicit initializers should be in
03076   // this same order but may be missing things.
03077   SmallVector<const void*, 32> IdealInitKeys;
03078 
03079   const CXXRecordDecl *ClassDecl = Constructor->getParent();
03080 
03081   // 1. Virtual bases.
03082   for (CXXRecordDecl::base_class_const_iterator VBase =
03083        ClassDecl->vbases_begin(),
03084        E = ClassDecl->vbases_end(); VBase != E; ++VBase)
03085     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
03086 
03087   // 2. Non-virtual bases.
03088   for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
03089        E = ClassDecl->bases_end(); Base != E; ++Base) {
03090     if (Base->isVirtual())
03091       continue;
03092     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
03093   }
03094 
03095   // 3. Direct fields.
03096   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
03097        E = ClassDecl->field_end(); Field != E; ++Field) {
03098     if (Field->isUnnamedBitfield())
03099       continue;
03100     
03101     IdealInitKeys.push_back(GetKeyForTopLevelField(&*Field));
03102   }
03103   
03104   unsigned NumIdealInits = IdealInitKeys.size();
03105   unsigned IdealIndex = 0;
03106 
03107   CXXCtorInitializer *PrevInit = 0;
03108   for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
03109     CXXCtorInitializer *Init = Inits[InitIndex];
03110     void *InitKey = GetKeyForMember(SemaRef.Context, Init);
03111 
03112     // Scan forward to try to find this initializer in the idealized
03113     // initializers list.
03114     for (; IdealIndex != NumIdealInits; ++IdealIndex)
03115       if (InitKey == IdealInitKeys[IdealIndex])
03116         break;
03117 
03118     // If we didn't find this initializer, it must be because we
03119     // scanned past it on a previous iteration.  That can only
03120     // happen if we're out of order;  emit a warning.
03121     if (IdealIndex == NumIdealInits && PrevInit) {
03122       Sema::SemaDiagnosticBuilder D =
03123         SemaRef.Diag(PrevInit->getSourceLocation(),
03124                      diag::warn_initializer_out_of_order);
03125 
03126       if (PrevInit->isAnyMemberInitializer())
03127         D << 0 << PrevInit->getAnyMember()->getDeclName();
03128       else
03129         D << 1 << PrevInit->getTypeSourceInfo()->getType();
03130       
03131       if (Init->isAnyMemberInitializer())
03132         D << 0 << Init->getAnyMember()->getDeclName();
03133       else
03134         D << 1 << Init->getTypeSourceInfo()->getType();
03135 
03136       // Move back to the initializer's location in the ideal list.
03137       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
03138         if (InitKey == IdealInitKeys[IdealIndex])
03139           break;
03140 
03141       assert(IdealIndex != NumIdealInits &&
03142              "initializer not found in initializer list");
03143     }
03144 
03145     PrevInit = Init;
03146   }
03147 }
03148 
03149 namespace {
03150 bool CheckRedundantInit(Sema &S,
03151                         CXXCtorInitializer *Init,
03152                         CXXCtorInitializer *&PrevInit) {
03153   if (!PrevInit) {
03154     PrevInit = Init;
03155     return false;
03156   }
03157 
03158   if (FieldDecl *Field = Init->getMember())
03159     S.Diag(Init->getSourceLocation(),
03160            diag::err_multiple_mem_initialization)
03161       << Field->getDeclName()
03162       << Init->getSourceRange();
03163   else {
03164     const Type *BaseClass = Init->getBaseClass();
03165     assert(BaseClass && "neither field nor base");
03166     S.Diag(Init->getSourceLocation(),
03167            diag::err_multiple_base_initialization)
03168       << QualType(BaseClass, 0)
03169       << Init->getSourceRange();
03170   }
03171   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
03172     << 0 << PrevInit->getSourceRange();
03173 
03174   return true;
03175 }
03176 
03177 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
03178 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
03179 
03180 bool CheckRedundantUnionInit(Sema &S,
03181                              CXXCtorInitializer *Init,
03182                              RedundantUnionMap &Unions) {
03183   FieldDecl *Field = Init->getAnyMember();
03184   RecordDecl *Parent = Field->getParent();
03185   NamedDecl *Child = Field;
03186 
03187   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
03188     if (Parent->isUnion()) {
03189       UnionEntry &En = Unions[Parent];
03190       if (En.first && En.first != Child) {
03191         S.Diag(Init->getSourceLocation(),
03192                diag::err_multiple_mem_union_initialization)
03193           << Field->getDeclName()
03194           << Init->getSourceRange();
03195         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
03196           << 0 << En.second->getSourceRange();
03197         return true;
03198       } 
03199       if (!En.first) {
03200         En.first = Child;
03201         En.second = Init;
03202       }
03203       if (!Parent->isAnonymousStructOrUnion())
03204         return false;
03205     }
03206 
03207     Child = Parent;
03208     Parent = cast<RecordDecl>(Parent->getDeclContext());
03209   }
03210 
03211   return false;
03212 }
03213 }
03214 
03215 /// ActOnMemInitializers - Handle the member initializers for a constructor.
03216 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
03217                                 SourceLocation ColonLoc,
03218                                 CXXCtorInitializer **meminits,
03219                                 unsigned NumMemInits,
03220                                 bool AnyErrors) {
03221   if (!ConstructorDecl)
03222     return;
03223 
03224   AdjustDeclIfTemplate(ConstructorDecl);
03225 
03226   CXXConstructorDecl *Constructor
03227     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
03228 
03229   if (!Constructor) {
03230     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
03231     return;
03232   }
03233   
03234   CXXCtorInitializer **MemInits =
03235     reinterpret_cast<CXXCtorInitializer **>(meminits);
03236 
03237   // Mapping for the duplicate initializers check.
03238   // For member initializers, this is keyed with a FieldDecl*.
03239   // For base initializers, this is keyed with a Type*.
03240   llvm::DenseMap<void*, CXXCtorInitializer *> Members;
03241 
03242   // Mapping for the inconsistent anonymous-union initializers check.
03243   RedundantUnionMap MemberUnions;
03244 
03245   bool HadError = false;
03246   for (unsigned i = 0; i < NumMemInits; i++) {
03247     CXXCtorInitializer *Init = MemInits[i];
03248 
03249     // Set the source order index.
03250     Init->setSourceOrder(i);
03251 
03252     if (Init->isAnyMemberInitializer()) {
03253       FieldDecl *Field = Init->getAnyMember();
03254       if (CheckRedundantInit(*this, Init, Members[Field]) ||
03255           CheckRedundantUnionInit(*this, Init, MemberUnions))
03256         HadError = true;
03257     } else if (Init->isBaseInitializer()) {
03258       void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
03259       if (CheckRedundantInit(*this, Init, Members[Key]))
03260         HadError = true;
03261     } else {
03262       assert(Init->isDelegatingInitializer());
03263       // This must be the only initializer
03264       if (i != 0 || NumMemInits > 1) {
03265         Diag(MemInits[0]->getSourceLocation(),
03266              diag::err_delegating_initializer_alone)
03267           << MemInits[0]->getSourceRange();
03268         HadError = true;
03269         // We will treat this as being the only initializer.
03270       }
03271       SetDelegatingInitializer(Constructor, MemInits[i]);
03272       // Return immediately as the initializer is set.
03273       return;
03274     }
03275   }
03276 
03277   if (HadError)
03278     return;
03279 
03280   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
03281 
03282   SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
03283 }
03284 
03285 void
03286 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
03287                                              CXXRecordDecl *ClassDecl) {
03288   // Ignore dependent contexts. Also ignore unions, since their members never
03289   // have destructors implicitly called.
03290   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
03291     return;
03292 
03293   // FIXME: all the access-control diagnostics are positioned on the
03294   // field/base declaration.  That's probably good; that said, the
03295   // user might reasonably want to know why the destructor is being
03296   // emitted, and we currently don't say.
03297   
03298   // Non-static data members.
03299   for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
03300        E = ClassDecl->field_end(); I != E; ++I) {
03301     FieldDecl *Field = &*I;
03302     if (Field->isInvalidDecl())
03303       continue;
03304     
03305     // Don't destroy incomplete or zero-length arrays.
03306     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
03307       continue;
03308 
03309     QualType FieldType = Context.getBaseElementType(Field->getType());
03310     
03311     const RecordType* RT = FieldType->getAs<RecordType>();
03312     if (!RT)
03313       continue;
03314     
03315     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
03316     if (FieldClassDecl->isInvalidDecl())
03317       continue;
03318     if (FieldClassDecl->hasIrrelevantDestructor())
03319       continue;
03320     // The destructor for an implicit anonymous union member is never invoked.
03321     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
03322       continue;
03323 
03324     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
03325     assert(Dtor && "No dtor found for FieldClassDecl!");
03326     CheckDestructorAccess(Field->getLocation(), Dtor,
03327                           PDiag(diag::err_access_dtor_field)
03328                             << Field->getDeclName()
03329                             << FieldType);
03330 
03331     MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
03332     DiagnoseUseOfDecl(Dtor, Location);
03333   }
03334 
03335   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
03336 
03337   // Bases.
03338   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
03339        E = ClassDecl->bases_end(); Base != E; ++Base) {
03340     // Bases are always records in a well-formed non-dependent class.
03341     const RecordType *RT = Base->getType()->getAs<RecordType>();
03342 
03343     // Remember direct virtual bases.
03344     if (Base->isVirtual())
03345       DirectVirtualBases.insert(RT);
03346 
03347     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
03348     // If our base class is invalid, we probably can't get its dtor anyway.
03349     if (BaseClassDecl->isInvalidDecl())
03350       continue;
03351     if (BaseClassDecl->hasIrrelevantDestructor())
03352       continue;
03353 
03354     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
03355     assert(Dtor && "No dtor found for BaseClassDecl!");
03356 
03357     // FIXME: caret should be on the start of the class name
03358     CheckDestructorAccess(Base->getLocStart(), Dtor,
03359                           PDiag(diag::err_access_dtor_base)
03360                             << Base->getType()
03361                             << Base->getSourceRange(),
03362                           Context.getTypeDeclType(ClassDecl));
03363     
03364     MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
03365     DiagnoseUseOfDecl(Dtor, Location);
03366   }
03367   
03368   // Virtual bases.
03369   for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
03370        E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
03371 
03372     // Bases are always records in a well-formed non-dependent class.
03373     const RecordType *RT = VBase->getType()->castAs<RecordType>();
03374 
03375     // Ignore direct virtual bases.
03376     if (DirectVirtualBases.count(RT))
03377       continue;
03378 
03379     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
03380     // If our base class is invalid, we probably can't get its dtor anyway.
03381     if (BaseClassDecl->isInvalidDecl())
03382       continue;
03383     if (BaseClassDecl->hasIrrelevantDestructor())
03384       continue;
03385 
03386     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
03387     assert(Dtor && "No dtor found for BaseClassDecl!");
03388     CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
03389                           PDiag(diag::err_access_dtor_vbase)
03390                             << VBase->getType(),
03391                           Context.getTypeDeclType(ClassDecl));
03392 
03393     MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
03394     DiagnoseUseOfDecl(Dtor, Location);
03395   }
03396 }
03397 
03398 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
03399   if (!CDtorDecl)
03400     return;
03401 
03402   if (CXXConstructorDecl *Constructor
03403       = dyn_cast<CXXConstructorDecl>(CDtorDecl))
03404     SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
03405 }
03406 
03407 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
03408                                   unsigned DiagID, AbstractDiagSelID SelID) {
03409   class NonAbstractTypeDiagnoser : public TypeDiagnoser {
03410     unsigned DiagID;
03411     AbstractDiagSelID SelID;
03412     
03413   public:
03414     NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
03415       : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
03416     
03417     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
03418       if (SelID == -1)
03419         S.Diag(Loc, DiagID) << T;
03420       else
03421         S.Diag(Loc, DiagID) << SelID << T;
03422     }
03423   } Diagnoser(DiagID, SelID);
03424   
03425   return RequireNonAbstractType(Loc, T, Diagnoser);
03426 }
03427 
03428 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
03429                                   TypeDiagnoser &Diagnoser) {
03430   if (!getLangOpts().CPlusPlus)
03431     return false;
03432 
03433   if (const ArrayType *AT = Context.getAsArrayType(T))
03434     return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
03435 
03436   if (const PointerType *PT = T->getAs<PointerType>()) {
03437     // Find the innermost pointer type.
03438     while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
03439       PT = T;
03440 
03441     if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
03442       return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
03443   }
03444 
03445   const RecordType *RT = T->getAs<RecordType>();
03446   if (!RT)
03447     return false;
03448 
03449   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
03450 
03451   // We can't answer whether something is abstract until it has a
03452   // definition.  If it's currently being defined, we'll walk back
03453   // over all the declarations when we have a full definition.
03454   const CXXRecordDecl *Def = RD->getDefinition();
03455   if (!Def || Def->isBeingDefined())
03456     return false;
03457 
03458   if (!RD->isAbstract())
03459     return false;
03460 
03461   Diagnoser.diagnose(*this, Loc, T);
03462   DiagnoseAbstractType(RD);
03463 
03464   return true;
03465 }
03466 
03467 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
03468   // Check if we've already emitted the list of pure virtual functions
03469   // for this class.
03470   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
03471     return;
03472 
03473   CXXFinalOverriderMap FinalOverriders;
03474   RD->getFinalOverriders(FinalOverriders);
03475 
03476   // Keep a set of seen pure methods so we won't diagnose the same method
03477   // more than once.
03478   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
03479   
03480   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 
03481                                    MEnd = FinalOverriders.end();
03482        M != MEnd; 
03483        ++M) {
03484     for (OverridingMethods::iterator SO = M->second.begin(), 
03485                                   SOEnd = M->second.end();
03486          SO != SOEnd; ++SO) {
03487       // C++ [class.abstract]p4:
03488       //   A class is abstract if it contains or inherits at least one
03489       //   pure virtual function for which the final overrider is pure
03490       //   virtual.
03491 
03492       // 
03493       if (SO->second.size() != 1)
03494         continue;
03495 
03496       if (!SO->second.front().Method->isPure())
03497         continue;
03498 
03499       if (!SeenPureMethods.insert(SO->second.front().Method))
03500         continue;
03501 
03502       Diag(SO->second.front().Method->getLocation(), 
03503            diag::note_pure_virtual_function) 
03504         << SO->second.front().Method->getDeclName() << RD->getDeclName();
03505     }
03506   }
03507 
03508   if (!PureVirtualClassDiagSet)
03509     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
03510   PureVirtualClassDiagSet->insert(RD);
03511 }
03512 
03513 namespace {
03514 struct AbstractUsageInfo {
03515   Sema &S;
03516   CXXRecordDecl *Record;
03517   CanQualType AbstractType;
03518   bool Invalid;
03519 
03520   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
03521     : S(S), Record(Record),
03522       AbstractType(S.Context.getCanonicalType(
03523                    S.Context.getTypeDeclType(Record))),
03524       Invalid(false) {}
03525 
03526   void DiagnoseAbstractType() {
03527     if (Invalid) return;
03528     S.DiagnoseAbstractType(Record);
03529     Invalid = true;
03530   }
03531 
03532   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
03533 };
03534 
03535 struct CheckAbstractUsage {
03536   AbstractUsageInfo &Info;
03537   const NamedDecl *Ctx;
03538 
03539   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
03540     : Info(Info), Ctx(Ctx) {}
03541 
03542   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
03543     switch (TL.getTypeLocClass()) {
03544 #define ABSTRACT_TYPELOC(CLASS, PARENT)
03545 #define TYPELOC(CLASS, PARENT) \
03546     case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
03547 #include "clang/AST/TypeLocNodes.def"
03548     }
03549   }
03550 
03551   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
03552     Visit(TL.getResultLoc(), Sema::AbstractReturnType);
03553     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
03554       if (!TL.getArg(I))
03555         continue;
03556       
03557       TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
03558       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
03559     }
03560   }
03561 
03562   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
03563     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
03564   }
03565 
03566   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
03567     // Visit the type parameters from a permissive context.
03568     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
03569       TemplateArgumentLoc TAL = TL.getArgLoc(I);
03570       if (TAL.getArgument().getKind() == TemplateArgument::Type)
03571         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
03572           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
03573       // TODO: other template argument types?
03574     }
03575   }
03576 
03577   // Visit pointee types from a permissive context.
03578 #define CheckPolymorphic(Type) \
03579   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
03580     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
03581   }
03582   CheckPolymorphic(PointerTypeLoc)
03583   CheckPolymorphic(ReferenceTypeLoc)
03584   CheckPolymorphic(MemberPointerTypeLoc)
03585   CheckPolymorphic(BlockPointerTypeLoc)
03586   CheckPolymorphic(AtomicTypeLoc)
03587 
03588   /// Handle all the types we haven't given a more specific
03589   /// implementation for above.
03590   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
03591     // Every other kind of type that we haven't called out already
03592     // that has an inner type is either (1) sugar or (2) contains that
03593     // inner type in some way as a subobject.
03594     if (TypeLoc Next = TL.getNextTypeLoc())
03595       return Visit(Next, Sel);
03596 
03597     // If there's no inner type and we're in a permissive context,
03598     // don't diagnose.
03599     if (Sel == Sema::AbstractNone) return;
03600 
03601     // Check whether the type matches the abstract type.
03602     QualType T = TL.getType();
03603     if (T->isArrayType()) {
03604       Sel = Sema::AbstractArrayType;
03605       T = Info.S.Context.getBaseElementType(T);
03606     }
03607     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
03608     if (CT != Info.AbstractType) return;
03609 
03610     // It matched; do some magic.
03611     if (Sel == Sema::AbstractArrayType) {
03612       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
03613         << T << TL.getSourceRange();
03614     } else {
03615       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
03616         << Sel << T << TL.getSourceRange();
03617     }
03618     Info.DiagnoseAbstractType();
03619   }
03620 };
03621 
03622 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
03623                                   Sema::AbstractDiagSelID Sel) {
03624   CheckAbstractUsage(*this, D).Visit(TL, Sel);
03625 }
03626 
03627 }
03628 
03629 /// Check for invalid uses of an abstract type in a method declaration.
03630 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
03631                                     CXXMethodDecl *MD) {
03632   // No need to do the check on definitions, which require that
03633   // the return/param types be complete.
03634   if (MD->doesThisDeclarationHaveABody())
03635     return;
03636 
03637   // For safety's sake, just ignore it if we don't have type source
03638   // information.  This should never happen for non-implicit methods,
03639   // but...
03640   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
03641     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
03642 }
03643 
03644 /// Check for invalid uses of an abstract type within a class definition.
03645 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
03646                                     CXXRecordDecl *RD) {
03647   for (CXXRecordDecl::decl_iterator
03648          I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
03649     Decl *D = *I;
03650     if (D->isImplicit()) continue;
03651 
03652     // Methods and method templates.
03653     if (isa<CXXMethodDecl>(D)) {
03654       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
03655     } else if (isa<FunctionTemplateDecl>(D)) {
03656       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
03657       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
03658 
03659     // Fields and static variables.
03660     } else if (isa<FieldDecl>(D)) {
03661       FieldDecl *FD = cast<FieldDecl>(D);
03662       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
03663         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
03664     } else if (isa<VarDecl>(D)) {
03665       VarDecl *VD = cast<VarDecl>(D);
03666       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
03667         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
03668 
03669     // Nested classes and class templates.
03670     } else if (isa<CXXRecordDecl>(D)) {
03671       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
03672     } else if (isa<ClassTemplateDecl>(D)) {
03673       CheckAbstractClassUsage(Info,
03674                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
03675     }
03676   }
03677 }
03678 
03679 /// \brief Perform semantic checks on a class definition that has been
03680 /// completing, introducing implicitly-declared members, checking for
03681 /// abstract types, etc.
03682 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
03683   if (!Record)
03684     return;
03685 
03686   if (Record->isAbstract() && !Record->isInvalidDecl()) {
03687     AbstractUsageInfo Info(*this, Record);
03688     CheckAbstractClassUsage(Info, Record);
03689   }
03690   
03691   // If this is not an aggregate type and has no user-declared constructor,
03692   // complain about any non-static data members of reference or const scalar
03693   // type, since they will never get initializers.
03694   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
03695       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
03696       !Record->isLambda()) {
03697     bool Complained = false;
03698     for (RecordDecl::field_iterator F = Record->field_begin(), 
03699                                  FEnd = Record->field_end();
03700          F != FEnd; ++F) {
03701       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
03702         continue;
03703 
03704       if (F->getType()->isReferenceType() ||
03705           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
03706         if (!Complained) {
03707           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
03708             << Record->getTagKind() << Record;
03709           Complained = true;
03710         }
03711         
03712         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
03713           << F->getType()->isReferenceType()
03714           << F->getDeclName();
03715       }
03716     }
03717   }
03718 
03719   if (Record->isDynamicClass() && !Record->isDependentType())
03720     DynamicClasses.push_back(Record);
03721 
03722   if (Record->getIdentifier()) {
03723     // C++ [class.mem]p13:
03724     //   If T is the name of a class, then each of the following shall have a 
03725     //   name different from T:
03726     //     - every member of every anonymous union that is a member of class T.
03727     //
03728     // C++ [class.mem]p14:
03729     //   In addition, if class T has a user-declared constructor (12.1), every 
03730     //   non-static data member of class T shall have a name different from T.
03731     for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
03732          R.first != R.second; ++R.first) {
03733       NamedDecl *D = *R.first;
03734       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
03735           isa<IndirectFieldDecl>(D)) {
03736         Diag(D->getLocation(), diag::err_member_name_of_class)
03737           << D->getDeclName();
03738         break;
03739       }
03740     }
03741   }
03742 
03743   // Warn if the class has virtual methods but non-virtual public destructor.
03744   if (Record->isPolymorphic() && !Record->isDependentType()) {
03745     CXXDestructorDecl *dtor = Record->getDestructor();
03746     if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
03747       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
03748            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
03749   }
03750 
03751   // See if a method overloads virtual methods in a base
03752   /// class without overriding any.
03753   if (!Record->isDependentType()) {
03754     for (CXXRecordDecl::method_iterator M = Record->method_begin(),
03755                                      MEnd = Record->method_end();
03756          M != MEnd; ++M) {
03757       if (!M->isStatic())
03758         DiagnoseHiddenVirtualMethods(Record, &*M);
03759     }
03760   }
03761 
03762   // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
03763   // function that is not a constructor declares that member function to be
03764   // const. [...] The class of which that function is a member shall be
03765   // a literal type.
03766   //
03767   // If the class has virtual bases, any constexpr members will already have
03768   // been diagnosed by the checks performed on the member declaration, so
03769   // suppress this (less useful) diagnostic.
03770   if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
03771       !Record->isLiteral() && !Record->getNumVBases()) {
03772     for (CXXRecordDecl::method_iterator M = Record->method_begin(),
03773                                      MEnd = Record->method_end();
03774          M != MEnd; ++M) {
03775       if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
03776         switch (Record->getTemplateSpecializationKind()) {
03777         case TSK_ImplicitInstantiation:
03778         case TSK_ExplicitInstantiationDeclaration:
03779         case TSK_ExplicitInstantiationDefinition:
03780           // If a template instantiates to a non-literal type, but its members
03781           // instantiate to constexpr functions, the template is technically
03782           // ill-formed, but we allow it for sanity.
03783           continue;
03784 
03785         case TSK_Undeclared:
03786         case TSK_ExplicitSpecialization:
03787           RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
03788                              diag::err_constexpr_method_non_literal);
03789           break;
03790         }
03791 
03792         // Only produce one error per class.
03793         break;
03794       }
03795     }
03796   }
03797 
03798   // Declare inherited constructors. We do this eagerly here because:
03799   // - The standard requires an eager diagnostic for conflicting inherited
03800   //   constructors from different classes.
03801   // - The lazy declaration of the other implicit constructors is so as to not
03802   //   waste space and performance on classes that are not meant to be
03803   //   instantiated (e.g. meta-functions). This doesn't apply to classes that
03804   //   have inherited constructors.
03805   DeclareInheritedConstructors(Record);
03806 
03807   if (!Record->isDependentType())
03808     CheckExplicitlyDefaultedMethods(Record);
03809 }
03810 
03811 void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
03812   for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
03813                                       ME = Record->method_end();
03814        MI != ME; ++MI)
03815     if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted())
03816       CheckExplicitlyDefaultedSpecialMember(&*MI);
03817 }
03818 
03819 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
03820   CXXRecordDecl *RD = MD->getParent();
03821   CXXSpecialMember CSM = getSpecialMember(MD);
03822 
03823   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
03824          "not an explicitly-defaulted special member");
03825 
03826   // Whether this was the first-declared instance of the constructor.
03827   // This affects whether we implicitly add an exception spec and constexpr.
03828   bool First = MD == MD->getCanonicalDecl();
03829 
03830   bool HadError = false;
03831 
03832   // C++11 [dcl.fct.def.default]p1:
03833   //   A function that is explicitly defaulted shall
03834   //     -- be a special member function (checked elsewhere),
03835   //     -- have the same type (except for ref-qualifiers, and except that a
03836   //        copy operation can take a non-const reference) as an implicit
03837   //        declaration, and
03838   //     -- not have default arguments.
03839   unsigned ExpectedParams = 1;
03840   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
03841     ExpectedParams = 0;
03842   if (MD->getNumParams() != ExpectedParams) {
03843     // This also checks for default arguments: a copy or move constructor with a
03844     // default argument is classified as a default constructor, and assignment
03845     // operations and destructors can't have default arguments.
03846     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
03847       << CSM << MD->getSourceRange();
03848     HadError = true;
03849   }
03850 
03851   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
03852 
03853   // Compute implicit exception specification, argument constness, constexpr
03854   // and triviality.
03855   ImplicitExceptionSpecification Spec(*this);
03856   bool Const = false;
03857   bool Constexpr = false;
03858   bool Trivial;
03859   switch (CSM) {
03860   case CXXDefaultConstructor:
03861     Spec = ComputeDefaultedDefaultCtorExceptionSpec(RD);
03862     if (Spec.isDelayed())
03863       // Exception specification depends on some deferred part of the class.
03864       // We'll try again when the class's definition has been fully processed.
03865       return;
03866     Constexpr = RD->defaultedDefaultConstructorIsConstexpr();
03867     Trivial = RD->hasTrivialDefaultConstructor();
03868     break;
03869   case CXXCopyConstructor:
03870     llvm::tie(Spec, Const) =
03871       ComputeDefaultedCopyCtorExceptionSpecAndConst(RD);
03872     Constexpr = RD->defaultedCopyConstructorIsConstexpr();
03873     Trivial = RD->hasTrivialCopyConstructor();
03874     break;
03875   case CXXCopyAssignment:
03876     llvm::tie(Spec, Const) =
03877       ComputeDefaultedCopyAssignmentExceptionSpecAndConst(RD);
03878     Trivial = RD->hasTrivialCopyAssignment();
03879     break;
03880   case CXXMoveConstructor:
03881     Spec = ComputeDefaultedMoveCtorExceptionSpec(RD);
03882     Constexpr = RD->defaultedMoveConstructorIsConstexpr();
03883     Trivial = RD->hasTrivialMoveConstructor();
03884     break;
03885   case CXXMoveAssignment:
03886     Spec = ComputeDefaultedMoveAssignmentExceptionSpec(RD);
03887     Trivial = RD->hasTrivialMoveAssignment();
03888     break;
03889   case CXXDestructor:
03890     Spec = ComputeDefaultedDtorExceptionSpec(RD);
03891     Trivial = RD->hasTrivialDestructor();
03892     break;
03893   case CXXInvalid:
03894     llvm_unreachable("non-special member explicitly defaulted!");
03895   }
03896 
03897   QualType ReturnType = Context.VoidTy;
03898   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
03899     // Check for return type matching.
03900     ReturnType = Type->getResultType();
03901     QualType ExpectedReturnType =
03902         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
03903     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
03904       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
03905         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
03906       HadError = true;
03907     }
03908 
03909     // A defaulted special member cannot have cv-qualifiers.
03910     if (Type->getTypeQuals()) {
03911       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
03912         << (CSM == CXXMoveAssignment);
03913       HadError = true;
03914     }
03915   }
03916 
03917   // Check for parameter type matching.
03918   QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
03919   if (ExpectedParams && ArgType->isReferenceType()) {
03920     // Argument must be reference to possibly-const T.
03921     QualType ReferentType = ArgType->getPointeeType();
03922 
03923     if (ReferentType.isVolatileQualified()) {
03924       Diag(MD->getLocation(),
03925            diag::err_defaulted_special_member_volatile_param) << CSM;
03926       HadError = true;
03927     }
03928 
03929     if (ReferentType.isConstQualified() && !Const) {
03930       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
03931         Diag(MD->getLocation(),
03932              diag::err_defaulted_special_member_copy_const_param)
03933           << (CSM == CXXCopyAssignment);
03934         // FIXME: Explain why this special member can't be const.
03935       } else {
03936         Diag(MD->getLocation(),
03937              diag::err_defaulted_special_member_move_const_param)
03938           << (CSM == CXXMoveAssignment);
03939       }
03940       HadError = true;
03941     }
03942 
03943     // If a function is explicitly defaulted on its first declaration, it shall
03944     // have the same parameter type as if it had been implicitly declared.
03945     // (Presumably this is to prevent it from being trivial?)
03946     if (!ReferentType.isConstQualified() && Const && First)
03947       Diag(MD->getLocation(),
03948            diag::err_defaulted_special_member_copy_non_const_param)
03949         << (CSM == CXXCopyAssignment);
03950   } else if (ExpectedParams) {
03951     // A copy assignment operator can take its argument by value, but a
03952     // defaulted one cannot.
03953     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
03954     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
03955     HadError = true;
03956   }
03957 
03958   // Rebuild the type with the implicit exception specification added.
03959   FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
03960   Spec.getEPI(EPI);
03961   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
03962     Context.getFunctionType(ReturnType, &ArgType, ExpectedParams, EPI));
03963 
03964   // C++11 [dcl.fct.def.default]p2:
03965   //   An explicitly-defaulted function may be declared constexpr only if it
03966   //   would have been implicitly declared as constexpr,
03967   // Do not apply this rule to members of class templates, since core issue 1358
03968   // makes such functions always instantiate to constexpr functions. For
03969   // non-constructors, this is checked elsewhere.
03970   if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
03971       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
03972     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
03973     HadError = true;
03974   }
03975   //   and may have an explicit exception-specification only if it is compatible
03976   //   with the exception-specification on the implicit declaration.
03977   if (Type->hasExceptionSpec() &&
03978       CheckEquivalentExceptionSpec(
03979         PDiag(diag::err_incorrect_defaulted_exception_spec) << CSM,
03980         PDiag(), ImplicitType, SourceLocation(), Type, MD->getLocation()))
03981     HadError = true;
03982 
03983   //   If a function is explicitly defaulted on its first declaration,
03984   if (First) {
03985     //  -- it is implicitly considered to be constexpr if the implicit
03986     //     definition would be,
03987     MD->setConstexpr(Constexpr);
03988 
03989     //  -- it is implicitly considered to have the same exception-specification
03990     //     as if it had been implicitly declared,
03991     MD->setType(QualType(ImplicitType, 0));
03992 
03993     // Such a function is also trivial if the implicitly-declared function
03994     // would have been.
03995     MD->setTrivial(Trivial);
03996   }
03997 
03998   if (ShouldDeleteSpecialMember(MD, CSM)) {
03999     if (First) {
04000       MD->setDeletedAsWritten();
04001     } else {
04002       // C++11 [dcl.fct.def.default]p4:
04003       //   [For a] user-provided explicitly-defaulted function [...] if such a
04004       //   function is implicitly defined as deleted, the program is ill-formed.
04005       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
04006       HadError = true;
04007     }
04008   }
04009 
04010   if (HadError)
04011     MD->setInvalidDecl();
04012 }
04013 
04014 namespace {
04015 struct SpecialMemberDeletionInfo {
04016   Sema &S;
04017   CXXMethodDecl *MD;
04018   Sema::CXXSpecialMember CSM;
04019   bool Diagnose;
04020 
04021   // Properties of the special member, computed for convenience.
04022   bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
04023   SourceLocation Loc;
04024 
04025   bool AllFieldsAreConst;
04026 
04027   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
04028                             Sema::CXXSpecialMember CSM, bool Diagnose)
04029     : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
04030       IsConstructor(false), IsAssignment(false), IsMove(false),
04031       ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
04032       AllFieldsAreConst(true) {
04033     switch (CSM) {
04034       case Sema::CXXDefaultConstructor:
04035       case Sema::CXXCopyConstructor:
04036         IsConstructor = true;
04037         break;
04038       case Sema::CXXMoveConstructor:
04039         IsConstructor = true;
04040         IsMove = true;
04041         break;
04042       case Sema::CXXCopyAssignment:
04043         IsAssignment = true;
04044         break;
04045       case Sema::CXXMoveAssignment:
04046         IsAssignment = true;
04047         IsMove = true;
04048         break;
04049       case Sema::CXXDestructor:
04050         break;
04051       case Sema::CXXInvalid:
04052         llvm_unreachable("invalid special member kind");
04053     }
04054 
04055     if (MD->getNumParams()) {
04056       ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
04057       VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
04058     }
04059   }
04060 
04061   bool inUnion() const { return MD->getParent()->isUnion(); }
04062 
04063   /// Look up the corresponding special member in the given class.
04064   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class) {
04065     unsigned TQ = MD->getTypeQualifiers();
04066     return S.LookupSpecialMember(Class, CSM, ConstArg, VolatileArg,
04067                                  MD->getRefQualifier() == RQ_RValue,
04068                                  TQ & Qualifiers::Const,
04069                                  TQ & Qualifiers::Volatile);
04070   }
04071 
04072   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
04073 
04074   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
04075   bool shouldDeleteForField(FieldDecl *FD);
04076   bool shouldDeleteForAllConstMembers();
04077 
04078   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj);
04079   bool shouldDeleteForSubobjectCall(Subobject Subobj,
04080                                     Sema::SpecialMemberOverloadResult *SMOR,
04081                                     bool IsDtorCallInCtor);
04082 
04083   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
04084 };
04085 }
04086 
04087 /// Is the given special member inaccessible when used on the given
04088 /// sub-object.
04089 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
04090                                              CXXMethodDecl *target) {
04091   /// If we're operating on a base class, the object type is the
04092   /// type of this special member.
04093   QualType objectTy;
04094   AccessSpecifier access = target->getAccess();;
04095   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
04096     objectTy = S.Context.getTypeDeclType(MD->getParent());
04097     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
04098 
04099   // If we're operating on a field, the object type is the type of the field.
04100   } else {
04101     objectTy = S.Context.getTypeDeclType(target->getParent());
04102   }
04103 
04104   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
04105 }
04106 
04107 /// Check whether we should delete a special member due to the implicit
04108 /// definition containing a call to a special member of a subobject.
04109 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
04110     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
04111     bool IsDtorCallInCtor) {
04112   CXXMethodDecl *Decl = SMOR->getMethod();
04113   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
04114 
04115   int DiagKind = -1;
04116 
04117   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
04118     DiagKind = !Decl ? 0 : 1;
04119   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
04120     DiagKind = 2;
04121   else if (!isAccessible(Subobj, Decl))
04122     DiagKind = 3;
04123   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
04124            !Decl->isTrivial()) {
04125     // A member of a union must have a trivial corresponding special member.
04126     // As a weird special case, a destructor call from a union's constructor
04127     // must be accessible and non-deleted, but need not be trivial. Such a
04128     // destructor is never actually called, but is semantically checked as
04129     // if it were.
04130     DiagKind = 4;
04131   }
04132 
04133   if (DiagKind == -1)
04134     return false;
04135 
04136   if (Diagnose) {
04137     if (Field) {
04138       S.Diag(Field->getLocation(),
04139              diag::note_deleted_special_member_class_subobject)
04140         << CSM << MD->getParent() << /*IsField*/true
04141         << Field << DiagKind << IsDtorCallInCtor;
04142     } else {
04143       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
04144       S.Diag(Base->getLocStart(),
04145              diag::note_deleted_special_member_class_subobject)
04146         << CSM << MD->getParent() << /*IsField*/false
04147         << Base->getType() << DiagKind << IsDtorCallInCtor;
04148     }
04149 
04150     if (DiagKind == 1)
04151       S.NoteDeletedFunction(Decl);
04152     // FIXME: Explain inaccessibility if DiagKind == 3.
04153   }
04154 
04155   return true;
04156 }
04157 
04158 /// Check whether we should delete a special member function due to having a
04159 /// direct or virtual base class or static data member of class type M.
04160 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
04161     CXXRecordDecl *Class, Subobject Subobj) {
04162   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
04163 
04164   // C++11 [class.ctor]p5:
04165   // -- any direct or virtual base class, or non-static data member with no
04166   //    brace-or-equal-initializer, has class type M (or array thereof) and
04167   //    either M has no default constructor or overload resolution as applied
04168   //    to M's default constructor results in an ambiguity or in a function
04169   //    that is deleted or inaccessible
04170   // C++11 [class.copy]p11, C++11 [class.copy]p23:
04171   // -- a direct or virtual base class B that cannot be copied/moved because
04172   //    overload resolution, as applied to B's corresponding special member,
04173   //    results in an ambiguity or a function that is deleted or inaccessible
04174   //    from the defaulted special member
04175   // C++11 [class.dtor]p5:
04176   // -- any direct or virtual base class [...] has a type with a destructor
04177   //    that is deleted or inaccessible
04178   if (!(CSM == Sema::CXXDefaultConstructor &&
04179         Field && Field->hasInClassInitializer()) &&
04180       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class), false))
04181     return true;
04182 
04183   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
04184   // -- any direct or virtual base class or non-static data member has a
04185   //    type with a destructor that is deleted or inaccessible
04186   if (IsConstructor) {
04187     Sema::SpecialMemberOverloadResult *SMOR =
04188         S.LookupSpecialMember(Class, Sema::CXXDestructor,
04189                               false, false, false, false, false);
04190     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
04191       return true;
04192   }
04193 
04194   return false;
04195 }
04196 
04197 /// Check whether we should delete a special member function due to the class
04198 /// having a particular direct or virtual base class.
04199 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
04200   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
04201   return shouldDeleteForClassSubobject(BaseClass, Base);
04202 }
04203 
04204 /// Check whether we should delete a special member function due to the class
04205 /// having a particular non-static data member.
04206 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
04207   QualType FieldType = S.Context.getBaseElementType(FD->getType());
04208   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
04209 
04210   if (CSM == Sema::CXXDefaultConstructor) {
04211     // For a default constructor, all references must be initialized in-class
04212     // and, if a union, it must have a non-const member.
04213     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
04214       if (Diagnose)
04215         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
04216           << MD->getParent() << FD << FieldType << /*Reference*/0;
04217       return true;
04218     }
04219     // C++11 [class.ctor]p5: any non-variant non-static data member of
04220     // const-qualified type (or array thereof) with no
04221     // brace-or-equal-initializer does not have a user-provided default
04222     // constructor.
04223     if (!inUnion() && FieldType.isConstQualified() &&
04224         !FD->hasInClassInitializer() &&
04225         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
04226       if (Diagnose)
04227         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
04228           << MD->getParent() << FD << FD->getType() << /*Const*/1;
04229       return true;
04230     }
04231 
04232     if (inUnion() && !FieldType.isConstQualified())
04233       AllFieldsAreConst = false;
04234   } else if (CSM == Sema::CXXCopyConstructor) {
04235     // For a copy constructor, data members must not be of rvalue reference
04236     // type.
04237     if (FieldType->isRValueReferenceType()) {
04238       if (Diagnose)
04239         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
04240           << MD->getParent() << FD << FieldType;
04241       return true;
04242     }
04243   } else if (IsAssignment) {
04244     // For an assignment operator, data members must not be of reference type.
04245     if (FieldType->isReferenceType()) {
04246       if (Diagnose)
04247         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
04248           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
04249       return true;
04250     }
04251     if (!FieldRecord && FieldType.isConstQualified()) {
04252       // C++11 [class.copy]p23:
04253       // -- a non-static data member of const non-class type (or array thereof)
04254       if (Diagnose)
04255         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
04256           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
04257       return true;
04258     }
04259   }
04260 
04261   if (FieldRecord) {
04262     // Some additional restrictions exist on the variant members.
04263     if (!inUnion() && FieldRecord->isUnion() &&
04264         FieldRecord->isAnonymousStructOrUnion()) {
04265       bool AllVariantFieldsAreConst = true;
04266 
04267       // FIXME: Handle anonymous unions declared within anonymous unions.
04268       for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
04269                                          UE = FieldRecord->field_end();
04270            UI != UE; ++UI) {
04271         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
04272 
04273         if (!UnionFieldType.isConstQualified())
04274           AllVariantFieldsAreConst = false;
04275 
04276         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
04277         if (UnionFieldRecord &&
04278             shouldDeleteForClassSubobject(UnionFieldRecord, &*UI))
04279           return true;
04280       }
04281 
04282       // At least one member in each anonymous union must be non-const
04283       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
04284           FieldRecord->field_begin() != FieldRecord->field_end()) {
04285         if (Diagnose)
04286           S.Diag(FieldRecord->getLocation(),
04287                  diag::note_deleted_default_ctor_all_const)
04288             << MD->getParent() << /*anonymous union*/1;
04289         return true;
04290       }
04291 
04292       // Don't check the implicit member of the anonymous union type.
04293       // This is technically non-conformant, but sanity demands it.
04294       return false;
04295     }
04296 
04297     if (shouldDeleteForClassSubobject(FieldRecord, FD))
04298       return true;
04299   }
04300 
04301   return false;
04302 }
04303 
04304 /// C++11 [class.ctor] p5:
04305 ///   A defaulted default constructor for a class X is defined as deleted if
04306 /// X is a union and all of its variant members are of const-qualified type.
04307 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
04308   // This is a silly definition, because it gives an empty union a deleted
04309   // default constructor. Don't do that.
04310   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
04311       (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
04312     if (Diagnose)
04313       S.Diag(MD->getParent()->getLocation(),
04314              diag::note_deleted_default_ctor_all_const)
04315         << MD->getParent() << /*not anonymous union*/0;
04316     return true;
04317   }
04318   return false;
04319 }
04320 
04321 /// Determine whether a defaulted special member function should be defined as
04322 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
04323 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
04324 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
04325                                      bool Diagnose) {
04326   assert(!MD->isInvalidDecl());
04327   CXXRecordDecl *RD = MD->getParent();
04328   assert(!RD->isDependentType() && "do deletion after instantiation");
04329   if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
04330     return false;
04331 
04332   // C++11 [expr.lambda.prim]p19:
04333   //   The closure type associated with a lambda-expression has a
04334   //   deleted (8.4.3) default constructor and a deleted copy
04335   //   assignment operator.
04336   if (RD->isLambda() &&
04337       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
04338     if (Diagnose)
04339       Diag(RD->getLocation(), diag::note_lambda_decl);
04340     return true;
04341   }
04342 
04343   // For an anonymous struct or union, the copy and assignment special members
04344   // will never be used, so skip the check. For an anonymous union declared at
04345   // namespace scope, the constructor and destructor are used.
04346   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
04347       RD->isAnonymousStructOrUnion())
04348     return false;
04349 
04350   // C++11 [class.copy]p7, p18:
04351   //   If the class definition declares a move constructor or move assignment
04352   //   operator, an implicitly declared copy constructor or copy assignment
04353   //   operator is defined as deleted.
04354   if (MD->isImplicit() &&
04355       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
04356     CXXMethodDecl *UserDeclaredMove = 0;
04357 
04358     // In Microsoft mode, a user-declared move only causes the deletion of the
04359     // corresponding copy operation, not both copy operations.
04360     if (RD->hasUserDeclaredMoveConstructor() &&
04361         (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
04362       if (!Diagnose) return true;
04363       UserDeclaredMove = RD->getMoveConstructor();
04364       assert(UserDeclaredMove);
04365     } else if (RD->hasUserDeclaredMoveAssignment() &&
04366                (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
04367       if (!Diagnose) return true;
04368       UserDeclaredMove = RD->getMoveAssignmentOperator();
04369       assert(UserDeclaredMove);
04370     }
04371 
04372     if (UserDeclaredMove) {
04373       Diag(UserDeclaredMove->getLocation(),
04374            diag::note_deleted_copy_user_declared_move)
04375         << (CSM == CXXCopyAssignment) << RD
04376         << UserDeclaredMove->isMoveAssignmentOperator();
04377       return true;
04378     }
04379   }
04380 
04381   // Do access control from the special member function
04382   ContextRAII MethodContext(*this, MD);
04383 
04384   // C++11 [class.dtor]p5:
04385   // -- for a virtual destructor, lookup of the non-array deallocation function
04386   //    results in an ambiguity or in a function that is deleted or inaccessible
04387   if (CSM == CXXDestructor && MD->isVirtual()) {
04388     FunctionDecl *OperatorDelete = 0;
04389     DeclarationName Name =
04390       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
04391     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
04392                                  OperatorDelete, false)) {
04393       if (Diagnose)
04394         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
04395       return true;
04396     }
04397   }
04398 
04399   SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
04400 
04401   for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
04402                                           BE = RD->bases_end(); BI != BE; ++BI)
04403     if (!BI->isVirtual() &&
04404         SMI.shouldDeleteForBase(BI))
04405       return true;
04406 
04407   for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
04408                                           BE = RD->vbases_end(); BI != BE; ++BI)
04409     if (SMI.shouldDeleteForBase(BI))
04410       return true;
04411 
04412   for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
04413                                      FE = RD->field_end(); FI != FE; ++FI)
04414     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
04415         SMI.shouldDeleteForField(&*FI))
04416       return true;
04417 
04418   if (SMI.shouldDeleteForAllConstMembers())
04419     return true;
04420 
04421   return false;
04422 }
04423 
04424 /// \brief Data used with FindHiddenVirtualMethod
04425 namespace {
04426   struct FindHiddenVirtualMethodData {
04427     Sema *S;
04428     CXXMethodDecl *Method;
04429     llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
04430     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
04431   };
04432 }
04433 
04434 /// \brief Member lookup function that determines whether a given C++
04435 /// method overloads virtual methods in a base class without overriding any,
04436 /// to be used with CXXRecordDecl::lookupInBases().
04437 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
04438                                     CXXBasePath &Path,
04439                                     void *UserData) {
04440   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
04441 
04442   FindHiddenVirtualMethodData &Data
04443     = *static_cast<FindHiddenVirtualMethodData*>(UserData);
04444 
04445   DeclarationName Name = Data.Method->getDeclName();
04446   assert(Name.getNameKind() == DeclarationName::Identifier);
04447 
04448   bool foundSameNameMethod = false;
04449   SmallVector<CXXMethodDecl *, 8> overloadedMethods;
04450   for (Path.Decls = BaseRecord->lookup(Name);
04451        Path.Decls.first != Path.Decls.second;
04452        ++Path.Decls.first) {
04453     NamedDecl *D = *Path.Decls.first;
04454     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
04455       MD = MD->getCanonicalDecl();
04456       foundSameNameMethod = true;
04457       // Interested only in hidden virtual methods.
04458       if (!MD->isVirtual())
04459         continue;
04460       // If the method we are checking overrides a method from its base
04461       // don't warn about the other overloaded methods.
04462       if (!Data.S->IsOverload(Data.Method, MD, false))
04463         return true;
04464       // Collect the overload only if its hidden.
04465       if (!Data.OverridenAndUsingBaseMethods.count(MD))
04466         overloadedMethods.push_back(MD);
04467     }
04468   }
04469 
04470   if (foundSameNameMethod)
04471     Data.OverloadedMethods.append(overloadedMethods.begin(),
04472                                    overloadedMethods.end());
04473   return foundSameNameMethod;
04474 }
04475 
04476 /// \brief See if a method overloads virtual methods in a base class without
04477 /// overriding any.
04478 void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
04479   if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
04480                                MD->getLocation()) == DiagnosticsEngine::Ignored)
04481     return;
04482   if (!MD->getDeclName().isIdentifier())
04483     return;
04484 
04485   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
04486                      /*bool RecordPaths=*/false,
04487                      /*bool DetectVirtual=*/false);
04488   FindHiddenVirtualMethodData Data;
04489   Data.Method = MD;
04490   Data.S = this;
04491 
04492   // Keep the base methods that were overriden or introduced in the subclass
04493   // by 'using' in a set. A base method not in this set is hidden.
04494   for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
04495        res.first != res.second; ++res.first) {
04496     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
04497       for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
04498                                           E = MD->end_overridden_methods();
04499            I != E; ++I)
04500         Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
04501     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
04502       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
04503         Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
04504   }
04505 
04506   if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
04507       !Data.OverloadedMethods.empty()) {
04508     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
04509       << MD << (Data.OverloadedMethods.size() > 1);
04510 
04511     for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
04512       CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
04513       Diag(overloadedMD->getLocation(),
04514            diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
04515     }
04516   }
04517 }
04518 
04519 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
04520                                              Decl *TagDecl,
04521                                              SourceLocation LBrac,
04522                                              SourceLocation RBrac,
04523                                              AttributeList *AttrList) {
04524   if (!TagDecl)
04525     return;
04526 
04527   AdjustDeclIfTemplate(TagDecl);
04528 
04529   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
04530               // strict aliasing violation!
04531               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
04532               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
04533 
04534   CheckCompletedCXXClass(
04535                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
04536 }
04537 
04538 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
04539 /// special functions, such as the default constructor, copy
04540 /// constructor, or destructor, to the given C++ class (C++
04541 /// [special]p1).  This routine can only be executed just before the
04542 /// definition of the class is complete.
04543 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
04544   if (!ClassDecl->hasUserDeclaredConstructor())
04545     ++ASTContext::NumImplicitDefaultConstructors;
04546 
04547   if (!ClassDecl->hasUserDeclaredCopyConstructor())
04548     ++ASTContext::NumImplicitCopyConstructors;
04549 
04550   if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
04551     ++ASTContext::NumImplicitMoveConstructors;
04552 
04553   if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
04554     ++ASTContext::NumImplicitCopyAssignmentOperators;
04555     
04556     // If we have a dynamic class, then the copy assignment operator may be 
04557     // virtual, so we have to declare it immediately. This ensures that, e.g.,
04558     // it shows up in the right place in the vtable and that we diagnose 
04559     // problems with the implicit exception specification.    
04560     if (ClassDecl->isDynamicClass())
04561       DeclareImplicitCopyAssignment(ClassDecl);
04562   }
04563 
04564   if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()) {
04565     ++ASTContext::NumImplicitMoveAssignmentOperators;
04566 
04567     // Likewise for the move assignment operator.
04568     if (ClassDecl->isDynamicClass())
04569       DeclareImplicitMoveAssignment(ClassDecl);
04570   }
04571 
04572   if (!ClassDecl->hasUserDeclaredDestructor()) {
04573     ++ASTContext::NumImplicitDestructors;
04574     
04575     // If we have a dynamic class, then the destructor may be virtual, so we 
04576     // have to declare the destructor immediately. This ensures that, e.g., it
04577     // shows up in the right place in the vtable and that we diagnose problems
04578     // with the implicit exception specification.
04579     if (ClassDecl->isDynamicClass())
04580       DeclareImplicitDestructor(ClassDecl);
04581   }
04582 }
04583 
04584 void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
04585   if (!D)
04586     return;
04587 
04588   int NumParamList = D->getNumTemplateParameterLists();
04589   for (int i = 0; i < NumParamList; i++) {
04590     TemplateParameterList* Params = D->getTemplateParameterList(i);
04591     for (TemplateParameterList::iterator Param = Params->begin(),
04592                                       ParamEnd = Params->end();
04593           Param != ParamEnd; ++Param) {
04594       NamedDecl *Named = cast<NamedDecl>(*Param);
04595       if (Named->getDeclName()) {
04596         S->AddDecl(Named);
04597         IdResolver.AddDecl(Named);
04598       }
04599     }
04600   }
04601 }
04602 
04603 void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
04604   if (!D)
04605     return;
04606   
04607   TemplateParameterList *Params = 0;
04608   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
04609     Params = Template->getTemplateParameters();
04610   else if (ClassTemplatePartialSpecializationDecl *PartialSpec
04611            = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
04612     Params = PartialSpec->getTemplateParameters();
04613   else
04614     return;
04615 
04616   for (TemplateParameterList::iterator Param = Params->begin(),
04617                                     ParamEnd = Params->end();
04618        Param != ParamEnd; ++Param) {
04619     NamedDecl *Named = cast<NamedDecl>(*Param);
04620     if (Named->getDeclName()) {
04621       S->AddDecl(Named);
04622       IdResolver.AddDecl(Named);
04623     }
04624   }
04625 }
04626 
04627 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
04628   if (!RecordD) return;
04629   AdjustDeclIfTemplate(RecordD);
04630   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
04631   PushDeclContext(S, Record);
04632 }
04633 
04634 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
04635   if (!RecordD) return;
04636   PopDeclContext();
04637 }
04638 
04639 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
04640 /// parsing a top-level (non-nested) C++ class, and we are now
04641 /// parsing those parts of the given Method declaration that could
04642 /// not be parsed earlier (C++ [class.mem]p2), such as default
04643 /// arguments. This action should enter the scope of the given
04644 /// Method declaration as if we had just parsed the qualified method
04645 /// name. However, it should not bring the parameters into scope;
04646 /// that will be performed by ActOnDelayedCXXMethodParameter.
04647 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
04648 }
04649 
04650 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
04651 /// C++ method declaration. We're (re-)introducing the given
04652 /// function parameter into scope for use in parsing later parts of
04653 /// the method declaration. For example, we could see an
04654 /// ActOnParamDefaultArgument event for this parameter.
04655 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
04656   if (!ParamD)
04657     return;
04658 
04659   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
04660 
04661   // If this parameter has an unparsed default argument, clear it out
04662   // to make way for the parsed default argument.
04663   if (Param->hasUnparsedDefaultArg())
04664     Param->setDefaultArg(0);
04665 
04666   S->AddDecl(Param);
04667   if (Param->getDeclName())
04668     IdResolver.AddDecl(Param);
04669 }
04670 
04671 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
04672 /// processing the delayed method declaration for Method. The method
04673 /// declaration is now considered finished. There may be a separate
04674 /// ActOnStartOfFunctionDef action later (not necessarily
04675 /// immediately!) for this method, if it was also defined inside the
04676 /// class body.
04677 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
04678   if (!MethodD)
04679     return;
04680 
04681   AdjustDeclIfTemplate(MethodD);
04682 
04683   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
04684 
04685   // Now that we have our default arguments, check the constructor
04686   // again. It could produce additional diagnostics or affect whether
04687   // the class has implicitly-declared destructors, among other
04688   // things.
04689   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
04690     CheckConstructor(Constructor);
04691 
04692   // Check the default arguments, which we may have added.
04693   if (!Method->isInvalidDecl())
04694     CheckCXXDefaultArguments(Method);
04695 }
04696 
04697 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
04698 /// the well-formedness of the constructor declarator @p D with type @p
04699 /// R. If there are any errors in the declarator, this routine will
04700 /// emit diagnostics and set the invalid bit to true.  In any case, the type
04701 /// will be updated to reflect a well-formed type for the constructor and
04702 /// returned.
04703 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
04704                                           StorageClass &SC) {
04705   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
04706 
04707   // C++ [class.ctor]p3:
04708   //   A constructor shall not be virtual (10.3) or static (9.4). A
04709   //   constructor can be invoked for a const, volatile or const
04710   //   volatile object. A constructor shall not be declared const,
04711   //   volatile, or const volatile (9.3.2).
04712   if (isVirtual) {
04713     if (!D.isInvalidType())
04714       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
04715         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
04716         << SourceRange(D.getIdentifierLoc());
04717     D.setInvalidType();
04718   }
04719   if (SC == SC_Static) {
04720     if (!D.isInvalidType())
04721       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
04722         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
04723         << SourceRange(D.getIdentifierLoc());
04724     D.setInvalidType();
04725     SC = SC_None;
04726   }
04727 
04728   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
04729   if (FTI.TypeQuals != 0) {
04730     if (FTI.TypeQuals & Qualifiers::Const)
04731       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
04732         << "const" << SourceRange(D.getIdentifierLoc());
04733     if (FTI.TypeQuals & Qualifiers::Volatile)
04734       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
04735         << "volatile" << SourceRange(D.getIdentifierLoc());
04736     if (FTI.TypeQuals & Qualifiers::Restrict)
04737       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
04738         << "restrict" << SourceRange(D.getIdentifierLoc());
04739     D.setInvalidType();
04740   }
04741 
04742   // C++0x [class.ctor]p4:
04743   //   A constructor shall not be declared with a ref-qualifier.
04744   if (FTI.hasRefQualifier()) {
04745     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
04746       << FTI.RefQualifierIsLValueRef 
04747       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
04748     D.setInvalidType();
04749   }
04750   
04751   // Rebuild the function type "R" without any type qualifiers (in
04752   // case any of the errors above fired) and with "void" as the
04753   // return type, since constructors don't have return types.
04754   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
04755   if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
04756     return R;
04757 
04758   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
04759   EPI.TypeQuals = 0;
04760   EPI.RefQualifier = RQ_None;
04761   
04762   return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
04763                                  Proto->getNumArgs(), EPI);
04764 }
04765 
04766 /// CheckConstructor - Checks a fully-formed constructor for
04767 /// well-formedness, issuing any diagnostics required. Returns true if
04768 /// the constructor declarator is invalid.
04769 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
04770   CXXRecordDecl *ClassDecl
04771     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
04772   if (!ClassDecl)
04773     return Constructor->setInvalidDecl();
04774 
04775   // C++ [class.copy]p3:
04776   //   A declaration of a constructor for a class X is ill-formed if
04777   //   its first parameter is of type (optionally cv-qualified) X and
04778   //   either there are no other parameters or else all other
04779   //   parameters have default arguments.
04780   if (!Constructor->isInvalidDecl() &&
04781       ((Constructor->getNumParams() == 1) ||
04782        (Constructor->getNumParams() > 1 &&
04783         Constructor->getParamDecl(1)->hasDefaultArg())) &&
04784       Constructor->getTemplateSpecializationKind()
04785                                               != TSK_ImplicitInstantiation) {
04786     QualType ParamType = Constructor->getParamDecl(0)->getType();
04787     QualType ClassTy = Context.getTagDeclType(ClassDecl);
04788     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
04789       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
04790       const char *ConstRef 
04791         = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 
04792                                                         : " const &";
04793       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
04794         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
04795 
04796       // FIXME: Rather that making the constructor invalid, we should endeavor
04797       // to fix the type.
04798       Constructor->setInvalidDecl();
04799     }
04800   }
04801 }
04802 
04803 /// CheckDestructor - Checks a fully-formed destructor definition for
04804 /// well-formedness, issuing any diagnostics required.  Returns true
04805 /// on error.
04806 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
04807   CXXRecordDecl *RD = Destructor->getParent();
04808   
04809   if (Destructor->isVirtual()) {
04810     SourceLocation Loc;
04811     
04812     if (!Destructor->isImplicit())
04813       Loc = Destructor->getLocation();
04814     else
04815       Loc = RD->getLocation();
04816     
04817     // If we have a virtual destructor, look up the deallocation function
04818     FunctionDecl *OperatorDelete = 0;
04819     DeclarationName Name = 
04820     Context.DeclarationNames.getCXXOperatorName(OO_Delete);
04821     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
04822       return true;
04823 
04824     MarkFunctionReferenced(Loc, OperatorDelete);
04825     
04826     Destructor->setOperatorDelete(OperatorDelete);
04827   }
04828   
04829   return false;
04830 }
04831 
04832 static inline bool
04833 FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
04834   return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
04835           FTI.ArgInfo[0].Param &&
04836           cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
04837 }
04838 
04839 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
04840 /// the well-formednes of the destructor declarator @p D with type @p
04841 /// R. If there are any errors in the declarator, this routine will
04842 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
04843 /// will be updated to reflect a well-formed type for the destructor and
04844 /// returned.
04845 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
04846                                          StorageClass& SC) {
04847   // C++ [class.dtor]p1:
04848   //   [...] A typedef-name that names a class is a class-name
04849   //   (7.1.3); however, a typedef-name that names a class shall not
04850   //   be used as the identifier in the declarator for a destructor
04851   //   declaration.
04852   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
04853   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
04854     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
04855       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
04856   else if (const TemplateSpecializationType *TST =
04857              DeclaratorType->getAs<TemplateSpecializationType>())
04858     if (TST->isTypeAlias())
04859       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
04860         << DeclaratorType << 1;
04861 
04862   // C++ [class.dtor]p2:
04863   //   A destructor is used to destroy objects of its class type. A
04864   //   destructor takes no parameters, and no return type can be
04865   //   specified for it (not even void). The address of a destructor
04866   //   shall not be taken. A destructor shall not be static. A
04867   //   destructor can be invoked for a const, volatile or const
04868   //   volatile object. A destructor shall not be declared const,
04869   //   volatile or const volatile (9.3.2).
04870   if (SC == SC_Static) {
04871     if (!D.isInvalidType())
04872       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
04873         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
04874         << SourceRange(D.getIdentifierLoc())
04875         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
04876     
04877     SC = SC_None;
04878   }
04879   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
04880     // Destructors don't have return types, but the parser will
04881     // happily parse something like:
04882     //
04883     //   class X {
04884     //     float ~X();
04885     //   };
04886     //
04887     // The return type will be eliminated later.
04888     Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
04889       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
04890       << SourceRange(D.getIdentifierLoc());
04891   }
04892 
04893   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
04894   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
04895     if (FTI.TypeQuals & Qualifiers::Const)
04896       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
04897         << "const" << SourceRange(D.getIdentifierLoc());
04898     if (FTI.TypeQuals & Qualifiers::Volatile)
04899       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
04900         << "volatile" << SourceRange(D.getIdentifierLoc());
04901     if (FTI.TypeQuals & Qualifiers::Restrict)
04902       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
04903         << "restrict" << SourceRange(D.getIdentifierLoc());
04904     D.setInvalidType();
04905   }
04906 
04907   // C++0x [class.dtor]p2:
04908   //   A destructor shall not be declared with a ref-qualifier.
04909   if (FTI.hasRefQualifier()) {
04910     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
04911       << FTI.RefQualifierIsLValueRef
04912       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
04913     D.setInvalidType();
04914   }
04915   
04916   // Make sure we don't have any parameters.
04917   if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
04918     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
04919 
04920     // Delete the parameters.
04921     FTI.freeArgs();
04922     D.setInvalidType();
04923   }
04924 
04925   // Make sure the destructor isn't variadic.
04926   if (FTI.isVariadic) {
04927     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
04928     D.setInvalidType();
04929   }
04930 
04931   // Rebuild the function type "R" without any type qualifiers or
04932   // parameters (in case any of the errors above fired) and with
04933   // "void" as the return type, since destructors don't have return
04934   // types. 
04935   if (!D.isInvalidType())
04936     return R;
04937 
04938   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
04939   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
04940   EPI.Variadic = false;
04941   EPI.TypeQuals = 0;
04942   EPI.RefQualifier = RQ_None;
04943   return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
04944 }
04945 
04946 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
04947 /// well-formednes of the conversion function declarator @p D with
04948 /// type @p R. If there are any errors in the declarator, this routine
04949 /// will emit diagnostics and return true. Otherwise, it will return
04950 /// false. Either way, the type @p R will be updated to reflect a
04951 /// well-formed type for the conversion operator.
04952 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
04953                                      StorageClass& SC) {
04954   // C++ [class.conv.fct]p1:
04955   //   Neither parameter types nor return type can be specified. The
04956   //   type of a conversion function (8.3.5) is "function taking no
04957   //   parameter returning conversion-type-id."
04958   if (SC == SC_Static) {
04959     if (!D.isInvalidType())
04960       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
04961         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
04962         << SourceRange(D.getIdentifierLoc());
04963     D.setInvalidType();
04964     SC = SC_None;
04965   }
04966 
04967   QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
04968 
04969   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
04970     // Conversion functions don't have return types, but the parser will
04971     // happily parse something like:
04972     //
04973     //   class X {
04974     //     float operator bool();
04975     //   };
04976     //
04977     // The return type will be changed later anyway.
04978     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
04979       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
04980       << SourceRange(D.getIdentifierLoc());
04981     D.setInvalidType();
04982   }
04983 
04984   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
04985 
04986   // Make sure we don't have any parameters.
04987   if (Proto->getNumArgs() > 0) {
04988     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
04989 
04990     // Delete the parameters.
04991     D.getFunctionTypeInfo().freeArgs();
04992     D.setInvalidType();
04993   } else if (Proto->isVariadic()) {
04994     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
04995     D.setInvalidType();
04996   }
04997 
04998   // Diagnose "&operator bool()" and other such nonsense.  This
04999   // is actually a gcc extension which we don't support.
05000   if (Proto->getResultType() != ConvType) {
05001     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
05002       << Proto->getResultType();
05003     D.setInvalidType();
05004     ConvType = Proto->getResultType();
05005   }
05006 
05007   // C++ [class.conv.fct]p4:
05008   //   The conversion-type-id shall not represent a function type nor
05009   //   an array type.
05010   if (ConvType->isArrayType()) {
05011     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
05012     ConvType = Context.getPointerType(ConvType);
05013     D.setInvalidType();
05014   } else if (ConvType->isFunctionType()) {
05015     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
05016     ConvType = Context.getPointerType(ConvType);
05017     D.setInvalidType();
05018   }
05019 
05020   // Rebuild the function type "R" without any parameters (in case any
05021   // of the errors above fired) and with the conversion type as the
05022   // return type.
05023   if (D.isInvalidType())
05024     R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
05025 
05026   // C++0x explicit conversion operators.
05027   if (D.getDeclSpec().isExplicitSpecified())
05028     Diag(D.getDeclSpec().getExplicitSpecLoc(),
05029          getLangOpts().CPlusPlus0x ?
05030            diag::warn_cxx98_compat_explicit_conversion_functions :
05031            diag::ext_explicit_conversion_functions)
05032       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
05033 }
05034 
05035 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
05036 /// the declaration of the given C++ conversion function. This routine
05037 /// is responsible for recording the conversion function in the C++
05038 /// class, if possible.
05039 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
05040   assert(Conversion && "Expected to receive a conversion function declaration");
05041 
05042   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
05043 
05044   // Make sure we aren't redeclaring the conversion function.
05045   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
05046 
05047   // C++ [class.conv.fct]p1:
05048   //   [...] A conversion function is never used to convert a
05049   //   (possibly cv-qualified) object to the (possibly cv-qualified)
05050   //   same object type (or a reference to it), to a (possibly
05051   //   cv-qualified) base class of that type (or a reference to it),
05052   //   or to (possibly cv-qualified) void.
05053   // FIXME: Suppress this warning if the conversion function ends up being a
05054   // virtual function that overrides a virtual function in a base class.
05055   QualType ClassType
05056     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
05057   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
05058     ConvType = ConvTypeRef->getPointeeType();
05059   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
05060       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
05061     /* Suppress diagnostics for instantiations. */;
05062   else if (ConvType->isRecordType()) {
05063     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
05064     if (ConvType == ClassType)
05065       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
05066         << ClassType;
05067     else if (IsDerivedFrom(ClassType, ConvType))
05068       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
05069         <<  ClassType << ConvType;
05070   } else if (ConvType->isVoidType()) {
05071     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
05072       << ClassType << ConvType;
05073   }
05074 
05075   if (FunctionTemplateDecl *ConversionTemplate
05076                                 = Conversion->getDescribedFunctionTemplate())
05077     return ConversionTemplate;
05078   
05079   return Conversion;
05080 }
05081 
05082 //===----------------------------------------------------------------------===//
05083 // Namespace Handling
05084 //===----------------------------------------------------------------------===//
05085 
05086 
05087 
05088 /// ActOnStartNamespaceDef - This is called at the start of a namespace
05089 /// definition.
05090 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
05091                                    SourceLocation InlineLoc,
05092                                    SourceLocation NamespaceLoc,
05093                                    SourceLocation IdentLoc,
05094                                    IdentifierInfo *II,
05095                                    SourceLocation LBrace,
05096                                    AttributeList *AttrList) {
05097   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
05098   // For anonymous namespace, take the location of the left brace.
05099   SourceLocation Loc = II ? IdentLoc : LBrace;
05100   bool IsInline = InlineLoc.isValid();
05101   bool IsInvalid = false;
05102   bool IsStd = false;
05103   bool AddToKnown = false;
05104   Scope *DeclRegionScope = NamespcScope->getParent();
05105 
05106   NamespaceDecl *PrevNS = 0;
05107   if (II) {
05108     // C++ [namespace.def]p2:
05109     //   The identifier in an original-namespace-definition shall not
05110     //   have been previously defined in the declarative region in
05111     //   which the original-namespace-definition appears. The
05112     //   identifier in an original-namespace-definition is the name of
05113     //   the namespace. Subsequently in that declarative region, it is
05114     //   treated as an original-namespace-name.
05115     //
05116     // Since namespace names are unique in their scope, and we don't
05117     // look through using directives, just look for any ordinary names.
05118     
05119     const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 
05120     Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 
05121     Decl::IDNS_Namespace;
05122     NamedDecl *PrevDecl = 0;
05123     for (DeclContext::lookup_result R 
05124          = CurContext->getRedeclContext()->lookup(II);
05125          R.first != R.second; ++R.first) {
05126       if ((*R.first)->getIdentifierNamespace() & IDNS) {
05127         PrevDecl = *R.first;
05128         break;
05129       }
05130     }
05131     
05132     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
05133     
05134     if (PrevNS) {
05135       // This is an extended namespace definition.
05136       if (IsInline != PrevNS->isInline()) {
05137         // inline-ness must match
05138         if (PrevNS->isInline()) {
05139           // The user probably just forgot the 'inline', so suggest that it
05140           // be added back.
05141           Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
05142             << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
05143         } else {
05144           Diag(Loc, diag::err_inline_namespace_mismatch)
05145             << IsInline;
05146         }
05147         Diag(PrevNS->getLocation(), diag::note_previous_definition);
05148         
05149         IsInline = PrevNS->isInline();
05150       }      
05151     } else if (PrevDecl) {
05152       // This is an invalid name redefinition.
05153       Diag(Loc, diag::err_redefinition_different_kind)
05154         << II;
05155       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
05156       IsInvalid = true;
05157       // Continue on to push Namespc as current DeclContext and return it.
05158     } else if (II->isStr("std") &&
05159                CurContext->getRedeclContext()->isTranslationUnit()) {
05160       // This is the first "real" definition of the namespace "std", so update
05161       // our cache of the "std" namespace to point at this definition.
05162       PrevNS = getStdNamespace();
05163       IsStd = true;
05164       AddToKnown = !IsInline;
05165     } else {
05166       // We've seen this namespace for the first time.
05167       AddToKnown = !IsInline;
05168     }
05169   } else {
05170     // Anonymous namespaces.
05171     
05172     // Determine whether the parent already has an anonymous namespace.
05173     DeclContext *Parent = CurContext->getRedeclContext();
05174     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
05175       PrevNS = TU->getAnonymousNamespace();
05176     } else {
05177       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
05178       PrevNS = ND->getAnonymousNamespace();
05179     }
05180 
05181     if (PrevNS && IsInline != PrevNS->isInline()) {
05182       // inline-ness must match
05183       Diag(Loc, diag::err_inline_namespace_mismatch)
05184         << IsInline;
05185       Diag(PrevNS->getLocation(), diag::note_previous_definition);
05186       
05187       // Recover by ignoring the new namespace's inline status.
05188       IsInline = PrevNS->isInline();
05189     }
05190   }
05191   
05192   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
05193                                                  StartLoc, Loc, II, PrevNS);
05194   if (IsInvalid)
05195     Namespc->setInvalidDecl();
05196   
05197   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
05198 
05199   // FIXME: Should we be merging attributes?
05200   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
05201     PushNamespaceVisibilityAttr(Attr, Loc);
05202 
05203   if (IsStd)
05204     StdNamespace = Namespc;
05205   if (AddToKnown)
05206     KnownNamespaces[Namespc] = false;
05207   
05208   if (II) {
05209     PushOnScopeChains(Namespc, DeclRegionScope);
05210   } else {
05211     // Link the anonymous namespace into its parent.
05212     DeclContext *Parent = CurContext->getRedeclContext();
05213     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
05214       TU->setAnonymousNamespace(Namespc);
05215     } else {
05216       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
05217     }
05218 
05219     CurContext->addDecl(Namespc);
05220 
05221     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
05222     //   behaves as if it were replaced by
05223     //     namespace unique { /* empty body */ }
05224     //     using namespace unique;
05225     //     namespace unique { namespace-body }
05226     //   where all occurrences of 'unique' in a translation unit are
05227     //   replaced by the same identifier and this identifier differs
05228     //   from all other identifiers in the entire program.
05229 
05230     // We just create the namespace with an empty name and then add an
05231     // implicit using declaration, just like the standard suggests.
05232     //
05233     // CodeGen enforces the "universally unique" aspect by giving all
05234     // declarations semantically contained within an anonymous
05235     // namespace internal linkage.
05236 
05237     if (!PrevNS) {
05238       UsingDirectiveDecl* UD
05239         = UsingDirectiveDecl::Create(Context, CurContext,
05240                                      /* 'using' */ LBrace,
05241                                      /* 'namespace' */ SourceLocation(),
05242                                      /* qualifier */ NestedNameSpecifierLoc(),
05243                                      /* identifier */ SourceLocation(),
05244                                      Namespc,
05245                                      /* Ancestor */ CurContext);
05246       UD->setImplicit();
05247       CurContext->addDecl(UD);
05248     }
05249   }
05250 
05251   // Although we could have an invalid decl (i.e. the namespace name is a
05252   // redefinition), push it as current DeclContext and try to continue parsing.
05253   // FIXME: We should be able to push Namespc here, so that the each DeclContext
05254   // for the namespace has the declarations that showed up in that particular
05255   // namespace definition.
05256   PushDeclContext(NamespcScope, Namespc);
05257   return Namespc;
05258 }
05259 
05260 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
05261 /// is a namespace alias, returns the namespace it points to.
05262 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
05263   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
05264     return AD->getNamespace();
05265   return dyn_cast_or_null<NamespaceDecl>(D);
05266 }
05267 
05268 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
05269 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
05270 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
05271   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
05272   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
05273   Namespc->setRBraceLoc(RBrace);
05274   PopDeclContext();
05275   if (Namespc->hasAttr<VisibilityAttr>())
05276     PopPragmaVisibility(true, RBrace);
05277 }
05278 
05279 CXXRecordDecl *Sema::getStdBadAlloc() const {
05280   return cast_or_null<CXXRecordDecl>(
05281                                   StdBadAlloc.get(Context.getExternalSource()));
05282 }
05283 
05284 NamespaceDecl *Sema::getStdNamespace() const {
05285   return cast_or_null<NamespaceDecl>(
05286                                  StdNamespace.get(Context.getExternalSource()));
05287 }
05288 
05289 /// \brief Retrieve the special "std" namespace, which may require us to 
05290 /// implicitly define the namespace.
05291 NamespaceDecl *Sema::getOrCreateStdNamespace() {
05292   if (!StdNamespace) {
05293     // The "std" namespace has not yet been defined, so build one implicitly.
05294     StdNamespace = NamespaceDecl::Create(Context, 
05295                                          Context.getTranslationUnitDecl(),
05296                                          /*Inline=*/false,
05297                                          SourceLocation(), SourceLocation(),
05298                                          &PP.getIdentifierTable().get("std"),
05299                                          /*PrevDecl=*/0);
05300     getStdNamespace()->setImplicit(true);
05301   }
05302   
05303   return getStdNamespace();
05304 }
05305 
05306 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
05307   assert(getLangOpts().CPlusPlus &&
05308          "Looking for std::initializer_list outside of C++.");
05309 
05310   // We're looking for implicit instantiations of
05311   // template <typename E> class std::initializer_list.
05312 
05313   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
05314     return false;
05315 
05316   ClassTemplateDecl *Template = 0;
05317   const TemplateArgument *Arguments = 0;
05318 
05319   if (const RecordType *RT = Ty->getAs<RecordType>()) {
05320 
05321     ClassTemplateSpecializationDecl *Specialization =
05322         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
05323     if (!Specialization)
05324       return false;
05325 
05326     Template = Specialization->getSpecializedTemplate();
05327     Arguments = Specialization->getTemplateArgs().data();
05328   } else if (const TemplateSpecializationType *TST =
05329                  Ty->getAs<TemplateSpecializationType>()) {
05330     Template = dyn_cast_or_null<ClassTemplateDecl>(
05331         TST->getTemplateName().getAsTemplateDecl());
05332     Arguments = TST->getArgs();
05333   }
05334   if (!Template)
05335     return false;
05336 
05337   if (!StdInitializerList) {
05338     // Haven't recognized std::initializer_list yet, maybe this is it.
05339     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
05340     if (TemplateClass->getIdentifier() !=
05341             &PP.getIdentifierTable().get("initializer_list") ||
05342         !getStdNamespace()->InEnclosingNamespaceSetOf(
05343             TemplateClass->getDeclContext()))
05344       return false;
05345     // This is a template called std::initializer_list, but is it the right
05346     // template?
05347     TemplateParameterList *Params = Template->getTemplateParameters();
05348     if (Params->getMinRequiredArguments() != 1)
05349       return false;
05350     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
05351       return false;
05352 
05353     // It's the right template.
05354     StdInitializerList = Template;
05355   }
05356 
05357   if (Template != StdInitializerList)
05358     return false;
05359 
05360   // This is an instance of std::initializer_list. Find the argument type.
05361   if (Element)
05362     *Element = Arguments[0].getAsType();
05363   return true;
05364 }
05365 
05366 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
05367   NamespaceDecl *Std = S.getStdNamespace();
05368   if (!Std) {
05369     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
05370     return 0;
05371   }
05372 
05373   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
05374                       Loc, Sema::LookupOrdinaryName);
05375   if (!S.LookupQualifiedName(Result, Std)) {
05376     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
05377     return 0;
05378   }
05379   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
05380   if (!Template) {
05381     Result.suppressDiagnostics();
05382     // We found something weird. Complain about the first thing we found.
05383     NamedDecl *Found = *Result.begin();
05384     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
05385     return 0;
05386   }
05387 
05388   // We found some template called std::initializer_list. Now verify that it's
05389   // correct.
05390   TemplateParameterList *Params = Template->getTemplateParameters();
05391   if (Params->getMinRequiredArguments() != 1 ||
05392       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
05393     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
05394     return 0;
05395   }
05396 
05397   return Template;
05398 }
05399 
05400 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
05401   if (!StdInitializerList) {
05402     StdInitializerList = LookupStdInitializerList(*this, Loc);
05403     if (!StdInitializerList)
05404       return QualType();
05405   }
05406 
05407   TemplateArgumentListInfo Args(Loc, Loc);
05408   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
05409                                        Context.getTrivialTypeSourceInfo(Element,
05410                                                                         Loc)));
05411   return Context.getCanonicalType(
05412       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
05413 }
05414 
05415 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
05416   // C++ [dcl.init.list]p2:
05417   //   A constructor is an initializer-list constructor if its first parameter
05418   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
05419   //   std::initializer_list<E> for some type E, and either there are no other
05420   //   parameters or else all other parameters have default arguments.
05421   if (Ctor->getNumParams() < 1 ||
05422       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
05423     return false;
05424 
05425   QualType ArgType = Ctor->getParamDecl(0)->getType();
05426   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
05427     ArgType = RT->getPointeeType().getUnqualifiedType();
05428 
05429   return isStdInitializerList(ArgType, 0);
05430 }
05431 
05432 /// \brief Determine whether a using statement is in a context where it will be
05433 /// apply in all contexts.
05434 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
05435   switch (CurContext->getDeclKind()) {
05436     case Decl::TranslationUnit:
05437       return true;
05438     case Decl::LinkageSpec:
05439       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
05440     default:
05441       return false;
05442   }
05443 }
05444 
05445 namespace {
05446 
05447 // Callback to only accept typo corrections that are namespaces.
05448 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
05449  public:
05450   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
05451     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
05452       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
05453     }
05454     return false;
05455   }
05456 };
05457 
05458 }
05459 
05460 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
05461                                        CXXScopeSpec &SS,
05462                                        SourceLocation IdentLoc,
05463                                        IdentifierInfo *Ident) {
05464   NamespaceValidatorCCC Validator;
05465   R.clear();
05466   if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
05467                                                R.getLookupKind(), Sc, &SS,
05468                                                Validator)) {
05469     std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
05470     std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
05471     if (DeclContext *DC = S.computeDeclContext(SS, false))
05472       S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
05473         << Ident << DC << CorrectedQuotedStr << SS.getRange()
05474         << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
05475     else
05476       S.Diag(IdentLoc, diag::err_using_directive_suggest)
05477         << Ident << CorrectedQuotedStr
05478         << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
05479 
05480     S.Diag(Corrected.getCorrectionDecl()->getLocation(),
05481          diag::note_namespace_defined_here) << CorrectedQuotedStr;
05482 
05483     R.addDecl(Corrected.getCorrectionDecl());
05484     return true;
05485   }
05486   return false;
05487 }
05488 
05489 Decl *Sema::ActOnUsingDirective(Scope *S,
05490                                           SourceLocation UsingLoc,
05491                                           SourceLocation NamespcLoc,
05492                                           CXXScopeSpec &SS,
05493                                           SourceLocation IdentLoc,
05494                                           IdentifierInfo *NamespcName,
05495                                           AttributeList *AttrList) {
05496   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
05497   assert(NamespcName && "Invalid NamespcName.");
05498   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
05499 
05500   // This can only happen along a recovery path.
05501   while (S->getFlags() & Scope::TemplateParamScope)
05502     S = S->getParent();
05503   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
05504 
05505   UsingDirectiveDecl *UDir = 0;
05506   NestedNameSpecifier *Qualifier = 0;
05507   if (SS.isSet())
05508     Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
05509   
05510   // Lookup namespace name.
05511   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
05512   LookupParsedName(R, S, &SS);
05513   if (R.isAmbiguous())
05514     return 0;
05515 
05516   if (R.empty()) {
05517     R.clear();
05518     // Allow "using namespace std;" or "using namespace ::std;" even if 
05519     // "std" hasn't been defined yet, for GCC compatibility.
05520     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
05521         NamespcName->isStr("std")) {
05522       Diag(IdentLoc, diag::ext_using_undefined_std);
05523       R.addDecl(getOrCreateStdNamespace());
05524       R.resolveKind();
05525     } 
05526     // Otherwise, attempt typo correction.
05527     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
05528   }
05529   
05530   if (!R.empty()) {
05531     NamedDecl *Named = R.getFoundDecl();
05532     assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
05533         && "expected namespace decl");
05534     // C++ [namespace.udir]p1:
05535     //   A using-directive specifies that the names in the nominated
05536     //   namespace can be used in the scope in which the
05537     //   using-directive appears after the using-directive. During
05538     //   unqualified name lookup (3.4.1), the names appear as if they
05539     //   were declared in the nearest enclosing namespace which
05540     //   contains both the using-directive and the nominated
05541     //   namespace. [Note: in this context, "contains" means "contains
05542     //   directly or indirectly". ]
05543 
05544     // Find enclosing context containing both using-directive and
05545     // nominated namespace.
05546     NamespaceDecl *NS = getNamespaceDecl(Named);
05547     DeclContext *CommonAncestor = cast<DeclContext>(NS);
05548     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
05549       CommonAncestor = CommonAncestor->getParent();
05550 
05551     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
05552                                       SS.getWithLocInContext(Context),
05553                                       IdentLoc, Named, CommonAncestor);
05554 
05555     if (IsUsingDirectiveInToplevelContext(CurContext) &&
05556         !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
05557       Diag(IdentLoc, diag::warn_using_directive_in_header);
05558     }
05559 
05560     PushUsingDirective(S, UDir);
05561   } else {
05562     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
05563   }
05564 
05565   // FIXME: We ignore attributes for now.
05566   return UDir;
05567 }
05568 
05569 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
05570   // If the scope has an associated entity and the using directive is at
05571   // namespace or translation unit scope, add the UsingDirectiveDecl into
05572   // its lookup structure so qualified name lookup can find it.
05573   DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
05574   if (Ctx && !Ctx->isFunctionOrMethod())
05575     Ctx->addDecl(UDir);
05576   else
05577     // Otherwise, it is at block sope. The using-directives will affect lookup
05578     // only to the end of the scope.
05579     S->PushUsingDirective(UDir);
05580 }
05581 
05582 
05583 Decl *Sema::ActOnUsingDeclaration(Scope *S,
05584                                   AccessSpecifier AS,
05585                                   bool HasUsingKeyword,
05586                                   SourceLocation UsingLoc,
05587                                   CXXScopeSpec &SS,
05588                                   UnqualifiedId &Name,
05589                                   AttributeList *AttrList,
05590                                   bool IsTypeName,
05591                                   SourceLocation TypenameLoc) {
05592   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
05593 
05594   switch (Name.getKind()) {
05595   case UnqualifiedId::IK_ImplicitSelfParam:
05596   case UnqualifiedId::IK_Identifier:
05597   case UnqualifiedId::IK_OperatorFunctionId:
05598   case UnqualifiedId::IK_LiteralOperatorId:
05599   case UnqualifiedId::IK_ConversionFunctionId:
05600     break;
05601       
05602   case UnqualifiedId::IK_ConstructorName:
05603   case UnqualifiedId::IK_ConstructorTemplateId:
05604     // C++11 inheriting constructors.
05605     Diag(Name.getLocStart(),
05606          getLangOpts().CPlusPlus0x ?
05607            // FIXME: Produce warn_cxx98_compat_using_decl_constructor
05608            //        instead once inheriting constructors work.
05609            diag::err_using_decl_constructor_unsupported :
05610            diag::err_using_decl_constructor)
05611       << SS.getRange();
05612 
05613     if (getLangOpts().CPlusPlus0x) break;
05614 
05615     return 0;
05616       
05617   case UnqualifiedId::IK_DestructorName:
05618     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
05619       << SS.getRange();
05620     return 0;
05621       
05622   case UnqualifiedId::IK_TemplateId:
05623     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
05624       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
05625     return 0;
05626   }
05627 
05628   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
05629   DeclarationName TargetName = TargetNameInfo.getName();
05630   if (!TargetName)
05631     return 0;
05632 
05633   // Warn about using declarations.
05634   // TODO: store that the declaration was written without 'using' and
05635   // talk about access decls instead of using decls in the
05636   // diagnostics.
05637   if (!HasUsingKeyword) {
05638     UsingLoc = Name.getLocStart();
05639     
05640     Diag(UsingLoc, diag::warn_access_decl_deprecated)
05641       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
05642   }
05643 
05644   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
05645       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
05646     return 0;
05647 
05648   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
05649                                         TargetNameInfo, AttrList,
05650                                         /* IsInstantiation */ false,
05651                                         IsTypeName, TypenameLoc);
05652   if (UD)
05653     PushOnScopeChains(UD, S, /*AddToContext*/ false);
05654 
05655   return UD;
05656 }
05657 
05658 /// \brief Determine whether a using declaration considers the given
05659 /// declarations as "equivalent", e.g., if they are redeclarations of
05660 /// the same entity or are both typedefs of the same type.
05661 static bool 
05662 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
05663                          bool &SuppressRedeclaration) {
05664   if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
05665     SuppressRedeclaration = false;
05666     return true;
05667   }
05668 
05669   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
05670     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
05671       SuppressRedeclaration = true;
05672       return Context.hasSameType(TD1->getUnderlyingType(),
05673                                  TD2->getUnderlyingType());
05674     }
05675 
05676   return false;
05677 }
05678 
05679 
05680 /// Determines whether to create a using shadow decl for a particular
05681 /// decl, given the set of decls existing prior to this using lookup.
05682 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
05683                                 const LookupResult &Previous) {
05684   // Diagnose finding a decl which is not from a base class of the
05685   // current class.  We do this now because there are cases where this
05686   // function will silently decide not to build a shadow decl, which
05687   // will pre-empt further diagnostics.
05688   //
05689   // We don't need to do this in C++0x because we do the check once on
05690   // the qualifier.
05691   //
05692   // FIXME: diagnose the following if we care enough:
05693   //   struct A { int foo; };
05694   //   struct B : A { using A::foo; };
05695   //   template <class T> struct C : A {};
05696   //   template <class T> struct D : C<T> { using B::foo; } // <---
05697   // This is invalid (during instantiation) in C++03 because B::foo
05698   // resolves to the using decl in B, which is not a base class of D<T>.
05699   // We can't diagnose it immediately because C<T> is an unknown
05700   // specialization.  The UsingShadowDecl in D<T> then points directly
05701   // to A::foo, which will look well-formed when we instantiate.
05702   // The right solution is to not collapse the shadow-decl chain.
05703   if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
05704     DeclContext *OrigDC = Orig->getDeclContext();
05705 
05706     // Handle enums and anonymous structs.
05707     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
05708     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
05709     while (OrigRec->isAnonymousStructOrUnion())
05710       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
05711 
05712     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
05713       if (OrigDC == CurContext) {
05714         Diag(Using->getLocation(),
05715              diag::err_using_decl_nested_name_specifier_is_current_class)
05716           << Using->getQualifierLoc().getSourceRange();
05717         Diag(Orig->getLocation(), diag::note_using_decl_target);
05718         return true;
05719       }
05720 
05721       Diag(Using->getQualifierLoc().getBeginLoc(),
05722            diag::err_using_decl_nested_name_specifier_is_not_base_class)
05723         << Using->getQualifier()
05724         << cast<CXXRecordDecl>(CurContext)
05725         << Using->getQualifierLoc().getSourceRange();
05726       Diag(Orig->getLocation(), diag::note_using_decl_target);
05727       return true;
05728     }
05729   }
05730 
05731   if (Previous.empty()) return false;
05732 
05733   NamedDecl *Target = Orig;
05734   if (isa<UsingShadowDecl>(Target))
05735     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
05736 
05737   // If the target happens to be one of the previous declarations, we
05738   // don't have a conflict.
05739   // 
05740   // FIXME: but we might be increasing its access, in which case we
05741   // should redeclare it.
05742   NamedDecl *NonTag = 0, *Tag = 0;
05743   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
05744          I != E; ++I) {
05745     NamedDecl *D = (*I)->getUnderlyingDecl();
05746     bool Result;
05747     if (IsEquivalentForUsingDecl(Context, D, Target, Result))
05748       return Result;
05749 
05750     (isa<TagDecl>(D) ? Tag : NonTag) = D;
05751   }
05752 
05753   if (Target->isFunctionOrFunctionTemplate()) {
05754     FunctionDecl *FD;
05755     if (isa<FunctionTemplateDecl>(Target))
05756       FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
05757     else
05758       FD = cast<FunctionDecl>(Target);
05759 
05760     NamedDecl *OldDecl = 0;
05761     switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
05762     case Ovl_Overload:
05763       return false;
05764 
05765     case Ovl_NonFunction:
05766       Diag(Using->getLocation(), diag::err_using_decl_conflict);
05767       break;
05768       
05769     // We found a decl with the exact signature.
05770     case Ovl_Match:
05771       // If we're in a record, we want to hide the target, so we
05772       // return true (without a diagnostic) to tell the caller not to
05773       // build a shadow decl.
05774       if (CurContext->isRecord())
05775         return true;
05776 
05777       // If we're not in a record, this is an error.
05778       Diag(Using->getLocation(), diag::err_using_decl_conflict);
05779       break;
05780     }
05781 
05782     Diag(Target->getLocation(), diag::note_using_decl_target);
05783     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
05784     return true;
05785   }
05786 
05787   // Target is not a function.
05788 
05789   if (isa<TagDecl>(Target)) {
05790     // No conflict between a tag and a non-tag.
05791     if (!Tag) return false;
05792 
05793     Diag(Using->getLocation(), diag::err_using_decl_conflict);
05794     Diag(Target->getLocation(), diag::note_using_decl_target);
05795     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
05796     return true;
05797   }
05798 
05799   // No conflict between a tag and a non-tag.
05800   if (!NonTag) return false;
05801 
05802   Diag(Using->getLocation(), diag::err_using_decl_conflict);
05803   Diag(Target->getLocation(), diag::note_using_decl_target);
05804   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
05805   return true;
05806 }
05807 
05808 /// Builds a shadow declaration corresponding to a 'using' declaration.
05809 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
05810                                             UsingDecl *UD,
05811                                             NamedDecl *Orig) {
05812 
05813   // If we resolved to another shadow declaration, just coalesce them.
05814   NamedDecl *Target = Orig;
05815   if (isa<UsingShadowDecl>(Target)) {
05816     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
05817     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
05818   }
05819   
05820   UsingShadowDecl *Shadow
05821     = UsingShadowDecl::Create(Context, CurContext,
05822                               UD->getLocation(), UD, Target);
05823   UD->addShadowDecl(Shadow);
05824   
05825   Shadow->setAccess(UD->getAccess());
05826   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
05827     Shadow->setInvalidDecl();
05828   
05829   if (S)
05830     PushOnScopeChains(Shadow, S);
05831   else
05832     CurContext->addDecl(Shadow);
05833 
05834 
05835   return Shadow;
05836 }
05837 
05838 /// Hides a using shadow declaration.  This is required by the current
05839 /// using-decl implementation when a resolvable using declaration in a
05840 /// class is followed by a declaration which would hide or override
05841 /// one or more of the using decl's targets; for example:
05842 ///
05843 ///   struct Base { void foo(int); };
05844 ///   struct Derived : Base {
05845 ///     using Base::foo;
05846 ///     void foo(int);
05847 ///   };
05848 ///
05849 /// The governing language is C++03 [namespace.udecl]p12:
05850 ///
05851 ///   When a using-declaration brings names from a base class into a
05852 ///   derived class scope, member functions in the derived class
05853 ///   override and/or hide member functions with the same name and
05854 ///   parameter types in a base class (rather than conflicting).
05855 ///
05856 /// There are two ways to implement this:
05857 ///   (1) optimistically create shadow decls when they're not hidden
05858 ///       by existing declarations, or
05859 ///   (2) don't create any shadow decls (or at least don't make them
05860 ///       visible) until we've fully parsed/instantiated the class.
05861 /// The problem with (1) is that we might have to retroactively remove
05862 /// a shadow decl, which requires several O(n) operations because the
05863 /// decl structures are (very reasonably) not designed for removal.
05864 /// (2) avoids this but is very fiddly and phase-dependent.
05865 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
05866   if (Shadow->getDeclName().getNameKind() ==
05867         DeclarationName::CXXConversionFunctionName)
05868     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
05869 
05870   // Remove it from the DeclContext...
05871   Shadow->getDeclContext()->removeDecl(Shadow);
05872 
05873   // ...and the scope, if applicable...
05874   if (S) {
05875     S->RemoveDecl(Shadow);
05876     IdResolver.RemoveDecl(Shadow);
05877   }
05878 
05879   // ...and the using decl.
05880   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
05881 
05882   // TODO: complain somehow if Shadow was used.  It shouldn't
05883   // be possible for this to happen, because...?
05884 }
05885 
05886 /// Builds a using declaration.
05887 ///
05888 /// \param IsInstantiation - Whether this call arises from an
05889 ///   instantiation of an unresolved using declaration.  We treat
05890 ///   the lookup differently for these declarations.
05891 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
05892                                        SourceLocation UsingLoc,
05893                                        CXXScopeSpec &SS,
05894                                        const DeclarationNameInfo &NameInfo,
05895                                        AttributeList *AttrList,
05896                                        bool IsInstantiation,
05897                                        bool IsTypeName,
05898                                        SourceLocation TypenameLoc) {
05899   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
05900   SourceLocation IdentLoc = NameInfo.getLoc();
05901   assert(IdentLoc.isValid() && "Invalid TargetName location.");
05902 
05903   // FIXME: We ignore attributes for now.
05904 
05905   if (SS.isEmpty()) {
05906     Diag(IdentLoc, diag::err_using_requires_qualname);
05907     return 0;
05908   }
05909 
05910   // Do the redeclaration lookup in the current scope.
05911   LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
05912                         ForRedeclaration);
05913   Previous.setHideTags(false);
05914   if (S) {
05915     LookupName(Previous, S);
05916 
05917     // It is really dumb that we have to do this.
05918     LookupResult::Filter F = Previous.makeFilter();
05919     while (F.hasNext()) {
05920       NamedDecl *D = F.next();
05921       if (!isDeclInScope(D, CurContext, S))
05922         F.erase();
05923     }
05924     F.done();
05925   } else {
05926     assert(IsInstantiation && "no scope in non-instantiation");
05927     assert(CurContext->isRecord() && "scope not record in instantiation");
05928     LookupQualifiedName(Previous, CurContext);
05929   }
05930 
05931   // Check for invalid redeclarations.
05932   if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
05933     return 0;
05934 
05935   // Check for bad qualifiers.
05936   if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
05937     return 0;
05938 
05939   DeclContext *LookupContext = computeDeclContext(SS);
05940   NamedDecl *D;
05941   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
05942   if (!LookupContext) {
05943     if (IsTypeName) {
05944       // FIXME: not all declaration name kinds are legal here
05945       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
05946                                               UsingLoc, TypenameLoc,
05947                                               QualifierLoc,
05948                                               IdentLoc, NameInfo.getName());
05949     } else {
05950       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 
05951                                            QualifierLoc, NameInfo);
05952     }
05953   } else {
05954     D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
05955                           NameInfo, IsTypeName);
05956   }
05957   D->setAccess(AS);
05958   CurContext->addDecl(D);
05959 
05960   if (!LookupContext) return D;
05961   UsingDecl *UD = cast<UsingDecl>(D);
05962 
05963   if (RequireCompleteDeclContext(SS, LookupContext)) {
05964     UD->setInvalidDecl();
05965     return UD;
05966   }
05967 
05968   // The normal rules do not apply to inheriting constructor declarations.
05969   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
05970     if (CheckInheritingConstructorUsingDecl(UD))
05971       UD->setInvalidDecl();
05972     return UD;
05973   }
05974 
05975   // Otherwise, look up the target name.
05976 
05977   LookupResult R(*this, NameInfo, LookupOrdinaryName);
05978 
05979   // Unlike most lookups, we don't always want to hide tag
05980   // declarations: tag names are visible through the using declaration
05981   // even if hidden by ordinary names, *except* in a dependent context
05982   // where it's important for the sanity of two-phase lookup.
05983   if (!IsInstantiation)
05984     R.setHideTags(false);
05985 
05986   // For the purposes of this lookup, we have a base object type
05987   // equal to that of the current context.
05988   if (CurContext->isRecord()) {
05989     R.setBaseObjectType(
05990                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
05991   }
05992 
05993   LookupQualifiedName(R, LookupContext);
05994 
05995   if (R.empty()) {
05996     Diag(IdentLoc, diag::err_no_member) 
05997       << NameInfo.getName() << LookupContext << SS.getRange();
05998     UD->setInvalidDecl();
05999     return UD;
06000   }
06001 
06002   if (R.isAmbiguous()) {
06003     UD->setInvalidDecl();
06004     return UD;
06005   }
06006 
06007   if (IsTypeName) {
06008     // If we asked for a typename and got a non-type decl, error out.
06009     if (!R.getAsSingle<TypeDecl>()) {
06010       Diag(IdentLoc, diag::err_using_typename_non_type);
06011       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
06012         Diag((*I)->getUnderlyingDecl()->getLocation(),
06013              diag::note_using_decl_target);
06014       UD->setInvalidDecl();
06015       return UD;
06016     }
06017   } else {
06018     // If we asked for a non-typename and we got a type, error out,
06019     // but only if this is an instantiation of an unresolved using
06020     // decl.  Otherwise just silently find the type name.
06021     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
06022       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
06023       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
06024       UD->setInvalidDecl();
06025       return UD;
06026     }
06027   }
06028 
06029   // C++0x N2914 [namespace.udecl]p6:
06030   // A using-declaration shall not name a namespace.
06031   if (R.getAsSingle<NamespaceDecl>()) {
06032     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
06033       << SS.getRange();
06034     UD->setInvalidDecl();
06035     return UD;
06036   }
06037 
06038   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
06039     if (!CheckUsingShadowDecl(UD, *I, Previous))
06040       BuildUsingShadowDecl(S, UD, *I);
06041   }
06042 
06043   return UD;
06044 }
06045 
06046 /// Additional checks for a using declaration referring to a constructor name.
06047 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
06048   assert(!UD->isTypeName() && "expecting a constructor name");
06049 
06050   const Type *SourceType = UD->getQualifier()->getAsType();
06051   assert(SourceType &&
06052          "Using decl naming constructor doesn't have type in scope spec.");
06053   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
06054 
06055   // Check whether the named type is a direct base class.
06056   CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
06057   CXXRecordDecl::base_class_iterator BaseIt, BaseE;
06058   for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
06059        BaseIt != BaseE; ++BaseIt) {
06060     CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
06061     if (CanonicalSourceType == BaseType)
06062       break;
06063     if (BaseIt->getType()->isDependentType())
06064       break;
06065   }
06066 
06067   if (BaseIt == BaseE) {
06068     // Did not find SourceType in the bases.
06069     Diag(UD->getUsingLocation(),
06070          diag::err_using_decl_constructor_not_in_direct_base)
06071       << UD->getNameInfo().getSourceRange()
06072       << QualType(SourceType, 0) << TargetClass;
06073     return true;
06074   }
06075 
06076   if (!CurContext->isDependentContext())
06077     BaseIt->setInheritConstructors();
06078 
06079   return false;
06080 }
06081 
06082 /// Checks that the given using declaration is not an invalid
06083 /// redeclaration.  Note that this is checking only for the using decl
06084 /// itself, not for any ill-formedness among the UsingShadowDecls.
06085 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
06086                                        bool isTypeName,
06087                                        const CXXScopeSpec &SS,
06088                                        SourceLocation NameLoc,
06089                                        const LookupResult &Prev) {
06090   // C++03 [namespace.udecl]p8:
06091   // C++0x [namespace.udecl]p10:
06092   //   A using-declaration is a declaration and can therefore be used
06093   //   repeatedly where (and only where) multiple declarations are
06094   //   allowed.
06095   //
06096   // That's in non-member contexts.
06097   if (!CurContext->getRedeclContext()->isRecord())
06098     return false;
06099 
06100   NestedNameSpecifier *Qual
06101     = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
06102 
06103   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
06104     NamedDecl *D = *I;
06105 
06106     bool DTypename;
06107     NestedNameSpecifier *DQual;
06108     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
06109       DTypename = UD->isTypeName();
06110       DQual = UD->getQualifier();
06111     } else if (UnresolvedUsingValueDecl *UD
06112                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
06113       DTypename = false;
06114       DQual = UD->getQualifier();
06115     } else if (UnresolvedUsingTypenameDecl *UD
06116                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
06117       DTypename = true;
06118       DQual = UD->getQualifier();
06119     } else continue;
06120 
06121     // using decls differ if one says 'typename' and the other doesn't.
06122     // FIXME: non-dependent using decls?
06123     if (isTypeName != DTypename) continue;
06124 
06125     // using decls differ if they name different scopes (but note that
06126     // template instantiation can cause this check to trigger when it
06127     // didn't before instantiation).
06128     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
06129         Context.getCanonicalNestedNameSpecifier(DQual))
06130       continue;
06131 
06132     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
06133     Diag(D->getLocation(), diag::note_using_decl) << 1;
06134     return true;
06135   }
06136 
06137   return false;
06138 }
06139 
06140 
06141 /// Checks that the given nested-name qualifier used in a using decl
06142 /// in the current context is appropriately related to the current
06143 /// scope.  If an error is found, diagnoses it and returns true.
06144 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
06145                                    const CXXScopeSpec &SS,
06146                                    SourceLocation NameLoc) {
06147   DeclContext *NamedContext = computeDeclContext(SS);
06148 
06149   if (!CurContext->isRecord()) {
06150     // C++03 [namespace.udecl]p3:
06151     // C++0x [namespace.udecl]p8:
06152     //   A using-declaration for a class member shall be a member-declaration.
06153 
06154     // If we weren't able to compute a valid scope, it must be a
06155     // dependent class scope.
06156     if (!NamedContext || NamedContext->isRecord()) {
06157       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
06158         << SS.getRange();
06159       return true;
06160     }
06161 
06162     // Otherwise, everything is known to be fine.
06163     return false;
06164   }
06165 
06166   // The current scope is a record.
06167 
06168   // If the named context is dependent, we can't decide much.
06169   if (!NamedContext) {
06170     // FIXME: in C++0x, we can diagnose if we can prove that the
06171     // nested-name-specifier does not refer to a base class, which is
06172     // still possible in some cases.
06173 
06174     // Otherwise we have to conservatively report that things might be
06175     // okay.
06176     return false;
06177   }
06178 
06179   if (!NamedContext->isRecord()) {
06180     // Ideally this would point at the last name in the specifier,
06181     // but we don't have that level of source info.
06182     Diag(SS.getRange().getBegin(),
06183          diag::err_using_decl_nested_name_specifier_is_not_class)
06184       << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
06185     return true;
06186   }
06187 
06188   if (!NamedContext->isDependentContext() &&
06189       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
06190     return true;
06191 
06192   if (getLangOpts().CPlusPlus0x) {
06193     // C++0x [namespace.udecl]p3:
06194     //   In a using-declaration used as a member-declaration, the
06195     //   nested-name-specifier shall name a base class of the class
06196     //   being defined.
06197 
06198     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
06199                                  cast<CXXRecordDecl>(NamedContext))) {
06200       if (CurContext == NamedContext) {
06201         Diag(NameLoc,
06202              diag::err_using_decl_nested_name_specifier_is_current_class)
06203           << SS.getRange();
06204         return true;
06205       }
06206 
06207       Diag(SS.getRange().getBegin(),
06208            diag::err_using_decl_nested_name_specifier_is_not_base_class)
06209         << (NestedNameSpecifier*) SS.getScopeRep()
06210         << cast<CXXRecordDecl>(CurContext)
06211         << SS.getRange();
06212       return true;
06213     }
06214 
06215     return false;
06216   }
06217 
06218   // C++03 [namespace.udecl]p4:
06219   //   A using-declaration used as a member-declaration shall refer
06220   //   to a member of a base class of the class being defined [etc.].
06221 
06222   // Salient point: SS doesn't have to name a base class as long as
06223   // lookup only finds members from base classes.  Therefore we can
06224   // diagnose here only if we can prove that that can't happen,
06225   // i.e. if the class hierarchies provably don't intersect.
06226 
06227   // TODO: it would be nice if "definitely valid" results were cached
06228   // in the UsingDecl and UsingShadowDecl so that these checks didn't
06229   // need to be repeated.
06230 
06231   struct UserData {
06232     llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
06233 
06234     static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
06235       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
06236       Data->Bases.insert(Base);
06237       return true;
06238     }
06239 
06240     bool hasDependentBases(const CXXRecordDecl *Class) {
06241       return !Class->forallBases(collect, this);
06242     }
06243 
06244     /// Returns true if the base is dependent or is one of the
06245     /// accumulated base classes.
06246     static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
06247       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
06248       return !Data->Bases.count(Base);
06249     }
06250 
06251     bool mightShareBases(const CXXRecordDecl *Class) {
06252       return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
06253     }
06254   };
06255 
06256   UserData Data;
06257 
06258   // Returns false if we find a dependent base.
06259   if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
06260     return false;
06261 
06262   // Returns false if the class has a dependent base or if it or one
06263   // of its bases is present in the base set of the current context.
06264   if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
06265     return false;
06266 
06267   Diag(SS.getRange().getBegin(),
06268        diag::err_using_decl_nested_name_specifier_is_not_base_class)
06269     << (NestedNameSpecifier*) SS.getScopeRep()
06270     << cast<CXXRecordDecl>(CurContext)
06271     << SS.getRange();
06272 
06273   return true;
06274 }
06275 
06276 Decl *Sema::ActOnAliasDeclaration(Scope *S,
06277                                   AccessSpecifier AS,
06278                                   MultiTemplateParamsArg TemplateParamLists,
06279                                   SourceLocation UsingLoc,
06280                                   UnqualifiedId &Name,
06281                                   TypeResult Type) {
06282   // Skip up to the relevant declaration scope.
06283   while (S->getFlags() & Scope::TemplateParamScope)
06284     S = S->getParent();
06285   assert((S->getFlags() & Scope::DeclScope) &&
06286          "got alias-declaration outside of declaration scope");
06287 
06288   if (Type.isInvalid())
06289     return 0;
06290 
06291   bool Invalid = false;
06292   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
06293   TypeSourceInfo *TInfo = 0;
06294   GetTypeFromParser(Type.get(), &TInfo);
06295 
06296   if (DiagnoseClassNameShadow(CurContext, NameInfo))
06297     return 0;
06298 
06299   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
06300                                       UPPC_DeclarationType)) {
06301     Invalid = true;
06302     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 
06303                                              TInfo->getTypeLoc().getBeginLoc());
06304   }
06305 
06306   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
06307   LookupName(Previous, S);
06308 
06309   // Warn about shadowing the name of a template parameter.
06310   if (Previous.isSingleResult() &&
06311       Previous.getFoundDecl()->isTemplateParameter()) {
06312     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
06313     Previous.clear();
06314   }
06315 
06316   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
06317          "name in alias declaration must be an identifier");
06318   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
06319                                                Name.StartLocation,
06320                                                Name.Identifier, TInfo);
06321 
06322   NewTD->setAccess(AS);
06323 
06324   if (Invalid)
06325     NewTD->setInvalidDecl();
06326 
06327   CheckTypedefForVariablyModifiedType(S, NewTD);
06328   Invalid |= NewTD->isInvalidDecl();
06329 
06330   bool Redeclaration = false;
06331 
06332   NamedDecl *NewND;
06333   if (TemplateParamLists.size()) {
06334     TypeAliasTemplateDecl *OldDecl = 0;
06335     TemplateParameterList *OldTemplateParams = 0;
06336 
06337     if (TemplateParamLists.size() != 1) {
06338       Diag(UsingLoc, diag::err_alias_template_extra_headers)
06339         << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
06340          TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
06341     }
06342     TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
06343 
06344     // Only consider previous declarations in the same scope.
06345     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
06346                          /*ExplicitInstantiationOrSpecialization*/false);
06347     if (!Previous.empty()) {
06348       Redeclaration = true;
06349 
06350       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
06351       if (!OldDecl && !Invalid) {
06352         Diag(UsingLoc, diag::err_redefinition_different_kind)
06353           << Name.Identifier;
06354 
06355         NamedDecl *OldD = Previous.getRepresentativeDecl();
06356         if (OldD->getLocation().isValid())
06357           Diag(OldD->getLocation(), diag::note_previous_definition);
06358 
06359         Invalid = true;
06360       }
06361 
06362       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
06363         if (TemplateParameterListsAreEqual(TemplateParams,
06364                                            OldDecl->getTemplateParameters(),
06365                                            /*Complain=*/true,
06366                                            TPL_TemplateMatch))
06367           OldTemplateParams = OldDecl->getTemplateParameters();
06368         else
06369           Invalid = true;
06370 
06371         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
06372         if (!Invalid &&
06373             !Context.hasSameType(OldTD->getUnderlyingType(),
06374                                  NewTD->getUnderlyingType())) {
06375           // FIXME: The C++0x standard does not clearly say this is ill-formed,
06376           // but we can't reasonably accept it.
06377           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
06378             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
06379           if (OldTD->getLocation().isValid())
06380             Diag(OldTD->getLocation(), diag::note_previous_definition);
06381           Invalid = true;
06382         }
06383       }
06384     }
06385 
06386     // Merge any previous default template arguments into our parameters,
06387     // and check the parameter list.
06388     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
06389                                    TPC_TypeAliasTemplate))
06390       return 0;
06391 
06392     TypeAliasTemplateDecl *NewDecl =
06393       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
06394                                     Name.Identifier, TemplateParams,
06395                                     NewTD);
06396 
06397     NewDecl->setAccess(AS);
06398 
06399     if (Invalid)
06400       NewDecl->setInvalidDecl();
06401     else if (OldDecl)
06402       NewDecl->setPreviousDeclaration(OldDecl);
06403 
06404     NewND = NewDecl;
06405   } else {
06406     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
06407     NewND = NewTD;
06408   }
06409 
06410   if (!Redeclaration)
06411     PushOnScopeChains(NewND, S);
06412 
06413   return NewND;
06414 }
06415 
06416 Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
06417                                              SourceLocation NamespaceLoc,
06418                                              SourceLocation AliasLoc,
06419                                              IdentifierInfo *Alias,
06420                                              CXXScopeSpec &SS,
06421                                              SourceLocation IdentLoc,
06422                                              IdentifierInfo *Ident) {
06423 
06424   // Lookup the namespace name.
06425   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
06426   LookupParsedName(R, S, &SS);
06427 
06428   // Check if we have a previous declaration with the same name.
06429   NamedDecl *PrevDecl
06430     = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 
06431                        ForRedeclaration);
06432   if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
06433     PrevDecl = 0;
06434 
06435   if (PrevDecl) {
06436     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
06437       // We already have an alias with the same name that points to the same
06438       // namespace, so don't create a new one.
06439       // FIXME: At some point, we'll want to create the (redundant)
06440       // declaration to maintain better source information.
06441       if (!R.isAmbiguous() && !R.empty() &&
06442           AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
06443         return 0;
06444     }
06445 
06446     unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
06447       diag::err_redefinition_different_kind;
06448     Diag(AliasLoc, DiagID) << Alias;
06449     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
06450     return 0;
06451   }
06452 
06453   if (R.isAmbiguous())
06454     return 0;
06455 
06456   if (R.empty()) {
06457     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
06458       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
06459       return 0;
06460     }
06461   }
06462 
06463   NamespaceAliasDecl *AliasDecl =
06464     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
06465                                Alias, SS.getWithLocInContext(Context),
06466                                IdentLoc, R.getFoundDecl());
06467 
06468   PushOnScopeChains(AliasDecl, S);
06469   return AliasDecl;
06470 }
06471 
06472 namespace {
06473   /// \brief Scoped object used to handle the state changes required in Sema
06474   /// to implicitly define the body of a C++ member function;
06475   class ImplicitlyDefinedFunctionScope {
06476     Sema &S;
06477     Sema::ContextRAII SavedContext;
06478     
06479   public:
06480     ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
06481       : S(S), SavedContext(S, Method) 
06482     {
06483       S.PushFunctionScope();
06484       S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
06485     }
06486     
06487     ~ImplicitlyDefinedFunctionScope() {
06488       S.PopExpressionEvaluationContext();
06489       S.PopFunctionScopeInfo();
06490     }
06491   };
06492 }
06493 
06494 Sema::ImplicitExceptionSpecification
06495 Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
06496   // C++ [except.spec]p14:
06497   //   An implicitly declared special member function (Clause 12) shall have an 
06498   //   exception-specification. [...]
06499   ImplicitExceptionSpecification ExceptSpec(*this);
06500   if (ClassDecl->isInvalidDecl())
06501     return ExceptSpec;
06502 
06503   // Direct base-class constructors.
06504   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
06505                                        BEnd = ClassDecl->bases_end();
06506        B != BEnd; ++B) {
06507     if (B->isVirtual()) // Handled below.
06508       continue;
06509     
06510     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
06511       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
06512       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
06513       // If this is a deleted function, add it anyway. This might be conformant
06514       // with the standard. This might not. I'm not sure. It might not matter.
06515       if (Constructor)
06516         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
06517     }
06518   }
06519 
06520   // Virtual base-class constructors.
06521   for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
06522                                        BEnd = ClassDecl->vbases_end();
06523        B != BEnd; ++B) {
06524     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
06525       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
06526       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
06527       // If this is a deleted function, add it anyway. This might be conformant
06528       // with the standard. This might not. I'm not sure. It might not matter.
06529       if (Constructor)
06530         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
06531     }
06532   }
06533 
06534   // Field constructors.
06535   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
06536                                FEnd = ClassDecl->field_end();
06537        F != FEnd; ++F) {
06538     if (F->hasInClassInitializer()) {
06539       if (Expr *E = F->getInClassInitializer())
06540         ExceptSpec.CalledExpr(E);
06541       else if (!F->isInvalidDecl())
06542         ExceptSpec.SetDelayed();
06543     } else if (const RecordType *RecordTy
06544               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
06545       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
06546       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
06547       // If this is a deleted function, add it anyway. This might be conformant
06548       // with the standard. This might not. I'm not sure. It might not matter.
06549       // In particular, the problem is that this function never gets called. It
06550       // might just be ill-formed because this function attempts to refer to
06551       // a deleted function here.
06552       if (Constructor)
06553         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
06554     }
06555   }
06556 
06557   return ExceptSpec;
06558 }
06559 
06560 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
06561                                                      CXXRecordDecl *ClassDecl) {
06562   // C++ [class.ctor]p5:
06563   //   A default constructor for a class X is a constructor of class X
06564   //   that can be called without an argument. If there is no
06565   //   user-declared constructor for class X, a default constructor is
06566   //   implicitly declared. An implicitly-declared default constructor
06567   //   is an inline public member of its class.
06568   assert(!ClassDecl->hasUserDeclaredConstructor() && 
06569          "Should not build implicit default constructor!");
06570 
06571   ImplicitExceptionSpecification Spec = 
06572     ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
06573   FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
06574 
06575   // Create the actual constructor declaration.
06576   CanQualType ClassType
06577     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
06578   SourceLocation ClassLoc = ClassDecl->getLocation();
06579   DeclarationName Name
06580     = Context.DeclarationNames.getCXXConstructorName(ClassType);
06581   DeclarationNameInfo NameInfo(Name, ClassLoc);
06582   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
06583       Context, ClassDecl, ClassLoc, NameInfo,
06584       Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
06585       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
06586       /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
06587         getLangOpts().CPlusPlus0x);
06588   DefaultCon->setAccess(AS_public);
06589   DefaultCon->setDefaulted();
06590   DefaultCon->setImplicit();
06591   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
06592   
06593   // Note that we have declared this constructor.
06594   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
06595   
06596   if (Scope *S = getScopeForContext(ClassDecl))
06597     PushOnScopeChains(DefaultCon, S, false);
06598   ClassDecl->addDecl(DefaultCon);
06599 
06600   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
06601     DefaultCon->setDeletedAsWritten();
06602   
06603   return DefaultCon;
06604 }
06605 
06606 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
06607                                             CXXConstructorDecl *Constructor) {
06608   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
06609           !Constructor->doesThisDeclarationHaveABody() &&
06610           !Constructor->isDeleted()) &&
06611     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
06612 
06613   CXXRecordDecl *ClassDecl = Constructor->getParent();
06614   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
06615 
06616   ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
06617   DiagnosticErrorTrap Trap(Diags);
06618   if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
06619       Trap.hasErrorOccurred()) {
06620     Diag(CurrentLocation, diag::note_member_synthesized_at) 
06621       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
06622     Constructor->setInvalidDecl();
06623     return;
06624   }
06625 
06626   SourceLocation Loc = Constructor->getLocation();
06627   Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
06628 
06629   Constructor->setUsed();
06630   MarkVTableUsed(CurrentLocation, ClassDecl);
06631 
06632   if (ASTMutationListener *L = getASTMutationListener()) {
06633     L->CompletedImplicitDefinition(Constructor);
06634   }
06635 }
06636 
06637 /// Get any existing defaulted default constructor for the given class. Do not
06638 /// implicitly define one if it does not exist.
06639 static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
06640                                                              CXXRecordDecl *D) {
06641   ASTContext &Context = Self.Context;
06642   QualType ClassType = Context.getTypeDeclType(D);
06643   DeclarationName ConstructorName
06644     = Context.DeclarationNames.getCXXConstructorName(
06645                       Context.getCanonicalType(ClassType.getUnqualifiedType()));
06646 
06647   DeclContext::lookup_const_iterator Con, ConEnd;
06648   for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
06649        Con != ConEnd; ++Con) {
06650     // A function template cannot be defaulted.
06651     if (isa<FunctionTemplateDecl>(*Con))
06652       continue;
06653 
06654     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
06655     if (Constructor->isDefaultConstructor())
06656       return Constructor->isDefaulted() ? Constructor : 0;
06657   }
06658   return 0;
06659 }
06660 
06661 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
06662   if (!D) return;
06663   AdjustDeclIfTemplate(D);
06664 
06665   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
06666   CXXConstructorDecl *CtorDecl
06667     = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
06668 
06669   if (!CtorDecl) return;
06670 
06671   // Compute the exception specification for the default constructor.
06672   const FunctionProtoType *CtorTy =
06673     CtorDecl->getType()->castAs<FunctionProtoType>();
06674   if (CtorTy->getExceptionSpecType() == EST_Delayed) {
06675     // FIXME: Don't do this unless the exception spec is needed.
06676     ImplicitExceptionSpecification Spec = 
06677       ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
06678     FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
06679     assert(EPI.ExceptionSpecType != EST_Delayed);
06680 
06681     CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
06682   }
06683 
06684   // If the default constructor is explicitly defaulted, checking the exception
06685   // specification is deferred until now.
06686   if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
06687       !ClassDecl->isDependentType())
06688     CheckExplicitlyDefaultedSpecialMember(CtorDecl);
06689 }
06690 
06691 void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
06692   // We start with an initial pass over the base classes to collect those that
06693   // inherit constructors from. If there are none, we can forgo all further
06694   // processing.
06695   typedef SmallVector<const RecordType *, 4> BasesVector;
06696   BasesVector BasesToInheritFrom;
06697   for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
06698                                           BaseE = ClassDecl->bases_end();
06699          BaseIt != BaseE; ++BaseIt) {
06700     if (BaseIt->getInheritConstructors()) {
06701       QualType Base = BaseIt->getType();
06702       if (Base->isDependentType()) {
06703         // If we inherit constructors from anything that is dependent, just
06704         // abort processing altogether. We'll get another chance for the
06705         // instantiations.
06706         return;
06707       }
06708       BasesToInheritFrom.push_back(Base->castAs<RecordType>());
06709     }
06710   }
06711   if (BasesToInheritFrom.empty())
06712     return;
06713 
06714   // Now collect the constructors that we already have in the current class.
06715   // Those take precedence over inherited constructors.
06716   // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
06717   //   unless there is a user-declared constructor with the same signature in
06718   //   the class where the using-declaration appears.
06719   llvm::SmallSet<const Type *, 8> ExistingConstructors;
06720   for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
06721                                     CtorE = ClassDecl->ctor_end();
06722        CtorIt != CtorE; ++CtorIt) {
06723     ExistingConstructors.insert(
06724         Context.getCanonicalType(CtorIt->getType()).getTypePtr());
06725   }
06726 
06727   DeclarationName CreatedCtorName =
06728       Context.DeclarationNames.getCXXConstructorName(
06729           ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
06730 
06731   // Now comes the true work.
06732   // First, we keep a map from constructor types to the base that introduced
06733   // them. Needed for finding conflicting constructors. We also keep the
06734   // actually inserted declarations in there, for pretty diagnostics.
06735   typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
06736   typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
06737   ConstructorToSourceMap InheritedConstructors;
06738   for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
06739                              BaseE = BasesToInheritFrom.end();
06740        BaseIt != BaseE; ++BaseIt) {
06741     const RecordType *Base = *BaseIt;
06742     CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
06743     CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
06744     for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
06745                                       CtorE = BaseDecl->ctor_end();
06746          CtorIt != CtorE; ++CtorIt) {
06747       // Find the using declaration for inheriting this base's constructors.
06748       // FIXME: Don't perform name lookup just to obtain a source location!
06749       DeclarationName Name =
06750           Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
06751       LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
06752       LookupQualifiedName(Result, CurContext);
06753       UsingDecl *UD = Result.getAsSingle<UsingDecl>();
06754       SourceLocation UsingLoc = UD ? UD->getLocation() :
06755                                      ClassDecl->getLocation();
06756 
06757       // C++0x [class.inhctor]p1: The candidate set of inherited constructors
06758       //   from the class X named in the using-declaration consists of actual
06759       //   constructors and notional constructors that result from the
06760       //   transformation of defaulted parameters as follows:
06761       //   - all non-template default constructors of X, and
06762       //   - for each non-template constructor of X that has at least one
06763       //     parameter with a default argument, the set of constructors that
06764       //     results from omitting any ellipsis parameter specification and
06765       //     successively omitting parameters with a default argument from the
06766       //     end of the parameter-type-list.
06767       CXXConstructorDecl *BaseCtor = &*CtorIt;
06768       bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
06769       const FunctionProtoType *BaseCtorType =
06770           BaseCtor->getType()->getAs<FunctionProtoType>();
06771 
06772       for (unsigned params = BaseCtor->getMinRequiredArguments(),
06773                     maxParams = BaseCtor->getNumParams();
06774            params <= maxParams; ++params) {
06775         // Skip default constructors. They're never inherited.
06776         if (params == 0)
06777           continue;
06778         // Skip copy and move constructors for the same reason.
06779         if (CanBeCopyOrMove && params == 1)
06780           continue;
06781 
06782         // Build up a function type for this particular constructor.
06783         // FIXME: The working paper does not consider that the exception spec
06784         // for the inheriting constructor might be larger than that of the
06785         // source. This code doesn't yet, either. When it does, this code will
06786         // need to be delayed until after exception specifications and in-class
06787         // member initializers are attached.
06788         const Type *NewCtorType;
06789         if (params == maxParams)
06790           NewCtorType = BaseCtorType;
06791         else {
06792           SmallVector<QualType, 16> Args;
06793           for (unsigned i = 0; i < params; ++i) {
06794             Args.push_back(BaseCtorType->getArgType(i));
06795           }
06796           FunctionProtoType::ExtProtoInfo ExtInfo =
06797               BaseCtorType->getExtProtoInfo();
06798           ExtInfo.Variadic = false;
06799           NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
06800                                                 Args.data(), params, ExtInfo)
06801                        .getTypePtr();
06802         }
06803         const Type *CanonicalNewCtorType =
06804             Context.getCanonicalType(NewCtorType);
06805 
06806         // Now that we have the type, first check if the class already has a
06807         // constructor with this signature.
06808         if (ExistingConstructors.count(CanonicalNewCtorType))
06809           continue;
06810 
06811         // Then we check if we have already declared an inherited constructor
06812         // with this signature.
06813         std::pair<ConstructorToSourceMap::iterator, bool> result =
06814             InheritedConstructors.insert(std::make_pair(
06815                 CanonicalNewCtorType,
06816                 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
06817         if (!result.second) {
06818           // Already in the map. If it came from a different class, that's an
06819           // error. Not if it's from the same.
06820           CanQualType PreviousBase = result.first->second.first;
06821           if (CanonicalBase != PreviousBase) {
06822             const CXXConstructorDecl *PrevCtor = result.first->second.second;
06823             const CXXConstructorDecl *PrevBaseCtor =
06824                 PrevCtor->getInheritedConstructor();
06825             assert(PrevBaseCtor && "Conflicting constructor was not inherited");
06826 
06827             Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
06828             Diag(BaseCtor->getLocation(),
06829                  diag::note_using_decl_constructor_conflict_current_ctor);
06830             Diag(PrevBaseCtor->getLocation(),
06831                  diag::note_using_decl_constructor_conflict_previous_ctor);
06832             Diag(PrevCtor->getLocation(),
06833                  diag::note_using_decl_constructor_conflict_previous_using);
06834           }
06835           continue;
06836         }
06837 
06838         // OK, we're there, now add the constructor.
06839         // C++0x [class.inhctor]p8: [...] that would be performed by a
06840         //   user-written inline constructor [...]
06841         DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
06842         CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
06843             Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
06844             /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
06845             /*ImplicitlyDeclared=*/true,
06846             // FIXME: Due to a defect in the standard, we treat inherited
06847             // constructors as constexpr even if that makes them ill-formed.
06848             /*Constexpr=*/BaseCtor->isConstexpr());
06849         NewCtor->setAccess(BaseCtor->getAccess());
06850 
06851         // Build up the parameter decls and add them.
06852         SmallVector<ParmVarDecl *, 16> ParamDecls;
06853         for (unsigned i = 0; i < params; ++i) {
06854           ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
06855                                                    UsingLoc, UsingLoc,
06856                                                    /*IdentifierInfo=*/0,
06857                                                    BaseCtorType->getArgType(i),
06858                                                    /*TInfo=*/0, SC_None,
06859                                                    SC_None, /*DefaultArg=*/0));
06860         }
06861         NewCtor->setParams(ParamDecls);
06862         NewCtor->setInheritedConstructor(BaseCtor);
06863 
06864         ClassDecl->addDecl(NewCtor);
06865         result.first->second.second = NewCtor;
06866       }
06867     }
06868   }
06869 }
06870 
06871 Sema::ImplicitExceptionSpecification
06872 Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
06873   // C++ [except.spec]p14: 
06874   //   An implicitly declared special member function (Clause 12) shall have 
06875   //   an exception-specification.
06876   ImplicitExceptionSpecification ExceptSpec(*this);
06877   if (ClassDecl->isInvalidDecl())
06878     return ExceptSpec;
06879 
06880   // Direct base-class destructors.
06881   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
06882                                        BEnd = ClassDecl->bases_end();
06883        B != BEnd; ++B) {
06884     if (B->isVirtual()) // Handled below.
06885       continue;
06886     
06887     if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
06888       ExceptSpec.CalledDecl(B->getLocStart(),
06889                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
06890   }
06891 
06892   // Virtual base-class destructors.
06893   for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
06894                                        BEnd = ClassDecl->vbases_end();
06895        B != BEnd; ++B) {
06896     if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
06897       ExceptSpec.CalledDecl(B->getLocStart(),
06898                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
06899   }
06900 
06901   // Field destructors.
06902   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
06903                                FEnd = ClassDecl->field_end();
06904        F != FEnd; ++F) {
06905     if (const RecordType *RecordTy
06906         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
06907       ExceptSpec.CalledDecl(F->getLocation(),
06908                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
06909   }
06910 
06911   return ExceptSpec;
06912 }
06913 
06914 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
06915   // C++ [class.dtor]p2:
06916   //   If a class has no user-declared destructor, a destructor is
06917   //   declared implicitly. An implicitly-declared destructor is an
06918   //   inline public member of its class.
06919   
06920   ImplicitExceptionSpecification Spec =
06921       ComputeDefaultedDtorExceptionSpec(ClassDecl); 
06922   FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
06923 
06924   // Create the actual destructor declaration.
06925   QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
06926 
06927   CanQualType ClassType
06928     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
06929   SourceLocation ClassLoc = ClassDecl->getLocation();
06930   DeclarationName Name
06931     = Context.DeclarationNames.getCXXDestructorName(ClassType);
06932   DeclarationNameInfo NameInfo(Name, ClassLoc);
06933   CXXDestructorDecl *Destructor
06934       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
06935                                   /*isInline=*/true,
06936                                   /*isImplicitlyDeclared=*/true);
06937   Destructor->setAccess(AS_public);
06938   Destructor->setDefaulted();
06939   Destructor->setImplicit();
06940   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
06941   
06942   // Note that we have declared this destructor.
06943   ++ASTContext::NumImplicitDestructorsDeclared;
06944   
06945   // Introduce this destructor into its scope.
06946   if (Scope *S = getScopeForContext(ClassDecl))
06947     PushOnScopeChains(Destructor, S, false);
06948   ClassDecl->addDecl(Destructor);
06949   
06950   // This could be uniqued if it ever proves significant.
06951   Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
06952 
06953   AddOverriddenMethods(ClassDecl, Destructor);
06954 
06955   if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
06956     Destructor->setDeletedAsWritten();
06957 
06958   return Destructor;
06959 }
06960 
06961 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
06962                                     CXXDestructorDecl *Destructor) {
06963   assert((Destructor->isDefaulted() &&
06964           !Destructor->doesThisDeclarationHaveABody() &&
06965           !Destructor->isDeleted()) &&
06966          "DefineImplicitDestructor - call it for implicit default dtor");
06967   CXXRecordDecl *ClassDecl = Destructor->getParent();
06968   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
06969 
06970   if (Destructor->isInvalidDecl())
06971     return;
06972 
06973   ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
06974 
06975   DiagnosticErrorTrap Trap(Diags);
06976   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
06977                                          Destructor->getParent());
06978 
06979   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
06980     Diag(CurrentLocation, diag::note_member_synthesized_at) 
06981       << CXXDestructor << Context.getTagDeclType(ClassDecl);
06982 
06983     Destructor->setInvalidDecl();
06984     return;
06985   }
06986 
06987   SourceLocation Loc = Destructor->getLocation();
06988   Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
06989   Destructor->setImplicitlyDefined(true);
06990   Destructor->setUsed();
06991   MarkVTableUsed(CurrentLocation, ClassDecl);
06992 
06993   if (ASTMutationListener *L = getASTMutationListener()) {
06994     L->CompletedImplicitDefinition(Destructor);
06995   }
06996 }
06997 
06998 /// \brief Perform any semantic analysis which needs to be delayed until all
06999 /// pending class member declarations have been parsed.
07000 void Sema::ActOnFinishCXXMemberDecls() {
07001   // Now we have parsed all exception specifications, determine the implicit
07002   // exception specifications for destructors.
07003   for (unsigned i = 0, e = DelayedDestructorExceptionSpecs.size();
07004        i != e; ++i) {
07005     CXXDestructorDecl *Dtor = DelayedDestructorExceptionSpecs[i];
07006     AdjustDestructorExceptionSpec(Dtor->getParent(), Dtor, true);
07007   }
07008   DelayedDestructorExceptionSpecs.clear();
07009 
07010   // Perform any deferred checking of exception specifications for virtual
07011   // destructors.
07012   for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
07013        i != e; ++i) {
07014     const CXXDestructorDecl *Dtor =
07015         DelayedDestructorExceptionSpecChecks[i].first;
07016     assert(!Dtor->getParent()->isDependentType() &&
07017            "Should not ever add destructors of templates into the list.");
07018     CheckOverridingFunctionExceptionSpec(Dtor,
07019         DelayedDestructorExceptionSpecChecks[i].second);
07020   }
07021   DelayedDestructorExceptionSpecChecks.clear();
07022 }
07023 
07024 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
07025                                          CXXDestructorDecl *destructor,
07026                                          bool WasDelayed) {
07027   // C++11 [class.dtor]p3:
07028   //   A declaration of a destructor that does not have an exception-
07029   //   specification is implicitly considered to have the same exception-
07030   //   specification as an implicit declaration.
07031   const FunctionProtoType *dtorType = destructor->getType()->
07032                                         getAs<FunctionProtoType>();
07033   if (!WasDelayed && dtorType->hasExceptionSpec())
07034     return;
07035 
07036   ImplicitExceptionSpecification exceptSpec =
07037       ComputeDefaultedDtorExceptionSpec(classDecl);
07038 
07039   // Replace the destructor's type, building off the existing one. Fortunately,
07040   // the only thing of interest in the destructor type is its extended info.
07041   // The return and arguments are fixed.
07042   FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
07043   epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
07044   epi.NumExceptions = exceptSpec.size();
07045   epi.Exceptions = exceptSpec.data();
07046   QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
07047 
07048   destructor->setType(ty);
07049 
07050   // If we can't compute the exception specification for this destructor yet
07051   // (because it depends on an exception specification which we have not parsed
07052   // yet), make a note that we need to try again when the class is complete.
07053   if (epi.ExceptionSpecType == EST_Delayed) {
07054     assert(!WasDelayed && "couldn't compute destructor exception spec");
07055     DelayedDestructorExceptionSpecs.push_back(destructor);
07056   }
07057 
07058   // FIXME: If the destructor has a body that could throw, and the newly created
07059   // spec doesn't allow exceptions, we should emit a warning, because this
07060   // change in behavior can break conforming C++03 programs at runtime.
07061   // However, we don't have a body yet, so it needs to be done somewhere else.
07062 }
07063 
07064 /// \brief Builds a statement that copies/moves the given entity from \p From to
07065 /// \c To.
07066 ///
07067 /// This routine is used to copy/move the members of a class with an
07068 /// implicitly-declared copy/move assignment operator. When the entities being
07069 /// copied are arrays, this routine builds for loops to copy them.
07070 ///
07071 /// \param S The Sema object used for type-checking.
07072 ///
07073 /// \param Loc The location where the implicit copy/move is being generated.
07074 ///
07075 /// \param T The type of the expressions being copied/moved. Both expressions
07076 /// must have this type.
07077 ///
07078 /// \param To The expression we are copying/moving to.
07079 ///
07080 /// \param From The expression we are copying/moving from.
07081 ///
07082 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
07083 /// Otherwise, it's a non-static member subobject.
07084 ///
07085 /// \param Copying Whether we're copying or moving.
07086 ///
07087 /// \param Depth Internal parameter recording the depth of the recursion.
07088 ///
07089 /// \returns A statement or a loop that copies the expressions.
07090 static StmtResult
07091 BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 
07092                       Expr *To, Expr *From,
07093                       bool CopyingBaseSubobject, bool Copying,
07094                       unsigned Depth = 0) {
07095   // C++0x [class.copy]p28:
07096   //   Each subobject is assigned in the manner appropriate to its type:
07097   //
07098   //     - if the subobject is of class type, as if by a call to operator= with
07099   //       the subobject as the object expression and the corresponding
07100   //       subobject of x as a single function argument (as if by explicit
07101   //       qualification; that is, ignoring any possible virtual overriding
07102   //       functions in more derived classes);
07103   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
07104     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
07105     
07106     // Look for operator=.
07107     DeclarationName Name
07108       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
07109     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
07110     S.LookupQualifiedName(OpLookup, ClassDecl, false);
07111     
07112     // Filter out any result that isn't a copy/move-assignment operator.
07113     LookupResult::Filter F = OpLookup.makeFilter();
07114     while (F.hasNext()) {
07115       NamedDecl *D = F.next();
07116       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
07117         if (Method->isCopyAssignmentOperator() ||
07118             (!Copying && Method->isMoveAssignmentOperator()))
07119           continue;
07120 
07121       F.erase();
07122     }
07123     F.done();
07124     
07125     // Suppress the protected check (C++ [class.protected]) for each of the
07126     // assignment operators we found. This strange dance is required when 
07127     // we're assigning via a base classes's copy-assignment operator. To
07128     // ensure that we're getting the right base class subobject (without 
07129     // ambiguities), we need to cast "this" to that subobject type; to
07130     // ensure that we don't go through the virtual call mechanism, we need
07131     // to qualify the operator= name with the base class (see below). However,
07132     // this means that if the base class has a protected copy assignment
07133     // operator, the protected member access check will fail. So, we
07134     // rewrite "protected" access to "public" access in this case, since we
07135     // know by construction that we're calling from a derived class.
07136     if (CopyingBaseSubobject) {
07137       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
07138            L != LEnd; ++L) {
07139         if (L.getAccess() == AS_protected)
07140           L.setAccess(AS_public);
07141       }
07142     }
07143     
07144     // Create the nested-name-specifier that will be used to qualify the
07145     // reference to operator=; this is required to suppress the virtual
07146     // call mechanism.
07147     CXXScopeSpec SS;
07148     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
07149     SS.MakeTrivial(S.Context, 
07150                    NestedNameSpecifier::Create(S.Context, 0, false, 
07151                                                CanonicalT),
07152                    Loc);
07153     
07154     // Create the reference to operator=.
07155     ExprResult OpEqualRef
07156       = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS, 
07157                                    /*TemplateKWLoc=*/SourceLocation(),
07158                                    /*FirstQualifierInScope=*/0,
07159                                    OpLookup,
07160                                    /*TemplateArgs=*/0,
07161                                    /*SuppressQualifierCheck=*/true);
07162     if (OpEqualRef.isInvalid())
07163       return StmtError();
07164     
07165     // Build the call to the assignment operator.
07166 
07167     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 
07168                                                   OpEqualRef.takeAs<Expr>(),
07169                                                   Loc, &From, 1, Loc);
07170     if (Call.isInvalid())
07171       return StmtError();
07172     
07173     return S.Owned(Call.takeAs<Stmt>());
07174   }
07175 
07176   //     - if the subobject is of scalar type, the built-in assignment 
07177   //       operator is used.
07178   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);  
07179   if (!ArrayTy) {
07180     ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
07181     if (Assignment.isInvalid())
07182       return StmtError();
07183     
07184     return S.Owned(Assignment.takeAs<Stmt>());
07185   }
07186     
07187   //     - if the subobject is an array, each element is assigned, in the 
07188   //       manner appropriate to the element type;
07189   
07190   // Construct a loop over the array bounds, e.g.,
07191   //
07192   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
07193   //
07194   // that will copy each of the array elements. 
07195   QualType SizeType = S.Context.getSizeType();
07196   
07197   // Create the iteration variable.
07198   IdentifierInfo *IterationVarName = 0;
07199   {
07200     SmallString<8> Str;
07201     llvm::raw_svector_ostream OS(Str);
07202     OS << "__i" << Depth;
07203     IterationVarName = &S.Context.Idents.get(OS.str());
07204   }
07205   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
07206                                           IterationVarName, SizeType,
07207                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
07208                                           SC_None, SC_None);
07209   
07210   // Initialize the iteration variable to zero.
07211   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
07212   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
07213 
07214   // Create a reference to the iteration variable; we'll use this several
07215   // times throughout.
07216   Expr *IterationVarRef
07217     = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
07218   assert(IterationVarRef && "Reference to invented variable cannot fail!");
07219   Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
07220   assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
07221 
07222   // Create the DeclStmt that holds the iteration variable.
07223   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
07224   
07225   // Create the comparison against the array bound.
07226   llvm::APInt Upper
07227     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
07228   Expr *Comparison
07229     = new (S.Context) BinaryOperator(IterationVarRefRVal,
07230                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
07231                                      BO_NE, S.Context.BoolTy,
07232                                      VK_RValue, OK_Ordinary, Loc);
07233   
07234   // Create the pre-increment of the iteration variable.
07235   Expr *Increment
07236     = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
07237                                     VK_LValue, OK_Ordinary, Loc);
07238   
07239   // Subscript the "from" and "to" expressions with the iteration variable.
07240   From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
07241                                                          IterationVarRefRVal,
07242                                                          Loc));
07243   To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
07244                                                        IterationVarRefRVal,
07245                                                        Loc));
07246   if (!Copying) // Cast to rvalue
07247     From = CastForMoving(S, From);
07248 
07249   // Build the copy/move for an individual element of the array.
07250   StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
07251                                           To, From, CopyingBaseSubobject,
07252                                           Copying, Depth + 1);
07253   if (Copy.isInvalid())
07254     return StmtError();
07255   
07256   // Construct the loop that copies all elements of this array.
07257   return S.ActOnForStmt(Loc, Loc, InitStmt, 
07258                         S.MakeFullExpr(Comparison),
07259                         0, S.MakeFullExpr(Increment),
07260                         Loc, Copy.take());
07261 }
07262 
07263 std::pair<Sema::ImplicitExceptionSpecification, bool>
07264 Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
07265                                                    CXXRecordDecl *ClassDecl) {
07266   if (ClassDecl->isInvalidDecl())
07267     return std::make_pair(ImplicitExceptionSpecification(*this), true);
07268 
07269   // C++ [class.copy]p10:
07270   //   If the class definition does not explicitly declare a copy
07271   //   assignment operator, one is declared implicitly.
07272   //   The implicitly-defined copy assignment operator for a class X
07273   //   will have the form
07274   //
07275   //       X& X::operator=(const X&)
07276   //
07277   //   if
07278   bool HasConstCopyAssignment = true;
07279   
07280   //       -- each direct base class B of X has a copy assignment operator
07281   //          whose parameter is of type const B&, const volatile B& or B,
07282   //          and
07283   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
07284                                        BaseEnd = ClassDecl->bases_end();
07285        HasConstCopyAssignment && Base != BaseEnd; ++Base) {
07286     // We'll handle this below
07287     if (LangOpts.CPlusPlus0x && Base->isVirtual())
07288       continue;
07289 
07290     assert(!Base->getType()->isDependentType() &&
07291            "Cannot generate implicit members for class with dependent bases.");
07292     CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
07293     HasConstCopyAssignment &=
07294       (bool)LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const,
07295                                     false, 0);
07296   }
07297 
07298   // In C++11, the above citation has "or virtual" added
07299   if (LangOpts.CPlusPlus0x) {
07300     for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
07301                                          BaseEnd = ClassDecl->vbases_end();
07302          HasConstCopyAssignment && Base != BaseEnd; ++Base) {
07303       assert(!Base->getType()->isDependentType() &&
07304              "Cannot generate implicit members for class with dependent bases.");
07305       CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
07306       HasConstCopyAssignment &=
07307         (bool)LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const,
07308                                       false, 0);
07309     }
07310   }
07311   
07312   //       -- for all the nonstatic data members of X that are of a class
07313   //          type M (or array thereof), each such class type has a copy
07314   //          assignment operator whose parameter is of type const M&,
07315   //          const volatile M& or M.
07316   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
07317                                   FieldEnd = ClassDecl->field_end();
07318        HasConstCopyAssignment && Field != FieldEnd;
07319        ++Field) {
07320     QualType FieldType = Context.getBaseElementType(Field->getType());
07321     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
07322       HasConstCopyAssignment &=
07323         (bool)LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const,
07324                                       false, 0);
07325     }
07326   }
07327   
07328   //   Otherwise, the implicitly declared copy assignment operator will
07329   //   have the form
07330   //
07331   //       X& X::operator=(X&)
07332   
07333   // C++ [except.spec]p14:
07334   //   An implicitly declared special member function (Clause 12) shall have an 
07335   //   exception-specification. [...]
07336 
07337   // It is unspecified whether or not an implicit copy assignment operator
07338   // attempts to deduplicate calls to assignment operators of virtual bases are
07339   // made. As such, this exception specification is effectively unspecified.
07340   // Based on a similar decision made for constness in C++0x, we're erring on
07341   // the side of assuming such calls to be made regardless of whether they
07342   // actually happen.
07343   ImplicitExceptionSpecification ExceptSpec(*this);
07344   unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
07345   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
07346                                        BaseEnd = ClassDecl->bases_end();
07347        Base != BaseEnd; ++Base) {
07348     if (Base->isVirtual())
07349       continue;
07350 
07351     CXXRecordDecl *BaseClassDecl
07352       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
07353     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
07354                                                             ArgQuals, false, 0))
07355       ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
07356   }
07357 
07358   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
07359                                        BaseEnd = ClassDecl->vbases_end();
07360        Base != BaseEnd; ++Base) {
07361     CXXRecordDecl *BaseClassDecl
07362       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
07363     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
07364                                                             ArgQuals, false, 0))
07365       ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
07366   }
07367 
07368   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
07369                                   FieldEnd = ClassDecl->field_end();
07370        Field != FieldEnd;
07371        ++Field) {
07372     QualType FieldType = Context.getBaseElementType(Field->getType());
07373     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
07374       if (CXXMethodDecl *CopyAssign =
07375           LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
07376         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
07377     }
07378   }
07379 
07380   return std::make_pair(ExceptSpec, HasConstCopyAssignment);
07381 }
07382 
07383 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
07384   // Note: The following rules are largely analoguous to the copy
07385   // constructor rules. Note that virtual bases are not taken into account
07386   // for determining the argument type of the operator. Note also that
07387   // operators taking an object instead of a reference are allowed.
07388 
07389   ImplicitExceptionSpecification Spec(*this);
07390   bool Const;
07391   llvm::tie(Spec, Const) =
07392     ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
07393 
07394   QualType ArgType = Context.getTypeDeclType(ClassDecl);
07395   QualType RetType = Context.getLValueReferenceType(ArgType);
07396   if (Const)
07397     ArgType = ArgType.withConst();
07398   ArgType = Context.getLValueReferenceType(ArgType);
07399 
07400   //   An implicitly-declared copy assignment operator is an inline public
07401   //   member of its class.
07402   FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
07403   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
07404   SourceLocation ClassLoc = ClassDecl->getLocation();
07405   DeclarationNameInfo NameInfo(Name, ClassLoc);
07406   CXXMethodDecl *CopyAssignment
07407     = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
07408                             Context.getFunctionType(RetType, &ArgType, 1, EPI),
07409                             /*TInfo=*/0, /*isStatic=*/false,
07410                             /*StorageClassAsWritten=*/SC_None,
07411                             /*isInline=*/true, /*isConstexpr=*/false,
07412                             SourceLocation());
07413   CopyAssignment->setAccess(AS_public);
07414   CopyAssignment->setDefaulted();
07415   CopyAssignment->setImplicit();
07416   CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
07417   
07418   // Add the parameter to the operator.
07419   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
07420                                                ClassLoc, ClassLoc, /*Id=*/0,
07421                                                ArgType, /*TInfo=*/0,
07422                                                SC_None,
07423                                                SC_None, 0);
07424   CopyAssignment->setParams(FromParam);
07425   
07426   // Note that we have added this copy-assignment operator.
07427   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
07428 
07429   if (Scope *S = getScopeForContext(ClassDecl))
07430     PushOnScopeChains(CopyAssignment, S, false);
07431   ClassDecl->addDecl(CopyAssignment);
07432   
07433   // C++0x [class.copy]p19:
07434   //   ....  If the class definition does not explicitly declare a copy
07435   //   assignment operator, there is no user-declared move constructor, and
07436   //   there is no user-declared move assignment operator, a copy assignment
07437   //   operator is implicitly declared as defaulted.
07438   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
07439     CopyAssignment->setDeletedAsWritten();
07440 
07441   AddOverriddenMethods(ClassDecl, CopyAssignment);
07442   return CopyAssignment;
07443 }
07444 
07445 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
07446                                         CXXMethodDecl *CopyAssignOperator) {
07447   assert((CopyAssignOperator->isDefaulted() && 
07448           CopyAssignOperator->isOverloadedOperator() &&
07449           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
07450           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
07451           !CopyAssignOperator->isDeleted()) &&
07452          "DefineImplicitCopyAssignment called for wrong function");
07453 
07454   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
07455 
07456   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
07457     CopyAssignOperator->setInvalidDecl();
07458     return;
07459   }
07460   
07461   CopyAssignOperator->setUsed();
07462 
07463   ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
07464   DiagnosticErrorTrap Trap(Diags);
07465 
07466   // C++0x [class.copy]p30:
07467   //   The implicitly-defined or explicitly-defaulted copy assignment operator
07468   //   for a non-union class X performs memberwise copy assignment of its 
07469   //   subobjects. The direct base classes of X are assigned first, in the 
07470   //   order of their declaration in the base-specifier-list, and then the 
07471   //   immediate non-static data members of X are assigned, in the order in 
07472   //   which they were declared in the class definition.
07473   
07474   // The statements that form the synthesized function body.
07475   ASTOwningVector<Stmt*> Statements(*this);
07476   
07477   // The parameter for the "other" object, which we are copying from.
07478   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
07479   Qualifiers OtherQuals = Other->getType().getQualifiers();
07480   QualType OtherRefType = Other->getType();
07481   if (const LValueReferenceType *OtherRef
07482                                 = OtherRefType->getAs<LValueReferenceType>()) {
07483     OtherRefType = OtherRef->getPointeeType();
07484     OtherQuals = OtherRefType.getQualifiers();
07485   }
07486   
07487   // Our location for everything implicitly-generated.
07488   SourceLocation Loc = CopyAssignOperator->getLocation();
07489   
07490   // Construct a reference to the "other" object. We'll be using this 
07491   // throughout the generated ASTs.
07492   Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
07493   assert(OtherRef && "Reference to parameter cannot fail!");
07494   
07495   // Construct the "this" pointer. We'll be using this throughout the generated
07496   // ASTs.
07497   Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
07498   assert(This && "Reference to this cannot fail!");
07499   
07500   // Assign base classes.
07501   bool Invalid = false;
07502   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
07503        E = ClassDecl->bases_end(); Base != E; ++Base) {
07504     // Form the assignment:
07505     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
07506     QualType BaseType = Base->getType().getUnqualifiedType();
07507     if (!BaseType->isRecordType()) {
07508       Invalid = true;
07509       continue;
07510     }
07511 
07512     CXXCastPath BasePath;
07513     BasePath.push_back(Base);
07514 
07515     // Construct the "from" expression, which is an implicit cast to the
07516     // appropriately-qualified base type.
07517     Expr *From = OtherRef;
07518     From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
07519                              CK_UncheckedDerivedToBase,
07520                              VK_LValue, &BasePath).take();
07521 
07522     // Dereference "this".
07523     ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
07524     
07525     // Implicitly cast "this" to the appropriately-qualified base type.
07526     To = ImpCastExprToType(To.take(), 
07527                            Context.getCVRQualifiedType(BaseType,
07528                                      CopyAssignOperator->getTypeQualifiers()),
07529                            CK_UncheckedDerivedToBase, 
07530                            VK_LValue, &BasePath);
07531 
07532     // Build the copy.
07533     StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
07534                                             To.get(), From,
07535                                             /*CopyingBaseSubobject=*/true,
07536                                             /*Copying=*/true);
07537     if (Copy.isInvalid()) {
07538       Diag(CurrentLocation, diag::note_member_synthesized_at) 
07539         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
07540       CopyAssignOperator->setInvalidDecl();
07541       return;
07542     }
07543     
07544     // Success! Record the copy.
07545     Statements.push_back(Copy.takeAs<Expr>());
07546   }
07547   
07548   // \brief Reference to the __builtin_memcpy function.
07549   Expr *BuiltinMemCpyRef = 0;
07550   // \brief Reference to the __builtin_objc_memmove_collectable function.
07551   Expr *CollectableMemCpyRef = 0;
07552   
07553   // Assign non-static members.
07554   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
07555                                   FieldEnd = ClassDecl->field_end(); 
07556        Field != FieldEnd; ++Field) {
07557     if (Field->isUnnamedBitfield())
07558       continue;
07559     
07560     // Check for members of reference type; we can't copy those.
07561     if (Field->getType()->isReferenceType()) {
07562       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
07563         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
07564       Diag(Field->getLocation(), diag::note_declared_at);
07565       Diag(CurrentLocation, diag::note_member_synthesized_at) 
07566         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
07567       Invalid = true;
07568       continue;
07569     }
07570     
07571     // Check for members of const-qualified, non-class type.
07572     QualType BaseType = Context.getBaseElementType(Field->getType());
07573     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
07574       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
07575         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
07576       Diag(Field->getLocation(), diag::note_declared_at);
07577       Diag(CurrentLocation, diag::note_member_synthesized_at) 
07578         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
07579       Invalid = true;      
07580       continue;
07581     }
07582 
07583     // Suppress assigning zero-width bitfields.
07584     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
07585       continue;
07586     
07587     QualType FieldType = Field->getType().getNonReferenceType();
07588     if (FieldType->isIncompleteArrayType()) {
07589       assert(ClassDecl->hasFlexibleArrayMember() && 
07590              "Incomplete array type is not valid");
07591       continue;
07592     }
07593     
07594     // Build references to the field in the object we're copying from and to.
07595     CXXScopeSpec SS; // Intentionally empty
07596     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
07597                               LookupMemberName);
07598     MemberLookup.addDecl(&*Field);
07599     MemberLookup.resolveKind();
07600     ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
07601                                                Loc, /*IsArrow=*/false,
07602                                                SS, SourceLocation(), 0,
07603                                                MemberLookup, 0);
07604     ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
07605                                              Loc, /*IsArrow=*/true,
07606                                              SS, SourceLocation(), 0,
07607                                              MemberLookup, 0);
07608     assert(!From.isInvalid() && "Implicit field reference cannot fail");
07609     assert(!To.isInvalid() && "Implicit field reference cannot fail");
07610     
07611     // If the field should be copied with __builtin_memcpy rather than via
07612     // explicit assignments, do so. This optimization only applies for arrays 
07613     // of scalars and arrays of class type with trivial copy-assignment 
07614     // operators.
07615     if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
07616         && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
07617       // Compute the size of the memory buffer to be copied.
07618       QualType SizeType = Context.getSizeType();
07619       llvm::APInt Size(Context.getTypeSize(SizeType), 
07620                        Context.getTypeSizeInChars(BaseType).getQuantity());
07621       for (const ConstantArrayType *Array
07622               = Context.getAsConstantArrayType(FieldType);
07623            Array; 
07624            Array = Context.getAsConstantArrayType(Array->getElementType())) {
07625         llvm::APInt ArraySize
07626           = Array->getSize().zextOrTrunc(Size.getBitWidth());
07627         Size *= ArraySize;
07628       }
07629           
07630       // Take the address of the field references for "from" and "to".
07631       From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
07632       To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
07633           
07634       bool NeedsCollectableMemCpy = 
07635           (BaseType->isRecordType() && 
07636            BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
07637           
07638       if (NeedsCollectableMemCpy) {
07639         if (!CollectableMemCpyRef) {
07640           // Create a reference to the __builtin_objc_memmove_collectable function.
07641           LookupResult R(*this, 
07642                          &Context.Idents.get("__builtin_objc_memmove_collectable"), 
07643                          Loc, LookupOrdinaryName);
07644           LookupName(R, TUScope, true);
07645         
07646           FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
07647           if (!CollectableMemCpy) {
07648             // Something went horribly wrong earlier, and we will have 
07649             // complained about it.
07650             Invalid = true;
07651             continue;
07652           }
07653         
07654           CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy, 
07655                                                   CollectableMemCpy->getType(),
07656                                                   VK_LValue, Loc, 0).take();
07657           assert(CollectableMemCpyRef && "Builtin reference cannot fail");
07658         }
07659       }
07660       // Create a reference to the __builtin_memcpy builtin function.
07661       else if (!BuiltinMemCpyRef) {
07662         LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
07663                        LookupOrdinaryName);
07664         LookupName(R, TUScope, true);
07665         
07666         FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
07667         if (!BuiltinMemCpy) {
07668           // Something went horribly wrong earlier, and we will have complained
07669           // about it.
07670           Invalid = true;
07671           continue;
07672         }
07673 
07674         BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy, 
07675                                             BuiltinMemCpy->getType(),
07676                                             VK_LValue, Loc, 0).take();
07677         assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
07678       }
07679           
07680       ASTOwningVector<Expr*> CallArgs(*this);
07681       CallArgs.push_back(To.takeAs<Expr>());
07682       CallArgs.push_back(From.takeAs<Expr>());
07683       CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
07684       ExprResult Call = ExprError();
07685       if (NeedsCollectableMemCpy)
07686         Call = ActOnCallExpr(/*Scope=*/0,
07687                              CollectableMemCpyRef,
07688                              Loc, move_arg(CallArgs), 
07689                              Loc);
07690       else
07691         Call = ActOnCallExpr(/*Scope=*/0,
07692                              BuiltinMemCpyRef,
07693                              Loc, move_arg(CallArgs), 
07694                              Loc);
07695           
07696       assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
07697       Statements.push_back(Call.takeAs<Expr>());
07698       continue;
07699     }
07700     
07701     // Build the copy of this field.
07702     StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType, 
07703                                             To.get(), From.get(),
07704                                             /*CopyingBaseSubobject=*/false,
07705                                             /*Copying=*/true);
07706     if (Copy.isInvalid()) {
07707       Diag(CurrentLocation, diag::note_member_synthesized_at) 
07708         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
07709       CopyAssignOperator->setInvalidDecl();
07710       return;
07711     }
07712     
07713     // Success! Record the copy.
07714     Statements.push_back(Copy.takeAs<Stmt>());
07715   }
07716 
07717   if (!Invalid) {
07718     // Add a "return *this;"
07719     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
07720     
07721     StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
07722     if (Return.isInvalid())
07723       Invalid = true;
07724     else {
07725       Statements.push_back(Return.takeAs<Stmt>());
07726 
07727       if (Trap.hasErrorOccurred()) {
07728         Diag(CurrentLocation, diag::note_member_synthesized_at) 
07729           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
07730         Invalid = true;
07731       }
07732     }
07733   }
07734 
07735   if (Invalid) {
07736     CopyAssignOperator->setInvalidDecl();
07737     return;
07738   }
07739 
07740   StmtResult Body;
07741   {
07742     CompoundScopeRAII CompoundScope(*this);
07743     Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
07744                              /*isStmtExpr=*/false);
07745     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
07746   }
07747   CopyAssignOperator->setBody(Body.takeAs<Stmt>());
07748 
07749   if (ASTMutationListener *L = getASTMutationListener()) {
07750     L->CompletedImplicitDefinition(CopyAssignOperator);
07751   }
07752 }
07753 
07754 Sema::ImplicitExceptionSpecification
07755 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
07756   ImplicitExceptionSpecification ExceptSpec(*this);
07757 
07758   if (ClassDecl->isInvalidDecl())
07759     return ExceptSpec;
07760 
07761   // C++0x [except.spec]p14:
07762   //   An implicitly declared special member function (Clause 12) shall have an 
07763   //   exception-specification. [...]
07764 
07765   // It is unspecified whether or not an implicit move assignment operator
07766   // attempts to deduplicate calls to assignment operators of virtual bases are
07767   // made. As such, this exception specification is effectively unspecified.
07768   // Based on a similar decision made for constness in C++0x, we're erring on
07769   // the side of assuming such calls to be made regardless of whether they
07770   // actually happen.
07771   // Note that a move constructor is not implicitly declared when there are
07772   // virtual bases, but it can still be user-declared and explicitly defaulted.
07773   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
07774                                        BaseEnd = ClassDecl->bases_end();
07775        Base != BaseEnd; ++Base) {
07776     if (Base->isVirtual())
07777       continue;
07778 
07779     CXXRecordDecl *BaseClassDecl
07780       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
07781     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
07782                                                            false, 0))
07783       ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
07784   }
07785 
07786   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
07787                                        BaseEnd = ClassDecl->vbases_end();
07788        Base != BaseEnd; ++Base) {
07789     CXXRecordDecl *BaseClassDecl
07790       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
07791     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
07792                                                            false, 0))
07793       ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
07794   }
07795 
07796   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
07797                                   FieldEnd = ClassDecl->field_end();
07798        Field != FieldEnd;
07799        ++Field) {
07800     QualType FieldType = Context.getBaseElementType(Field->getType());
07801     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
07802       if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
07803                                                              false, 0))
07804         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
07805     }
07806   }
07807 
07808   return ExceptSpec;
07809 }
07810 
07811 /// Determine whether the class type has any direct or indirect virtual base
07812 /// classes which have a non-trivial move assignment operator.
07813 static bool
07814 hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
07815   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
07816                                           BaseEnd = ClassDecl->vbases_end();
07817        Base != BaseEnd; ++Base) {
07818     CXXRecordDecl *BaseClass =
07819         cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
07820 
07821     // Try to declare the move assignment. If it would be deleted, then the
07822     // class does not have a non-trivial move assignment.
07823     if (BaseClass->needsImplicitMoveAssignment())
07824       S.DeclareImplicitMoveAssignment(BaseClass);
07825 
07826     // If the class has both a trivial move assignment and a non-trivial move
07827     // assignment, hasTrivialMoveAssignment() is false.
07828     if (BaseClass->hasDeclaredMoveAssignment() &&
07829         !BaseClass->hasTrivialMoveAssignment())
07830       return true;
07831   }
07832 
07833   return false;
07834 }
07835 
07836 /// Determine whether the given type either has a move constructor or is
07837 /// trivially copyable.
07838 static bool
07839 hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
07840   Type = S.Context.getBaseElementType(Type);
07841 
07842   // FIXME: Technically, non-trivially-copyable non-class types, such as
07843   // reference types, are supposed to return false here, but that appears
07844   // to be a standard defect.
07845   CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
07846   if (!ClassDecl || !ClassDecl->getDefinition())
07847     return true;
07848 
07849   if (Type.isTriviallyCopyableType(S.Context))
07850     return true;
07851 
07852   if (IsConstructor) {
07853     if (ClassDecl->needsImplicitMoveConstructor())
07854       S.DeclareImplicitMoveConstructor(ClassDecl);
07855     return ClassDecl->hasDeclaredMoveConstructor();
07856   }
07857 
07858   if (ClassDecl->needsImplicitMoveAssignment())
07859     S.DeclareImplicitMoveAssignment(ClassDecl);
07860   return ClassDecl->hasDeclaredMoveAssignment();
07861 }
07862 
07863 /// Determine whether all non-static data members and direct or virtual bases
07864 /// of class \p ClassDecl have either a move operation, or are trivially
07865 /// copyable.
07866 static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
07867                                             bool IsConstructor) {
07868   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
07869                                           BaseEnd = ClassDecl->bases_end();
07870        Base != BaseEnd; ++Base) {
07871     if (Base->isVirtual())
07872       continue;
07873 
07874     if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
07875       return false;
07876   }
07877 
07878   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
07879                                           BaseEnd = ClassDecl->vbases_end();
07880        Base != BaseEnd; ++Base) {
07881     if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
07882       return false;
07883   }
07884 
07885   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
07886                                      FieldEnd = ClassDecl->field_end();
07887        Field != FieldEnd; ++Field) {
07888     if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
07889       return false;
07890   }
07891 
07892   return true;
07893 }
07894 
07895 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
07896   // C++11 [class.copy]p20:
07897   //   If the definition of a class X does not explicitly declare a move
07898   //   assignment operator, one will be implicitly declared as defaulted
07899   //   if and only if:
07900   //
07901   //   - [first 4 bullets]
07902   assert(ClassDecl->needsImplicitMoveAssignment());
07903 
07904   // [Checked after we build the declaration]
07905   //   - the move assignment operator would not be implicitly defined as
07906   //     deleted,
07907 
07908   // [DR1402]:
07909   //   - X has no direct or indirect virtual base class with a non-trivial
07910   //     move assignment operator, and
07911   //   - each of X's non-static data members and direct or virtual base classes
07912   //     has a type that either has a move assignment operator or is trivially
07913   //     copyable.
07914   if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
07915       !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
07916     ClassDecl->setFailedImplicitMoveAssignment();
07917     return 0;
07918   }
07919 
07920   // Note: The following rules are largely analoguous to the move
07921   // constructor rules.
07922 
07923   ImplicitExceptionSpecification Spec(
07924       ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
07925 
07926   QualType ArgType = Context.getTypeDeclType(ClassDecl);
07927   QualType RetType = Context.getLValueReferenceType(ArgType);
07928   ArgType = Context.getRValueReferenceType(ArgType);
07929 
07930   //   An implicitly-declared move assignment operator is an inline public
07931   //   member of its class.
07932   FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
07933   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
07934   SourceLocation ClassLoc = ClassDecl->getLocation();
07935   DeclarationNameInfo NameInfo(Name, ClassLoc);
07936   CXXMethodDecl *MoveAssignment
07937     = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
07938                             Context.getFunctionType(RetType, &ArgType, 1, EPI),
07939                             /*TInfo=*/0, /*isStatic=*/false,
07940                             /*StorageClassAsWritten=*/SC_None,
07941                             /*isInline=*/true,
07942                             /*isConstexpr=*/false,
07943                             SourceLocation());
07944   MoveAssignment->setAccess(AS_public);
07945   MoveAssignment->setDefaulted();
07946   MoveAssignment->setImplicit();
07947   MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
07948 
07949   // Add the parameter to the operator.
07950   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
07951                                                ClassLoc, ClassLoc, /*Id=*/0,
07952                                                ArgType, /*TInfo=*/0,
07953                                                SC_None,
07954                                                SC_None, 0);
07955   MoveAssignment->setParams(FromParam);
07956 
07957   // Note that we have added this copy-assignment operator.
07958   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
07959 
07960   // C++0x [class.copy]p9:
07961   //   If the definition of a class X does not explicitly declare a move
07962   //   assignment operator, one will be implicitly declared as defaulted if and
07963   //   only if:
07964   //   [...]
07965   //   - the move assignment operator would not be implicitly defined as
07966   //     deleted.
07967   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
07968     // Cache this result so that we don't try to generate this over and over
07969     // on every lookup, leaking memory and wasting time.
07970     ClassDecl->setFailedImplicitMoveAssignment();
07971     return 0;
07972   }
07973 
07974   if (Scope *S = getScopeForContext(ClassDecl))
07975     PushOnScopeChains(MoveAssignment, S, false);
07976   ClassDecl->addDecl(MoveAssignment);
07977 
07978   AddOverriddenMethods(ClassDecl, MoveAssignment);
07979   return MoveAssignment;
07980 }
07981 
07982 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
07983                                         CXXMethodDecl *MoveAssignOperator) {
07984   assert((MoveAssignOperator->isDefaulted() && 
07985           MoveAssignOperator->isOverloadedOperator() &&
07986           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
07987           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
07988           !MoveAssignOperator->isDeleted()) &&
07989          "DefineImplicitMoveAssignment called for wrong function");
07990 
07991   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
07992 
07993   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
07994     MoveAssignOperator->setInvalidDecl();
07995     return;
07996   }
07997   
07998   MoveAssignOperator->setUsed();
07999 
08000   ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
08001   DiagnosticErrorTrap Trap(Diags);
08002 
08003   // C++0x [class.copy]p28:
08004   //   The implicitly-defined or move assignment operator for a non-union class
08005   //   X performs memberwise move assignment of its subobjects. The direct base
08006   //   classes of X are assigned first, in the order of their declaration in the
08007   //   base-specifier-list, and then the immediate non-static data members of X
08008   //   are assigned, in the order in which they were declared in the class
08009   //   definition.
08010 
08011   // The statements that form the synthesized function body.
08012   ASTOwningVector<Stmt*> Statements(*this);
08013 
08014   // The parameter for the "other" object, which we are move from.
08015   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
08016   QualType OtherRefType = Other->getType()->
08017       getAs<RValueReferenceType>()->getPointeeType();
08018   assert(OtherRefType.getQualifiers() == 0 &&
08019          "Bad argument type of defaulted move assignment");
08020 
08021   // Our location for everything implicitly-generated.
08022   SourceLocation Loc = MoveAssignOperator->getLocation();
08023 
08024   // Construct a reference to the "other" object. We'll be using this 
08025   // throughout the generated ASTs.
08026   Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
08027   assert(OtherRef && "Reference to parameter cannot fail!");
08028   // Cast to rvalue.
08029   OtherRef = CastForMoving(*this, OtherRef);
08030 
08031   // Construct the "this" pointer. We'll be using this throughout the generated
08032   // ASTs.
08033   Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
08034   assert(This && "Reference to this cannot fail!");
08035 
08036   // Assign base classes.
08037   bool Invalid = false;
08038   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
08039        E = ClassDecl->bases_end(); Base != E; ++Base) {
08040     // Form the assignment:
08041     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
08042     QualType BaseType = Base->getType().getUnqualifiedType();
08043     if (!BaseType->isRecordType()) {
08044       Invalid = true;
08045       continue;
08046     }
08047 
08048     CXXCastPath BasePath;
08049     BasePath.push_back(Base);
08050 
08051     // Construct the "from" expression, which is an implicit cast to the
08052     // appropriately-qualified base type.
08053     Expr *From = OtherRef;
08054     From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
08055                              VK_XValue, &BasePath).take();
08056 
08057     // Dereference "this".
08058     ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
08059 
08060     // Implicitly cast "this" to the appropriately-qualified base type.
08061     To = ImpCastExprToType(To.take(), 
08062                            Context.getCVRQualifiedType(BaseType,
08063                                      MoveAssignOperator->getTypeQualifiers()),
08064                            CK_UncheckedDerivedToBase, 
08065                            VK_LValue, &BasePath);
08066 
08067     // Build the move.
08068     StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
08069                                             To.get(), From,
08070                                             /*CopyingBaseSubobject=*/true,
08071                                             /*Copying=*/false);
08072     if (Move.isInvalid()) {
08073       Diag(CurrentLocation, diag::note_member_synthesized_at) 
08074         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
08075       MoveAssignOperator->setInvalidDecl();
08076       return;
08077     }
08078 
08079     // Success! Record the move.
08080     Statements.push_back(Move.takeAs<Expr>());
08081   }
08082 
08083   // \brief Reference to the __builtin_memcpy function.
08084   Expr *BuiltinMemCpyRef = 0;
08085   // \brief Reference to the __builtin_objc_memmove_collectable function.
08086   Expr *CollectableMemCpyRef = 0;
08087 
08088   // Assign non-static members.
08089   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
08090                                   FieldEnd = ClassDecl->field_end(); 
08091        Field != FieldEnd; ++Field) {
08092     if (Field->isUnnamedBitfield())
08093       continue;
08094 
08095     // Check for members of reference type; we can't move those.
08096     if (Field->getType()->isReferenceType()) {
08097       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
08098         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
08099       Diag(Field->getLocation(), diag::note_declared_at);
08100       Diag(CurrentLocation, diag::note_member_synthesized_at) 
08101         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
08102       Invalid = true;
08103       continue;
08104     }
08105 
08106     // Check for members of const-qualified, non-class type.
08107     QualType BaseType = Context.getBaseElementType(Field->getType());
08108     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
08109       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
08110         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
08111       Diag(Field->getLocation(), diag::note_declared_at);
08112       Diag(CurrentLocation, diag::note_member_synthesized_at) 
08113         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
08114       Invalid = true;      
08115       continue;
08116     }
08117 
08118     // Suppress assigning zero-width bitfields.
08119     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
08120       continue;
08121     
08122     QualType FieldType = Field->getType().getNonReferenceType();
08123     if (FieldType->isIncompleteArrayType()) {
08124       assert(ClassDecl->hasFlexibleArrayMember() && 
08125              "Incomplete array type is not valid");
08126       continue;
08127     }
08128     
08129     // Build references to the field in the object we're copying from and to.
08130     CXXScopeSpec SS; // Intentionally empty
08131     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
08132                               LookupMemberName);
08133     MemberLookup.addDecl(&*Field);
08134     MemberLookup.resolveKind();
08135     ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
08136                                                Loc, /*IsArrow=*/false,
08137                                                SS, SourceLocation(), 0,
08138                                                MemberLookup, 0);
08139     ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
08140                                              Loc, /*IsArrow=*/true,
08141                                              SS, SourceLocation(), 0,
08142                                              MemberLookup, 0);
08143     assert(!From.isInvalid() && "Implicit field reference cannot fail");
08144     assert(!To.isInvalid() && "Implicit field reference cannot fail");
08145 
08146     assert(!From.get()->isLValue() && // could be xvalue or prvalue
08147         "Member reference with rvalue base must be rvalue except for reference "
08148         "members, which aren't allowed for move assignment.");
08149 
08150     // If the field should be copied with __builtin_memcpy rather than via
08151     // explicit assignments, do so. This optimization only applies for arrays 
08152     // of scalars and arrays of class type with trivial move-assignment 
08153     // operators.
08154     if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
08155         && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
08156       // Compute the size of the memory buffer to be copied.
08157       QualType SizeType = Context.getSizeType();
08158       llvm::APInt Size(Context.getTypeSize(SizeType), 
08159                        Context.getTypeSizeInChars(BaseType).getQuantity());
08160       for (const ConstantArrayType *Array
08161               = Context.getAsConstantArrayType(FieldType);
08162            Array; 
08163            Array = Context.getAsConstantArrayType(Array->getElementType())) {
08164         llvm::APInt ArraySize
08165           = Array->getSize().zextOrTrunc(Size.getBitWidth());
08166         Size *= ArraySize;
08167       }
08168 
08169       // Take the address of the field references for "from" and "to". We
08170       // directly construct UnaryOperators here because semantic analysis
08171       // does not permit us to take the address of an xvalue.
08172       From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
08173                              Context.getPointerType(From.get()->getType()),
08174                              VK_RValue, OK_Ordinary, Loc);
08175       To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
08176                            Context.getPointerType(To.get()->getType()),
08177                            VK_RValue, OK_Ordinary, Loc);
08178           
08179       bool NeedsCollectableMemCpy = 
08180           (BaseType->isRecordType() && 
08181            BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
08182           
08183       if (NeedsCollectableMemCpy) {
08184         if (!CollectableMemCpyRef) {
08185           // Create a reference to the __builtin_objc_memmove_collectable function.
08186           LookupResult R(*this, 
08187                          &Context.Idents.get("__builtin_objc_memmove_collectable"), 
08188                          Loc, LookupOrdinaryName);
08189           LookupName(R, TUScope, true);
08190         
08191           FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
08192           if (!CollectableMemCpy) {
08193             // Something went horribly wrong earlier, and we will have 
08194             // complained about it.
08195             Invalid = true;
08196             continue;
08197           }
08198         
08199           CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy, 
08200                                                   CollectableMemCpy->getType(),
08201                                                   VK_LValue, Loc, 0).take();
08202           assert(CollectableMemCpyRef && "Builtin reference cannot fail");
08203         }
08204       }
08205       // Create a reference to the __builtin_memcpy builtin function.
08206       else if (!BuiltinMemCpyRef) {
08207         LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
08208                        LookupOrdinaryName);
08209         LookupName(R, TUScope, true);
08210         
08211         FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
08212         if (!BuiltinMemCpy) {
08213           // Something went horribly wrong earlier, and we will have complained
08214           // about it.
08215           Invalid = true;
08216           continue;
08217         }
08218 
08219         BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy, 
08220                                             BuiltinMemCpy->getType(),
08221                                             VK_LValue, Loc, 0).take();
08222         assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
08223       }
08224           
08225       ASTOwningVector<Expr*> CallArgs(*this);
08226       CallArgs.push_back(To.takeAs<Expr>());
08227       CallArgs.push_back(From.takeAs<Expr>());
08228       CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
08229       ExprResult Call = ExprError();
08230       if (NeedsCollectableMemCpy)
08231         Call = ActOnCallExpr(/*Scope=*/0,
08232                              CollectableMemCpyRef,
08233                              Loc, move_arg(CallArgs), 
08234                              Loc);
08235       else
08236         Call = ActOnCallExpr(/*Scope=*/0,
08237                              BuiltinMemCpyRef,
08238                              Loc, move_arg(CallArgs), 
08239                              Loc);
08240           
08241       assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
08242       Statements.push_back(Call.takeAs<Expr>());
08243       continue;
08244     }
08245     
08246     // Build the move of this field.
08247     StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType, 
08248                                             To.get(), From.get(),
08249                                             /*CopyingBaseSubobject=*/false,
08250                                             /*Copying=*/false);
08251     if (Move.isInvalid()) {
08252       Diag(CurrentLocation, diag::note_member_synthesized_at) 
08253         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
08254       MoveAssignOperator->setInvalidDecl();
08255       return;
08256     }
08257     
08258     // Success! Record the copy.
08259     Statements.push_back(Move.takeAs<Stmt>());
08260   }
08261 
08262   if (!Invalid) {
08263     // Add a "return *this;"
08264     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
08265     
08266     StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
08267     if (Return.isInvalid())
08268       Invalid = true;
08269     else {
08270       Statements.push_back(Return.takeAs<Stmt>());
08271 
08272       if (Trap.hasErrorOccurred()) {
08273         Diag(CurrentLocation, diag::note_member_synthesized_at) 
08274           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
08275         Invalid = true;
08276       }
08277     }
08278   }
08279 
08280   if (Invalid) {
08281     MoveAssignOperator->setInvalidDecl();
08282     return;
08283   }
08284 
08285   StmtResult Body;
08286   {
08287     CompoundScopeRAII CompoundScope(*this);
08288     Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
08289                              /*isStmtExpr=*/false);
08290     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
08291   }
08292   MoveAssignOperator->setBody(Body.takeAs<Stmt>());
08293 
08294   if (ASTMutationListener *L = getASTMutationListener()) {
08295     L->CompletedImplicitDefinition(MoveAssignOperator);
08296   }
08297 }
08298 
08299 std::pair<Sema::ImplicitExceptionSpecification, bool>
08300 Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
08301   if (ClassDecl->isInvalidDecl())
08302     return std::make_pair(ImplicitExceptionSpecification(*this), true);
08303 
08304   // C++ [class.copy]p5:
08305   //   The implicitly-declared copy constructor for a class X will
08306   //   have the form
08307   //
08308   //       X::X(const X&)
08309   //
08310   //   if
08311   // FIXME: It ought to be possible to store this on the record.
08312   bool HasConstCopyConstructor = true;
08313   
08314   //     -- each direct or virtual base class B of X has a copy
08315   //        constructor whose first parameter is of type const B& or
08316   //        const volatile B&, and
08317   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
08318                                        BaseEnd = ClassDecl->bases_end();
08319        HasConstCopyConstructor && Base != BaseEnd; 
08320        ++Base) {
08321     // Virtual bases are handled below.
08322     if (Base->isVirtual())
08323       continue;
08324     
08325     CXXRecordDecl *BaseClassDecl
08326       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
08327     HasConstCopyConstructor &=
08328       (bool)LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const);
08329   }
08330 
08331   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
08332                                        BaseEnd = ClassDecl->vbases_end();
08333        HasConstCopyConstructor && Base != BaseEnd; 
08334        ++Base) {
08335     CXXRecordDecl *BaseClassDecl
08336       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
08337     HasConstCopyConstructor &=
08338       (bool)LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const);
08339   }
08340   
08341   //     -- for all the nonstatic data members of X that are of a
08342   //        class type M (or array thereof), each such class type
08343   //        has a copy constructor whose first parameter is of type
08344   //        const M& or const volatile M&.
08345   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
08346                                   FieldEnd = ClassDecl->field_end();
08347        HasConstCopyConstructor && Field != FieldEnd;
08348        ++Field) {
08349     QualType FieldType = Context.getBaseElementType(Field->getType());
08350     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
08351       HasConstCopyConstructor &=
08352         (bool)LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const);
08353     }
08354   }
08355   //   Otherwise, the implicitly declared copy constructor will have
08356   //   the form
08357   //
08358   //       X::X(X&)
08359  
08360   // C++ [except.spec]p14:
08361   //   An implicitly declared special member function (Clause 12) shall have an 
08362   //   exception-specification. [...]
08363   ImplicitExceptionSpecification ExceptSpec(*this);
08364   unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
08365   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
08366                                        BaseEnd = ClassDecl->bases_end();
08367        Base != BaseEnd; 
08368        ++Base) {
08369     // Virtual bases are handled below.
08370     if (Base->isVirtual())
08371       continue;
08372     
08373     CXXRecordDecl *BaseClassDecl
08374       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
08375     if (CXXConstructorDecl *CopyConstructor =
08376           LookupCopyingConstructor(BaseClassDecl, Quals))
08377       ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
08378   }
08379   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
08380                                        BaseEnd = ClassDecl->vbases_end();
08381        Base != BaseEnd; 
08382        ++Base) {
08383     CXXRecordDecl *BaseClassDecl
08384       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
08385     if (CXXConstructorDecl *CopyConstructor =
08386           LookupCopyingConstructor(BaseClassDecl, Quals))
08387       ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
08388   }
08389   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
08390                                   FieldEnd = ClassDecl->field_end();
08391        Field != FieldEnd;
08392        ++Field) {
08393     QualType FieldType = Context.getBaseElementType(Field->getType());
08394     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
08395       if (CXXConstructorDecl *CopyConstructor =
08396         LookupCopyingConstructor(FieldClassDecl, Quals))
08397       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
08398     }
08399   }
08400 
08401   return std::make_pair(ExceptSpec, HasConstCopyConstructor);
08402 }
08403 
08404 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
08405                                                     CXXRecordDecl *ClassDecl) {
08406   // C++ [class.copy]p4:
08407   //   If the class definition does not explicitly declare a copy
08408   //   constructor, one is declared implicitly.
08409 
08410   ImplicitExceptionSpecification Spec(*this);
08411   bool Const;
08412   llvm::tie(Spec, Const) =
08413     ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
08414 
08415   QualType ClassType = Context.getTypeDeclType(ClassDecl);
08416   QualType ArgType = ClassType;
08417   if (Const)
08418     ArgType = ArgType.withConst();
08419   ArgType = Context.getLValueReferenceType(ArgType);
08420  
08421   FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
08422 
08423   DeclarationName Name
08424     = Context.DeclarationNames.getCXXConstructorName(
08425                                            Context.getCanonicalType(ClassType));
08426   SourceLocation ClassLoc = ClassDecl->getLocation();
08427   DeclarationNameInfo NameInfo(Name, ClassLoc);
08428 
08429   //   An implicitly-declared copy constructor is an inline public
08430   //   member of its class.
08431   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
08432       Context, ClassDecl, ClassLoc, NameInfo,
08433       Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
08434       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
08435       /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
08436         getLangOpts().CPlusPlus0x);
08437   CopyConstructor->setAccess(AS_public);
08438   CopyConstructor->setDefaulted();
08439   CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
08440 
08441   // Note that we have declared this constructor.
08442   ++ASTContext::NumImplicitCopyConstructorsDeclared;
08443   
08444   // Add the parameter to the constructor.
08445   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
08446                                                ClassLoc, ClassLoc,
08447                                                /*IdentifierInfo=*/0,
08448                                                ArgType, /*TInfo=*/0,
08449                                                SC_None,
08450                                                SC_None, 0);
08451   CopyConstructor->setParams(FromParam);
08452 
08453   if (Scope *S = getScopeForContext(ClassDecl))
08454     PushOnScopeChains(CopyConstructor, S, false);
08455   ClassDecl->addDecl(CopyConstructor);
08456 
08457   // C++11 [class.copy]p8:
08458   //   ... If the class definition does not explicitly declare a copy
08459   //   constructor, there is no user-declared move constructor, and there is no
08460   //   user-declared move assignment operator, a copy constructor is implicitly
08461   //   declared as defaulted.
08462   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
08463     CopyConstructor->setDeletedAsWritten();
08464 
08465   return CopyConstructor;
08466 }
08467 
08468 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
08469                                    CXXConstructorDecl *CopyConstructor) {
08470   assert((CopyConstructor->isDefaulted() &&
08471           CopyConstructor->isCopyConstructor() &&
08472           !CopyConstructor->doesThisDeclarationHaveABody() &&
08473           !CopyConstructor->isDeleted()) &&
08474          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
08475 
08476   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
08477   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
08478 
08479   ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
08480   DiagnosticErrorTrap Trap(Diags);
08481 
08482   if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
08483       Trap.hasErrorOccurred()) {
08484     Diag(CurrentLocation, diag::note_member_synthesized_at) 
08485       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
08486     CopyConstructor->setInvalidDecl();
08487   }  else {
08488     Sema::CompoundScopeRAII CompoundScope(*this);
08489     CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
08490                                                CopyConstructor->getLocation(),
08491                                                MultiStmtArg(*this, 0, 0),
08492                                                /*isStmtExpr=*/false)
08493                                                               .takeAs<Stmt>());
08494     CopyConstructor->setImplicitlyDefined(true);
08495   }
08496   
08497   CopyConstructor->setUsed();
08498   if (ASTMutationListener *L = getASTMutationListener()) {
08499     L->CompletedImplicitDefinition(CopyConstructor);
08500   }
08501 }
08502 
08503 Sema::ImplicitExceptionSpecification
08504 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
08505   // C++ [except.spec]p14:
08506   //   An implicitly declared special member function (Clause 12) shall have an 
08507   //   exception-specification. [...]
08508   ImplicitExceptionSpecification ExceptSpec(*this);
08509   if (ClassDecl->isInvalidDecl())
08510     return ExceptSpec;
08511 
08512   // Direct base-class constructors.
08513   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
08514                                        BEnd = ClassDecl->bases_end();
08515        B != BEnd; ++B) {
08516     if (B->isVirtual()) // Handled below.
08517       continue;
08518     
08519     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
08520       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
08521       CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
08522       // If this is a deleted function, add it anyway. This might be conformant
08523       // with the standard. This might not. I'm not sure. It might not matter.
08524       if (Constructor)
08525         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
08526     }
08527   }
08528 
08529   // Virtual base-class constructors.
08530   for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
08531                                        BEnd = ClassDecl->vbases_end();
08532        B != BEnd; ++B) {
08533     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
08534       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
08535       CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
08536       // If this is a deleted function, add it anyway. This might be conformant
08537       // with the standard. This might not. I'm not sure. It might not matter.
08538       if (Constructor)
08539         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
08540     }
08541   }
08542 
08543   // Field constructors.
08544   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
08545                                FEnd = ClassDecl->field_end();
08546        F != FEnd; ++F) {
08547     if (const RecordType *RecordTy
08548               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
08549       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
08550       CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
08551       // If this is a deleted function, add it anyway. This might be conformant
08552       // with the standard. This might not. I'm not sure. It might not matter.
08553       // In particular, the problem is that this function never gets called. It
08554       // might just be ill-formed because this function attempts to refer to
08555       // a deleted function here.
08556       if (Constructor)
08557         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
08558     }
08559   }
08560 
08561   return ExceptSpec;
08562 }
08563 
08564 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
08565                                                     CXXRecordDecl *ClassDecl) {
08566   // C++11 [class.copy]p9:
08567   //   If the definition of a class X does not explicitly declare a move
08568   //   constructor, one will be implicitly declared as defaulted if and only if:
08569   //
08570   //   - [first 4 bullets]
08571   assert(ClassDecl->needsImplicitMoveConstructor());
08572 
08573   // [Checked after we build the declaration]
08574   //   - the move assignment operator would not be implicitly defined as
08575   //     deleted,
08576 
08577   // [DR1402]:
08578   //   - each of X's non-static data members and direct or virtual base classes
08579   //     has a type that either has a move constructor or is trivially copyable.
08580   if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
08581     ClassDecl->setFailedImplicitMoveConstructor();
08582     return 0;
08583   }
08584 
08585   ImplicitExceptionSpecification Spec(
08586       ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
08587 
08588   QualType ClassType = Context.getTypeDeclType(ClassDecl);
08589   QualType ArgType = Context.getRValueReferenceType(ClassType);
08590  
08591   FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
08592 
08593   DeclarationName Name
08594     = Context.DeclarationNames.getCXXConstructorName(
08595                                            Context.getCanonicalType(ClassType));
08596   SourceLocation ClassLoc = ClassDecl->getLocation();
08597   DeclarationNameInfo NameInfo(Name, ClassLoc);
08598 
08599   // C++0x [class.copy]p11:
08600   //   An implicitly-declared copy/move constructor is an inline public
08601   //   member of its class.
08602   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
08603       Context, ClassDecl, ClassLoc, NameInfo,
08604       Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
08605       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
08606       /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
08607         getLangOpts().CPlusPlus0x);
08608   MoveConstructor->setAccess(AS_public);
08609   MoveConstructor->setDefaulted();
08610   MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
08611 
08612   // Add the parameter to the constructor.
08613   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
08614                                                ClassLoc, ClassLoc,
08615                                                /*IdentifierInfo=*/0,
08616                                                ArgType, /*TInfo=*/0,
08617                                                SC_None,
08618                                                SC_None, 0);
08619   MoveConstructor->setParams(FromParam);
08620 
08621   // C++0x [class.copy]p9:
08622   //   If the definition of a class X does not explicitly declare a move
08623   //   constructor, one will be implicitly declared as defaulted if and only if:
08624   //   [...]
08625   //   - the move constructor would not be implicitly defined as deleted.
08626   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
08627     // Cache this result so that we don't try to generate this over and over
08628     // on every lookup, leaking memory and wasting time.
08629     ClassDecl->setFailedImplicitMoveConstructor();
08630     return 0;
08631   }
08632 
08633   // Note that we have declared this constructor.
08634   ++ASTContext::NumImplicitMoveConstructorsDeclared;
08635 
08636   if (Scope *S = getScopeForContext(ClassDecl))
08637     PushOnScopeChains(MoveConstructor, S, false);
08638   ClassDecl->addDecl(MoveConstructor);
08639 
08640   return MoveConstructor;
08641 }
08642 
08643 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
08644                                    CXXConstructorDecl *MoveConstructor) {
08645   assert((MoveConstructor->isDefaulted() &&
08646           MoveConstructor->isMoveConstructor() &&
08647           !MoveConstructor->doesThisDeclarationHaveABody() &&
08648           !MoveConstructor->isDeleted()) &&
08649          "DefineImplicitMoveConstructor - call it for implicit move ctor");
08650 
08651   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
08652   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
08653 
08654   ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
08655   DiagnosticErrorTrap Trap(Diags);
08656 
08657   if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
08658       Trap.hasErrorOccurred()) {
08659     Diag(CurrentLocation, diag::note_member_synthesized_at) 
08660       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
08661     MoveConstructor->setInvalidDecl();
08662   }  else {
08663     Sema::CompoundScopeRAII CompoundScope(*this);
08664     MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
08665                                                MoveConstructor->getLocation(),
08666                                                MultiStmtArg(*this, 0, 0),
08667                                                /*isStmtExpr=*/false)
08668                                                               .takeAs<Stmt>());
08669     MoveConstructor->setImplicitlyDefined(true);
08670   }
08671 
08672   MoveConstructor->setUsed();
08673 
08674   if (ASTMutationListener *L = getASTMutationListener()) {
08675     L->CompletedImplicitDefinition(MoveConstructor);
08676   }
08677 }
08678 
08679 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
08680   return FD->isDeleted() && 
08681          (FD->isDefaulted() || FD->isImplicit()) &&
08682          isa<CXXMethodDecl>(FD);
08683 }
08684 
08685 /// \brief Mark the call operator of the given lambda closure type as "used".
08686 static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
08687   CXXMethodDecl *CallOperator 
08688     = cast<CXXMethodDecl>(
08689         *Lambda->lookup(
08690           S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
08691   CallOperator->setReferenced();
08692   CallOperator->setUsed();
08693 }
08694 
08695 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
08696        SourceLocation CurrentLocation,
08697        CXXConversionDecl *Conv) 
08698 {
08699   CXXRecordDecl *Lambda = Conv->getParent();
08700   
08701   // Make sure that the lambda call operator is marked used.
08702   markLambdaCallOperatorUsed(*this, Lambda);
08703   
08704   Conv->setUsed();
08705   
08706   ImplicitlyDefinedFunctionScope Scope(*this, Conv);
08707   DiagnosticErrorTrap Trap(Diags);
08708   
08709   // Return the address of the __invoke function.
08710   DeclarationName InvokeName = &Context.Idents.get("__invoke");
08711   CXXMethodDecl *Invoke 
08712     = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
08713   Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
08714                                        VK_LValue, Conv->getLocation()).take();
08715   assert(FunctionRef && "Can't refer to __invoke function?");
08716   Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
08717   Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1, 
08718                                            Conv->getLocation(),
08719                                            Conv->getLocation()));
08720     
08721   // Fill in the __invoke function with a dummy implementation. IR generation
08722   // will fill in the actual details.
08723   Invoke->setUsed();
08724   Invoke->setReferenced();
08725   Invoke->setBody(new (Context) CompoundStmt(Context, 0, 0, Conv->getLocation(),
08726                                              Conv->getLocation()));
08727   
08728   if (ASTMutationListener *L = getASTMutationListener()) {
08729     L->CompletedImplicitDefinition(Conv);
08730     L->CompletedImplicitDefinition(Invoke);
08731   }
08732 }
08733 
08734 void Sema::DefineImplicitLambdaToBlockPointerConversion(
08735        SourceLocation CurrentLocation,
08736        CXXConversionDecl *Conv) 
08737 {
08738   Conv->setUsed();
08739   
08740   ImplicitlyDefinedFunctionScope Scope(*this, Conv);
08741   DiagnosticErrorTrap Trap(Diags);
08742   
08743   // Copy-initialize the lambda object as needed to capture it.
08744   Expr *This = ActOnCXXThis(CurrentLocation).take();
08745   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
08746   
08747   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
08748                                                         Conv->getLocation(),
08749                                                         Conv, DerefThis);
08750 
08751   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
08752   // behavior.  Note that only the general conversion function does this
08753   // (since it's unusable otherwise); in the case where we inline the
08754   // block literal, it has block literal lifetime semantics.
08755   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
08756     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
08757                                           CK_CopyAndAutoreleaseBlockObject,
08758                                           BuildBlock.get(), 0, VK_RValue);
08759 
08760   if (BuildBlock.isInvalid()) {
08761     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
08762     Conv->setInvalidDecl();
08763     return;
08764   }
08765 
08766   // Create the return statement that returns the block from the conversion
08767   // function.
08768   StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
08769   if (Return.isInvalid()) {
08770     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
08771     Conv->setInvalidDecl();
08772     return;
08773   }
08774 
08775   // Set the body of the conversion function.
08776   Stmt *ReturnS = Return.take();
08777   Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1, 
08778                                            Conv->getLocation(), 
08779                                            Conv->getLocation()));
08780   
08781   // We're done; notify the mutation listener, if any.
08782   if (ASTMutationListener *L = getASTMutationListener()) {
08783     L->CompletedImplicitDefinition(Conv);
08784   }
08785 }
08786 
08787 /// \brief Determine whether the given list arguments contains exactly one 
08788 /// "real" (non-default) argument.
08789 static bool hasOneRealArgument(MultiExprArg Args) {
08790   switch (Args.size()) {
08791   case 0:
08792     return false;
08793     
08794   default:
08795     if (!Args.get()[1]->isDefaultArgument())
08796       return false;
08797     
08798     // fall through
08799   case 1:
08800     return !Args.get()[0]->isDefaultArgument();
08801   }
08802   
08803   return false;
08804 }
08805 
08806 ExprResult
08807 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
08808                             CXXConstructorDecl *Constructor,
08809                             MultiExprArg ExprArgs,
08810                             bool HadMultipleCandidates,
08811                             bool RequiresZeroInit,
08812                             unsigned ConstructKind,
08813                             SourceRange ParenRange) {
08814   bool Elidable = false;
08815 
08816   // C++0x [class.copy]p34:
08817   //   When certain criteria are met, an implementation is allowed to
08818   //   omit the copy/move construction of a class object, even if the
08819   //   copy/move constructor and/or destructor for the object have
08820   //   side effects. [...]
08821   //     - when a temporary class object that has not been bound to a
08822   //       reference (12.2) would be copied/moved to a class object
08823   //       with the same cv-unqualified type, the copy/move operation
08824   //       can be omitted by constructing the temporary object
08825   //       directly into the target of the omitted copy/move
08826   if (ConstructKind == CXXConstructExpr::CK_Complete &&
08827       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
08828     Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
08829     Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
08830   }
08831 
08832   return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
08833                                Elidable, move(ExprArgs), HadMultipleCandidates,
08834                                RequiresZeroInit, ConstructKind, ParenRange);
08835 }
08836 
08837 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
08838 /// including handling of its default argument expressions.
08839 ExprResult
08840 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
08841                             CXXConstructorDecl *Constructor, bool Elidable,
08842                             MultiExprArg ExprArgs,
08843                             bool HadMultipleCandidates,
08844                             bool RequiresZeroInit,
08845                             unsigned ConstructKind,
08846                             SourceRange ParenRange) {
08847   unsigned NumExprs = ExprArgs.size();
08848   Expr **Exprs = (Expr **)ExprArgs.release();
08849 
08850   for (specific_attr_iterator<NonNullAttr>
08851            i = Constructor->specific_attr_begin<NonNullAttr>(),
08852            e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
08853     const NonNullAttr *NonNull = *i;
08854     CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
08855   }
08856 
08857   MarkFunctionReferenced(ConstructLoc, Constructor);
08858   return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
08859                                         Constructor, Elidable, Exprs, NumExprs,
08860                                         HadMultipleCandidates, /*FIXME*/false,
08861                                         RequiresZeroInit,
08862               static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
08863                                         ParenRange));
08864 }
08865 
08866 bool Sema::InitializeVarWithConstructor(VarDecl *VD,
08867                                         CXXConstructorDecl *Constructor,
08868                                         MultiExprArg Exprs,
08869                                         bool HadMultipleCandidates) {
08870   // FIXME: Provide the correct paren SourceRange when available.
08871   ExprResult TempResult =
08872     BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
08873                           move(Exprs), HadMultipleCandidates, false,
08874                           CXXConstructExpr::CK_Complete, SourceRange());
08875   if (TempResult.isInvalid())
08876     return true;
08877 
08878   Expr *Temp = TempResult.takeAs<Expr>();
08879   CheckImplicitConversions(Temp, VD->getLocation());
08880   MarkFunctionReferenced(VD->getLocation(), Constructor);
08881   Temp = MaybeCreateExprWithCleanups(Temp);
08882   VD->setInit(Temp);
08883 
08884   return false;
08885 }
08886 
08887 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
08888   if (VD->isInvalidDecl()) return;
08889 
08890   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
08891   if (ClassDecl->isInvalidDecl()) return;
08892   if (ClassDecl->hasIrrelevantDestructor()) return;
08893   if (ClassDecl->isDependentContext()) return;
08894 
08895   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
08896   MarkFunctionReferenced(VD->getLocation(), Destructor);
08897   CheckDestructorAccess(VD->getLocation(), Destructor,
08898                         PDiag(diag::err_access_dtor_var)
08899                         << VD->getDeclName()
08900                         << VD->getType());
08901   DiagnoseUseOfDecl(Destructor, VD->getLocation());
08902 
08903   if (!VD->hasGlobalStorage()) return;
08904 
08905   // Emit warning for non-trivial dtor in global scope (a real global,
08906   // class-static, function-static).
08907   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
08908 
08909   // TODO: this should be re-enabled for static locals by !CXAAtExit
08910   if (!VD->isStaticLocal())
08911     Diag(VD->getLocation(), diag::warn_global_destructor);
08912 }
08913 
08914 /// \brief Given a constructor and the set of arguments provided for the
08915 /// constructor, convert the arguments and add any required default arguments
08916 /// to form a proper call to this constructor.
08917 ///
08918 /// \returns true if an error occurred, false otherwise.
08919 bool 
08920 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
08921                               MultiExprArg ArgsPtr,
08922                               SourceLocation Loc,                                    
08923                               ASTOwningVector<Expr*> &ConvertedArgs,
08924                               bool AllowExplicit) {
08925   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
08926   unsigned NumArgs = ArgsPtr.size();
08927   Expr **Args = (Expr **)ArgsPtr.get();
08928 
08929   const FunctionProtoType *Proto 
08930     = Constructor->getType()->getAs<FunctionProtoType>();
08931   assert(Proto && "Constructor without a prototype?");
08932   unsigned NumArgsInProto = Proto->getNumArgs();
08933   
08934   // If too few arguments are available, we'll fill in the rest with defaults.
08935   if (NumArgs < NumArgsInProto)
08936     ConvertedArgs.reserve(NumArgsInProto);
08937   else
08938     ConvertedArgs.reserve(NumArgs);
08939 
08940   VariadicCallType CallType = 
08941     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
08942   SmallVector<Expr *, 8> AllArgs;
08943   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
08944                                         Proto, 0, Args, NumArgs, AllArgs, 
08945                                         CallType, AllowExplicit);
08946   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
08947 
08948   DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
08949 
08950   // FIXME: Missing call to CheckFunctionCall or equivalent
08951 
08952   return Invalid;
08953 }
08954 
08955 static inline bool
08956 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 
08957                                        const FunctionDecl *FnDecl) {
08958   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
08959   if (isa<NamespaceDecl>(DC)) {
08960     return SemaRef.Diag(FnDecl->getLocation(), 
08961                         diag::err_operator_new_delete_declared_in_namespace)
08962       << FnDecl->getDeclName();
08963   }
08964   
08965   if (isa<TranslationUnitDecl>(DC) && 
08966       FnDecl->getStorageClass() == SC_Static) {
08967     return SemaRef.Diag(FnDecl->getLocation(),
08968                         diag::err_operator_new_delete_declared_static)
08969       << FnDecl->getDeclName();
08970   }
08971   
08972   return false;
08973 }
08974 
08975 static inline bool
08976 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
08977                             CanQualType ExpectedResultType,
08978                             CanQualType ExpectedFirstParamType,
08979                             unsigned DependentParamTypeDiag,
08980                             unsigned InvalidParamTypeDiag) {
08981   QualType ResultType = 
08982     FnDecl->getType()->getAs<FunctionType>()->getResultType();
08983 
08984   // Check that the result type is not dependent.
08985   if (ResultType->isDependentType())
08986     return SemaRef.Diag(FnDecl->getLocation(),
08987                         diag::err_operator_new_delete_dependent_result_type)
08988     << FnDecl->getDeclName() << ExpectedResultType;
08989 
08990   // Check that the result type is what we expect.
08991   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
08992     return SemaRef.Diag(FnDecl->getLocation(),
08993                         diag::err_operator_new_delete_invalid_result_type) 
08994     << FnDecl->getDeclName() << ExpectedResultType;
08995   
08996   // A function template must have at least 2 parameters.
08997   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
08998     return SemaRef.Diag(FnDecl->getLocation(),
08999                       diag::err_operator_new_delete_template_too_few_parameters)
09000         << FnDecl->getDeclName();
09001   
09002   // The function decl must have at least 1 parameter.
09003   if (FnDecl->getNumParams() == 0)
09004     return SemaRef.Diag(FnDecl->getLocation(),
09005                         diag::err_operator_new_delete_too_few_parameters)
09006       << FnDecl->getDeclName();
09007  
09008   // Check the the first parameter type is not dependent.
09009   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
09010   if (FirstParamType->isDependentType())
09011     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
09012       << FnDecl->getDeclName() << ExpectedFirstParamType;
09013 
09014   // Check that the first parameter type is what we expect.
09015   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 
09016       ExpectedFirstParamType)
09017     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
09018     << FnDecl->getDeclName() << ExpectedFirstParamType;
09019   
09020   return false;
09021 }
09022 
09023 static bool
09024 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
09025   // C++ [basic.stc.dynamic.allocation]p1:
09026   //   A program is ill-formed if an allocation function is declared in a
09027   //   namespace scope other than global scope or declared static in global 
09028   //   scope.
09029   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
09030     return true;
09031 
09032   CanQualType SizeTy = 
09033     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
09034 
09035   // C++ [basic.stc.dynamic.allocation]p1:
09036   //  The return type shall be void*. The first parameter shall have type 
09037   //  std::size_t.
09038   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 
09039                                   SizeTy,
09040                                   diag::err_operator_new_dependent_param_type,
09041                                   diag::err_operator_new_param_type))
09042     return true;
09043 
09044   // C++ [basic.stc.dynamic.allocation]p1:
09045   //  The first parameter shall not have an associated default argument.
09046   if (FnDecl->getParamDecl(0)->hasDefaultArg())
09047     return SemaRef.Diag(FnDecl->getLocation(),
09048                         diag::err_operator_new_default_arg)
09049       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
09050 
09051   return false;
09052 }
09053 
09054 static bool
09055 CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
09056   // C++ [basic.stc.dynamic.deallocation]p1:
09057   //   A program is ill-formed if deallocation functions are declared in a
09058   //   namespace scope other than global scope or declared static in global 
09059   //   scope.
09060   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
09061     return true;
09062 
09063   // C++ [basic.stc.dynamic.deallocation]p2:
09064   //   Each deallocation function shall return void and its first parameter 
09065   //   shall be void*.
09066   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 
09067                                   SemaRef.Context.VoidPtrTy,
09068                                  diag::err_operator_delete_dependent_param_type,
09069                                  diag::err_operator_delete_param_type))
09070     return true;
09071 
09072   return false;
09073 }
09074 
09075 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
09076 /// of this overloaded operator is well-formed. If so, returns false;
09077 /// otherwise, emits appropriate diagnostics and returns true.
09078 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
09079   assert(FnDecl && FnDecl->isOverloadedOperator() &&
09080          "Expected an overloaded operator declaration");
09081 
09082   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
09083 
09084   // C++ [over.oper]p5:
09085   //   The allocation and deallocation functions, operator new,
09086   //   operator new[], operator delete and operator delete[], are
09087   //   described completely in 3.7.3. The attributes and restrictions
09088   //   found in the rest of this subclause do not apply to them unless
09089   //   explicitly stated in 3.7.3.
09090   if (Op == OO_Delete || Op == OO_Array_Delete)
09091     return CheckOperatorDeleteDeclaration(*this, FnDecl);
09092   
09093   if (Op == OO_New || Op == OO_Array_New)
09094     return CheckOperatorNewDeclaration(*this, FnDecl);
09095 
09096   // C++ [over.oper]p6:
09097   //   An operator function shall either be a non-static member
09098   //   function or be a non-member function and have at least one
09099   //   parameter whose type is a class, a reference to a class, an
09100   //   enumeration, or a reference to an enumeration.
09101   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
09102     if (MethodDecl->isStatic())
09103       return Diag(FnDecl->getLocation(),
09104                   diag::err_operator_overload_static) << FnDecl->getDeclName();
09105   } else {
09106     bool ClassOrEnumParam = false;
09107     for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
09108                                    ParamEnd = FnDecl->param_end();
09109          Param != ParamEnd; ++Param) {
09110       QualType ParamType = (*Param)->getType().getNonReferenceType();
09111       if (ParamType->isDependentType() || ParamType->isRecordType() ||
09112           ParamType->isEnumeralType()) {
09113         ClassOrEnumParam = true;
09114         break;
09115       }
09116     }
09117 
09118     if (!ClassOrEnumParam)
09119       return Diag(FnDecl->getLocation(),
09120                   diag::err_operator_overload_needs_class_or_enum)
09121         << FnDecl->getDeclName();
09122   }
09123 
09124   // C++ [over.oper]p8:
09125   //   An operator function cannot have default arguments (8.3.6),
09126   //   except where explicitly stated below.
09127   //
09128   // Only the function-call operator allows default arguments
09129   // (C++ [over.call]p1).
09130   if (Op != OO_Call) {
09131     for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
09132          Param != FnDecl->param_end(); ++Param) {
09133       if ((*Param)->hasDefaultArg())
09134         return Diag((*Param)->getLocation(),
09135                     diag::err_operator_overload_default_arg)
09136           << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
09137     }
09138   }
09139 
09140   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
09141     { false, false, false }
09142 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
09143     , { Unary, Binary, MemberOnly }
09144 #include "clang/Basic/OperatorKinds.def"
09145   };
09146 
09147   bool CanBeUnaryOperator = OperatorUses[Op][0];
09148   bool CanBeBinaryOperator = OperatorUses[Op][1];
09149   bool MustBeMemberOperator = OperatorUses[Op][2];
09150 
09151   // C++ [over.oper]p8:
09152   //   [...] Operator functions cannot have more or fewer parameters
09153   //   than the number required for the corresponding operator, as
09154   //   described in the rest of this subclause.
09155   unsigned NumParams = FnDecl->getNumParams()
09156                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
09157   if (Op != OO_Call &&
09158       ((NumParams == 1 && !CanBeUnaryOperator) ||
09159        (NumParams == 2 && !CanBeBinaryOperator) ||
09160        (NumParams < 1) || (NumParams > 2))) {
09161     // We have the wrong number of parameters.
09162     unsigned ErrorKind;
09163     if (CanBeUnaryOperator && CanBeBinaryOperator) {
09164       ErrorKind = 2;  // 2 -> unary or binary.
09165     } else if (CanBeUnaryOperator) {
09166       ErrorKind = 0;  // 0 -> unary
09167     } else {
09168       assert(CanBeBinaryOperator &&
09169              "All non-call overloaded operators are unary or binary!");
09170       ErrorKind = 1;  // 1 -> binary
09171     }
09172 
09173     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
09174       << FnDecl->getDeclName() << NumParams << ErrorKind;
09175   }
09176 
09177   // Overloaded operators other than operator() cannot be variadic.
09178   if (Op != OO_Call &&
09179       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
09180     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
09181       << FnDecl->getDeclName();
09182   }
09183 
09184   // Some operators must be non-static member functions.
09185   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
09186     return Diag(FnDecl->getLocation(),
09187                 diag::err_operator_overload_must_be_member)
09188       << FnDecl->getDeclName();
09189   }
09190 
09191   // C++ [over.inc]p1:
09192   //   The user-defined function called operator++ implements the
09193   //   prefix and postfix ++ operator. If this function is a member
09194   //   function with no parameters, or a non-member function with one
09195   //   parameter of class or enumeration type, it defines the prefix
09196   //   increment operator ++ for objects of that type. If the function
09197   //   is a member function with one parameter (which shall be of type
09198   //   int) or a non-member function with two parameters (the second
09199   //   of which shall be of type int), it defines the postfix
09200   //   increment operator ++ for objects of that type.
09201   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
09202     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
09203     bool ParamIsInt = false;
09204     if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
09205       ParamIsInt = BT->getKind() == BuiltinType::Int;
09206 
09207     if (!ParamIsInt)
09208       return Diag(LastParam->getLocation(),
09209                   diag::err_operator_overload_post_incdec_must_be_int)
09210         << LastParam->getType() << (Op == OO_MinusMinus);
09211   }
09212 
09213   return false;
09214 }
09215 
09216 /// CheckLiteralOperatorDeclaration - Check whether the declaration
09217 /// of this literal operator function is well-formed. If so, returns
09218 /// false; otherwise, emits appropriate diagnostics and returns true.
09219 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
09220   if (isa<CXXMethodDecl>(FnDecl)) {
09221     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
09222       << FnDecl->getDeclName();
09223     return true;
09224   }
09225 
09226   if (FnDecl->isExternC()) {
09227     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
09228     return true;
09229   }
09230 
09231   bool Valid = false;
09232 
09233   // This might be the definition of a literal operator template.
09234   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
09235   // This might be a specialization of a literal operator template.
09236   if (!TpDecl)
09237     TpDecl = FnDecl->getPrimaryTemplate();
09238 
09239   // template <char...> type operator "" name() is the only valid template
09240   // signature, and the only valid signature with no parameters.
09241   if (TpDecl) {
09242     if (FnDecl->param_size() == 0) {
09243       // Must have only one template parameter
09244       TemplateParameterList *Params = TpDecl->getTemplateParameters();
09245       if (Params->size() == 1) {
09246         NonTypeTemplateParmDecl *PmDecl =
09247           cast<NonTypeTemplateParmDecl>(Params->getParam(0));
09248 
09249         // The template parameter must be a char parameter pack.
09250         if (PmDecl && PmDecl->isTemplateParameterPack() &&
09251             Context.hasSameType(PmDecl->getType(), Context.CharTy))
09252           Valid = true;
09253       }
09254     }
09255   } else if (FnDecl->param_size()) {
09256     // Check the first parameter
09257     FunctionDecl::param_iterator Param = FnDecl->param_begin();
09258 
09259     QualType T = (*Param)->getType().getUnqualifiedType();
09260 
09261     // unsigned long long int, long double, and any character type are allowed
09262     // as the only parameters.
09263     if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
09264         Context.hasSameType(T, Context.LongDoubleTy) ||
09265         Context.hasSameType(T, Context.CharTy) ||
09266         Context.hasSameType(T, Context.WCharTy) ||
09267         Context.hasSameType(T, Context.Char16Ty) ||
09268         Context.hasSameType(T, Context.Char32Ty)) {
09269       if (++Param == FnDecl->param_end())
09270         Valid = true;
09271       goto FinishedParams;
09272     }
09273 
09274     // Otherwise it must be a pointer to const; let's strip those qualifiers.
09275     const PointerType *PT = T->getAs<PointerType>();
09276     if (!PT)
09277       goto FinishedParams;
09278     T = PT->getPointeeType();
09279     if (!T.isConstQualified() || T.isVolatileQualified())
09280       goto FinishedParams;
09281     T = T.getUnqualifiedType();
09282 
09283     // Move on to the second parameter;
09284     ++Param;
09285 
09286     // If there is no second parameter, the first must be a const char *
09287     if (Param == FnDecl->param_end()) {
09288       if (Context.hasSameType(T, Context.CharTy))
09289         Valid = true;
09290       goto FinishedParams;
09291     }
09292 
09293     // const char *, const wchar_t*, const char16_t*, and const char32_t*
09294     // are allowed as the first parameter to a two-parameter function
09295     if (!(Context.hasSameType(T, Context.CharTy) ||
09296           Context.hasSameType(T, Context.WCharTy) ||
09297           Context.hasSameType(T, Context.Char16Ty) ||
09298           Context.hasSameType(T, Context.Char32Ty)))
09299       goto FinishedParams;
09300 
09301     // The second and final parameter must be an std::size_t
09302     T = (*Param)->getType().getUnqualifiedType();
09303     if (Context.hasSameType(T, Context.getSizeType()) &&
09304         ++Param == FnDecl->param_end())
09305       Valid = true;
09306   }
09307 
09308   // FIXME: This diagnostic is absolutely terrible.
09309 FinishedParams:
09310   if (!Valid) {
09311     Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
09312       << FnDecl->getDeclName();
09313     return true;
09314   }
09315 
09316   // A parameter-declaration-clause containing a default argument is not
09317   // equivalent to any of the permitted forms.
09318   for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
09319                                     ParamEnd = FnDecl->param_end();
09320        Param != ParamEnd; ++Param) {
09321     if ((*Param)->hasDefaultArg()) {
09322       Diag((*Param)->getDefaultArgRange().getBegin(),
09323            diag::err_literal_operator_default_argument)
09324         << (*Param)->getDefaultArgRange();
09325       break;
09326     }
09327   }
09328 
09329   StringRef LiteralName
09330     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
09331   if (LiteralName[0] != '_') {
09332     // C++11 [usrlit.suffix]p1:
09333     //   Literal suffix identifiers that do not start with an underscore
09334     //   are reserved for future standardization.
09335     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
09336   }
09337 
09338   return false;
09339 }
09340 
09341 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
09342 /// linkage specification, including the language and (if present)
09343 /// the '{'. ExternLoc is the location of the 'extern', LangLoc is
09344 /// the location of the language string literal, which is provided
09345 /// by Lang/StrSize. LBraceLoc, if valid, provides the location of
09346 /// the '{' brace. Otherwise, this linkage specification does not
09347 /// have any braces.
09348 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
09349                                            SourceLocation LangLoc,
09350                                            StringRef Lang,
09351                                            SourceLocation LBraceLoc) {
09352   LinkageSpecDecl::LanguageIDs Language;
09353   if (Lang == "\"C\"")
09354     Language = LinkageSpecDecl::lang_c;
09355   else if (Lang == "\"C++\"")
09356     Language = LinkageSpecDecl::lang_cxx;
09357   else {
09358     Diag(LangLoc, diag::err_bad_language);
09359     return 0;
09360   }
09361 
09362   // FIXME: Add all the various semantics of linkage specifications
09363 
09364   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
09365                                                ExternLoc, LangLoc, Language);
09366   CurContext->addDecl(D);
09367   PushDeclContext(S, D);
09368   return D;
09369 }
09370 
09371 /// ActOnFinishLinkageSpecification - Complete the definition of
09372 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
09373 /// valid, it's the position of the closing '}' brace in a linkage
09374 /// specification that uses braces.
09375 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
09376                                             Decl *LinkageSpec,
09377                                             SourceLocation RBraceLoc) {
09378   if (LinkageSpec) {
09379     if (RBraceLoc.isValid()) {
09380       LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
09381       LSDecl->setRBraceLoc(RBraceLoc);
09382     }
09383     PopDeclContext();
09384   }
09385   return LinkageSpec;
09386 }
09387 
09388 /// \brief Perform semantic analysis for the variable declaration that
09389 /// occurs within a C++ catch clause, returning the newly-created
09390 /// variable.
09391 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
09392                                          TypeSourceInfo *TInfo,
09393                                          SourceLocation StartLoc,
09394                                          SourceLocation Loc,
09395                                          IdentifierInfo *Name) {
09396   bool Invalid = false;
09397   QualType ExDeclType = TInfo->getType();
09398   
09399   // Arrays and functions decay.
09400   if (ExDeclType->isArrayType())
09401     ExDeclType = Context.getArrayDecayedType(ExDeclType);
09402   else if (ExDeclType->isFunctionType())
09403     ExDeclType = Context.getPointerType(ExDeclType);
09404 
09405   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
09406   // The exception-declaration shall not denote a pointer or reference to an
09407   // incomplete type, other than [cv] void*.
09408   // N2844 forbids rvalue references.
09409   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
09410     Diag(Loc, diag::err_catch_rvalue_ref);
09411     Invalid = true;
09412   }
09413 
09414   QualType BaseType = ExDeclType;
09415   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
09416   unsigned DK = diag::err_catch_incomplete;
09417   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
09418     BaseType = Ptr->getPointeeType();
09419     Mode = 1;
09420     DK = diag::err_catch_incomplete_ptr;
09421   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
09422     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
09423     BaseType = Ref->getPointeeType();
09424     Mode = 2;
09425     DK = diag::err_catch_incomplete_ref;
09426   }
09427   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
09428       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
09429     Invalid = true;
09430 
09431   if (!Invalid && !ExDeclType->isDependentType() &&
09432       RequireNonAbstractType(Loc, ExDeclType,
09433                              diag::err_abstract_type_in_decl,
09434                              AbstractVariableType))
09435     Invalid = true;
09436 
09437   // Only the non-fragile NeXT runtime currently supports C++ catches
09438   // of ObjC types, and no runtime supports catching ObjC types by value.
09439   if (!Invalid && getLangOpts().ObjC1) {
09440     QualType T = ExDeclType;
09441     if (const ReferenceType *RT = T->getAs<ReferenceType>())
09442       T = RT->getPointeeType();
09443 
09444     if (T->isObjCObjectType()) {
09445       Diag(Loc, diag::err_objc_object_catch);
09446       Invalid = true;
09447     } else if (T->isObjCObjectPointerType()) {
09448       if (!getLangOpts().ObjCNonFragileABI)
09449         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
09450     }
09451   }
09452 
09453   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
09454                                     ExDeclType, TInfo, SC_None, SC_None);
09455   ExDecl->setExceptionVariable(true);
09456   
09457   // In ARC, infer 'retaining' for variables of retainable type.
09458   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
09459     Invalid = true;
09460 
09461   if (!Invalid && !ExDeclType->isDependentType()) {
09462     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
09463       // C++ [except.handle]p16:
09464       //   The object declared in an exception-declaration or, if the 
09465       //   exception-declaration does not specify a name, a temporary (12.2) is 
09466       //   copy-initialized (8.5) from the exception object. [...]
09467       //   The object is destroyed when the handler exits, after the destruction
09468       //   of any automatic objects initialized within the handler.
09469       //
09470       // We just pretend to initialize the object with itself, then make sure 
09471       // it can be destroyed later.
09472       QualType initType = ExDeclType;
09473 
09474       InitializedEntity entity =
09475         InitializedEntity::InitializeVariable(ExDecl);
09476       InitializationKind initKind =
09477         InitializationKind::CreateCopy(Loc, SourceLocation());
09478 
09479       Expr *opaqueValue =
09480         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
09481       InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
09482       ExprResult result = sequence.Perform(*this, entity, initKind,
09483                                            MultiExprArg(&opaqueValue, 1));
09484       if (result.isInvalid())
09485         Invalid = true;
09486       else {
09487         // If the constructor used was non-trivial, set this as the
09488         // "initializer".
09489         CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
09490         if (!construct->getConstructor()->isTrivial()) {
09491           Expr *init = MaybeCreateExprWithCleanups(construct);
09492           ExDecl->setInit(init);
09493         }
09494         
09495         // And make sure it's destructable.
09496         FinalizeVarWithDestructor(ExDecl, recordType);
09497       }
09498     }
09499   }
09500   
09501   if (Invalid)
09502     ExDecl->setInvalidDecl();
09503 
09504   return ExDecl;
09505 }
09506 
09507 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
09508 /// handler.
09509 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
09510   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
09511   bool Invalid = D.isInvalidType();
09512 
09513   // Check for unexpanded parameter packs.
09514   if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
09515                                                UPPC_ExceptionType)) {
09516     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 
09517                                              D.getIdentifierLoc());
09518     Invalid = true;
09519   }
09520 
09521   IdentifierInfo *II = D.getIdentifier();
09522   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
09523                                              LookupOrdinaryName,
09524                                              ForRedeclaration)) {
09525     // The scope should be freshly made just for us. There is just no way
09526     // it contains any previous declaration.
09527     assert(!S->isDeclScope(PrevDecl));
09528     if (PrevDecl->isTemplateParameter()) {
09529       // Maybe we will complain about the shadowed template parameter.
09530       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
09531       PrevDecl = 0;
09532     }
09533   }
09534 
09535   if (D.getCXXScopeSpec().isSet() && !Invalid) {
09536     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
09537       << D.getCXXScopeSpec().getRange();
09538     Invalid = true;
09539   }
09540 
09541   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
09542                                               D.getLocStart(),
09543                                               D.getIdentifierLoc(),
09544                                               D.getIdentifier());
09545   if (Invalid)
09546     ExDecl->setInvalidDecl();
09547 
09548   // Add the exception declaration into this scope.
09549   if (II)
09550     PushOnScopeChains(ExDecl, S);
09551   else
09552     CurContext->addDecl(ExDecl);
09553 
09554   ProcessDeclAttributes(S, ExDecl, D);
09555   return ExDecl;
09556 }
09557 
09558 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
09559                                          Expr *AssertExpr,
09560                                          Expr *AssertMessageExpr_,
09561                                          SourceLocation RParenLoc) {
09562   StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
09563 
09564   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
09565     // In a static_assert-declaration, the constant-expression shall be a
09566     // constant expression that can be contextually converted to bool.
09567     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
09568     if (Converted.isInvalid())
09569       return 0;
09570 
09571     llvm::APSInt Cond;
09572     if (VerifyIntegerConstantExpression(Converted.get(), &Cond,
09573           diag::err_static_assert_expression_is_not_constant,
09574           /*AllowFold=*/false).isInvalid())
09575       return 0;
09576 
09577     if (!Cond) {
09578       llvm::SmallString<256> MsgBuffer;
09579       llvm::raw_svector_ostream Msg(MsgBuffer);
09580       AssertMessage->printPretty(Msg, Context, 0, getPrintingPolicy());
09581       Diag(StaticAssertLoc, diag::err_static_assert_failed)
09582         << Msg.str() << AssertExpr->getSourceRange();
09583     }
09584   }
09585 
09586   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
09587     return 0;
09588 
09589   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
09590                                         AssertExpr, AssertMessage, RParenLoc);
09591 
09592   CurContext->addDecl(Decl);
09593   return Decl;
09594 }
09595 
09596 /// \brief Perform semantic analysis of the given friend type declaration.
09597 ///
09598 /// \returns A friend declaration that.
09599 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
09600                                       SourceLocation FriendLoc,
09601                                       TypeSourceInfo *TSInfo) {
09602   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
09603   
09604   QualType T = TSInfo->getType();
09605   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
09606   
09607   // C++03 [class.friend]p2:
09608   //   An elaborated-type-specifier shall be used in a friend declaration
09609   //   for a class.*
09610   //
09611   //   * The class-key of the elaborated-type-specifier is required.
09612   if (!ActiveTemplateInstantiations.empty()) {
09613     // Do not complain about the form of friend template types during
09614     // template instantiation; we will already have complained when the
09615     // template was declared.
09616   } else if (!T->isElaboratedTypeSpecifier()) {
09617     // If we evaluated the type to a record type, suggest putting
09618     // a tag in front.
09619     if (const RecordType *RT = T->getAs<RecordType>()) {
09620       RecordDecl *RD = RT->getDecl();
09621       
09622       std::string InsertionText = std::string(" ") + RD->getKindName();
09623       
09624       Diag(TypeRange.getBegin(),
09625            getLangOpts().CPlusPlus0x ?
09626              diag::warn_cxx98_compat_unelaborated_friend_type :
09627              diag::ext_unelaborated_friend_type)
09628         << (unsigned) RD->getTagKind()
09629         << T
09630         << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
09631                                       InsertionText);
09632     } else {
09633       Diag(FriendLoc,
09634            getLangOpts().CPlusPlus0x ?
09635              diag::warn_cxx98_compat_nonclass_type_friend :
09636              diag::ext_nonclass_type_friend)
09637         << T
09638         << SourceRange(FriendLoc, TypeRange.getEnd());
09639     }
09640   } else if (T->getAs<EnumType>()) {
09641     Diag(FriendLoc,
09642          getLangOpts().CPlusPlus0x ?
09643            diag::warn_cxx98_compat_enum_friend :
09644            diag::ext_enum_friend)
09645       << T
09646       << SourceRange(FriendLoc, TypeRange.getEnd());
09647   }
09648   
09649   // C++0x [class.friend]p3:
09650   //   If the type specifier in a friend declaration designates a (possibly
09651   //   cv-qualified) class type, that class is declared as a friend; otherwise, 
09652   //   the friend declaration is ignored.
09653   
09654   // FIXME: C++0x has some syntactic restrictions on friend type declarations
09655   // in [class.friend]p3 that we do not implement.
09656   
09657   return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
09658 }
09659 
09660 /// Handle a friend tag declaration where the scope specifier was
09661 /// templated.
09662 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
09663                                     unsigned TagSpec, SourceLocation TagLoc,
09664                                     CXXScopeSpec &SS,
09665                                     IdentifierInfo *Name, SourceLocation NameLoc,
09666                                     AttributeList *Attr,
09667                                     MultiTemplateParamsArg TempParamLists) {
09668   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
09669 
09670   bool isExplicitSpecialization = false;
09671   bool Invalid = false;
09672 
09673   if (TemplateParameterList *TemplateParams
09674         = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
09675                                                   TempParamLists.get(),
09676                                                   TempParamLists.size(),
09677                                                   /*friend*/ true,
09678                                                   isExplicitSpecialization,
09679                                                   Invalid)) {
09680     if (TemplateParams->size() > 0) {
09681       // This is a declaration of a class template.
09682       if (Invalid)
09683         return 0;
09684 
09685       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
09686                                 SS, Name, NameLoc, Attr,
09687                                 TemplateParams, AS_public,
09688                                 /*ModulePrivateLoc=*/SourceLocation(),
09689                                 TempParamLists.size() - 1,
09690                    (TemplateParameterList**) TempParamLists.release()).take();
09691     } else {
09692       // The "template<>" header is extraneous.
09693       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
09694         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
09695       isExplicitSpecialization = true;
09696     }
09697   }
09698 
09699   if (Invalid) return 0;
09700 
09701   bool isAllExplicitSpecializations = true;
09702   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
09703     if (TempParamLists.get()[I]->size()) {
09704       isAllExplicitSpecializations = false;
09705       break;
09706     }
09707   }
09708 
09709   // FIXME: don't ignore attributes.
09710 
09711   // If it's explicit specializations all the way down, just forget
09712   // about the template header and build an appropriate non-templated
09713   // friend.  TODO: for source fidelity, remember the headers.
09714   if (isAllExplicitSpecializations) {
09715     if (SS.isEmpty()) {
09716       bool Owned = false;
09717       bool IsDependent = false;
09718       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
09719                       Attr, AS_public, 
09720                       /*ModulePrivateLoc=*/SourceLocation(),
09721                       MultiTemplateParamsArg(), Owned, IsDependent, 
09722                       /*ScopedEnumKWLoc=*/SourceLocation(),
09723                       /*ScopedEnumUsesClassTag=*/false,
09724                       /*UnderlyingType=*/TypeResult());          
09725     }
09726     
09727     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
09728     ElaboratedTypeKeyword Keyword
09729       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
09730     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
09731                                    *Name, NameLoc);
09732     if (T.isNull())
09733       return 0;
09734 
09735     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
09736     if (isa<DependentNameType>(T)) {
09737       DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
09738       TL.setElaboratedKeywordLoc(TagLoc);
09739       TL.setQualifierLoc(QualifierLoc);
09740       TL.setNameLoc(NameLoc);
09741     } else {
09742       ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
09743       TL.setElaboratedKeywordLoc(TagLoc);
09744       TL.setQualifierLoc(QualifierLoc);
09745       cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
09746     }
09747 
09748     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
09749                                             TSI, FriendLoc);
09750     Friend->setAccess(AS_public);
09751     CurContext->addDecl(Friend);
09752     return Friend;
09753   }
09754   
09755   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
09756   
09757 
09758 
09759   // Handle the case of a templated-scope friend class.  e.g.
09760   //   template <class T> class A<T>::B;
09761   // FIXME: we don't support these right now.
09762   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
09763   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
09764   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
09765   DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
09766   TL.setElaboratedKeywordLoc(TagLoc);
09767   TL.setQualifierLoc(SS.getWithLocInContext(Context));
09768   TL.setNameLoc(NameLoc);
09769 
09770   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
09771                                           TSI, FriendLoc);
09772   Friend->setAccess(AS_public);
09773   Friend->setUnsupportedFriend(true);
09774   CurContext->addDecl(Friend);
09775   return Friend;
09776 }
09777 
09778 
09779 /// Handle a friend type declaration.  This works in tandem with
09780 /// ActOnTag.
09781 ///
09782 /// Notes on friend class templates:
09783 ///
09784 /// We generally treat friend class declarations as if they were
09785 /// declaring a class.  So, for example, the elaborated type specifier
09786 /// in a friend declaration is required to obey the restrictions of a
09787 /// class-head (i.e. no typedefs in the scope chain), template
09788 /// parameters are required to match up with simple template-ids, &c.
09789 /// However, unlike when declaring a template specialization, it's
09790 /// okay to refer to a template specialization without an empty
09791 /// template parameter declaration, e.g.
09792 ///   friend class A<T>::B<unsigned>;
09793 /// We permit this as a special case; if there are any template
09794 /// parameters present at all, require proper matching, i.e.
09795 ///   template <> template <class T> friend class A<int>::B;
09796 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
09797                                 MultiTemplateParamsArg TempParams) {
09798   SourceLocation Loc = DS.getLocStart();
09799 
09800   assert(DS.isFriendSpecified());
09801   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
09802 
09803   // Try to convert the decl specifier to a type.  This works for
09804   // friend templates because ActOnTag never produces a ClassTemplateDecl
09805   // for a TUK_Friend.
09806   Declarator TheDeclarator(DS, Declarator::MemberContext);
09807   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
09808   QualType T = TSI->getType();
09809   if (TheDeclarator.isInvalidType())
09810     return 0;
09811 
09812   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
09813     return 0;
09814 
09815   // This is definitely an error in C++98.  It's probably meant to
09816   // be forbidden in C++0x, too, but the specification is just
09817   // poorly written.
09818   //
09819   // The problem is with declarations like the following:
09820   //   template <T> friend A<T>::foo;
09821   // where deciding whether a class C is a friend or not now hinges
09822   // on whether there exists an instantiation of A that causes
09823   // 'foo' to equal C.  There are restrictions on class-heads
09824   // (which we declare (by fiat) elaborated friend declarations to
09825   // be) that makes this tractable.
09826   //
09827   // FIXME: handle "template <> friend class A<T>;", which
09828   // is possibly well-formed?  Who even knows?
09829   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
09830     Diag(Loc, diag::err_tagless_friend_type_template)
09831       << DS.getSourceRange();
09832     return 0;
09833   }
09834   
09835   // C++98 [class.friend]p1: A friend of a class is a function
09836   //   or class that is not a member of the class . . .
09837   // This is fixed in DR77, which just barely didn't make the C++03
09838   // deadline.  It's also a very silly restriction that seriously
09839   // affects inner classes and which nobody else seems to implement;
09840   // thus we never diagnose it, not even in -pedantic.
09841   //
09842   // But note that we could warn about it: it's always useless to
09843   // friend one of your own members (it's not, however, worthless to
09844   // friend a member of an arbitrary specialization of your template).
09845 
09846   Decl *D;
09847   if (unsigned NumTempParamLists = TempParams.size())
09848     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
09849                                    NumTempParamLists,
09850                                    TempParams.release(),
09851                                    TSI,
09852                                    DS.getFriendSpecLoc());
09853   else
09854     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
09855   
09856   if (!D)
09857     return 0;
09858   
09859   D->setAccess(AS_public);
09860   CurContext->addDecl(D);
09861 
09862   return D;
09863 }
09864 
09865 Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
09866                                     MultiTemplateParamsArg TemplateParams) {
09867   const DeclSpec &DS = D.getDeclSpec();
09868 
09869   assert(DS.isFriendSpecified());
09870   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
09871 
09872   SourceLocation Loc = D.getIdentifierLoc();
09873   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
09874 
09875   // C++ [class.friend]p1
09876   //   A friend of a class is a function or class....
09877   // Note that this sees through typedefs, which is intended.
09878   // It *doesn't* see through dependent types, which is correct
09879   // according to [temp.arg.type]p3:
09880   //   If a declaration acquires a function type through a
09881   //   type dependent on a template-parameter and this causes
09882   //   a declaration that does not use the syntactic form of a
09883   //   function declarator to have a function type, the program
09884   //   is ill-formed.
09885   if (!TInfo->getType()->isFunctionType()) {
09886     Diag(Loc, diag::err_unexpected_friend);
09887 
09888     // It might be worthwhile to try to recover by creating an
09889     // appropriate declaration.
09890     return 0;
09891   }
09892 
09893   // C++ [namespace.memdef]p3
09894   //  - If a friend declaration in a non-local class first declares a
09895   //    class or function, the friend class or function is a member
09896   //    of the innermost enclosing namespace.
09897   //  - The name of the friend is not found by simple name lookup
09898   //    until a matching declaration is provided in that namespace
09899   //    scope (either before or after the class declaration granting
09900   //    friendship).
09901   //  - If a friend function is called, its name may be found by the
09902   //    name lookup that considers functions from namespaces and
09903   //    classes associated with the types of the function arguments.
09904   //  - When looking for a prior declaration of a class or a function
09905   //    declared as a friend, scopes outside the innermost enclosing
09906   //    namespace scope are not considered.
09907 
09908   CXXScopeSpec &SS = D.getCXXScopeSpec();
09909   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
09910   DeclarationName Name = NameInfo.getName();
09911   assert(Name);
09912 
09913   // Check for unexpanded parameter packs.
09914   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
09915       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
09916       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
09917     return 0;
09918 
09919   // The context we found the declaration in, or in which we should
09920   // create the declaration.
09921   DeclContext *DC;
09922   Scope *DCScope = S;
09923   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
09924                         ForRedeclaration);
09925 
09926   // FIXME: there are different rules in local classes
09927 
09928   // There are four cases here.
09929   //   - There's no scope specifier, in which case we just go to the
09930   //     appropriate scope and look for a function or function template
09931   //     there as appropriate.
09932   // Recover from invalid scope qualifiers as if they just weren't there.
09933   if (SS.isInvalid() || !SS.isSet()) {
09934     // C++0x [namespace.memdef]p3:
09935     //   If the name in a friend declaration is neither qualified nor
09936     //   a template-id and the declaration is a function or an
09937     //   elaborated-type-specifier, the lookup to determine whether
09938     //   the entity has been previously declared shall not consider
09939     //   any scopes outside the innermost enclosing namespace.
09940     // C++0x [class.friend]p11:
09941     //   If a friend declaration appears in a local class and the name
09942     //   specified is an unqualified name, a prior declaration is
09943     //   looked up without considering scopes that are outside the
09944     //   innermost enclosing non-class scope. For a friend function
09945     //   declaration, if there is no prior declaration, the program is
09946     //   ill-formed.
09947     bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
09948     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
09949 
09950     // Find the appropriate context according to the above.
09951     DC = CurContext;
09952     while (true) {
09953       // Skip class contexts.  If someone can cite chapter and verse
09954       // for this behavior, that would be nice --- it's what GCC and
09955       // EDG do, and it seems like a reasonable intent, but the spec
09956       // really only says that checks for unqualified existing
09957       // declarations should stop at the nearest enclosing namespace,
09958       // not that they should only consider the nearest enclosing
09959       // namespace.
09960       while (DC->isRecord() || DC->isTransparentContext()) 
09961         DC = DC->getParent();
09962 
09963       LookupQualifiedName(Previous, DC);
09964 
09965       // TODO: decide what we think about using declarations.
09966       if (isLocal || !Previous.empty())
09967         break;
09968 
09969       if (isTemplateId) {
09970         if (isa<TranslationUnitDecl>(DC)) break;
09971       } else {
09972         if (DC->isFileContext()) break;
09973       }
09974       DC = DC->getParent();
09975     }
09976 
09977     // C++ [class.friend]p1: A friend of a class is a function or
09978     //   class that is not a member of the class . . .
09979     // C++11 changes this for both friend types and functions.
09980     // Most C++ 98 compilers do seem to give an error here, so
09981     // we do, too.
09982     if (!Previous.empty() && DC->Equals(CurContext))
09983       Diag(DS.getFriendSpecLoc(),
09984            getLangOpts().CPlusPlus0x ?
09985              diag::warn_cxx98_compat_friend_is_member :
09986              diag::err_friend_is_member);
09987 
09988     DCScope = getScopeForDeclContext(S, DC);
09989     
09990     // C++ [class.friend]p6:
09991     //   A function can be defined in a friend declaration of a class if and 
09992     //   only if the class is a non-local class (9.8), the function name is
09993     //   unqualified, and the function has namespace scope.
09994     if (isLocal && D.isFunctionDefinition()) {
09995       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
09996     }
09997     
09998   //   - There's a non-dependent scope specifier, in which case we
09999   //     compute it and do a previous lookup there for a function
10000   //     or function template.
10001   } else if (!SS.getScopeRep()->isDependent()) {
10002     DC = computeDeclContext(SS);
10003     if (!DC) return 0;
10004 
10005     if (RequireCompleteDeclContext(SS, DC)) return 0;
10006 
10007     LookupQualifiedName(Previous, DC);
10008 
10009     // Ignore things found implicitly in the wrong scope.
10010     // TODO: better diagnostics for this case.  Suggesting the right
10011     // qualified scope would be nice...
10012     LookupResult::Filter F = Previous.makeFilter();
10013     while (F.hasNext()) {
10014       NamedDecl *D = F.next();
10015       if (!DC->InEnclosingNamespaceSetOf(
10016               D->getDeclContext()->getRedeclContext()))
10017         F.erase();
10018     }
10019     F.done();
10020 
10021     if (Previous.empty()) {
10022       D.setInvalidType();
10023       Diag(Loc, diag::err_qualified_friend_not_found)
10024           << Name << TInfo->getType();
10025       return 0;
10026     }
10027 
10028     // C++ [class.friend]p1: A friend of a class is a function or
10029     //   class that is not a member of the class . . .
10030     if (DC->Equals(CurContext))
10031       Diag(DS.getFriendSpecLoc(),
10032            getLangOpts().CPlusPlus0x ?
10033              diag::warn_cxx98_compat_friend_is_member :
10034              diag::err_friend_is_member);
10035     
10036     if (D.isFunctionDefinition()) {
10037       // C++ [class.friend]p6:
10038       //   A function can be defined in a friend declaration of a class if and 
10039       //   only if the class is a non-local class (9.8), the function name is
10040       //   unqualified, and the function has namespace scope.
10041       SemaDiagnosticBuilder DB
10042         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10043       
10044       DB << SS.getScopeRep();
10045       if (DC->isFileContext())
10046         DB << FixItHint::CreateRemoval(SS.getRange());
10047       SS.clear();
10048     }
10049 
10050   //   - There's a scope specifier that does not match any template
10051   //     parameter lists, in which case we use some arbitrary context,
10052   //     create a method or method template, and wait for instantiation.
10053   //   - There's a scope specifier that does match some template
10054   //     parameter lists, which we don't handle right now.
10055   } else {
10056     if (D.isFunctionDefinition()) {
10057       // C++ [class.friend]p6:
10058       //   A function can be defined in a friend declaration of a class if and 
10059       //   only if the class is a non-local class (9.8), the function name is
10060       //   unqualified, and the function has namespace scope.
10061       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10062         << SS.getScopeRep();
10063     }
10064     
10065     DC = CurContext;
10066     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
10067   }
10068   
10069   if (!DC->isRecord()) {
10070     // This implies that it has to be an operator or function.
10071     if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10072         D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10073         D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
10074       Diag(Loc, diag::err_introducing_special_friend) <<
10075         (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10076          D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
10077       return 0;
10078     }
10079   }
10080 
10081   // FIXME: This is an egregious hack to cope with cases where the scope stack
10082   // does not contain the declaration context, i.e., in an out-of-line 
10083   // definition of a class.
10084   Scope FakeDCScope(S, Scope::DeclScope, Diags);
10085   if (!DCScope) {
10086     FakeDCScope.setEntity(DC);
10087     DCScope = &FakeDCScope;
10088   }
10089   
10090   bool AddToScope = true;
10091   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10092                                           move(TemplateParams), AddToScope);
10093   if (!ND) return 0;
10094 
10095   assert(ND->getDeclContext() == DC);
10096   assert(ND->getLexicalDeclContext() == CurContext);
10097 
10098   // Add the function declaration to the appropriate lookup tables,
10099   // adjusting the redeclarations list as necessary.  We don't
10100   // want to do this yet if the friending class is dependent.
10101   //
10102   // Also update the scope-based lookup if the target context's
10103   // lookup context is in lexical scope.
10104   if (!CurContext->isDependentContext()) {
10105     DC = DC->getRedeclContext();
10106     DC->makeDeclVisibleInContext(ND);
10107     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
10108       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
10109   }
10110 
10111   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
10112                                        D.getIdentifierLoc(), ND,
10113                                        DS.getFriendSpecLoc());
10114   FrD->setAccess(AS_public);
10115   CurContext->addDecl(FrD);
10116 
10117   if (ND->isInvalidDecl())
10118     FrD->setInvalidDecl();
10119   else {
10120     FunctionDecl *FD;
10121     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10122       FD = FTD->getTemplatedDecl();
10123     else
10124       FD = cast<FunctionDecl>(ND);
10125 
10126     // Mark templated-scope function declarations as unsupported.
10127     if (FD->getNumTemplateParameterLists())
10128       FrD->setUnsupportedFriend(true);
10129   }
10130 
10131   return ND;
10132 }
10133 
10134 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10135   AdjustDeclIfTemplate(Dcl);
10136 
10137   FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10138   if (!Fn) {
10139     Diag(DelLoc, diag::err_deleted_non_function);
10140     return;
10141   }
10142   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
10143     Diag(DelLoc, diag::err_deleted_decl_not_first);
10144     Diag(Prev->getLocation(), diag::note_previous_declaration);
10145     // If the declaration wasn't the first, we delete the function anyway for
10146     // recovery.
10147   }
10148   Fn->setDeletedAsWritten();
10149 
10150   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10151   if (!MD)
10152     return;
10153 
10154   // A deleted special member function is trivial if the corresponding
10155   // implicitly-declared function would have been.
10156   switch (getSpecialMember(MD)) {
10157   case CXXInvalid:
10158     break;
10159   case CXXDefaultConstructor:
10160     MD->setTrivial(MD->getParent()->hasTrivialDefaultConstructor());
10161     break;
10162   case CXXCopyConstructor:
10163     MD->setTrivial(MD->getParent()->hasTrivialCopyConstructor());
10164     break;
10165   case CXXMoveConstructor:
10166     MD->setTrivial(MD->getParent()->hasTrivialMoveConstructor());
10167     break;
10168   case CXXCopyAssignment:
10169     MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
10170     break;
10171   case CXXMoveAssignment:
10172     MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
10173     break;
10174   case CXXDestructor:
10175     MD->setTrivial(MD->getParent()->hasTrivialDestructor());
10176     break;
10177   }
10178 }
10179 
10180 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10181   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10182 
10183   if (MD) {
10184     if (MD->getParent()->isDependentType()) {
10185       MD->setDefaulted();
10186       MD->setExplicitlyDefaulted();
10187       return;
10188     }
10189 
10190     CXXSpecialMember Member = getSpecialMember(MD);
10191     if (Member == CXXInvalid) {
10192       Diag(DefaultLoc, diag::err_default_special_members);
10193       return;
10194     }
10195 
10196     MD->setDefaulted();
10197     MD->setExplicitlyDefaulted();
10198 
10199     // If this definition appears within the record, do the checking when
10200     // the record is complete.
10201     const FunctionDecl *Primary = MD;
10202     if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10203       // Find the uninstantiated declaration that actually had the '= default'
10204       // on it.
10205       MD->getTemplateInstantiationPattern()->isDefined(Primary);
10206 
10207     if (Primary == Primary->getCanonicalDecl())
10208       return;
10209 
10210     switch (Member) {
10211     case CXXDefaultConstructor: {
10212       CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10213       CheckExplicitlyDefaultedSpecialMember(CD);
10214       if (!CD->isInvalidDecl())
10215         DefineImplicitDefaultConstructor(DefaultLoc, CD);
10216       break;
10217     }
10218 
10219     case CXXCopyConstructor: {
10220       CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10221       CheckExplicitlyDefaultedSpecialMember(CD);
10222       if (!CD->isInvalidDecl())
10223         DefineImplicitCopyConstructor(DefaultLoc, CD);
10224       break;
10225     }
10226 
10227     case CXXCopyAssignment: {
10228       CheckExplicitlyDefaultedSpecialMember(MD);
10229       if (!MD->isInvalidDecl())
10230         DefineImplicitCopyAssignment(DefaultLoc, MD);
10231       break;
10232     }
10233 
10234     case CXXDestructor: {
10235       CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10236       CheckExplicitlyDefaultedSpecialMember(DD);
10237       if (!DD->isInvalidDecl())
10238         DefineImplicitDestructor(DefaultLoc, DD);
10239       break;
10240     }
10241 
10242     case CXXMoveConstructor: {
10243       CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10244       CheckExplicitlyDefaultedSpecialMember(CD);
10245       if (!CD->isInvalidDecl())
10246         DefineImplicitMoveConstructor(DefaultLoc, CD);
10247       break;
10248     }
10249 
10250     case CXXMoveAssignment: {
10251       CheckExplicitlyDefaultedSpecialMember(MD);
10252       if (!MD->isInvalidDecl())
10253         DefineImplicitMoveAssignment(DefaultLoc, MD);
10254       break;
10255     }
10256 
10257     case CXXInvalid:
10258       llvm_unreachable("Invalid special member.");
10259     }
10260   } else {
10261     Diag(DefaultLoc, diag::err_default_special_members);
10262   }
10263 }
10264 
10265 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
10266   for (Stmt::child_range CI = S->children(); CI; ++CI) {
10267     Stmt *SubStmt = *CI;
10268     if (!SubStmt)
10269       continue;
10270     if (isa<ReturnStmt>(SubStmt))
10271       Self.Diag(SubStmt->getLocStart(),
10272            diag::err_return_in_constructor_handler);
10273     if (!isa<Expr>(SubStmt))
10274       SearchForReturnInStmt(Self, SubStmt);
10275   }
10276 }
10277 
10278 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10279   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10280     CXXCatchStmt *Handler = TryBlock->getHandler(I);
10281     SearchForReturnInStmt(*this, Handler);
10282   }
10283 }
10284 
10285 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
10286                                              const CXXMethodDecl *Old) {
10287   QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10288   QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
10289 
10290   if (Context.hasSameType(NewTy, OldTy) ||
10291       NewTy->isDependentType() || OldTy->isDependentType())
10292     return false;
10293 
10294   // Check if the return types are covariant
10295   QualType NewClassTy, OldClassTy;
10296 
10297   /// Both types must be pointers or references to classes.
10298   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10299     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
10300       NewClassTy = NewPT->getPointeeType();
10301       OldClassTy = OldPT->getPointeeType();
10302     }
10303   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10304     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10305       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10306         NewClassTy = NewRT->getPointeeType();
10307         OldClassTy = OldRT->getPointeeType();
10308       }
10309     }
10310   }
10311 
10312   // The return types aren't either both pointers or references to a class type.
10313   if (NewClassTy.isNull()) {
10314     Diag(New->getLocation(),
10315          diag::err_different_return_type_for_overriding_virtual_function)
10316       << New->getDeclName() << NewTy << OldTy;
10317     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10318 
10319     return true;
10320   }
10321 
10322   // C++ [class.virtual]p6:
10323   //   If the return type of D::f differs from the return type of B::f, the 
10324   //   class type in the return type of D::f shall be complete at the point of
10325   //   declaration of D::f or shall be the class type D.
10326   if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10327     if (!RT->isBeingDefined() &&
10328         RequireCompleteType(New->getLocation(), NewClassTy, 
10329                             diag::err_covariant_return_incomplete,
10330                             New->getDeclName()))
10331     return true;
10332   }
10333 
10334   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
10335     // Check if the new class derives from the old class.
10336     if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10337       Diag(New->getLocation(),
10338            diag::err_covariant_return_not_derived)
10339       << New->getDeclName() << NewTy << OldTy;
10340       Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10341       return true;
10342     }
10343 
10344     // Check if we the conversion from derived to base is valid.
10345     if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
10346                     diag::err_covariant_return_inaccessible_base,
10347                     diag::err_covariant_return_ambiguous_derived_to_base_conv,
10348                     // FIXME: Should this point to the return type?
10349                     New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
10350       // FIXME: this note won't trigger for delayed access control
10351       // diagnostics, and it's impossible to get an undelayed error
10352       // here from access control during the original parse because
10353       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
10354       Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10355       return true;
10356     }
10357   }
10358 
10359   // The qualifiers of the return types must be the same.
10360   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
10361     Diag(New->getLocation(),
10362          diag::err_covariant_return_type_different_qualifications)
10363     << New->getDeclName() << NewTy << OldTy;
10364     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10365     return true;
10366   };
10367 
10368 
10369   // The new class type must have the same or less qualifiers as the old type.
10370   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10371     Diag(New->getLocation(),
10372          diag::err_covariant_return_type_class_type_more_qualified)
10373     << New->getDeclName() << NewTy << OldTy;
10374     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10375     return true;
10376   };
10377 
10378   return false;
10379 }
10380 
10381 /// \brief Mark the given method pure.
10382 ///
10383 /// \param Method the method to be marked pure.
10384 ///
10385 /// \param InitRange the source range that covers the "0" initializer.
10386 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
10387   SourceLocation EndLoc = InitRange.getEnd();
10388   if (EndLoc.isValid())
10389     Method->setRangeEnd(EndLoc);
10390 
10391   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10392     Method->setPure();
10393     return false;
10394   }
10395 
10396   if (!Method->isInvalidDecl())
10397     Diag(Method->getLocation(), diag::err_non_virtual_pure)
10398       << Method->getDeclName() << InitRange;
10399   return true;
10400 }
10401 
10402 /// \brief Determine whether the given declaration is a static data member.
10403 static bool isStaticDataMember(Decl *D) {
10404   VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
10405   if (!Var)
10406     return false;
10407   
10408   return Var->isStaticDataMember();
10409 }
10410 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10411 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
10412 /// is a fresh scope pushed for just this purpose.
10413 ///
10414 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10415 /// static data member of class X, names should be looked up in the scope of
10416 /// class X.
10417 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
10418   // If there is no declaration, there was an error parsing it.
10419   if (D == 0 || D->isInvalidDecl()) return;
10420 
10421   // We should only get called for declarations with scope specifiers, like:
10422   //   int foo::bar;
10423   assert(D->isOutOfLine());
10424   EnterDeclaratorContext(S, D->getDeclContext());
10425   
10426   // If we are parsing the initializer for a static data member, push a
10427   // new expression evaluation context that is associated with this static
10428   // data member.
10429   if (isStaticDataMember(D))
10430     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
10431 }
10432 
10433 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
10434 /// initializer for the out-of-line declaration 'D'.
10435 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
10436   // If there is no declaration, there was an error parsing it.
10437   if (D == 0 || D->isInvalidDecl()) return;
10438 
10439   if (isStaticDataMember(D))
10440     PopExpressionEvaluationContext();  
10441 
10442   assert(D->isOutOfLine());
10443   ExitDeclaratorContext(S);
10444 }
10445 
10446 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10447 /// C++ if/switch/while/for statement.
10448 /// e.g: "if (int x = f()) {...}"
10449 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
10450   // C++ 6.4p2:
10451   // The declarator shall not specify a function or an array.
10452   // The type-specifier-seq shall not contain typedef and shall not declare a
10453   // new class or enumeration.
10454   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10455          "Parser allowed 'typedef' as storage class of condition decl.");
10456 
10457   Decl *Dcl = ActOnDeclarator(S, D);
10458   if (!Dcl)
10459     return true;
10460 
10461   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10462     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
10463       << D.getSourceRange();
10464     return true;
10465   }
10466 
10467   return Dcl;
10468 }
10469 
10470 void Sema::LoadExternalVTableUses() {
10471   if (!ExternalSource)
10472     return;
10473   
10474   SmallVector<ExternalVTableUse, 4> VTables;
10475   ExternalSource->ReadUsedVTables(VTables);
10476   SmallVector<VTableUse, 4> NewUses;
10477   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10478     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10479       = VTablesUsed.find(VTables[I].Record);
10480     // Even if a definition wasn't required before, it may be required now.
10481     if (Pos != VTablesUsed.end()) {
10482       if (!Pos->second && VTables[I].DefinitionRequired)
10483         Pos->second = true;
10484       continue;
10485     }
10486     
10487     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10488     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10489   }
10490   
10491   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10492 }
10493 
10494 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10495                           bool DefinitionRequired) {
10496   // Ignore any vtable uses in unevaluated operands or for classes that do
10497   // not have a vtable.
10498   if (!Class->isDynamicClass() || Class->isDependentContext() ||
10499       CurContext->isDependentContext() ||
10500       ExprEvalContexts.back().Context == Unevaluated)
10501     return;
10502 
10503   // Try to insert this class into the map.
10504   LoadExternalVTableUses();
10505   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10506   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10507     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10508   if (!Pos.second) {
10509     // If we already had an entry, check to see if we are promoting this vtable
10510     // to required a definition. If so, we need to reappend to the VTableUses
10511     // list, since we may have already processed the first entry.
10512     if (DefinitionRequired && !Pos.first->second) {
10513       Pos.first->second = true;
10514     } else {
10515       // Otherwise, we can early exit.
10516       return;
10517     }
10518   }
10519 
10520   // Local classes need to have their virtual members marked
10521   // immediately. For all other classes, we mark their virtual members
10522   // at the end of the translation unit.
10523   if (Class->isLocalClass())
10524     MarkVirtualMembersReferenced(Loc, Class);
10525   else
10526     VTableUses.push_back(std::make_pair(Class, Loc));
10527 }
10528 
10529 bool Sema::DefineUsedVTables() {
10530   LoadExternalVTableUses();
10531   if (VTableUses.empty())
10532     return false;
10533 
10534   // Note: The VTableUses vector could grow as a result of marking
10535   // the members of a class as "used", so we check the size each
10536   // time through the loop and prefer indices (with are stable) to
10537   // iterators (which are not).
10538   bool DefinedAnything = false;
10539   for (unsigned I = 0; I != VTableUses.size(); ++I) {
10540     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
10541     if (!Class)
10542       continue;
10543 
10544     SourceLocation Loc = VTableUses[I].second;
10545 
10546     // If this class has a key function, but that key function is
10547     // defined in another translation unit, we don't need to emit the
10548     // vtable even though we're using it.
10549     const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
10550     if (KeyFunction && !KeyFunction->hasBody()) {
10551       switch (KeyFunction->getTemplateSpecializationKind()) {
10552       case TSK_Undeclared:
10553       case TSK_ExplicitSpecialization:
10554       case TSK_ExplicitInstantiationDeclaration:
10555         // The key function is in another translation unit.
10556         continue;
10557 
10558       case TSK_ExplicitInstantiationDefinition:
10559       case TSK_ImplicitInstantiation:
10560         // We will be instantiating the key function.
10561         break;
10562       }
10563     } else if (!KeyFunction) {
10564       // If we have a class with no key function that is the subject
10565       // of an explicit instantiation declaration, suppress the
10566       // vtable; it will live with the explicit instantiation
10567       // definition.
10568       bool IsExplicitInstantiationDeclaration
10569         = Class->getTemplateSpecializationKind()
10570                                       == TSK_ExplicitInstantiationDeclaration;
10571       for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10572                                  REnd = Class->redecls_end();
10573            R != REnd; ++R) {
10574         TemplateSpecializationKind TSK
10575           = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10576         if (TSK == TSK_ExplicitInstantiationDeclaration)
10577           IsExplicitInstantiationDeclaration = true;
10578         else if (TSK == TSK_ExplicitInstantiationDefinition) {
10579           IsExplicitInstantiationDeclaration = false;
10580           break;
10581         }
10582       }
10583 
10584       if (IsExplicitInstantiationDeclaration)
10585         continue;
10586     }
10587 
10588     // Mark all of the virtual members of this class as referenced, so
10589     // that we can build a vtable. Then, tell the AST consumer that a
10590     // vtable for this class is required.
10591     DefinedAnything = true;
10592     MarkVirtualMembersReferenced(Loc, Class);
10593     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10594     Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10595 
10596     // Optionally warn if we're emitting a weak vtable.
10597     if (Class->getLinkage() == ExternalLinkage &&
10598         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
10599       const FunctionDecl *KeyFunctionDef = 0;
10600       if (!KeyFunction || 
10601           (KeyFunction->hasBody(KeyFunctionDef) && 
10602            KeyFunctionDef->isInlined()))
10603         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10604              TSK_ExplicitInstantiationDefinition 
10605              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 
10606           << Class;
10607     }
10608   }
10609   VTableUses.clear();
10610 
10611   return DefinedAnything;
10612 }
10613 
10614 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10615                                         const CXXRecordDecl *RD) {
10616   for (CXXRecordDecl::method_iterator i = RD->method_begin(), 
10617        e = RD->method_end(); i != e; ++i) {
10618     CXXMethodDecl *MD = &*i;
10619 
10620     // C++ [basic.def.odr]p2:
10621     //   [...] A virtual member function is used if it is not pure. [...]
10622     if (MD->isVirtual() && !MD->isPure())
10623       MarkFunctionReferenced(Loc, MD);
10624   }
10625 
10626   // Only classes that have virtual bases need a VTT.
10627   if (RD->getNumVBases() == 0)
10628     return;
10629 
10630   for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10631            e = RD->bases_end(); i != e; ++i) {
10632     const CXXRecordDecl *Base =
10633         cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
10634     if (Base->getNumVBases() == 0)
10635       continue;
10636     MarkVirtualMembersReferenced(Loc, Base);
10637   }
10638 }
10639 
10640 /// SetIvarInitializers - This routine builds initialization ASTs for the
10641 /// Objective-C implementation whose ivars need be initialized.
10642 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10643   if (!getLangOpts().CPlusPlus)
10644     return;
10645   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
10646     SmallVector<ObjCIvarDecl*, 8> ivars;
10647     CollectIvarsToConstructOrDestruct(OID, ivars);
10648     if (ivars.empty())
10649       return;
10650     SmallVector<CXXCtorInitializer*, 32> AllToInit;
10651     for (unsigned i = 0; i < ivars.size(); i++) {
10652       FieldDecl *Field = ivars[i];
10653       if (Field->isInvalidDecl())
10654         continue;
10655       
10656       CXXCtorInitializer *Member;
10657       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10658       InitializationKind InitKind = 
10659         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10660       
10661       InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
10662       ExprResult MemberInit = 
10663         InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
10664       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
10665       // Note, MemberInit could actually come back empty if no initialization 
10666       // is required (e.g., because it would call a trivial default constructor)
10667       if (!MemberInit.get() || MemberInit.isInvalid())
10668         continue;
10669 
10670       Member =
10671         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10672                                          SourceLocation(),
10673                                          MemberInit.takeAs<Expr>(),
10674                                          SourceLocation());
10675       AllToInit.push_back(Member);
10676       
10677       // Be sure that the destructor is accessible and is marked as referenced.
10678       if (const RecordType *RecordTy
10679                   = Context.getBaseElementType(Field->getType())
10680                                                         ->getAs<RecordType>()) {
10681                     CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
10682         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
10683           MarkFunctionReferenced(Field->getLocation(), Destructor);
10684           CheckDestructorAccess(Field->getLocation(), Destructor,
10685                             PDiag(diag::err_access_dtor_ivar)
10686                               << Context.getBaseElementType(Field->getType()));
10687         }
10688       }      
10689     }
10690     ObjCImplementation->setIvarInitializers(Context, 
10691                                             AllToInit.data(), AllToInit.size());
10692   }
10693 }
10694 
10695 static
10696 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10697                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10698                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10699                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10700                            Sema &S) {
10701   llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10702                                                    CE = Current.end();
10703   if (Ctor->isInvalidDecl())
10704     return;
10705 
10706   const FunctionDecl *FNTarget = 0;
10707   CXXConstructorDecl *Target;
10708   
10709   // We ignore the result here since if we don't have a body, Target will be
10710   // null below.
10711   (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10712   Target
10713 = const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10714 
10715   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10716                      // Avoid dereferencing a null pointer here.
10717                      *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10718 
10719   if (!Current.insert(Canonical))
10720     return;
10721 
10722   // We know that beyond here, we aren't chaining into a cycle.
10723   if (!Target || !Target->isDelegatingConstructor() ||
10724       Target->isInvalidDecl() || Valid.count(TCanonical)) {
10725     for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10726       Valid.insert(*CI);
10727     Current.clear();
10728   // We've hit a cycle.
10729   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10730              Current.count(TCanonical)) {
10731     // If we haven't diagnosed this cycle yet, do so now.
10732     if (!Invalid.count(TCanonical)) {
10733       S.Diag((*Ctor->init_begin())->getSourceLocation(),
10734              diag::warn_delegating_ctor_cycle)
10735         << Ctor;
10736 
10737       // Don't add a note for a function delegating directo to itself.
10738       if (TCanonical != Canonical)
10739         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10740 
10741       CXXConstructorDecl *C = Target;
10742       while (C->getCanonicalDecl() != Canonical) {
10743         (void)C->getTargetConstructor()->hasBody(FNTarget);
10744         assert(FNTarget && "Ctor cycle through bodiless function");
10745 
10746         C
10747        = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10748         S.Diag(C->getLocation(), diag::note_which_delegates_to);
10749       }
10750     }
10751 
10752     for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10753       Invalid.insert(*CI);
10754     Current.clear();
10755   } else {
10756     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10757   }
10758 }
10759    
10760 
10761 void Sema::CheckDelegatingCtorCycles() {
10762   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10763 
10764   llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10765                                                    CE = Current.end();
10766 
10767   for (DelegatingCtorDeclsType::iterator
10768          I = DelegatingCtorDecls.begin(ExternalSource),
10769          E = DelegatingCtorDecls.end();
10770        I != E; ++I) {
10771    DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
10772   }
10773 
10774   for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10775     (*CI)->setInvalidDecl();
10776 }
10777 
10778 namespace {
10779   /// \brief AST visitor that finds references to the 'this' expression.
10780   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
10781     Sema &S;
10782     
10783   public:
10784     explicit FindCXXThisExpr(Sema &S) : S(S) { }
10785     
10786     bool VisitCXXThisExpr(CXXThisExpr *E) {
10787       S.Diag(E->getLocation(), diag::err_this_static_member_func)
10788         << E->isImplicit();
10789       return false;
10790     }
10791   };
10792 }
10793 
10794 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
10795   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
10796   if (!TSInfo)
10797     return false;
10798   
10799   TypeLoc TL = TSInfo->getTypeLoc();
10800   FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
10801   if (!ProtoTL)
10802     return false;
10803   
10804   // C++11 [expr.prim.general]p3:
10805   //   [The expression this] shall not appear before the optional 
10806   //   cv-qualifier-seq and it shall not appear within the declaration of a 
10807   //   static member function (although its type and value category are defined
10808   //   within a static member function as they are within a non-static member
10809   //   function). [ Note: this is because declaration matching does not occur
10810   //  until the complete declarator is known. - end note ]
10811   const FunctionProtoType *Proto = ProtoTL->getTypePtr();
10812   FindCXXThisExpr Finder(*this);
10813   
10814   // If the return type came after the cv-qualifier-seq, check it now.
10815   if (Proto->hasTrailingReturn() &&
10816       !Finder.TraverseTypeLoc(ProtoTL->getResultLoc()))
10817     return true;
10818 
10819   // Check the exception specification.
10820   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
10821     return true;
10822   
10823   return checkThisInStaticMemberFunctionAttributes(Method);
10824 }
10825 
10826 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
10827   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
10828   if (!TSInfo)
10829     return false;
10830   
10831   TypeLoc TL = TSInfo->getTypeLoc();
10832   FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
10833   if (!ProtoTL)
10834     return false;
10835   
10836   const FunctionProtoType *Proto = ProtoTL->getTypePtr();
10837   FindCXXThisExpr Finder(*this);
10838 
10839   switch (Proto->getExceptionSpecType()) {
10840   case EST_Uninstantiated:
10841   case EST_BasicNoexcept:
10842   case EST_Delayed:
10843   case EST_DynamicNone:
10844   case EST_MSAny:
10845   case EST_None:
10846     break;
10847     
10848   case EST_ComputedNoexcept:
10849     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
10850       return true;
10851     
10852   case EST_Dynamic:
10853     for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
10854          EEnd = Proto->exception_end();
10855          E != EEnd; ++E) {
10856       if (!Finder.TraverseType(*E))
10857         return true;
10858     }
10859     break;
10860   }
10861 
10862   return false;
10863 }
10864 
10865 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
10866   FindCXXThisExpr Finder(*this);
10867 
10868   // Check attributes.
10869   for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
10870        A != AEnd; ++A) {
10871     // FIXME: This should be emitted by tblgen.
10872     Expr *Arg = 0;
10873     ArrayRef<Expr *> Args;
10874     if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
10875       Arg = G->getArg();
10876     else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
10877       Arg = G->getArg();
10878     else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
10879       Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
10880     else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
10881       Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
10882     else if (ExclusiveLockFunctionAttr *ELF 
10883                = dyn_cast<ExclusiveLockFunctionAttr>(*A))
10884       Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
10885     else if (SharedLockFunctionAttr *SLF 
10886                = dyn_cast<SharedLockFunctionAttr>(*A))
10887       Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
10888     else if (ExclusiveTrylockFunctionAttr *ETLF
10889                = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
10890       Arg = ETLF->getSuccessValue();
10891       Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
10892     } else if (SharedTrylockFunctionAttr *STLF
10893                  = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
10894       Arg = STLF->getSuccessValue();
10895       Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
10896     } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
10897       Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
10898     else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
10899       Arg = LR->getArg();
10900     else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
10901       Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
10902     else if (ExclusiveLocksRequiredAttr *ELR 
10903                = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
10904       Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
10905     else if (SharedLocksRequiredAttr *SLR 
10906                = dyn_cast<SharedLocksRequiredAttr>(*A))
10907       Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
10908 
10909     if (Arg && !Finder.TraverseStmt(Arg))
10910       return true;
10911     
10912     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
10913       if (!Finder.TraverseStmt(Args[I]))
10914         return true;
10915     }
10916   }
10917   
10918   return false;
10919 }
10920 
10921 void
10922 Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
10923                                   ArrayRef<ParsedType> DynamicExceptions,
10924                                   ArrayRef<SourceRange> DynamicExceptionRanges,
10925                                   Expr *NoexceptExpr,
10926                                   llvm::SmallVectorImpl<QualType> &Exceptions,
10927                                   FunctionProtoType::ExtProtoInfo &EPI) {
10928   Exceptions.clear();
10929   EPI.ExceptionSpecType = EST;
10930   if (EST == EST_Dynamic) {
10931     Exceptions.reserve(DynamicExceptions.size());
10932     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
10933       // FIXME: Preserve type source info.
10934       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
10935 
10936       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
10937       collectUnexpandedParameterPacks(ET, Unexpanded);
10938       if (!Unexpanded.empty()) {
10939         DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
10940                                          UPPC_ExceptionType,
10941                                          Unexpanded);
10942         continue;
10943       }
10944 
10945       // Check that the type is valid for an exception spec, and
10946       // drop it if not.
10947       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
10948         Exceptions.push_back(ET);
10949     }
10950     EPI.NumExceptions = Exceptions.size();
10951     EPI.Exceptions = Exceptions.data();
10952     return;
10953   }
10954   
10955   if (EST == EST_ComputedNoexcept) {
10956     // If an error occurred, there's no expression here.
10957     if (NoexceptExpr) {
10958       assert((NoexceptExpr->isTypeDependent() ||
10959               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
10960               Context.BoolTy) &&
10961              "Parser should have made sure that the expression is boolean");
10962       if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
10963         EPI.ExceptionSpecType = EST_BasicNoexcept;
10964         return;
10965       }
10966       
10967       if (!NoexceptExpr->isValueDependent())
10968         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
10969                          diag::err_noexcept_needs_constant_expression,
10970                          /*AllowFold*/ false).take();
10971       EPI.NoexceptExpr = NoexceptExpr;
10972     }
10973     return;
10974   }
10975 }
10976 
10977 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function
10978 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
10979   // Implicitly declared functions (e.g. copy constructors) are
10980   // __host__ __device__
10981   if (D->isImplicit())
10982     return CFT_HostDevice;
10983 
10984   if (D->hasAttr<CUDAGlobalAttr>())
10985     return CFT_Global;
10986 
10987   if (D->hasAttr<CUDADeviceAttr>()) {
10988     if (D->hasAttr<CUDAHostAttr>())
10989       return CFT_HostDevice;
10990     else
10991       return CFT_Device;
10992   }
10993 
10994   return CFT_Host;
10995 }
10996 
10997 bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
10998                            CUDAFunctionTarget CalleeTarget) {
10999   // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11000   // Callable from the device only."
11001   if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11002     return true;
11003 
11004   // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11005   // Callable from the host only."
11006   // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11007   // Callable from the host only."
11008   if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11009       (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11010     return true;
11011 
11012   if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11013     return true;
11014 
11015   return false;
11016 }