clang API Documentation

SemaDecl.cpp
Go to the documentation of this file.
00001 //===--- SemaDecl.cpp - Semantic Analysis for 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 declarations.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/Sema/SemaInternal.h"
00015 #include "TypeLocBuilder.h"
00016 #include "clang/AST/ASTConsumer.h"
00017 #include "clang/AST/ASTContext.h"
00018 #include "clang/AST/ASTLambda.h"
00019 #include "clang/AST/CXXInheritance.h"
00020 #include "clang/AST/CharUnits.h"
00021 #include "clang/AST/CommentDiagnostic.h"
00022 #include "clang/AST/DeclCXX.h"
00023 #include "clang/AST/DeclObjC.h"
00024 #include "clang/AST/DeclTemplate.h"
00025 #include "clang/AST/EvaluatedExprVisitor.h"
00026 #include "clang/AST/ExprCXX.h"
00027 #include "clang/AST/StmtCXX.h"
00028 #include "clang/Basic/Builtins.h"
00029 #include "clang/Basic/PartialDiagnostic.h"
00030 #include "clang/Basic/SourceManager.h"
00031 #include "clang/Basic/TargetInfo.h"
00032 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
00033 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
00034 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
00035 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
00036 #include "clang/Parse/ParseDiagnostic.h"
00037 #include "clang/Sema/CXXFieldCollector.h"
00038 #include "clang/Sema/DeclSpec.h"
00039 #include "clang/Sema/DelayedDiagnostic.h"
00040 #include "clang/Sema/Initialization.h"
00041 #include "clang/Sema/Lookup.h"
00042 #include "clang/Sema/ParsedTemplate.h"
00043 #include "clang/Sema/Scope.h"
00044 #include "clang/Sema/ScopeInfo.h"
00045 #include "clang/Sema/Template.h"
00046 #include "llvm/ADT/SmallString.h"
00047 #include "llvm/ADT/Triple.h"
00048 #include <algorithm>
00049 #include <cstring>
00050 #include <functional>
00051 using namespace clang;
00052 using namespace sema;
00053 
00054 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
00055   if (OwnedType) {
00056     Decl *Group[2] = { OwnedType, Ptr };
00057     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
00058   }
00059 
00060   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
00061 }
00062 
00063 namespace {
00064 
00065 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
00066  public:
00067   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
00068                        bool AllowTemplates=false)
00069       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
00070         AllowClassTemplates(AllowTemplates) {
00071     WantExpressionKeywords = false;
00072     WantCXXNamedCasts = false;
00073     WantRemainingKeywords = false;
00074   }
00075 
00076   bool ValidateCandidate(const TypoCorrection &candidate) override {
00077     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
00078       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
00079       bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
00080       return (IsType || AllowedTemplate) &&
00081              (AllowInvalidDecl || !ND->isInvalidDecl());
00082     }
00083     return !WantClassName && candidate.isKeyword();
00084   }
00085 
00086  private:
00087   bool AllowInvalidDecl;
00088   bool WantClassName;
00089   bool AllowClassTemplates;
00090 };
00091 
00092 }
00093 
00094 /// \brief Determine whether the token kind starts a simple-type-specifier.
00095 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
00096   switch (Kind) {
00097   // FIXME: Take into account the current language when deciding whether a
00098   // token kind is a valid type specifier
00099   case tok::kw_short:
00100   case tok::kw_long:
00101   case tok::kw___int64:
00102   case tok::kw___int128:
00103   case tok::kw_signed:
00104   case tok::kw_unsigned:
00105   case tok::kw_void:
00106   case tok::kw_char:
00107   case tok::kw_int:
00108   case tok::kw_half:
00109   case tok::kw_float:
00110   case tok::kw_double:
00111   case tok::kw_wchar_t:
00112   case tok::kw_bool:
00113   case tok::kw___underlying_type:
00114     return true;
00115 
00116   case tok::annot_typename:
00117   case tok::kw_char16_t:
00118   case tok::kw_char32_t:
00119   case tok::kw_typeof:
00120   case tok::annot_decltype:
00121   case tok::kw_decltype:
00122     return getLangOpts().CPlusPlus;
00123 
00124   default:
00125     break;
00126   }
00127 
00128   return false;
00129 }
00130 
00131 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
00132                                                       const IdentifierInfo &II,
00133                                                       SourceLocation NameLoc) {
00134   // Find the first parent class template context, if any.
00135   // FIXME: Perform the lookup in all enclosing class templates.
00136   const CXXRecordDecl *RD = nullptr;
00137   for (DeclContext *DC = S.CurContext; DC; DC = DC->getParent()) {
00138     RD = dyn_cast<CXXRecordDecl>(DC);
00139     if (RD && RD->getDescribedClassTemplate())
00140       break;
00141   }
00142   if (!RD)
00143     return ParsedType();
00144 
00145   // Look for type decls in dependent base classes that have known primary
00146   // templates.
00147   bool FoundTypeDecl = false;
00148   for (const auto &Base : RD->bases()) {
00149     auto *TST = Base.getType()->getAs<TemplateSpecializationType>();
00150     if (!TST || !TST->isDependentType())
00151       continue;
00152     auto *TD = TST->getTemplateName().getAsTemplateDecl();
00153     if (!TD)
00154       continue;
00155     auto *BasePrimaryTemplate =
00156         dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
00157     if (!BasePrimaryTemplate)
00158       continue;
00159     // FIXME: Allow lookup into non-dependent bases of dependent bases, possibly
00160     // by calling or integrating with the main LookupQualifiedName mechanism.
00161     for (NamedDecl *ND : BasePrimaryTemplate->lookup(&II)) {
00162       if (FoundTypeDecl)
00163         return ParsedType();
00164       FoundTypeDecl = isa<TypeDecl>(ND);
00165       if (!FoundTypeDecl)
00166         return ParsedType();
00167     }
00168   }
00169   if (!FoundTypeDecl)
00170     return ParsedType();
00171 
00172   // We found some types in dependent base classes.  Recover as if the user
00173   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
00174   // lookup during template instantiation.
00175   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
00176 
00177   ASTContext &Context = S.Context;
00178   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
00179                                           cast<Type>(Context.getRecordType(RD)));
00180   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
00181 
00182   CXXScopeSpec SS;
00183   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
00184 
00185   TypeLocBuilder Builder;
00186   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
00187   DepTL.setNameLoc(NameLoc);
00188   DepTL.setElaboratedKeywordLoc(SourceLocation());
00189   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
00190   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
00191 }
00192 
00193 /// \brief If the identifier refers to a type name within this scope,
00194 /// return the declaration of that type.
00195 ///
00196 /// This routine performs ordinary name lookup of the identifier II
00197 /// within the given scope, with optional C++ scope specifier SS, to
00198 /// determine whether the name refers to a type. If so, returns an
00199 /// opaque pointer (actually a QualType) corresponding to that
00200 /// type. Otherwise, returns NULL.
00201 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
00202                              Scope *S, CXXScopeSpec *SS,
00203                              bool isClassName, bool HasTrailingDot,
00204                              ParsedType ObjectTypePtr,
00205                              bool IsCtorOrDtorName,
00206                              bool WantNontrivialTypeSourceInfo,
00207                              IdentifierInfo **CorrectedII) {
00208   // Determine where we will perform name lookup.
00209   DeclContext *LookupCtx = nullptr;
00210   if (ObjectTypePtr) {
00211     QualType ObjectType = ObjectTypePtr.get();
00212     if (ObjectType->isRecordType())
00213       LookupCtx = computeDeclContext(ObjectType);
00214   } else if (SS && SS->isNotEmpty()) {
00215     LookupCtx = computeDeclContext(*SS, false);
00216 
00217     if (!LookupCtx) {
00218       if (isDependentScopeSpecifier(*SS)) {
00219         // C++ [temp.res]p3:
00220         //   A qualified-id that refers to a type and in which the
00221         //   nested-name-specifier depends on a template-parameter (14.6.2)
00222         //   shall be prefixed by the keyword typename to indicate that the
00223         //   qualified-id denotes a type, forming an
00224         //   elaborated-type-specifier (7.1.5.3).
00225         //
00226         // We therefore do not perform any name lookup if the result would
00227         // refer to a member of an unknown specialization.
00228         if (!isClassName && !IsCtorOrDtorName)
00229           return ParsedType();
00230         
00231         // We know from the grammar that this name refers to a type,
00232         // so build a dependent node to describe the type.
00233         if (WantNontrivialTypeSourceInfo)
00234           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
00235         
00236         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
00237         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
00238                                        II, NameLoc);
00239         return ParsedType::make(T);
00240       }
00241       
00242       return ParsedType();
00243     }
00244     
00245     if (!LookupCtx->isDependentContext() &&
00246         RequireCompleteDeclContext(*SS, LookupCtx))
00247       return ParsedType();
00248   }
00249 
00250   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
00251   // lookup for class-names.
00252   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
00253                                       LookupOrdinaryName;
00254   LookupResult Result(*this, &II, NameLoc, Kind);
00255   if (LookupCtx) {
00256     // Perform "qualified" name lookup into the declaration context we
00257     // computed, which is either the type of the base of a member access
00258     // expression or the declaration context associated with a prior
00259     // nested-name-specifier.
00260     LookupQualifiedName(Result, LookupCtx);
00261 
00262     if (ObjectTypePtr && Result.empty()) {
00263       // C++ [basic.lookup.classref]p3:
00264       //   If the unqualified-id is ~type-name, the type-name is looked up
00265       //   in the context of the entire postfix-expression. If the type T of 
00266       //   the object expression is of a class type C, the type-name is also
00267       //   looked up in the scope of class C. At least one of the lookups shall
00268       //   find a name that refers to (possibly cv-qualified) T.
00269       LookupName(Result, S);
00270     }
00271   } else {
00272     // Perform unqualified name lookup.
00273     LookupName(Result, S);
00274 
00275     // For unqualified lookup in a class template in MSVC mode, look into
00276     // dependent base classes where the primary class template is known.
00277     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
00278       if (ParsedType TypeInBase =
00279               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
00280         return TypeInBase;
00281     }
00282   }
00283 
00284   NamedDecl *IIDecl = nullptr;
00285   switch (Result.getResultKind()) {
00286   case LookupResult::NotFound:
00287   case LookupResult::NotFoundInCurrentInstantiation:
00288     if (CorrectedII) {
00289       TypoCorrection Correction = CorrectTypo(
00290           Result.getLookupNameInfo(), Kind, S, SS,
00291           llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
00292           CTK_ErrorRecovery);
00293       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
00294       TemplateTy Template;
00295       bool MemberOfUnknownSpecialization;
00296       UnqualifiedId TemplateName;
00297       TemplateName.setIdentifier(NewII, NameLoc);
00298       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
00299       CXXScopeSpec NewSS, *NewSSPtr = SS;
00300       if (SS && NNS) {
00301         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
00302         NewSSPtr = &NewSS;
00303       }
00304       if (Correction && (NNS || NewII != &II) &&
00305           // Ignore a correction to a template type as the to-be-corrected
00306           // identifier is not a template (typo correction for template names
00307           // is handled elsewhere).
00308           !(getLangOpts().CPlusPlus && NewSSPtr &&
00309             isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
00310                            false, Template, MemberOfUnknownSpecialization))) {
00311         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
00312                                     isClassName, HasTrailingDot, ObjectTypePtr,
00313                                     IsCtorOrDtorName,
00314                                     WantNontrivialTypeSourceInfo);
00315         if (Ty) {
00316           diagnoseTypo(Correction,
00317                        PDiag(diag::err_unknown_type_or_class_name_suggest)
00318                          << Result.getLookupName() << isClassName);
00319           if (SS && NNS)
00320             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
00321           *CorrectedII = NewII;
00322           return Ty;
00323         }
00324       }
00325     }
00326     // If typo correction failed or was not performed, fall through
00327   case LookupResult::FoundOverloaded:
00328   case LookupResult::FoundUnresolvedValue:
00329     Result.suppressDiagnostics();
00330     return ParsedType();
00331 
00332   case LookupResult::Ambiguous:
00333     // Recover from type-hiding ambiguities by hiding the type.  We'll
00334     // do the lookup again when looking for an object, and we can
00335     // diagnose the error then.  If we don't do this, then the error
00336     // about hiding the type will be immediately followed by an error
00337     // that only makes sense if the identifier was treated like a type.
00338     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
00339       Result.suppressDiagnostics();
00340       return ParsedType();
00341     }
00342 
00343     // Look to see if we have a type anywhere in the list of results.
00344     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
00345          Res != ResEnd; ++Res) {
00346       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
00347         if (!IIDecl ||
00348             (*Res)->getLocation().getRawEncoding() <
00349               IIDecl->getLocation().getRawEncoding())
00350           IIDecl = *Res;
00351       }
00352     }
00353 
00354     if (!IIDecl) {
00355       // None of the entities we found is a type, so there is no way
00356       // to even assume that the result is a type. In this case, don't
00357       // complain about the ambiguity. The parser will either try to
00358       // perform this lookup again (e.g., as an object name), which
00359       // will produce the ambiguity, or will complain that it expected
00360       // a type name.
00361       Result.suppressDiagnostics();
00362       return ParsedType();
00363     }
00364 
00365     // We found a type within the ambiguous lookup; diagnose the
00366     // ambiguity and then return that type. This might be the right
00367     // answer, or it might not be, but it suppresses any attempt to
00368     // perform the name lookup again.
00369     break;
00370 
00371   case LookupResult::Found:
00372     IIDecl = Result.getFoundDecl();
00373     break;
00374   }
00375 
00376   assert(IIDecl && "Didn't find decl");
00377 
00378   QualType T;
00379   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
00380     DiagnoseUseOfDecl(IIDecl, NameLoc);
00381 
00382     T = Context.getTypeDeclType(TD);
00383     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
00384 
00385     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
00386     // constructor or destructor name (in such a case, the scope specifier
00387     // will be attached to the enclosing Expr or Decl node).
00388     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
00389       if (WantNontrivialTypeSourceInfo) {
00390         // Construct a type with type-source information.
00391         TypeLocBuilder Builder;
00392         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
00393         
00394         T = getElaboratedType(ETK_None, *SS, T);
00395         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
00396         ElabTL.setElaboratedKeywordLoc(SourceLocation());
00397         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
00398         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
00399       } else {
00400         T = getElaboratedType(ETK_None, *SS, T);
00401       }
00402     }
00403   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
00404     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
00405     if (!HasTrailingDot)
00406       T = Context.getObjCInterfaceType(IDecl);
00407   }
00408 
00409   if (T.isNull()) {
00410     // If it's not plausibly a type, suppress diagnostics.
00411     Result.suppressDiagnostics();
00412     return ParsedType();
00413   }
00414   return ParsedType::make(T);
00415 }
00416 
00417 // Builds a fake NNS for the given decl context.
00418 static NestedNameSpecifier *
00419 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
00420   for (;; DC = DC->getLookupParent()) {
00421     DC = DC->getPrimaryContext();
00422     auto *ND = dyn_cast<NamespaceDecl>(DC);
00423     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
00424       return NestedNameSpecifier::Create(Context, nullptr, ND);
00425     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
00426       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
00427                                          RD->getTypeForDecl());
00428     else if (isa<TranslationUnitDecl>(DC))
00429       return NestedNameSpecifier::GlobalSpecifier(Context);
00430   }
00431   llvm_unreachable("something isn't in TU scope?");
00432 }
00433 
00434 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
00435                                                 SourceLocation NameLoc) {
00436   // Accepting an undeclared identifier as a default argument for a template
00437   // type parameter is a Microsoft extension.
00438   Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
00439 
00440   // Build a fake DependentNameType that will perform lookup into CurContext at
00441   // instantiation time.  The name specifier isn't dependent, so template
00442   // instantiation won't transform it.  It will retry the lookup, however.
00443   NestedNameSpecifier *NNS =
00444       synthesizeCurrentNestedNameSpecifier(Context, CurContext);
00445   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
00446 
00447   // Build type location information.  We synthesized the qualifier, so we have
00448   // to build a fake NestedNameSpecifierLoc.
00449   NestedNameSpecifierLocBuilder NNSLocBuilder;
00450   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
00451   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
00452 
00453   TypeLocBuilder Builder;
00454   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
00455   DepTL.setNameLoc(NameLoc);
00456   DepTL.setElaboratedKeywordLoc(SourceLocation());
00457   DepTL.setQualifierLoc(QualifierLoc);
00458   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
00459 }
00460 
00461 /// isTagName() - This method is called *for error recovery purposes only*
00462 /// to determine if the specified name is a valid tag name ("struct foo").  If
00463 /// so, this returns the TST for the tag corresponding to it (TST_enum,
00464 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
00465 /// cases in C where the user forgot to specify the tag.
00466 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
00467   // Do a tag name lookup in this scope.
00468   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
00469   LookupName(R, S, false);
00470   R.suppressDiagnostics();
00471   if (R.getResultKind() == LookupResult::Found)
00472     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
00473       switch (TD->getTagKind()) {
00474       case TTK_Struct: return DeclSpec::TST_struct;
00475       case TTK_Interface: return DeclSpec::TST_interface;
00476       case TTK_Union:  return DeclSpec::TST_union;
00477       case TTK_Class:  return DeclSpec::TST_class;
00478       case TTK_Enum:   return DeclSpec::TST_enum;
00479       }
00480     }
00481 
00482   return DeclSpec::TST_unspecified;
00483 }
00484 
00485 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
00486 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
00487 /// then downgrade the missing typename error to a warning.
00488 /// This is needed for MSVC compatibility; Example:
00489 /// @code
00490 /// template<class T> class A {
00491 /// public:
00492 ///   typedef int TYPE;
00493 /// };
00494 /// template<class T> class B : public A<T> {
00495 /// public:
00496 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
00497 /// };
00498 /// @endcode
00499 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
00500   if (CurContext->isRecord()) {
00501     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
00502       return true;
00503 
00504     const Type *Ty = SS->getScopeRep()->getAsType();
00505 
00506     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
00507     for (const auto &Base : RD->bases())
00508       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
00509         return true;
00510     return S->isFunctionPrototypeScope();
00511   } 
00512   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
00513 }
00514 
00515 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
00516                                    SourceLocation IILoc,
00517                                    Scope *S,
00518                                    CXXScopeSpec *SS,
00519                                    ParsedType &SuggestedType,
00520                                    bool AllowClassTemplates) {
00521   // We don't have anything to suggest (yet).
00522   SuggestedType = ParsedType();
00523   
00524   // There may have been a typo in the name of the type. Look up typo
00525   // results, in case we have something that we can suggest.
00526   if (TypoCorrection Corrected =
00527           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
00528                       llvm::make_unique<TypeNameValidatorCCC>(
00529                           false, false, AllowClassTemplates),
00530                       CTK_ErrorRecovery)) {
00531     if (Corrected.isKeyword()) {
00532       // We corrected to a keyword.
00533       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
00534       II = Corrected.getCorrectionAsIdentifierInfo();
00535     } else {
00536       // We found a similarly-named type or interface; suggest that.
00537       if (!SS || !SS->isSet()) {
00538         diagnoseTypo(Corrected,
00539                      PDiag(diag::err_unknown_typename_suggest) << II);
00540       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
00541         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
00542         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
00543                                 II->getName().equals(CorrectedStr);
00544         diagnoseTypo(Corrected,
00545                      PDiag(diag::err_unknown_nested_typename_suggest)
00546                        << II << DC << DroppedSpecifier << SS->getRange());
00547       } else {
00548         llvm_unreachable("could not have corrected a typo here");
00549       }
00550 
00551       CXXScopeSpec tmpSS;
00552       if (Corrected.getCorrectionSpecifier())
00553         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
00554                           SourceRange(IILoc));
00555       SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
00556                                   IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
00557                                   false, ParsedType(),
00558                                   /*IsCtorOrDtorName=*/false,
00559                                   /*NonTrivialTypeSourceInfo=*/true);
00560     }
00561     return;
00562   }
00563 
00564   if (getLangOpts().CPlusPlus) {
00565     // See if II is a class template that the user forgot to pass arguments to.
00566     UnqualifiedId Name;
00567     Name.setIdentifier(II, IILoc);
00568     CXXScopeSpec EmptySS;
00569     TemplateTy TemplateResult;
00570     bool MemberOfUnknownSpecialization;
00571     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
00572                        Name, ParsedType(), true, TemplateResult,
00573                        MemberOfUnknownSpecialization) == TNK_Type_template) {
00574       TemplateName TplName = TemplateResult.get();
00575       Diag(IILoc, diag::err_template_missing_args) << TplName;
00576       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
00577         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
00578           << TplDecl->getTemplateParameters()->getSourceRange();
00579       }
00580       return;
00581     }
00582   }
00583 
00584   // FIXME: Should we move the logic that tries to recover from a missing tag
00585   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
00586   
00587   if (!SS || (!SS->isSet() && !SS->isInvalid()))
00588     Diag(IILoc, diag::err_unknown_typename) << II;
00589   else if (DeclContext *DC = computeDeclContext(*SS, false))
00590     Diag(IILoc, diag::err_typename_nested_not_found) 
00591       << II << DC << SS->getRange();
00592   else if (isDependentScopeSpecifier(*SS)) {
00593     unsigned DiagID = diag::err_typename_missing;
00594     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
00595       DiagID = diag::ext_typename_missing;
00596 
00597     Diag(SS->getRange().getBegin(), DiagID)
00598       << SS->getScopeRep() << II->getName()
00599       << SourceRange(SS->getRange().getBegin(), IILoc)
00600       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
00601     SuggestedType = ActOnTypenameType(S, SourceLocation(),
00602                                       *SS, *II, IILoc).get();
00603   } else {
00604     assert(SS && SS->isInvalid() && 
00605            "Invalid scope specifier has already been diagnosed");
00606   }
00607 }
00608 
00609 /// \brief Determine whether the given result set contains either a type name
00610 /// or 
00611 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
00612   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
00613                        NextToken.is(tok::less);
00614   
00615   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
00616     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
00617       return true;
00618     
00619     if (CheckTemplate && isa<TemplateDecl>(*I))
00620       return true;
00621   }
00622   
00623   return false;
00624 }
00625 
00626 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
00627                                     Scope *S, CXXScopeSpec &SS,
00628                                     IdentifierInfo *&Name,
00629                                     SourceLocation NameLoc) {
00630   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
00631   SemaRef.LookupParsedName(R, S, &SS);
00632   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
00633     StringRef FixItTagName;
00634     switch (Tag->getTagKind()) {
00635       case TTK_Class:
00636         FixItTagName = "class ";
00637         break;
00638 
00639       case TTK_Enum:
00640         FixItTagName = "enum ";
00641         break;
00642 
00643       case TTK_Struct:
00644         FixItTagName = "struct ";
00645         break;
00646 
00647       case TTK_Interface:
00648         FixItTagName = "__interface ";
00649         break;
00650 
00651       case TTK_Union:
00652         FixItTagName = "union ";
00653         break;
00654     }
00655 
00656     StringRef TagName = FixItTagName.drop_back();
00657     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
00658       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
00659       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
00660 
00661     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
00662          I != IEnd; ++I)
00663       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
00664         << Name << TagName;
00665 
00666     // Replace lookup results with just the tag decl.
00667     Result.clear(Sema::LookupTagName);
00668     SemaRef.LookupParsedName(Result, S, &SS);
00669     return true;
00670   }
00671 
00672   return false;
00673 }
00674 
00675 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
00676 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
00677                                   QualType T, SourceLocation NameLoc) {
00678   ASTContext &Context = S.Context;
00679 
00680   TypeLocBuilder Builder;
00681   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
00682 
00683   T = S.getElaboratedType(ETK_None, SS, T);
00684   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
00685   ElabTL.setElaboratedKeywordLoc(SourceLocation());
00686   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
00687   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
00688 }
00689 
00690 Sema::NameClassification
00691 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
00692                    SourceLocation NameLoc, const Token &NextToken,
00693                    bool IsAddressOfOperand,
00694                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
00695   DeclarationNameInfo NameInfo(Name, NameLoc);
00696   ObjCMethodDecl *CurMethod = getCurMethodDecl();
00697 
00698   if (NextToken.is(tok::coloncolon)) {
00699     BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
00700                                 QualType(), false, SS, nullptr, false);
00701   }
00702 
00703   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
00704   LookupParsedName(Result, S, &SS, !CurMethod);
00705 
00706   // For unqualified lookup in a class template in MSVC mode, look into
00707   // dependent base classes where the primary class template is known.
00708   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
00709     if (ParsedType TypeInBase =
00710             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
00711       return TypeInBase;
00712   }
00713 
00714   // Perform lookup for Objective-C instance variables (including automatically 
00715   // synthesized instance variables), if we're in an Objective-C method.
00716   // FIXME: This lookup really, really needs to be folded in to the normal
00717   // unqualified lookup mechanism.
00718   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
00719     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
00720     if (E.get() || E.isInvalid())
00721       return E;
00722   }
00723   
00724   bool SecondTry = false;
00725   bool IsFilteredTemplateName = false;
00726   
00727 Corrected:
00728   switch (Result.getResultKind()) {
00729   case LookupResult::NotFound:
00730     // If an unqualified-id is followed by a '(', then we have a function
00731     // call.
00732     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
00733       // In C++, this is an ADL-only call.
00734       // FIXME: Reference?
00735       if (getLangOpts().CPlusPlus)
00736         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
00737       
00738       // C90 6.3.2.2:
00739       //   If the expression that precedes the parenthesized argument list in a 
00740       //   function call consists solely of an identifier, and if no 
00741       //   declaration is visible for this identifier, the identifier is 
00742       //   implicitly declared exactly as if, in the innermost block containing
00743       //   the function call, the declaration
00744       //
00745       //     extern int identifier (); 
00746       //
00747       //   appeared. 
00748       // 
00749       // We also allow this in C99 as an extension.
00750       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
00751         Result.addDecl(D);
00752         Result.resolveKind();
00753         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
00754       }
00755     }
00756     
00757     // In C, we first see whether there is a tag type by the same name, in 
00758     // which case it's likely that the user just forget to write "enum", 
00759     // "struct", or "union".
00760     if (!getLangOpts().CPlusPlus && !SecondTry &&
00761         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
00762       break;
00763     }
00764 
00765     // Perform typo correction to determine if there is another name that is
00766     // close to this name.
00767     if (!SecondTry && CCC) {
00768       SecondTry = true;
00769       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
00770                                                  Result.getLookupKind(), S, 
00771                                                  &SS, std::move(CCC),
00772                                                  CTK_ErrorRecovery)) {
00773         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
00774         unsigned QualifiedDiag = diag::err_no_member_suggest;
00775 
00776         NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
00777         NamedDecl *UnderlyingFirstDecl
00778           = FirstDecl? FirstDecl->getUnderlyingDecl() : nullptr;
00779         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
00780             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
00781           UnqualifiedDiag = diag::err_no_template_suggest;
00782           QualifiedDiag = diag::err_no_member_template_suggest;
00783         } else if (UnderlyingFirstDecl && 
00784                    (isa<TypeDecl>(UnderlyingFirstDecl) || 
00785                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
00786                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
00787           UnqualifiedDiag = diag::err_unknown_typename_suggest;
00788           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
00789         }
00790 
00791         if (SS.isEmpty()) {
00792           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
00793         } else {// FIXME: is this even reachable? Test it.
00794           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
00795           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
00796                                   Name->getName().equals(CorrectedStr);
00797           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
00798                                     << Name << computeDeclContext(SS, false)
00799                                     << DroppedSpecifier << SS.getRange());
00800         }
00801 
00802         // Update the name, so that the caller has the new name.
00803         Name = Corrected.getCorrectionAsIdentifierInfo();
00804 
00805         // Typo correction corrected to a keyword.
00806         if (Corrected.isKeyword())
00807           return Name;
00808 
00809         // Also update the LookupResult...
00810         // FIXME: This should probably go away at some point
00811         Result.clear();
00812         Result.setLookupName(Corrected.getCorrection());
00813         if (FirstDecl)
00814           Result.addDecl(FirstDecl);
00815 
00816         // If we found an Objective-C instance variable, let
00817         // LookupInObjCMethod build the appropriate expression to
00818         // reference the ivar.
00819         // FIXME: This is a gross hack.
00820         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
00821           Result.clear();
00822           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
00823           return E;
00824         }
00825         
00826         goto Corrected;
00827       }
00828     }
00829       
00830     // We failed to correct; just fall through and let the parser deal with it.
00831     Result.suppressDiagnostics();
00832     return NameClassification::Unknown();
00833       
00834   case LookupResult::NotFoundInCurrentInstantiation: {
00835     // We performed name lookup into the current instantiation, and there were 
00836     // dependent bases, so we treat this result the same way as any other
00837     // dependent nested-name-specifier.
00838       
00839     // C++ [temp.res]p2:
00840     //   A name used in a template declaration or definition and that is 
00841     //   dependent on a template-parameter is assumed not to name a type 
00842     //   unless the applicable name lookup finds a type name or the name is 
00843     //   qualified by the keyword typename.
00844     //
00845     // FIXME: If the next token is '<', we might want to ask the parser to
00846     // perform some heroics to see if we actually have a 
00847     // template-argument-list, which would indicate a missing 'template'
00848     // keyword here.
00849     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
00850                                       NameInfo, IsAddressOfOperand,
00851                                       /*TemplateArgs=*/nullptr);
00852   }
00853 
00854   case LookupResult::Found:
00855   case LookupResult::FoundOverloaded:
00856   case LookupResult::FoundUnresolvedValue:
00857     break;
00858       
00859   case LookupResult::Ambiguous:
00860     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
00861         hasAnyAcceptableTemplateNames(Result)) {
00862       // C++ [temp.local]p3:
00863       //   A lookup that finds an injected-class-name (10.2) can result in an
00864       //   ambiguity in certain cases (for example, if it is found in more than
00865       //   one base class). If all of the injected-class-names that are found
00866       //   refer to specializations of the same class template, and if the name
00867       //   is followed by a template-argument-list, the reference refers to the
00868       //   class template itself and not a specialization thereof, and is not
00869       //   ambiguous.
00870       //
00871       // This filtering can make an ambiguous result into an unambiguous one,
00872       // so try again after filtering out template names.
00873       FilterAcceptableTemplateNames(Result);
00874       if (!Result.isAmbiguous()) {
00875         IsFilteredTemplateName = true;
00876         break;
00877       }
00878     }
00879       
00880     // Diagnose the ambiguity and return an error.
00881     return NameClassification::Error();
00882   }
00883   
00884   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
00885       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
00886     // C++ [temp.names]p3:
00887     //   After name lookup (3.4) finds that a name is a template-name or that
00888     //   an operator-function-id or a literal- operator-id refers to a set of
00889     //   overloaded functions any member of which is a function template if 
00890     //   this is followed by a <, the < is always taken as the delimiter of a
00891     //   template-argument-list and never as the less-than operator.
00892     if (!IsFilteredTemplateName)
00893       FilterAcceptableTemplateNames(Result);
00894     
00895     if (!Result.empty()) {
00896       bool IsFunctionTemplate;
00897       bool IsVarTemplate;
00898       TemplateName Template;
00899       if (Result.end() - Result.begin() > 1) {
00900         IsFunctionTemplate = true;
00901         Template = Context.getOverloadedTemplateName(Result.begin(), 
00902                                                      Result.end());
00903       } else {
00904         TemplateDecl *TD
00905           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
00906         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
00907         IsVarTemplate = isa<VarTemplateDecl>(TD);
00908 
00909         if (SS.isSet() && !SS.isInvalid())
00910           Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 
00911                                                     /*TemplateKeyword=*/false,
00912                                                       TD);
00913         else
00914           Template = TemplateName(TD);
00915       }
00916       
00917       if (IsFunctionTemplate) {
00918         // Function templates always go through overload resolution, at which
00919         // point we'll perform the various checks (e.g., accessibility) we need
00920         // to based on which function we selected.
00921         Result.suppressDiagnostics();
00922         
00923         return NameClassification::FunctionTemplate(Template);
00924       }
00925 
00926       return IsVarTemplate ? NameClassification::VarTemplate(Template)
00927                            : NameClassification::TypeTemplate(Template);
00928     }
00929   }
00930 
00931   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
00932   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
00933     DiagnoseUseOfDecl(Type, NameLoc);
00934     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
00935     QualType T = Context.getTypeDeclType(Type);
00936     if (SS.isNotEmpty())
00937       return buildNestedType(*this, SS, T, NameLoc);
00938     return ParsedType::make(T);
00939   }
00940 
00941   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
00942   if (!Class) {
00943     // FIXME: It's unfortunate that we don't have a Type node for handling this.
00944     if (ObjCCompatibleAliasDecl *Alias =
00945             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
00946       Class = Alias->getClassInterface();
00947   }
00948   
00949   if (Class) {
00950     DiagnoseUseOfDecl(Class, NameLoc);
00951     
00952     if (NextToken.is(tok::period)) {
00953       // Interface. <something> is parsed as a property reference expression.
00954       // Just return "unknown" as a fall-through for now.
00955       Result.suppressDiagnostics();
00956       return NameClassification::Unknown();
00957     }
00958     
00959     QualType T = Context.getObjCInterfaceType(Class);
00960     return ParsedType::make(T);
00961   }
00962 
00963   // We can have a type template here if we're classifying a template argument.
00964   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
00965     return NameClassification::TypeTemplate(
00966         TemplateName(cast<TemplateDecl>(FirstDecl)));
00967 
00968   // Check for a tag type hidden by a non-type decl in a few cases where it
00969   // seems likely a type is wanted instead of the non-type that was found.
00970   bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
00971   if ((NextToken.is(tok::identifier) ||
00972        (NextIsOp &&
00973         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
00974       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
00975     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
00976     DiagnoseUseOfDecl(Type, NameLoc);
00977     QualType T = Context.getTypeDeclType(Type);
00978     if (SS.isNotEmpty())
00979       return buildNestedType(*this, SS, T, NameLoc);
00980     return ParsedType::make(T);
00981   }
00982   
00983   if (FirstDecl->isCXXClassMember())
00984     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
00985                                            nullptr);
00986 
00987   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
00988   return BuildDeclarationNameExpr(SS, Result, ADL);
00989 }
00990 
00991 // Determines the context to return to after temporarily entering a
00992 // context.  This depends in an unnecessarily complicated way on the
00993 // exact ordering of callbacks from the parser.
00994 DeclContext *Sema::getContainingDC(DeclContext *DC) {
00995 
00996   // Functions defined inline within classes aren't parsed until we've
00997   // finished parsing the top-level class, so the top-level class is
00998   // the context we'll need to return to.
00999   // A Lambda call operator whose parent is a class must not be treated 
01000   // as an inline member function.  A Lambda can be used legally
01001   // either as an in-class member initializer or a default argument.  These
01002   // are parsed once the class has been marked complete and so the containing
01003   // context would be the nested class (when the lambda is defined in one);
01004   // If the class is not complete, then the lambda is being used in an 
01005   // ill-formed fashion (such as to specify the width of a bit-field, or
01006   // in an array-bound) - in which case we still want to return the 
01007   // lexically containing DC (which could be a nested class). 
01008   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
01009     DC = DC->getLexicalParent();
01010 
01011     // A function not defined within a class will always return to its
01012     // lexical context.
01013     if (!isa<CXXRecordDecl>(DC))
01014       return DC;
01015 
01016     // A C++ inline method/friend is parsed *after* the topmost class
01017     // it was declared in is fully parsed ("complete");  the topmost
01018     // class is the context we need to return to.
01019     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
01020       DC = RD;
01021 
01022     // Return the declaration context of the topmost class the inline method is
01023     // declared in.
01024     return DC;
01025   }
01026 
01027   return DC->getLexicalParent();
01028 }
01029 
01030 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
01031   assert(getContainingDC(DC) == CurContext &&
01032       "The next DeclContext should be lexically contained in the current one.");
01033   CurContext = DC;
01034   S->setEntity(DC);
01035 }
01036 
01037 void Sema::PopDeclContext() {
01038   assert(CurContext && "DeclContext imbalance!");
01039 
01040   CurContext = getContainingDC(CurContext);
01041   assert(CurContext && "Popped translation unit!");
01042 }
01043 
01044 /// EnterDeclaratorContext - Used when we must lookup names in the context
01045 /// of a declarator's nested name specifier.
01046 ///
01047 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
01048   // C++0x [basic.lookup.unqual]p13:
01049   //   A name used in the definition of a static data member of class
01050   //   X (after the qualified-id of the static member) is looked up as
01051   //   if the name was used in a member function of X.
01052   // C++0x [basic.lookup.unqual]p14:
01053   //   If a variable member of a namespace is defined outside of the
01054   //   scope of its namespace then any name used in the definition of
01055   //   the variable member (after the declarator-id) is looked up as
01056   //   if the definition of the variable member occurred in its
01057   //   namespace.
01058   // Both of these imply that we should push a scope whose context
01059   // is the semantic context of the declaration.  We can't use
01060   // PushDeclContext here because that context is not necessarily
01061   // lexically contained in the current context.  Fortunately,
01062   // the containing scope should have the appropriate information.
01063 
01064   assert(!S->getEntity() && "scope already has entity");
01065 
01066 #ifndef NDEBUG
01067   Scope *Ancestor = S->getParent();
01068   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
01069   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
01070 #endif
01071 
01072   CurContext = DC;
01073   S->setEntity(DC);
01074 }
01075 
01076 void Sema::ExitDeclaratorContext(Scope *S) {
01077   assert(S->getEntity() == CurContext && "Context imbalance!");
01078 
01079   // Switch back to the lexical context.  The safety of this is
01080   // enforced by an assert in EnterDeclaratorContext.
01081   Scope *Ancestor = S->getParent();
01082   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
01083   CurContext = Ancestor->getEntity();
01084 
01085   // We don't need to do anything with the scope, which is going to
01086   // disappear.
01087 }
01088 
01089 
01090 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
01091   // We assume that the caller has already called
01092   // ActOnReenterTemplateScope so getTemplatedDecl() works.
01093   FunctionDecl *FD = D->getAsFunction();
01094   if (!FD)
01095     return;
01096 
01097   // Same implementation as PushDeclContext, but enters the context
01098   // from the lexical parent, rather than the top-level class.
01099   assert(CurContext == FD->getLexicalParent() &&
01100     "The next DeclContext should be lexically contained in the current one.");
01101   CurContext = FD;
01102   S->setEntity(CurContext);
01103 
01104   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
01105     ParmVarDecl *Param = FD->getParamDecl(P);
01106     // If the parameter has an identifier, then add it to the scope
01107     if (Param->getIdentifier()) {
01108       S->AddDecl(Param);
01109       IdResolver.AddDecl(Param);
01110     }
01111   }
01112 }
01113 
01114 
01115 void Sema::ActOnExitFunctionContext() {
01116   // Same implementation as PopDeclContext, but returns to the lexical parent,
01117   // rather than the top-level class.
01118   assert(CurContext && "DeclContext imbalance!");
01119   CurContext = CurContext->getLexicalParent();
01120   assert(CurContext && "Popped translation unit!");
01121 }
01122 
01123 
01124 /// \brief Determine whether we allow overloading of the function
01125 /// PrevDecl with another declaration.
01126 ///
01127 /// This routine determines whether overloading is possible, not
01128 /// whether some new function is actually an overload. It will return
01129 /// true in C++ (where we can always provide overloads) or, as an
01130 /// extension, in C when the previous function is already an
01131 /// overloaded function declaration or has the "overloadable"
01132 /// attribute.
01133 static bool AllowOverloadingOfFunction(LookupResult &Previous,
01134                                        ASTContext &Context) {
01135   if (Context.getLangOpts().CPlusPlus)
01136     return true;
01137 
01138   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
01139     return true;
01140 
01141   return (Previous.getResultKind() == LookupResult::Found
01142           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
01143 }
01144 
01145 /// Add this decl to the scope shadowed decl chains.
01146 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
01147   // Move up the scope chain until we find the nearest enclosing
01148   // non-transparent context. The declaration will be introduced into this
01149   // scope.
01150   while (S->getEntity() && S->getEntity()->isTransparentContext())
01151     S = S->getParent();
01152 
01153   // Add scoped declarations into their context, so that they can be
01154   // found later. Declarations without a context won't be inserted
01155   // into any context.
01156   if (AddToContext)
01157     CurContext->addDecl(D);
01158 
01159   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
01160   // are function-local declarations.
01161   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
01162       !D->getDeclContext()->getRedeclContext()->Equals(
01163         D->getLexicalDeclContext()->getRedeclContext()) &&
01164       !D->getLexicalDeclContext()->isFunctionOrMethod())
01165     return;
01166 
01167   // Template instantiations should also not be pushed into scope.
01168   if (isa<FunctionDecl>(D) &&
01169       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
01170     return;
01171 
01172   // If this replaces anything in the current scope, 
01173   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
01174                                IEnd = IdResolver.end();
01175   for (; I != IEnd; ++I) {
01176     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
01177       S->RemoveDecl(*I);
01178       IdResolver.RemoveDecl(*I);
01179 
01180       // Should only need to replace one decl.
01181       break;
01182     }
01183   }
01184 
01185   S->AddDecl(D);
01186   
01187   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
01188     // Implicitly-generated labels may end up getting generated in an order that
01189     // isn't strictly lexical, which breaks name lookup. Be careful to insert
01190     // the label at the appropriate place in the identifier chain.
01191     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
01192       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
01193       if (IDC == CurContext) {
01194         if (!S->isDeclScope(*I))
01195           continue;
01196       } else if (IDC->Encloses(CurContext))
01197         break;
01198     }
01199     
01200     IdResolver.InsertDeclAfter(I, D);
01201   } else {
01202     IdResolver.AddDecl(D);
01203   }
01204 }
01205 
01206 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
01207   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
01208     TUScope->AddDecl(D);
01209 }
01210 
01211 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
01212                          bool AllowInlineNamespace) {
01213   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
01214 }
01215 
01216 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
01217   DeclContext *TargetDC = DC->getPrimaryContext();
01218   do {
01219     if (DeclContext *ScopeDC = S->getEntity())
01220       if (ScopeDC->getPrimaryContext() == TargetDC)
01221         return S;
01222   } while ((S = S->getParent()));
01223 
01224   return nullptr;
01225 }
01226 
01227 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
01228                                             DeclContext*,
01229                                             ASTContext&);
01230 
01231 /// Filters out lookup results that don't fall within the given scope
01232 /// as determined by isDeclInScope.
01233 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
01234                                 bool ConsiderLinkage,
01235                                 bool AllowInlineNamespace) {
01236   LookupResult::Filter F = R.makeFilter();
01237   while (F.hasNext()) {
01238     NamedDecl *D = F.next();
01239 
01240     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
01241       continue;
01242 
01243     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
01244       continue;
01245 
01246     F.erase();
01247   }
01248 
01249   F.done();
01250 }
01251 
01252 static bool isUsingDecl(NamedDecl *D) {
01253   return isa<UsingShadowDecl>(D) ||
01254          isa<UnresolvedUsingTypenameDecl>(D) ||
01255          isa<UnresolvedUsingValueDecl>(D);
01256 }
01257 
01258 /// Removes using shadow declarations from the lookup results.
01259 static void RemoveUsingDecls(LookupResult &R) {
01260   LookupResult::Filter F = R.makeFilter();
01261   while (F.hasNext())
01262     if (isUsingDecl(F.next()))
01263       F.erase();
01264 
01265   F.done();
01266 }
01267 
01268 /// \brief Check for this common pattern:
01269 /// @code
01270 /// class S {
01271 ///   S(const S&); // DO NOT IMPLEMENT
01272 ///   void operator=(const S&); // DO NOT IMPLEMENT
01273 /// };
01274 /// @endcode
01275 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
01276   // FIXME: Should check for private access too but access is set after we get
01277   // the decl here.
01278   if (D->doesThisDeclarationHaveABody())
01279     return false;
01280 
01281   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
01282     return CD->isCopyConstructor();
01283   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
01284     return Method->isCopyAssignmentOperator();
01285   return false;
01286 }
01287 
01288 // We need this to handle
01289 //
01290 // typedef struct {
01291 //   void *foo() { return 0; }
01292 // } A;
01293 //
01294 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
01295 // for example. If 'A', foo will have external linkage. If we have '*A',
01296 // foo will have no linkage. Since we can't know until we get to the end
01297 // of the typedef, this function finds out if D might have non-external linkage.
01298 // Callers should verify at the end of the TU if it D has external linkage or
01299 // not.
01300 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
01301   const DeclContext *DC = D->getDeclContext();
01302   while (!DC->isTranslationUnit()) {
01303     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
01304       if (!RD->hasNameForLinkage())
01305         return true;
01306     }
01307     DC = DC->getParent();
01308   }
01309 
01310   return !D->isExternallyVisible();
01311 }
01312 
01313 // FIXME: This needs to be refactored; some other isInMainFile users want
01314 // these semantics.
01315 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
01316   if (S.TUKind != TU_Complete)
01317     return false;
01318   return S.SourceMgr.isInMainFile(Loc);
01319 }
01320 
01321 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
01322   assert(D);
01323 
01324   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
01325     return false;
01326 
01327   // Ignore all entities declared within templates, and out-of-line definitions
01328   // of members of class templates.
01329   if (D->getDeclContext()->isDependentContext() ||
01330       D->getLexicalDeclContext()->isDependentContext())
01331     return false;
01332 
01333   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
01334     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
01335       return false;
01336 
01337     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
01338       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
01339         return false;
01340     } else {
01341       // 'static inline' functions are defined in headers; don't warn.
01342       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
01343         return false;
01344     }
01345 
01346     if (FD->doesThisDeclarationHaveABody() &&
01347         Context.DeclMustBeEmitted(FD))
01348       return false;
01349   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
01350     // Constants and utility variables are defined in headers with internal
01351     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
01352     // like "inline".)
01353     if (!isMainFileLoc(*this, VD->getLocation()))
01354       return false;
01355 
01356     if (Context.DeclMustBeEmitted(VD))
01357       return false;
01358 
01359     if (VD->isStaticDataMember() &&
01360         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
01361       return false;
01362   } else {
01363     return false;
01364   }
01365 
01366   // Only warn for unused decls internal to the translation unit.
01367   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
01368   // for inline functions defined in the main source file, for instance.
01369   return mightHaveNonExternalLinkage(D);
01370 }
01371 
01372 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
01373   if (!D)
01374     return;
01375 
01376   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
01377     const FunctionDecl *First = FD->getFirstDecl();
01378     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
01379       return; // First should already be in the vector.
01380   }
01381 
01382   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
01383     const VarDecl *First = VD->getFirstDecl();
01384     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
01385       return; // First should already be in the vector.
01386   }
01387 
01388   if (ShouldWarnIfUnusedFileScopedDecl(D))
01389     UnusedFileScopedDecls.push_back(D);
01390 }
01391 
01392 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
01393   if (D->isInvalidDecl())
01394     return false;
01395 
01396   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
01397       D->hasAttr<ObjCPreciseLifetimeAttr>())
01398     return false;
01399 
01400   if (isa<LabelDecl>(D))
01401     return true;
01402 
01403   // Except for labels, we only care about unused decls that are local to
01404   // functions.
01405   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
01406   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
01407     // For dependent types, the diagnostic is deferred.
01408     WithinFunction =
01409         WithinFunction || (R->isLocalClass() && !R->isDependentType());
01410   if (!WithinFunction)
01411     return false;
01412 
01413   if (isa<TypedefNameDecl>(D))
01414     return true;
01415   
01416   // White-list anything that isn't a local variable.
01417   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
01418     return false;
01419 
01420   // Types of valid local variables should be complete, so this should succeed.
01421   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
01422 
01423     // White-list anything with an __attribute__((unused)) type.
01424     QualType Ty = VD->getType();
01425 
01426     // Only look at the outermost level of typedef.
01427     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
01428       if (TT->getDecl()->hasAttr<UnusedAttr>())
01429         return false;
01430     }
01431 
01432     // If we failed to complete the type for some reason, or if the type is
01433     // dependent, don't diagnose the variable. 
01434     if (Ty->isIncompleteType() || Ty->isDependentType())
01435       return false;
01436 
01437     if (const TagType *TT = Ty->getAs<TagType>()) {
01438       const TagDecl *Tag = TT->getDecl();
01439       if (Tag->hasAttr<UnusedAttr>())
01440         return false;
01441 
01442       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
01443         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
01444           return false;
01445 
01446         if (const Expr *Init = VD->getInit()) {
01447           if (const ExprWithCleanups *Cleanups =
01448                   dyn_cast<ExprWithCleanups>(Init))
01449             Init = Cleanups->getSubExpr();
01450           const CXXConstructExpr *Construct =
01451             dyn_cast<CXXConstructExpr>(Init);
01452           if (Construct && !Construct->isElidable()) {
01453             CXXConstructorDecl *CD = Construct->getConstructor();
01454             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
01455               return false;
01456           }
01457         }
01458       }
01459     }
01460 
01461     // TODO: __attribute__((unused)) templates?
01462   }
01463   
01464   return true;
01465 }
01466 
01467 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
01468                                      FixItHint &Hint) {
01469   if (isa<LabelDecl>(D)) {
01470     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
01471                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
01472     if (AfterColon.isInvalid())
01473       return;
01474     Hint = FixItHint::CreateRemoval(CharSourceRange::
01475                                     getCharRange(D->getLocStart(), AfterColon));
01476   }
01477   return;
01478 }
01479 
01480 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
01481   if (D->getTypeForDecl()->isDependentType())
01482     return;
01483 
01484   for (auto *TmpD : D->decls()) {
01485     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
01486       DiagnoseUnusedDecl(T);
01487     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
01488       DiagnoseUnusedNestedTypedefs(R);
01489   }
01490 }
01491 
01492 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
01493 /// unless they are marked attr(unused).
01494 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
01495   if (!ShouldDiagnoseUnusedDecl(D))
01496     return;
01497 
01498   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
01499     // typedefs can be referenced later on, so the diagnostics are emitted
01500     // at end-of-translation-unit.
01501     UnusedLocalTypedefNameCandidates.insert(TD);
01502     return;
01503   }
01504   
01505   FixItHint Hint;
01506   GenerateFixForUnusedDecl(D, Context, Hint);
01507 
01508   unsigned DiagID;
01509   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
01510     DiagID = diag::warn_unused_exception_param;
01511   else if (isa<LabelDecl>(D))
01512     DiagID = diag::warn_unused_label;
01513   else
01514     DiagID = diag::warn_unused_variable;
01515 
01516   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
01517 }
01518 
01519 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
01520   // Verify that we have no forward references left.  If so, there was a goto
01521   // or address of a label taken, but no definition of it.  Label fwd
01522   // definitions are indicated with a null substmt which is also not a resolved
01523   // MS inline assembly label name.
01524   bool Diagnose = false;
01525   if (L->isMSAsmLabel())
01526     Diagnose = !L->isResolvedMSAsmLabel();
01527   else
01528     Diagnose = L->getStmt() == nullptr;
01529   if (Diagnose)
01530     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
01531 }
01532 
01533 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
01534   S->mergeNRVOIntoParent();
01535 
01536   if (S->decl_empty()) return;
01537   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
01538          "Scope shouldn't contain decls!");
01539 
01540   for (auto *TmpD : S->decls()) {
01541     assert(TmpD && "This decl didn't get pushed??");
01542 
01543     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
01544     NamedDecl *D = cast<NamedDecl>(TmpD);
01545 
01546     if (!D->getDeclName()) continue;
01547 
01548     // Diagnose unused variables in this scope.
01549     if (!S->hasUnrecoverableErrorOccurred()) {
01550       DiagnoseUnusedDecl(D);
01551       if (const auto *RD = dyn_cast<RecordDecl>(D))
01552         DiagnoseUnusedNestedTypedefs(RD);
01553     }
01554     
01555     // If this was a forward reference to a label, verify it was defined.
01556     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
01557       CheckPoppedLabel(LD, *this);
01558     
01559     // Remove this name from our lexical scope.
01560     IdResolver.RemoveDecl(D);
01561   }
01562 }
01563 
01564 /// \brief Look for an Objective-C class in the translation unit.
01565 ///
01566 /// \param Id The name of the Objective-C class we're looking for. If
01567 /// typo-correction fixes this name, the Id will be updated
01568 /// to the fixed name.
01569 ///
01570 /// \param IdLoc The location of the name in the translation unit.
01571 ///
01572 /// \param DoTypoCorrection If true, this routine will attempt typo correction
01573 /// if there is no class with the given name.
01574 ///
01575 /// \returns The declaration of the named Objective-C class, or NULL if the
01576 /// class could not be found.
01577 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
01578                                               SourceLocation IdLoc,
01579                                               bool DoTypoCorrection) {
01580   // The third "scope" argument is 0 since we aren't enabling lazy built-in
01581   // creation from this context.
01582   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
01583 
01584   if (!IDecl && DoTypoCorrection) {
01585     // Perform typo correction at the given location, but only if we
01586     // find an Objective-C class name.
01587     if (TypoCorrection C = CorrectTypo(
01588             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
01589             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
01590             CTK_ErrorRecovery)) {
01591       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
01592       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
01593       Id = IDecl->getIdentifier();
01594     }
01595   }
01596   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
01597   // This routine must always return a class definition, if any.
01598   if (Def && Def->getDefinition())
01599       Def = Def->getDefinition();
01600   return Def;
01601 }
01602 
01603 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
01604 /// from S, where a non-field would be declared. This routine copes
01605 /// with the difference between C and C++ scoping rules in structs and
01606 /// unions. For example, the following code is well-formed in C but
01607 /// ill-formed in C++:
01608 /// @code
01609 /// struct S6 {
01610 ///   enum { BAR } e;
01611 /// };
01612 ///
01613 /// void test_S6() {
01614 ///   struct S6 a;
01615 ///   a.e = BAR;
01616 /// }
01617 /// @endcode
01618 /// For the declaration of BAR, this routine will return a different
01619 /// scope. The scope S will be the scope of the unnamed enumeration
01620 /// within S6. In C++, this routine will return the scope associated
01621 /// with S6, because the enumeration's scope is a transparent
01622 /// context but structures can contain non-field names. In C, this
01623 /// routine will return the translation unit scope, since the
01624 /// enumeration's scope is a transparent context and structures cannot
01625 /// contain non-field names.
01626 Scope *Sema::getNonFieldDeclScope(Scope *S) {
01627   while (((S->getFlags() & Scope::DeclScope) == 0) ||
01628          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
01629          (S->isClassScope() && !getLangOpts().CPlusPlus))
01630     S = S->getParent();
01631   return S;
01632 }
01633 
01634 /// \brief Looks up the declaration of "struct objc_super" and
01635 /// saves it for later use in building builtin declaration of
01636 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
01637 /// pre-existing declaration exists no action takes place.
01638 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
01639                                         IdentifierInfo *II) {
01640   if (!II->isStr("objc_msgSendSuper"))
01641     return;
01642   ASTContext &Context = ThisSema.Context;
01643     
01644   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
01645                       SourceLocation(), Sema::LookupTagName);
01646   ThisSema.LookupName(Result, S);
01647   if (Result.getResultKind() == LookupResult::Found)
01648     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
01649       Context.setObjCSuperType(Context.getTagDeclType(TD));
01650 }
01651 
01652 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
01653   switch (Error) {
01654   case ASTContext::GE_None:
01655     return "";
01656   case ASTContext::GE_Missing_stdio:
01657     return "stdio.h";
01658   case ASTContext::GE_Missing_setjmp:
01659     return "setjmp.h";
01660   case ASTContext::GE_Missing_ucontext:
01661     return "ucontext.h";
01662   }
01663   llvm_unreachable("unhandled error kind");
01664 }
01665 
01666 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
01667 /// file scope.  lazily create a decl for it. ForRedeclaration is true
01668 /// if we're creating this built-in in anticipation of redeclaring the
01669 /// built-in.
01670 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
01671                                      Scope *S, bool ForRedeclaration,
01672                                      SourceLocation Loc) {
01673   LookupPredefedObjCSuperType(*this, S, II);
01674 
01675   ASTContext::GetBuiltinTypeError Error;
01676   QualType R = Context.GetBuiltinType(ID, Error);
01677   if (Error) {
01678     if (ForRedeclaration)
01679       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
01680           << getHeaderName(Error)
01681           << Context.BuiltinInfo.GetName(ID);
01682     return nullptr;
01683   }
01684 
01685   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
01686     Diag(Loc, diag::ext_implicit_lib_function_decl)
01687       << Context.BuiltinInfo.GetName(ID)
01688       << R;
01689     if (Context.BuiltinInfo.getHeaderName(ID) &&
01690         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
01691       Diag(Loc, diag::note_include_header_or_declare)
01692           << Context.BuiltinInfo.getHeaderName(ID)
01693           << Context.BuiltinInfo.GetName(ID);
01694   }
01695 
01696   DeclContext *Parent = Context.getTranslationUnitDecl();
01697   if (getLangOpts().CPlusPlus) {
01698     LinkageSpecDecl *CLinkageDecl =
01699         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
01700                                 LinkageSpecDecl::lang_c, false);
01701     CLinkageDecl->setImplicit();
01702     Parent->addDecl(CLinkageDecl);
01703     Parent = CLinkageDecl;
01704   }
01705 
01706   FunctionDecl *New = FunctionDecl::Create(Context,
01707                                            Parent,
01708                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
01709                                            SC_Extern,
01710                                            false,
01711                                            /*hasPrototype=*/true);
01712   New->setImplicit();
01713 
01714   // Create Decl objects for each parameter, adding them to the
01715   // FunctionDecl.
01716   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
01717     SmallVector<ParmVarDecl*, 16> Params;
01718     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
01719       ParmVarDecl *parm =
01720           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
01721                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
01722                               SC_None, nullptr);
01723       parm->setScopeInfo(0, i);
01724       Params.push_back(parm);
01725     }
01726     New->setParams(Params);
01727   }
01728 
01729   AddKnownFunctionAttributes(New);
01730   RegisterLocallyScopedExternCDecl(New, S);
01731 
01732   // TUScope is the translation-unit scope to insert this function into.
01733   // FIXME: This is hideous. We need to teach PushOnScopeChains to
01734   // relate Scopes to DeclContexts, and probably eliminate CurContext
01735   // entirely, but we're not there yet.
01736   DeclContext *SavedContext = CurContext;
01737   CurContext = Parent;
01738   PushOnScopeChains(New, TUScope);
01739   CurContext = SavedContext;
01740   return New;
01741 }
01742 
01743 /// \brief Filter out any previous declarations that the given declaration
01744 /// should not consider because they are not permitted to conflict, e.g.,
01745 /// because they come from hidden sub-modules and do not refer to the same
01746 /// entity.
01747 static void filterNonConflictingPreviousDecls(ASTContext &context,
01748                                               NamedDecl *decl,
01749                                               LookupResult &previous){
01750   // This is only interesting when modules are enabled.
01751   if (!context.getLangOpts().Modules)
01752     return;
01753 
01754   // Empty sets are uninteresting.
01755   if (previous.empty())
01756     return;
01757 
01758   LookupResult::Filter filter = previous.makeFilter();
01759   while (filter.hasNext()) {
01760     NamedDecl *old = filter.next();
01761 
01762     // Non-hidden declarations are never ignored.
01763     if (!old->isHidden())
01764       continue;
01765 
01766     if (!old->isExternallyVisible())
01767       filter.erase();
01768   }
01769 
01770   filter.done();
01771 }
01772 
01773 /// Typedef declarations don't have linkage, but they still denote the same
01774 /// entity if their types are the same.
01775 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
01776 /// isSameEntity.
01777 static void filterNonConflictingPreviousTypedefDecls(ASTContext &Context,
01778                                                      TypedefNameDecl *Decl,
01779                                                      LookupResult &Previous) {
01780   // This is only interesting when modules are enabled.
01781   if (!Context.getLangOpts().Modules)
01782     return;
01783 
01784   // Empty sets are uninteresting.
01785   if (Previous.empty())
01786     return;
01787 
01788   LookupResult::Filter Filter = Previous.makeFilter();
01789   while (Filter.hasNext()) {
01790     NamedDecl *Old = Filter.next();
01791 
01792     // Non-hidden declarations are never ignored.
01793     if (!Old->isHidden())
01794       continue;
01795 
01796     // Declarations of the same entity are not ignored, even if they have
01797     // different linkages.
01798     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old))
01799       if (Context.hasSameType(OldTD->getUnderlyingType(),
01800                               Decl->getUnderlyingType()))
01801         continue;
01802 
01803     if (!Old->isExternallyVisible())
01804       Filter.erase();
01805   }
01806 
01807   Filter.done();
01808 }
01809 
01810 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
01811   QualType OldType;
01812   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
01813     OldType = OldTypedef->getUnderlyingType();
01814   else
01815     OldType = Context.getTypeDeclType(Old);
01816   QualType NewType = New->getUnderlyingType();
01817 
01818   if (NewType->isVariablyModifiedType()) {
01819     // Must not redefine a typedef with a variably-modified type.
01820     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
01821     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
01822       << Kind << NewType;
01823     if (Old->getLocation().isValid())
01824       Diag(Old->getLocation(), diag::note_previous_definition);
01825     New->setInvalidDecl();
01826     return true;    
01827   }
01828   
01829   if (OldType != NewType &&
01830       !OldType->isDependentType() &&
01831       !NewType->isDependentType() &&
01832       !Context.hasSameType(OldType, NewType)) { 
01833     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
01834     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
01835       << Kind << NewType << OldType;
01836     if (Old->getLocation().isValid())
01837       Diag(Old->getLocation(), diag::note_previous_definition);
01838     New->setInvalidDecl();
01839     return true;
01840   }
01841   return false;
01842 }
01843 
01844 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
01845 /// same name and scope as a previous declaration 'Old'.  Figure out
01846 /// how to resolve this situation, merging decls or emitting
01847 /// diagnostics as appropriate. If there was an error, set New to be invalid.
01848 ///
01849 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
01850   // If the new decl is known invalid already, don't bother doing any
01851   // merging checks.
01852   if (New->isInvalidDecl()) return;
01853 
01854   // Allow multiple definitions for ObjC built-in typedefs.
01855   // FIXME: Verify the underlying types are equivalent!
01856   if (getLangOpts().ObjC1) {
01857     const IdentifierInfo *TypeID = New->getIdentifier();
01858     switch (TypeID->getLength()) {
01859     default: break;
01860     case 2:
01861       {
01862         if (!TypeID->isStr("id"))
01863           break;
01864         QualType T = New->getUnderlyingType();
01865         if (!T->isPointerType())
01866           break;
01867         if (!T->isVoidPointerType()) {
01868           QualType PT = T->getAs<PointerType>()->getPointeeType();
01869           if (!PT->isStructureType())
01870             break;
01871         }
01872         Context.setObjCIdRedefinitionType(T);
01873         // Install the built-in type for 'id', ignoring the current definition.
01874         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
01875         return;
01876       }
01877     case 5:
01878       if (!TypeID->isStr("Class"))
01879         break;
01880       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
01881       // Install the built-in type for 'Class', ignoring the current definition.
01882       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
01883       return;
01884     case 3:
01885       if (!TypeID->isStr("SEL"))
01886         break;
01887       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
01888       // Install the built-in type for 'SEL', ignoring the current definition.
01889       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
01890       return;
01891     }
01892     // Fall through - the typedef name was not a builtin type.
01893   }
01894 
01895   // Verify the old decl was also a type.
01896   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
01897   if (!Old) {
01898     Diag(New->getLocation(), diag::err_redefinition_different_kind)
01899       << New->getDeclName();
01900 
01901     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
01902     if (OldD->getLocation().isValid())
01903       Diag(OldD->getLocation(), diag::note_previous_definition);
01904 
01905     return New->setInvalidDecl();
01906   }
01907 
01908   // If the old declaration is invalid, just give up here.
01909   if (Old->isInvalidDecl())
01910     return New->setInvalidDecl();
01911 
01912   // If the typedef types are not identical, reject them in all languages and
01913   // with any extensions enabled.
01914   if (isIncompatibleTypedef(Old, New))
01915     return;
01916 
01917   // The types match.  Link up the redeclaration chain and merge attributes if
01918   // the old declaration was a typedef.
01919   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
01920     New->setPreviousDecl(Typedef);
01921     mergeDeclAttributes(New, Old);
01922   }
01923 
01924   if (getLangOpts().MicrosoftExt)
01925     return;
01926 
01927   if (getLangOpts().CPlusPlus) {
01928     // C++ [dcl.typedef]p2:
01929     //   In a given non-class scope, a typedef specifier can be used to
01930     //   redefine the name of any type declared in that scope to refer
01931     //   to the type to which it already refers.
01932     if (!isa<CXXRecordDecl>(CurContext))
01933       return;
01934 
01935     // C++0x [dcl.typedef]p4:
01936     //   In a given class scope, a typedef specifier can be used to redefine 
01937     //   any class-name declared in that scope that is not also a typedef-name
01938     //   to refer to the type to which it already refers.
01939     //
01940     // This wording came in via DR424, which was a correction to the
01941     // wording in DR56, which accidentally banned code like:
01942     //
01943     //   struct S {
01944     //     typedef struct A { } A;
01945     //   };
01946     //
01947     // in the C++03 standard. We implement the C++0x semantics, which
01948     // allow the above but disallow
01949     //
01950     //   struct S {
01951     //     typedef int I;
01952     //     typedef int I;
01953     //   };
01954     //
01955     // since that was the intent of DR56.
01956     if (!isa<TypedefNameDecl>(Old))
01957       return;
01958 
01959     Diag(New->getLocation(), diag::err_redefinition)
01960       << New->getDeclName();
01961     Diag(Old->getLocation(), diag::note_previous_definition);
01962     return New->setInvalidDecl();
01963   }
01964 
01965   // Modules always permit redefinition of typedefs, as does C11.
01966   if (getLangOpts().Modules || getLangOpts().C11)
01967     return;
01968   
01969   // If we have a redefinition of a typedef in C, emit a warning.  This warning
01970   // is normally mapped to an error, but can be controlled with
01971   // -Wtypedef-redefinition.  If either the original or the redefinition is
01972   // in a system header, don't emit this for compatibility with GCC.
01973   if (getDiagnostics().getSuppressSystemWarnings() &&
01974       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
01975        Context.getSourceManager().isInSystemHeader(New->getLocation())))
01976     return;
01977 
01978   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
01979     << New->getDeclName();
01980   Diag(Old->getLocation(), diag::note_previous_definition);
01981   return;
01982 }
01983 
01984 /// DeclhasAttr - returns true if decl Declaration already has the target
01985 /// attribute.
01986 static bool DeclHasAttr(const Decl *D, const Attr *A) {
01987   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
01988   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
01989   for (const auto *i : D->attrs())
01990     if (i->getKind() == A->getKind()) {
01991       if (Ann) {
01992         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
01993           return true;
01994         continue;
01995       }
01996       // FIXME: Don't hardcode this check
01997       if (OA && isa<OwnershipAttr>(i))
01998         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
01999       return true;
02000     }
02001 
02002   return false;
02003 }
02004 
02005 static bool isAttributeTargetADefinition(Decl *D) {
02006   if (VarDecl *VD = dyn_cast<VarDecl>(D))
02007     return VD->isThisDeclarationADefinition();
02008   if (TagDecl *TD = dyn_cast<TagDecl>(D))
02009     return TD->isCompleteDefinition() || TD->isBeingDefined();
02010   return true;
02011 }
02012 
02013 /// Merge alignment attributes from \p Old to \p New, taking into account the
02014 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
02015 ///
02016 /// \return \c true if any attributes were added to \p New.
02017 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
02018   // Look for alignas attributes on Old, and pick out whichever attribute
02019   // specifies the strictest alignment requirement.
02020   AlignedAttr *OldAlignasAttr = nullptr;
02021   AlignedAttr *OldStrictestAlignAttr = nullptr;
02022   unsigned OldAlign = 0;
02023   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
02024     // FIXME: We have no way of representing inherited dependent alignments
02025     // in a case like:
02026     //   template<int A, int B> struct alignas(A) X;
02027     //   template<int A, int B> struct alignas(B) X {};
02028     // For now, we just ignore any alignas attributes which are not on the
02029     // definition in such a case.
02030     if (I->isAlignmentDependent())
02031       return false;
02032 
02033     if (I->isAlignas())
02034       OldAlignasAttr = I;
02035 
02036     unsigned Align = I->getAlignment(S.Context);
02037     if (Align > OldAlign) {
02038       OldAlign = Align;
02039       OldStrictestAlignAttr = I;
02040     }
02041   }
02042 
02043   // Look for alignas attributes on New.
02044   AlignedAttr *NewAlignasAttr = nullptr;
02045   unsigned NewAlign = 0;
02046   for (auto *I : New->specific_attrs<AlignedAttr>()) {
02047     if (I->isAlignmentDependent())
02048       return false;
02049 
02050     if (I->isAlignas())
02051       NewAlignasAttr = I;
02052 
02053     unsigned Align = I->getAlignment(S.Context);
02054     if (Align > NewAlign)
02055       NewAlign = Align;
02056   }
02057 
02058   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
02059     // Both declarations have 'alignas' attributes. We require them to match.
02060     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
02061     // fall short. (If two declarations both have alignas, they must both match
02062     // every definition, and so must match each other if there is a definition.)
02063 
02064     // If either declaration only contains 'alignas(0)' specifiers, then it
02065     // specifies the natural alignment for the type.
02066     if (OldAlign == 0 || NewAlign == 0) {
02067       QualType Ty;
02068       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
02069         Ty = VD->getType();
02070       else
02071         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
02072 
02073       if (OldAlign == 0)
02074         OldAlign = S.Context.getTypeAlign(Ty);
02075       if (NewAlign == 0)
02076         NewAlign = S.Context.getTypeAlign(Ty);
02077     }
02078 
02079     if (OldAlign != NewAlign) {
02080       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
02081         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
02082         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
02083       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
02084     }
02085   }
02086 
02087   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
02088     // C++11 [dcl.align]p6:
02089     //   if any declaration of an entity has an alignment-specifier,
02090     //   every defining declaration of that entity shall specify an
02091     //   equivalent alignment.
02092     // C11 6.7.5/7:
02093     //   If the definition of an object does not have an alignment
02094     //   specifier, any other declaration of that object shall also
02095     //   have no alignment specifier.
02096     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
02097       << OldAlignasAttr;
02098     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
02099       << OldAlignasAttr;
02100   }
02101 
02102   bool AnyAdded = false;
02103 
02104   // Ensure we have an attribute representing the strictest alignment.
02105   if (OldAlign > NewAlign) {
02106     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
02107     Clone->setInherited(true);
02108     New->addAttr(Clone);
02109     AnyAdded = true;
02110   }
02111 
02112   // Ensure we have an alignas attribute if the old declaration had one.
02113   if (OldAlignasAttr && !NewAlignasAttr &&
02114       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
02115     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
02116     Clone->setInherited(true);
02117     New->addAttr(Clone);
02118     AnyAdded = true;
02119   }
02120 
02121   return AnyAdded;
02122 }
02123 
02124 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
02125                                const InheritableAttr *Attr, bool Override) {
02126   InheritableAttr *NewAttr = nullptr;
02127   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
02128   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
02129     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
02130                                       AA->getIntroduced(), AA->getDeprecated(),
02131                                       AA->getObsoleted(), AA->getUnavailable(),
02132                                       AA->getMessage(), Override,
02133                                       AttrSpellingListIndex);
02134   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
02135     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
02136                                     AttrSpellingListIndex);
02137   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
02138     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
02139                                         AttrSpellingListIndex);
02140   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
02141     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
02142                                    AttrSpellingListIndex);
02143   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
02144     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
02145                                    AttrSpellingListIndex);
02146   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
02147     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
02148                                 FA->getFormatIdx(), FA->getFirstArg(),
02149                                 AttrSpellingListIndex);
02150   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
02151     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
02152                                  AttrSpellingListIndex);
02153   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
02154     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
02155                                        AttrSpellingListIndex,
02156                                        IA->getSemanticSpelling());
02157   else if (isa<AlignedAttr>(Attr))
02158     // AlignedAttrs are handled separately, because we need to handle all
02159     // such attributes on a declaration at the same time.
02160     NewAttr = nullptr;
02161   else if (isa<DeprecatedAttr>(Attr) && Override)
02162     NewAttr = nullptr;
02163   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
02164     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
02165 
02166   if (NewAttr) {
02167     NewAttr->setInherited(true);
02168     D->addAttr(NewAttr);
02169     return true;
02170   }
02171 
02172   return false;
02173 }
02174 
02175 static const Decl *getDefinition(const Decl *D) {
02176   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
02177     return TD->getDefinition();
02178   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
02179     const VarDecl *Def = VD->getDefinition();
02180     if (Def)
02181       return Def;
02182     return VD->getActingDefinition();
02183   }
02184   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
02185     const FunctionDecl* Def;
02186     if (FD->isDefined(Def))
02187       return Def;
02188   }
02189   return nullptr;
02190 }
02191 
02192 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
02193   for (const auto *Attribute : D->attrs())
02194     if (Attribute->getKind() == Kind)
02195       return true;
02196   return false;
02197 }
02198 
02199 /// checkNewAttributesAfterDef - If we already have a definition, check that
02200 /// there are no new attributes in this declaration.
02201 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
02202   if (!New->hasAttrs())
02203     return;
02204 
02205   const Decl *Def = getDefinition(Old);
02206   if (!Def || Def == New)
02207     return;
02208 
02209   AttrVec &NewAttributes = New->getAttrs();
02210   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
02211     const Attr *NewAttribute = NewAttributes[I];
02212 
02213     if (isa<AliasAttr>(NewAttribute)) {
02214       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
02215         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
02216       else {
02217         VarDecl *VD = cast<VarDecl>(New);
02218         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
02219                                 VarDecl::TentativeDefinition
02220                             ? diag::err_alias_after_tentative
02221                             : diag::err_redefinition;
02222         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
02223         S.Diag(Def->getLocation(), diag::note_previous_definition);
02224         VD->setInvalidDecl();
02225       }
02226       ++I;
02227       continue;
02228     }
02229 
02230     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
02231       // Tentative definitions are only interesting for the alias check above.
02232       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
02233         ++I;
02234         continue;
02235       }
02236     }
02237 
02238     if (hasAttribute(Def, NewAttribute->getKind())) {
02239       ++I;
02240       continue; // regular attr merging will take care of validating this.
02241     }
02242 
02243     if (isa<C11NoReturnAttr>(NewAttribute)) {
02244       // C's _Noreturn is allowed to be added to a function after it is defined.
02245       ++I;
02246       continue;
02247     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
02248       if (AA->isAlignas()) { 
02249         // C++11 [dcl.align]p6:
02250         //   if any declaration of an entity has an alignment-specifier,
02251         //   every defining declaration of that entity shall specify an
02252         //   equivalent alignment.
02253         // C11 6.7.5/7:
02254         //   If the definition of an object does not have an alignment
02255         //   specifier, any other declaration of that object shall also
02256         //   have no alignment specifier.
02257         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
02258           << AA;
02259         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
02260           << AA;
02261         NewAttributes.erase(NewAttributes.begin() + I);
02262         --E;
02263         continue;
02264       }
02265     }
02266 
02267     S.Diag(NewAttribute->getLocation(),
02268            diag::warn_attribute_precede_definition);
02269     S.Diag(Def->getLocation(), diag::note_previous_definition);
02270     NewAttributes.erase(NewAttributes.begin() + I);
02271     --E;
02272   }
02273 }
02274 
02275 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
02276 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
02277                                AvailabilityMergeKind AMK) {
02278   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
02279     UsedAttr *NewAttr = OldAttr->clone(Context);
02280     NewAttr->setInherited(true);
02281     New->addAttr(NewAttr);
02282   }
02283 
02284   if (!Old->hasAttrs() && !New->hasAttrs())
02285     return;
02286 
02287   // attributes declared post-definition are currently ignored
02288   checkNewAttributesAfterDef(*this, New, Old);
02289 
02290   if (!Old->hasAttrs())
02291     return;
02292 
02293   bool foundAny = New->hasAttrs();
02294 
02295   // Ensure that any moving of objects within the allocated map is done before
02296   // we process them.
02297   if (!foundAny) New->setAttrs(AttrVec());
02298 
02299   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
02300     bool Override = false;
02301     // Ignore deprecated/unavailable/availability attributes if requested.
02302     if (isa<DeprecatedAttr>(I) ||
02303         isa<UnavailableAttr>(I) ||
02304         isa<AvailabilityAttr>(I)) {
02305       switch (AMK) {
02306       case AMK_None:
02307         continue;
02308 
02309       case AMK_Redeclaration:
02310         break;
02311 
02312       case AMK_Override:
02313         Override = true;
02314         break;
02315       }
02316     }
02317 
02318     // Already handled.
02319     if (isa<UsedAttr>(I))
02320       continue;
02321 
02322     if (mergeDeclAttribute(*this, New, I, Override))
02323       foundAny = true;
02324   }
02325 
02326   if (mergeAlignedAttrs(*this, New, Old))
02327     foundAny = true;
02328 
02329   if (!foundAny) New->dropAttrs();
02330 }
02331 
02332 /// mergeParamDeclAttributes - Copy attributes from the old parameter
02333 /// to the new one.
02334 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
02335                                      const ParmVarDecl *oldDecl,
02336                                      Sema &S) {
02337   // C++11 [dcl.attr.depend]p2:
02338   //   The first declaration of a function shall specify the
02339   //   carries_dependency attribute for its declarator-id if any declaration
02340   //   of the function specifies the carries_dependency attribute.
02341   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
02342   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
02343     S.Diag(CDA->getLocation(),
02344            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
02345     // Find the first declaration of the parameter.
02346     // FIXME: Should we build redeclaration chains for function parameters?
02347     const FunctionDecl *FirstFD =
02348       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
02349     const ParmVarDecl *FirstVD =
02350       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
02351     S.Diag(FirstVD->getLocation(),
02352            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
02353   }
02354 
02355   if (!oldDecl->hasAttrs())
02356     return;
02357 
02358   bool foundAny = newDecl->hasAttrs();
02359 
02360   // Ensure that any moving of objects within the allocated map is
02361   // done before we process them.
02362   if (!foundAny) newDecl->setAttrs(AttrVec());
02363 
02364   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
02365     if (!DeclHasAttr(newDecl, I)) {
02366       InheritableAttr *newAttr =
02367         cast<InheritableParamAttr>(I->clone(S.Context));
02368       newAttr->setInherited(true);
02369       newDecl->addAttr(newAttr);
02370       foundAny = true;
02371     }
02372   }
02373 
02374   if (!foundAny) newDecl->dropAttrs();
02375 }
02376 
02377 namespace {
02378 
02379 /// Used in MergeFunctionDecl to keep track of function parameters in
02380 /// C.
02381 struct GNUCompatibleParamWarning {
02382   ParmVarDecl *OldParm;
02383   ParmVarDecl *NewParm;
02384   QualType PromotedType;
02385 };
02386 
02387 }
02388 
02389 /// getSpecialMember - get the special member enum for a method.
02390 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
02391   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
02392     if (Ctor->isDefaultConstructor())
02393       return Sema::CXXDefaultConstructor;
02394 
02395     if (Ctor->isCopyConstructor())
02396       return Sema::CXXCopyConstructor;
02397 
02398     if (Ctor->isMoveConstructor())
02399       return Sema::CXXMoveConstructor;
02400   } else if (isa<CXXDestructorDecl>(MD)) {
02401     return Sema::CXXDestructor;
02402   } else if (MD->isCopyAssignmentOperator()) {
02403     return Sema::CXXCopyAssignment;
02404   } else if (MD->isMoveAssignmentOperator()) {
02405     return Sema::CXXMoveAssignment;
02406   }
02407 
02408   return Sema::CXXInvalid;
02409 }
02410 
02411 // Determine whether the previous declaration was a definition, implicit
02412 // declaration, or a declaration.
02413 template <typename T>
02414 static std::pair<diag::kind, SourceLocation>
02415 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
02416   diag::kind PrevDiag;
02417   SourceLocation OldLocation = Old->getLocation();
02418   if (Old->isThisDeclarationADefinition())
02419     PrevDiag = diag::note_previous_definition;
02420   else if (Old->isImplicit()) {
02421     PrevDiag = diag::note_previous_implicit_declaration;
02422     if (OldLocation.isInvalid())
02423       OldLocation = New->getLocation();
02424   } else
02425     PrevDiag = diag::note_previous_declaration;
02426   return std::make_pair(PrevDiag, OldLocation);
02427 }
02428 
02429 /// canRedefineFunction - checks if a function can be redefined. Currently,
02430 /// only extern inline functions can be redefined, and even then only in
02431 /// GNU89 mode.
02432 static bool canRedefineFunction(const FunctionDecl *FD,
02433                                 const LangOptions& LangOpts) {
02434   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
02435           !LangOpts.CPlusPlus &&
02436           FD->isInlineSpecified() &&
02437           FD->getStorageClass() == SC_Extern);
02438 }
02439 
02440 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
02441   const AttributedType *AT = T->getAs<AttributedType>();
02442   while (AT && !AT->isCallingConv())
02443     AT = AT->getModifiedType()->getAs<AttributedType>();
02444   return AT;
02445 }
02446 
02447 template <typename T>
02448 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
02449   const DeclContext *DC = Old->getDeclContext();
02450   if (DC->isRecord())
02451     return false;
02452 
02453   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
02454   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
02455     return true;
02456   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
02457     return true;
02458   return false;
02459 }
02460 
02461 /// MergeFunctionDecl - We just parsed a function 'New' from
02462 /// declarator D which has the same name and scope as a previous
02463 /// declaration 'Old'.  Figure out how to resolve this situation,
02464 /// merging decls or emitting diagnostics as appropriate.
02465 ///
02466 /// In C++, New and Old must be declarations that are not
02467 /// overloaded. Use IsOverload to determine whether New and Old are
02468 /// overloaded, and to select the Old declaration that New should be
02469 /// merged with.
02470 ///
02471 /// Returns true if there was an error, false otherwise.
02472 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
02473                              Scope *S, bool MergeTypeWithOld) {
02474   // Verify the old decl was also a function.
02475   FunctionDecl *Old = OldD->getAsFunction();
02476   if (!Old) {
02477     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
02478       if (New->getFriendObjectKind()) {
02479         Diag(New->getLocation(), diag::err_using_decl_friend);
02480         Diag(Shadow->getTargetDecl()->getLocation(),
02481              diag::note_using_decl_target);
02482         Diag(Shadow->getUsingDecl()->getLocation(),
02483              diag::note_using_decl) << 0;
02484         return true;
02485       }
02486 
02487       // C++11 [namespace.udecl]p14:
02488       //   If a function declaration in namespace scope or block scope has the
02489       //   same name and the same parameter-type-list as a function introduced
02490       //   by a using-declaration, and the declarations do not declare the same
02491       //   function, the program is ill-formed.
02492 
02493       // Check whether the two declarations might declare the same function.
02494       Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl());
02495       if (Old &&
02496           !Old->getDeclContext()->getRedeclContext()->Equals(
02497               New->getDeclContext()->getRedeclContext()) &&
02498           !(Old->isExternC() && New->isExternC()))
02499         Old = nullptr;
02500 
02501       if (!Old) {
02502         Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
02503         Diag(Shadow->getTargetDecl()->getLocation(),
02504              diag::note_using_decl_target);
02505         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
02506         return true;
02507       }
02508       OldD = Old;
02509     } else {
02510       Diag(New->getLocation(), diag::err_redefinition_different_kind)
02511         << New->getDeclName();
02512       Diag(OldD->getLocation(), diag::note_previous_definition);
02513       return true;
02514     }
02515   }
02516 
02517   // If the old declaration is invalid, just give up here.
02518   if (Old->isInvalidDecl())
02519     return true;
02520 
02521   diag::kind PrevDiag;
02522   SourceLocation OldLocation;
02523   std::tie(PrevDiag, OldLocation) =
02524       getNoteDiagForInvalidRedeclaration(Old, New);
02525 
02526   // Don't complain about this if we're in GNU89 mode and the old function
02527   // is an extern inline function.
02528   // Don't complain about specializations. They are not supposed to have
02529   // storage classes.
02530   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
02531       New->getStorageClass() == SC_Static &&
02532       Old->hasExternalFormalLinkage() &&
02533       !New->getTemplateSpecializationInfo() &&
02534       !canRedefineFunction(Old, getLangOpts())) {
02535     if (getLangOpts().MicrosoftExt) {
02536       Diag(New->getLocation(), diag::ext_static_non_static) << New;
02537       Diag(OldLocation, PrevDiag);
02538     } else {
02539       Diag(New->getLocation(), diag::err_static_non_static) << New;
02540       Diag(OldLocation, PrevDiag);
02541       return true;
02542     }
02543   }
02544 
02545 
02546   // If a function is first declared with a calling convention, but is later
02547   // declared or defined without one, all following decls assume the calling
02548   // convention of the first.
02549   //
02550   // It's OK if a function is first declared without a calling convention,
02551   // but is later declared or defined with the default calling convention.
02552   //
02553   // To test if either decl has an explicit calling convention, we look for
02554   // AttributedType sugar nodes on the type as written.  If they are missing or
02555   // were canonicalized away, we assume the calling convention was implicit.
02556   //
02557   // Note also that we DO NOT return at this point, because we still have
02558   // other tests to run.
02559   QualType OldQType = Context.getCanonicalType(Old->getType());
02560   QualType NewQType = Context.getCanonicalType(New->getType());
02561   const FunctionType *OldType = cast<FunctionType>(OldQType);
02562   const FunctionType *NewType = cast<FunctionType>(NewQType);
02563   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
02564   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
02565   bool RequiresAdjustment = false;
02566 
02567   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
02568     FunctionDecl *First = Old->getFirstDecl();
02569     const FunctionType *FT =
02570         First->getType().getCanonicalType()->castAs<FunctionType>();
02571     FunctionType::ExtInfo FI = FT->getExtInfo();
02572     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
02573     if (!NewCCExplicit) {
02574       // Inherit the CC from the previous declaration if it was specified
02575       // there but not here.
02576       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
02577       RequiresAdjustment = true;
02578     } else {
02579       // Calling conventions aren't compatible, so complain.
02580       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
02581       Diag(New->getLocation(), diag::err_cconv_change)
02582         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
02583         << !FirstCCExplicit
02584         << (!FirstCCExplicit ? "" :
02585             FunctionType::getNameForCallConv(FI.getCC()));
02586 
02587       // Put the note on the first decl, since it is the one that matters.
02588       Diag(First->getLocation(), diag::note_previous_declaration);
02589       return true;
02590     }
02591   }
02592 
02593   // FIXME: diagnose the other way around?
02594   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
02595     NewTypeInfo = NewTypeInfo.withNoReturn(true);
02596     RequiresAdjustment = true;
02597   }
02598 
02599   // Merge regparm attribute.
02600   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
02601       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
02602     if (NewTypeInfo.getHasRegParm()) {
02603       Diag(New->getLocation(), diag::err_regparm_mismatch)
02604         << NewType->getRegParmType()
02605         << OldType->getRegParmType();
02606       Diag(OldLocation, diag::note_previous_declaration);
02607       return true;
02608     }
02609 
02610     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
02611     RequiresAdjustment = true;
02612   }
02613 
02614   // Merge ns_returns_retained attribute.
02615   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
02616     if (NewTypeInfo.getProducesResult()) {
02617       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
02618       Diag(OldLocation, diag::note_previous_declaration);
02619       return true;
02620     }
02621     
02622     NewTypeInfo = NewTypeInfo.withProducesResult(true);
02623     RequiresAdjustment = true;
02624   }
02625   
02626   if (RequiresAdjustment) {
02627     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
02628     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
02629     New->setType(QualType(AdjustedType, 0));
02630     NewQType = Context.getCanonicalType(New->getType());
02631     NewType = cast<FunctionType>(NewQType);
02632   }
02633 
02634   // If this redeclaration makes the function inline, we may need to add it to
02635   // UndefinedButUsed.
02636   if (!Old->isInlined() && New->isInlined() &&
02637       !New->hasAttr<GNUInlineAttr>() &&
02638       (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
02639       Old->isUsed(false) &&
02640       !Old->isDefined() && !New->isThisDeclarationADefinition())
02641     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
02642                                            SourceLocation()));
02643 
02644   // If this redeclaration makes it newly gnu_inline, we don't want to warn
02645   // about it.
02646   if (New->hasAttr<GNUInlineAttr>() &&
02647       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
02648     UndefinedButUsed.erase(Old->getCanonicalDecl());
02649   }
02650   
02651   if (getLangOpts().CPlusPlus) {
02652     // (C++98 13.1p2):
02653     //   Certain function declarations cannot be overloaded:
02654     //     -- Function declarations that differ only in the return type
02655     //        cannot be overloaded.
02656 
02657     // Go back to the type source info to compare the declared return types,
02658     // per C++1y [dcl.type.auto]p13:
02659     //   Redeclarations or specializations of a function or function template
02660     //   with a declared return type that uses a placeholder type shall also
02661     //   use that placeholder, not a deduced type.
02662     QualType OldDeclaredReturnType =
02663         (Old->getTypeSourceInfo()
02664              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
02665              : OldType)->getReturnType();
02666     QualType NewDeclaredReturnType =
02667         (New->getTypeSourceInfo()
02668              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
02669              : NewType)->getReturnType();
02670     QualType ResQT;
02671     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
02672         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
02673           New->isLocalExternDecl())) {
02674       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
02675           OldDeclaredReturnType->isObjCObjectPointerType())
02676         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
02677       if (ResQT.isNull()) {
02678         if (New->isCXXClassMember() && New->isOutOfLine())
02679           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
02680               << New << New->getReturnTypeSourceRange();
02681         else
02682           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
02683               << New->getReturnTypeSourceRange();
02684         Diag(OldLocation, PrevDiag) << Old << Old->getType()
02685                                     << Old->getReturnTypeSourceRange();
02686         return true;
02687       }
02688       else
02689         NewQType = ResQT;
02690     }
02691 
02692     QualType OldReturnType = OldType->getReturnType();
02693     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
02694     if (OldReturnType != NewReturnType) {
02695       // If this function has a deduced return type and has already been
02696       // defined, copy the deduced value from the old declaration.
02697       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
02698       if (OldAT && OldAT->isDeduced()) {
02699         New->setType(
02700             SubstAutoType(New->getType(),
02701                           OldAT->isDependentType() ? Context.DependentTy
02702                                                    : OldAT->getDeducedType()));
02703         NewQType = Context.getCanonicalType(
02704             SubstAutoType(NewQType,
02705                           OldAT->isDependentType() ? Context.DependentTy
02706                                                    : OldAT->getDeducedType()));
02707       }
02708     }
02709 
02710     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
02711     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
02712     if (OldMethod && NewMethod) {
02713       // Preserve triviality.
02714       NewMethod->setTrivial(OldMethod->isTrivial());
02715 
02716       // MSVC allows explicit template specialization at class scope:
02717       // 2 CXXMethodDecls referring to the same function will be injected.
02718       // We don't want a redeclaration error.
02719       bool IsClassScopeExplicitSpecialization =
02720                               OldMethod->isFunctionTemplateSpecialization() &&
02721                               NewMethod->isFunctionTemplateSpecialization();
02722       bool isFriend = NewMethod->getFriendObjectKind();
02723 
02724       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
02725           !IsClassScopeExplicitSpecialization) {
02726         //    -- Member function declarations with the same name and the
02727         //       same parameter types cannot be overloaded if any of them
02728         //       is a static member function declaration.
02729         if (OldMethod->isStatic() != NewMethod->isStatic()) {
02730           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
02731           Diag(OldLocation, PrevDiag) << Old << Old->getType();
02732           return true;
02733         }
02734 
02735         // C++ [class.mem]p1:
02736         //   [...] A member shall not be declared twice in the
02737         //   member-specification, except that a nested class or member
02738         //   class template can be declared and then later defined.
02739         if (ActiveTemplateInstantiations.empty()) {
02740           unsigned NewDiag;
02741           if (isa<CXXConstructorDecl>(OldMethod))
02742             NewDiag = diag::err_constructor_redeclared;
02743           else if (isa<CXXDestructorDecl>(NewMethod))
02744             NewDiag = diag::err_destructor_redeclared;
02745           else if (isa<CXXConversionDecl>(NewMethod))
02746             NewDiag = diag::err_conv_function_redeclared;
02747           else
02748             NewDiag = diag::err_member_redeclared;
02749 
02750           Diag(New->getLocation(), NewDiag);
02751         } else {
02752           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
02753             << New << New->getType();
02754         }
02755         Diag(OldLocation, PrevDiag) << Old << Old->getType();
02756 
02757       // Complain if this is an explicit declaration of a special
02758       // member that was initially declared implicitly.
02759       //
02760       // As an exception, it's okay to befriend such methods in order
02761       // to permit the implicit constructor/destructor/operator calls.
02762       } else if (OldMethod->isImplicit()) {
02763         if (isFriend) {
02764           NewMethod->setImplicit();
02765         } else {
02766           Diag(NewMethod->getLocation(),
02767                diag::err_definition_of_implicitly_declared_member) 
02768             << New << getSpecialMember(OldMethod);
02769           return true;
02770         }
02771       } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
02772         Diag(NewMethod->getLocation(),
02773              diag::err_definition_of_explicitly_defaulted_member)
02774           << getSpecialMember(OldMethod);
02775         return true;
02776       }
02777     }
02778 
02779     // C++11 [dcl.attr.noreturn]p1:
02780     //   The first declaration of a function shall specify the noreturn
02781     //   attribute if any declaration of that function specifies the noreturn
02782     //   attribute.
02783     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
02784     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
02785       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
02786       Diag(Old->getFirstDecl()->getLocation(),
02787            diag::note_noreturn_missing_first_decl);
02788     }
02789 
02790     // C++11 [dcl.attr.depend]p2:
02791     //   The first declaration of a function shall specify the
02792     //   carries_dependency attribute for its declarator-id if any declaration
02793     //   of the function specifies the carries_dependency attribute.
02794     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
02795     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
02796       Diag(CDA->getLocation(),
02797            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
02798       Diag(Old->getFirstDecl()->getLocation(),
02799            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
02800     }
02801 
02802     // (C++98 8.3.5p3):
02803     //   All declarations for a function shall agree exactly in both the
02804     //   return type and the parameter-type-list.
02805     // We also want to respect all the extended bits except noreturn.
02806 
02807     // noreturn should now match unless the old type info didn't have it.
02808     QualType OldQTypeForComparison = OldQType;
02809     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
02810       assert(OldQType == QualType(OldType, 0));
02811       const FunctionType *OldTypeForComparison
02812         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
02813       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
02814       assert(OldQTypeForComparison.isCanonical());
02815     }
02816 
02817     if (haveIncompatibleLanguageLinkages(Old, New)) {
02818       // As a special case, retain the language linkage from previous
02819       // declarations of a friend function as an extension.
02820       //
02821       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
02822       // and is useful because there's otherwise no way to specify language
02823       // linkage within class scope.
02824       //
02825       // Check cautiously as the friend object kind isn't yet complete.
02826       if (New->getFriendObjectKind() != Decl::FOK_None) {
02827         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
02828         Diag(OldLocation, PrevDiag);
02829       } else {
02830         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
02831         Diag(OldLocation, PrevDiag);
02832         return true;
02833       }
02834     }
02835 
02836     if (OldQTypeForComparison == NewQType)
02837       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
02838 
02839     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
02840         New->isLocalExternDecl()) {
02841       // It's OK if we couldn't merge types for a local function declaraton
02842       // if either the old or new type is dependent. We'll merge the types
02843       // when we instantiate the function.
02844       return false;
02845     }
02846 
02847     // Fall through for conflicting redeclarations and redefinitions.
02848   }
02849 
02850   // C: Function types need to be compatible, not identical. This handles
02851   // duplicate function decls like "void f(int); void f(enum X);" properly.
02852   if (!getLangOpts().CPlusPlus &&
02853       Context.typesAreCompatible(OldQType, NewQType)) {
02854     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
02855     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
02856     const FunctionProtoType *OldProto = nullptr;
02857     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
02858         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
02859       // The old declaration provided a function prototype, but the
02860       // new declaration does not. Merge in the prototype.
02861       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
02862       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
02863       NewQType =
02864           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
02865                                   OldProto->getExtProtoInfo());
02866       New->setType(NewQType);
02867       New->setHasInheritedPrototype();
02868 
02869       // Synthesize parameters with the same types.
02870       SmallVector<ParmVarDecl*, 16> Params;
02871       for (const auto &ParamType : OldProto->param_types()) {
02872         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
02873                                                  SourceLocation(), nullptr,
02874                                                  ParamType, /*TInfo=*/nullptr,
02875                                                  SC_None, nullptr);
02876         Param->setScopeInfo(0, Params.size());
02877         Param->setImplicit();
02878         Params.push_back(Param);
02879       }
02880 
02881       New->setParams(Params);
02882     }
02883 
02884     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
02885   }
02886 
02887   // GNU C permits a K&R definition to follow a prototype declaration
02888   // if the declared types of the parameters in the K&R definition
02889   // match the types in the prototype declaration, even when the
02890   // promoted types of the parameters from the K&R definition differ
02891   // from the types in the prototype. GCC then keeps the types from
02892   // the prototype.
02893   //
02894   // If a variadic prototype is followed by a non-variadic K&R definition,
02895   // the K&R definition becomes variadic.  This is sort of an edge case, but
02896   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
02897   // C99 6.9.1p8.
02898   if (!getLangOpts().CPlusPlus &&
02899       Old->hasPrototype() && !New->hasPrototype() &&
02900       New->getType()->getAs<FunctionProtoType>() &&
02901       Old->getNumParams() == New->getNumParams()) {
02902     SmallVector<QualType, 16> ArgTypes;
02903     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
02904     const FunctionProtoType *OldProto
02905       = Old->getType()->getAs<FunctionProtoType>();
02906     const FunctionProtoType *NewProto
02907       = New->getType()->getAs<FunctionProtoType>();
02908 
02909     // Determine whether this is the GNU C extension.
02910     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
02911                                                NewProto->getReturnType());
02912     bool LooseCompatible = !MergedReturn.isNull();
02913     for (unsigned Idx = 0, End = Old->getNumParams();
02914          LooseCompatible && Idx != End; ++Idx) {
02915       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
02916       ParmVarDecl *NewParm = New->getParamDecl(Idx);
02917       if (Context.typesAreCompatible(OldParm->getType(),
02918                                      NewProto->getParamType(Idx))) {
02919         ArgTypes.push_back(NewParm->getType());
02920       } else if (Context.typesAreCompatible(OldParm->getType(),
02921                                             NewParm->getType(),
02922                                             /*CompareUnqualified=*/true)) {
02923         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
02924                                            NewProto->getParamType(Idx) };
02925         Warnings.push_back(Warn);
02926         ArgTypes.push_back(NewParm->getType());
02927       } else
02928         LooseCompatible = false;
02929     }
02930 
02931     if (LooseCompatible) {
02932       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
02933         Diag(Warnings[Warn].NewParm->getLocation(),
02934              diag::ext_param_promoted_not_compatible_with_prototype)
02935           << Warnings[Warn].PromotedType
02936           << Warnings[Warn].OldParm->getType();
02937         if (Warnings[Warn].OldParm->getLocation().isValid())
02938           Diag(Warnings[Warn].OldParm->getLocation(),
02939                diag::note_previous_declaration);
02940       }
02941 
02942       if (MergeTypeWithOld)
02943         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
02944                                              OldProto->getExtProtoInfo()));
02945       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
02946     }
02947 
02948     // Fall through to diagnose conflicting types.
02949   }
02950 
02951   // A function that has already been declared has been redeclared or
02952   // defined with a different type; show an appropriate diagnostic.
02953 
02954   // If the previous declaration was an implicitly-generated builtin
02955   // declaration, then at the very least we should use a specialized note.
02956   unsigned BuiltinID;
02957   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
02958     // If it's actually a library-defined builtin function like 'malloc'
02959     // or 'printf', just warn about the incompatible redeclaration.
02960     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
02961       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
02962       Diag(OldLocation, diag::note_previous_builtin_declaration)
02963         << Old << Old->getType();
02964 
02965       // If this is a global redeclaration, just forget hereafter
02966       // about the "builtin-ness" of the function.
02967       //
02968       // Doing this for local extern declarations is problematic.  If
02969       // the builtin declaration remains visible, a second invalid
02970       // local declaration will produce a hard error; if it doesn't
02971       // remain visible, a single bogus local redeclaration (which is
02972       // actually only a warning) could break all the downstream code.
02973       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
02974         New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
02975 
02976       return false;
02977     }
02978 
02979     PrevDiag = diag::note_previous_builtin_declaration;
02980   }
02981 
02982   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
02983   Diag(OldLocation, PrevDiag) << Old << Old->getType();
02984   return true;
02985 }
02986 
02987 /// \brief Completes the merge of two function declarations that are
02988 /// known to be compatible.
02989 ///
02990 /// This routine handles the merging of attributes and other
02991 /// properties of function declarations from the old declaration to
02992 /// the new declaration, once we know that New is in fact a
02993 /// redeclaration of Old.
02994 ///
02995 /// \returns false
02996 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
02997                                         Scope *S, bool MergeTypeWithOld) {
02998   // Merge the attributes
02999   mergeDeclAttributes(New, Old);
03000 
03001   // Merge "pure" flag.
03002   if (Old->isPure())
03003     New->setPure();
03004 
03005   // Merge "used" flag.
03006   if (Old->getMostRecentDecl()->isUsed(false))
03007     New->setIsUsed();
03008 
03009   // Merge attributes from the parameters.  These can mismatch with K&R
03010   // declarations.
03011   if (New->getNumParams() == Old->getNumParams())
03012     for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
03013       mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
03014                                *this);
03015 
03016   if (getLangOpts().CPlusPlus)
03017     return MergeCXXFunctionDecl(New, Old, S);
03018 
03019   // Merge the function types so the we get the composite types for the return
03020   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
03021   // was visible.
03022   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
03023   if (!Merged.isNull() && MergeTypeWithOld)
03024     New->setType(Merged);
03025 
03026   return false;
03027 }
03028 
03029 
03030 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
03031                                 ObjCMethodDecl *oldMethod) {
03032 
03033   // Merge the attributes, including deprecated/unavailable
03034   AvailabilityMergeKind MergeKind =
03035     isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
03036                                                    : AMK_Override;
03037   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
03038 
03039   // Merge attributes from the parameters.
03040   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
03041                                        oe = oldMethod->param_end();
03042   for (ObjCMethodDecl::param_iterator
03043          ni = newMethod->param_begin(), ne = newMethod->param_end();
03044        ni != ne && oi != oe; ++ni, ++oi)
03045     mergeParamDeclAttributes(*ni, *oi, *this);
03046 
03047   CheckObjCMethodOverride(newMethod, oldMethod);
03048 }
03049 
03050 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
03051 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
03052 /// emitting diagnostics as appropriate.
03053 ///
03054 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
03055 /// to here in AddInitializerToDecl. We can't check them before the initializer
03056 /// is attached.
03057 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
03058                              bool MergeTypeWithOld) {
03059   if (New->isInvalidDecl() || Old->isInvalidDecl())
03060     return;
03061 
03062   QualType MergedT;
03063   if (getLangOpts().CPlusPlus) {
03064     if (New->getType()->isUndeducedType()) {
03065       // We don't know what the new type is until the initializer is attached.
03066       return;
03067     } else if (Context.hasSameType(New->getType(), Old->getType())) {
03068       // These could still be something that needs exception specs checked.
03069       return MergeVarDeclExceptionSpecs(New, Old);
03070     }
03071     // C++ [basic.link]p10:
03072     //   [...] the types specified by all declarations referring to a given
03073     //   object or function shall be identical, except that declarations for an
03074     //   array object can specify array types that differ by the presence or
03075     //   absence of a major array bound (8.3.4).
03076     else if (Old->getType()->isIncompleteArrayType() &&
03077              New->getType()->isArrayType()) {
03078       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
03079       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
03080       if (Context.hasSameType(OldArray->getElementType(),
03081                               NewArray->getElementType()))
03082         MergedT = New->getType();
03083     } else if (Old->getType()->isArrayType() &&
03084                New->getType()->isIncompleteArrayType()) {
03085       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
03086       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
03087       if (Context.hasSameType(OldArray->getElementType(),
03088                               NewArray->getElementType()))
03089         MergedT = Old->getType();
03090     } else if (New->getType()->isObjCObjectPointerType() &&
03091                Old->getType()->isObjCObjectPointerType()) {
03092       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
03093                                               Old->getType());
03094     }
03095   } else {
03096     // C 6.2.7p2:
03097     //   All declarations that refer to the same object or function shall have
03098     //   compatible type.
03099     MergedT = Context.mergeTypes(New->getType(), Old->getType());
03100   }
03101   if (MergedT.isNull()) {
03102     // It's OK if we couldn't merge types if either type is dependent, for a
03103     // block-scope variable. In other cases (static data members of class
03104     // templates, variable templates, ...), we require the types to be
03105     // equivalent.
03106     // FIXME: The C++ standard doesn't say anything about this.
03107     if ((New->getType()->isDependentType() ||
03108          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
03109       // If the old type was dependent, we can't merge with it, so the new type
03110       // becomes dependent for now. We'll reproduce the original type when we
03111       // instantiate the TypeSourceInfo for the variable.
03112       if (!New->getType()->isDependentType() && MergeTypeWithOld)
03113         New->setType(Context.DependentTy);
03114       return;
03115     }
03116 
03117     // FIXME: Even if this merging succeeds, some other non-visible declaration
03118     // of this variable might have an incompatible type. For instance:
03119     //
03120     //   extern int arr[];
03121     //   void f() { extern int arr[2]; }
03122     //   void g() { extern int arr[3]; }
03123     //
03124     // Neither C nor C++ requires a diagnostic for this, but we should still try
03125     // to diagnose it.
03126     Diag(New->getLocation(), diag::err_redefinition_different_type)
03127       << New->getDeclName() << New->getType() << Old->getType();
03128     Diag(Old->getLocation(), diag::note_previous_definition);
03129     return New->setInvalidDecl();
03130   }
03131 
03132   // Don't actually update the type on the new declaration if the old
03133   // declaration was an extern declaration in a different scope.
03134   if (MergeTypeWithOld)
03135     New->setType(MergedT);
03136 }
03137 
03138 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
03139                                   LookupResult &Previous) {
03140   // C11 6.2.7p4:
03141   //   For an identifier with internal or external linkage declared
03142   //   in a scope in which a prior declaration of that identifier is
03143   //   visible, if the prior declaration specifies internal or
03144   //   external linkage, the type of the identifier at the later
03145   //   declaration becomes the composite type.
03146   //
03147   // If the variable isn't visible, we do not merge with its type.
03148   if (Previous.isShadowed())
03149     return false;
03150 
03151   if (S.getLangOpts().CPlusPlus) {
03152     // C++11 [dcl.array]p3:
03153     //   If there is a preceding declaration of the entity in the same
03154     //   scope in which the bound was specified, an omitted array bound
03155     //   is taken to be the same as in that earlier declaration.
03156     return NewVD->isPreviousDeclInSameBlockScope() ||
03157            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
03158             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
03159   } else {
03160     // If the old declaration was function-local, don't merge with its
03161     // type unless we're in the same function.
03162     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
03163            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
03164   }
03165 }
03166 
03167 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
03168 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
03169 /// situation, merging decls or emitting diagnostics as appropriate.
03170 ///
03171 /// Tentative definition rules (C99 6.9.2p2) are checked by
03172 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
03173 /// definitions here, since the initializer hasn't been attached.
03174 ///
03175 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
03176   // If the new decl is already invalid, don't do any other checking.
03177   if (New->isInvalidDecl())
03178     return;
03179 
03180   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
03181 
03182   // Verify the old decl was also a variable or variable template.
03183   VarDecl *Old = nullptr;
03184   VarTemplateDecl *OldTemplate = nullptr;
03185   if (Previous.isSingleResult()) {
03186     if (NewTemplate) {
03187       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
03188       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
03189     } else
03190       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
03191   }
03192   if (!Old) {
03193     Diag(New->getLocation(), diag::err_redefinition_different_kind)
03194       << New->getDeclName();
03195     Diag(Previous.getRepresentativeDecl()->getLocation(),
03196          diag::note_previous_definition);
03197     return New->setInvalidDecl();
03198   }
03199 
03200   if (!shouldLinkPossiblyHiddenDecl(Old, New))
03201     return;
03202 
03203   // Ensure the template parameters are compatible.
03204   if (NewTemplate &&
03205       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
03206                                       OldTemplate->getTemplateParameters(),
03207                                       /*Complain=*/true, TPL_TemplateMatch))
03208     return;
03209 
03210   // C++ [class.mem]p1:
03211   //   A member shall not be declared twice in the member-specification [...]
03212   // 
03213   // Here, we need only consider static data members.
03214   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
03215     Diag(New->getLocation(), diag::err_duplicate_member) 
03216       << New->getIdentifier();
03217     Diag(Old->getLocation(), diag::note_previous_declaration);
03218     New->setInvalidDecl();
03219   }
03220   
03221   mergeDeclAttributes(New, Old);
03222   // Warn if an already-declared variable is made a weak_import in a subsequent 
03223   // declaration
03224   if (New->hasAttr<WeakImportAttr>() &&
03225       Old->getStorageClass() == SC_None &&
03226       !Old->hasAttr<WeakImportAttr>()) {
03227     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
03228     Diag(Old->getLocation(), diag::note_previous_definition);
03229     // Remove weak_import attribute on new declaration.
03230     New->dropAttr<WeakImportAttr>();
03231   }
03232 
03233   // Merge the types.
03234   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
03235 
03236   if (New->isInvalidDecl())
03237     return;
03238 
03239   diag::kind PrevDiag;
03240   SourceLocation OldLocation;
03241   std::tie(PrevDiag, OldLocation) =
03242       getNoteDiagForInvalidRedeclaration(Old, New);
03243 
03244   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
03245   if (New->getStorageClass() == SC_Static &&
03246       !New->isStaticDataMember() &&
03247       Old->hasExternalFormalLinkage()) {
03248     if (getLangOpts().MicrosoftExt) {
03249       Diag(New->getLocation(), diag::ext_static_non_static)
03250           << New->getDeclName();
03251       Diag(OldLocation, PrevDiag);
03252     } else {
03253       Diag(New->getLocation(), diag::err_static_non_static)
03254           << New->getDeclName();
03255       Diag(OldLocation, PrevDiag);
03256       return New->setInvalidDecl();
03257     }
03258   }
03259   // C99 6.2.2p4:
03260   //   For an identifier declared with the storage-class specifier
03261   //   extern in a scope in which a prior declaration of that
03262   //   identifier is visible,23) if the prior declaration specifies
03263   //   internal or external linkage, the linkage of the identifier at
03264   //   the later declaration is the same as the linkage specified at
03265   //   the prior declaration. If no prior declaration is visible, or
03266   //   if the prior declaration specifies no linkage, then the
03267   //   identifier has external linkage.
03268   if (New->hasExternalStorage() && Old->hasLinkage())
03269     /* Okay */;
03270   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
03271            !New->isStaticDataMember() &&
03272            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
03273     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
03274     Diag(OldLocation, PrevDiag);
03275     return New->setInvalidDecl();
03276   }
03277 
03278   // Check if extern is followed by non-extern and vice-versa.
03279   if (New->hasExternalStorage() &&
03280       !Old->hasLinkage() && Old->isLocalVarDecl()) {
03281     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
03282     Diag(OldLocation, PrevDiag);
03283     return New->setInvalidDecl();
03284   }
03285   if (Old->hasLinkage() && New->isLocalVarDecl() &&
03286       !New->hasExternalStorage()) {
03287     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
03288     Diag(OldLocation, PrevDiag);
03289     return New->setInvalidDecl();
03290   }
03291 
03292   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
03293 
03294   // FIXME: The test for external storage here seems wrong? We still
03295   // need to check for mismatches.
03296   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
03297       // Don't complain about out-of-line definitions of static members.
03298       !(Old->getLexicalDeclContext()->isRecord() &&
03299         !New->getLexicalDeclContext()->isRecord())) {
03300     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
03301     Diag(OldLocation, PrevDiag);
03302     return New->setInvalidDecl();
03303   }
03304 
03305   if (New->getTLSKind() != Old->getTLSKind()) {
03306     if (!Old->getTLSKind()) {
03307       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
03308       Diag(OldLocation, PrevDiag);
03309     } else if (!New->getTLSKind()) {
03310       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
03311       Diag(OldLocation, PrevDiag);
03312     } else {
03313       // Do not allow redeclaration to change the variable between requiring
03314       // static and dynamic initialization.
03315       // FIXME: GCC allows this, but uses the TLS keyword on the first
03316       // declaration to determine the kind. Do we need to be compatible here?
03317       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
03318         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
03319       Diag(OldLocation, PrevDiag);
03320     }
03321   }
03322 
03323   // C++ doesn't have tentative definitions, so go right ahead and check here.
03324   const VarDecl *Def;
03325   if (getLangOpts().CPlusPlus &&
03326       New->isThisDeclarationADefinition() == VarDecl::Definition &&
03327       (Def = Old->getDefinition())) {
03328     Diag(New->getLocation(), diag::err_redefinition) << New;
03329     Diag(Def->getLocation(), diag::note_previous_definition);
03330     New->setInvalidDecl();
03331     return;
03332   }
03333 
03334   if (haveIncompatibleLanguageLinkages(Old, New)) {
03335     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
03336     Diag(OldLocation, PrevDiag);
03337     New->setInvalidDecl();
03338     return;
03339   }
03340 
03341   // Merge "used" flag.
03342   if (Old->getMostRecentDecl()->isUsed(false))
03343     New->setIsUsed();
03344 
03345   // Keep a chain of previous declarations.
03346   New->setPreviousDecl(Old);
03347   if (NewTemplate)
03348     NewTemplate->setPreviousDecl(OldTemplate);
03349 
03350   // Inherit access appropriately.
03351   New->setAccess(Old->getAccess());
03352   if (NewTemplate)
03353     NewTemplate->setAccess(New->getAccess());
03354 }
03355 
03356 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
03357 /// no declarator (e.g. "struct foo;") is parsed.
03358 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
03359                                        DeclSpec &DS) {
03360   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
03361 }
03362 
03363 static void HandleTagNumbering(Sema &S, const TagDecl *Tag, Scope *TagScope) {
03364   if (!S.Context.getLangOpts().CPlusPlus)
03365     return;
03366 
03367   if (isa<CXXRecordDecl>(Tag->getParent())) {
03368     // If this tag is the direct child of a class, number it if
03369     // it is anonymous.
03370     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
03371       return;
03372     MangleNumberingContext &MCtx =
03373         S.Context.getManglingNumberContext(Tag->getParent());
03374     S.Context.setManglingNumber(
03375         Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
03376     return;
03377   }
03378 
03379   // If this tag isn't a direct child of a class, number it if it is local.
03380   Decl *ManglingContextDecl;
03381   if (MangleNumberingContext *MCtx =
03382           S.getCurrentMangleNumberContext(Tag->getDeclContext(),
03383                                           ManglingContextDecl)) {
03384     S.Context.setManglingNumber(
03385         Tag,
03386         MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
03387   }
03388 }
03389 
03390 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
03391 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
03392 /// parameters to cope with template friend declarations.
03393 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
03394                                        DeclSpec &DS,
03395                                        MultiTemplateParamsArg TemplateParams,
03396                                        bool IsExplicitInstantiation) {
03397   Decl *TagD = nullptr;
03398   TagDecl *Tag = nullptr;
03399   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
03400       DS.getTypeSpecType() == DeclSpec::TST_struct ||
03401       DS.getTypeSpecType() == DeclSpec::TST_interface ||
03402       DS.getTypeSpecType() == DeclSpec::TST_union ||
03403       DS.getTypeSpecType() == DeclSpec::TST_enum) {
03404     TagD = DS.getRepAsDecl();
03405 
03406     if (!TagD) // We probably had an error
03407       return nullptr;
03408 
03409     // Note that the above type specs guarantee that the
03410     // type rep is a Decl, whereas in many of the others
03411     // it's a Type.
03412     if (isa<TagDecl>(TagD))
03413       Tag = cast<TagDecl>(TagD);
03414     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
03415       Tag = CTD->getTemplatedDecl();
03416   }
03417 
03418   if (Tag) {
03419     HandleTagNumbering(*this, Tag, S);
03420     Tag->setFreeStanding();
03421     if (Tag->isInvalidDecl())
03422       return Tag;
03423   }
03424 
03425   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
03426     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
03427     // or incomplete types shall not be restrict-qualified."
03428     if (TypeQuals & DeclSpec::TQ_restrict)
03429       Diag(DS.getRestrictSpecLoc(),
03430            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
03431            << DS.getSourceRange();
03432   }
03433 
03434   if (DS.isConstexprSpecified()) {
03435     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
03436     // and definitions of functions and variables.
03437     if (Tag)
03438       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
03439         << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
03440             DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
03441             DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
03442             DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
03443     else
03444       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
03445     // Don't emit warnings after this error.
03446     return TagD;
03447   }
03448 
03449   DiagnoseFunctionSpecifiers(DS);
03450 
03451   if (DS.isFriendSpecified()) {
03452     // If we're dealing with a decl but not a TagDecl, assume that
03453     // whatever routines created it handled the friendship aspect.
03454     if (TagD && !Tag)
03455       return nullptr;
03456     return ActOnFriendTypeDecl(S, DS, TemplateParams);
03457   }
03458 
03459   CXXScopeSpec &SS = DS.getTypeSpecScope();
03460   bool IsExplicitSpecialization =
03461     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
03462   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
03463       !IsExplicitInstantiation && !IsExplicitSpecialization) {
03464     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
03465     // nested-name-specifier unless it is an explicit instantiation
03466     // or an explicit specialization.
03467     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
03468     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
03469       << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
03470           DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
03471           DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
03472           DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
03473       << SS.getRange();
03474     return nullptr;
03475   }
03476 
03477   // Track whether this decl-specifier declares anything.
03478   bool DeclaresAnything = true;
03479 
03480   // Handle anonymous struct definitions.
03481   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
03482     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
03483         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
03484       if (getLangOpts().CPlusPlus ||
03485           Record->getDeclContext()->isRecord())
03486         return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy());
03487 
03488       DeclaresAnything = false;
03489     }
03490   }
03491 
03492   // C11 6.7.2.1p2:
03493   //   A struct-declaration that does not declare an anonymous structure or
03494   //   anonymous union shall contain a struct-declarator-list.
03495   //
03496   // This rule also existed in C89 and C99; the grammar for struct-declaration
03497   // did not permit a struct-declaration without a struct-declarator-list.
03498   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
03499       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
03500     // Check for Microsoft C extension: anonymous struct/union member.
03501     // Handle 2 kinds of anonymous struct/union:
03502     //   struct STRUCT;
03503     //   union UNION;
03504     // and
03505     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
03506     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
03507     if ((Tag && Tag->getDeclName()) ||
03508         DS.getTypeSpecType() == DeclSpec::TST_typename) {
03509       RecordDecl *Record = nullptr;
03510       if (Tag)
03511         Record = dyn_cast<RecordDecl>(Tag);
03512       else if (const RecordType *RT =
03513                    DS.getRepAsType().get()->getAsStructureType())
03514         Record = RT->getDecl();
03515       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
03516         Record = UT->getDecl();
03517 
03518       if (Record && getLangOpts().MicrosoftExt) {
03519         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
03520           << Record->isUnion() << DS.getSourceRange();
03521         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
03522       }
03523 
03524       DeclaresAnything = false;
03525     }
03526   }
03527 
03528   // Skip all the checks below if we have a type error.
03529   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
03530       (TagD && TagD->isInvalidDecl()))
03531     return TagD;
03532 
03533   if (getLangOpts().CPlusPlus &&
03534       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
03535     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
03536       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
03537           !Enum->getIdentifier() && !Enum->isInvalidDecl())
03538         DeclaresAnything = false;
03539 
03540   if (!DS.isMissingDeclaratorOk()) {
03541     // Customize diagnostic for a typedef missing a name.
03542     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
03543       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
03544         << DS.getSourceRange();
03545     else
03546       DeclaresAnything = false;
03547   }
03548 
03549   if (DS.isModulePrivateSpecified() &&
03550       Tag && Tag->getDeclContext()->isFunctionOrMethod())
03551     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
03552       << Tag->getTagKind()
03553       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
03554 
03555   ActOnDocumentableDecl(TagD);
03556 
03557   // C 6.7/2:
03558   //   A declaration [...] shall declare at least a declarator [...], a tag,
03559   //   or the members of an enumeration.
03560   // C++ [dcl.dcl]p3:
03561   //   [If there are no declarators], and except for the declaration of an
03562   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
03563   //   names into the program, or shall redeclare a name introduced by a
03564   //   previous declaration.
03565   if (!DeclaresAnything) {
03566     // In C, we allow this as a (popular) extension / bug. Don't bother
03567     // producing further diagnostics for redundant qualifiers after this.
03568     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
03569     return TagD;
03570   }
03571 
03572   // C++ [dcl.stc]p1:
03573   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
03574   //   init-declarator-list of the declaration shall not be empty.
03575   // C++ [dcl.fct.spec]p1:
03576   //   If a cv-qualifier appears in a decl-specifier-seq, the
03577   //   init-declarator-list of the declaration shall not be empty.
03578   //
03579   // Spurious qualifiers here appear to be valid in C.
03580   unsigned DiagID = diag::warn_standalone_specifier;
03581   if (getLangOpts().CPlusPlus)
03582     DiagID = diag::ext_standalone_specifier;
03583 
03584   // Note that a linkage-specification sets a storage class, but
03585   // 'extern "C" struct foo;' is actually valid and not theoretically
03586   // useless.
03587   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
03588     if (SCS == DeclSpec::SCS_mutable)
03589       // Since mutable is not a viable storage class specifier in C, there is
03590       // no reason to treat it as an extension. Instead, diagnose as an error.
03591       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
03592     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
03593       Diag(DS.getStorageClassSpecLoc(), DiagID)
03594         << DeclSpec::getSpecifierName(SCS);
03595   }
03596 
03597   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
03598     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
03599       << DeclSpec::getSpecifierName(TSCS);
03600   if (DS.getTypeQualifiers()) {
03601     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
03602       Diag(DS.getConstSpecLoc(), DiagID) << "const";
03603     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
03604       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
03605     // Restrict is covered above.
03606     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
03607       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
03608   }
03609 
03610   // Warn about ignored type attributes, for example:
03611   // __attribute__((aligned)) struct A;
03612   // Attributes should be placed after tag to apply to type declaration.
03613   if (!DS.getAttributes().empty()) {
03614     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
03615     if (TypeSpecType == DeclSpec::TST_class ||
03616         TypeSpecType == DeclSpec::TST_struct ||
03617         TypeSpecType == DeclSpec::TST_interface ||
03618         TypeSpecType == DeclSpec::TST_union ||
03619         TypeSpecType == DeclSpec::TST_enum) {
03620       AttributeList* attrs = DS.getAttributes().getList();
03621       while (attrs) {
03622         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
03623         << attrs->getName()
03624         << (TypeSpecType == DeclSpec::TST_class ? 0 :
03625             TypeSpecType == DeclSpec::TST_struct ? 1 :
03626             TypeSpecType == DeclSpec::TST_union ? 2 :
03627             TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
03628         attrs = attrs->getNext();
03629       }
03630     }
03631   }
03632 
03633   return TagD;
03634 }
03635 
03636 /// We are trying to inject an anonymous member into the given scope;
03637 /// check if there's an existing declaration that can't be overloaded.
03638 ///
03639 /// \return true if this is a forbidden redeclaration
03640 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
03641                                          Scope *S,
03642                                          DeclContext *Owner,
03643                                          DeclarationName Name,
03644                                          SourceLocation NameLoc,
03645                                          unsigned diagnostic) {
03646   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
03647                  Sema::ForRedeclaration);
03648   if (!SemaRef.LookupName(R, S)) return false;
03649 
03650   if (R.getAsSingle<TagDecl>())
03651     return false;
03652 
03653   // Pick a representative declaration.
03654   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
03655   assert(PrevDecl && "Expected a non-null Decl");
03656 
03657   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
03658     return false;
03659 
03660   SemaRef.Diag(NameLoc, diagnostic) << Name;
03661   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
03662 
03663   return true;
03664 }
03665 
03666 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
03667 /// anonymous struct or union AnonRecord into the owning context Owner
03668 /// and scope S. This routine will be invoked just after we realize
03669 /// that an unnamed union or struct is actually an anonymous union or
03670 /// struct, e.g.,
03671 ///
03672 /// @code
03673 /// union {
03674 ///   int i;
03675 ///   float f;
03676 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
03677 ///    // f into the surrounding scope.x
03678 /// @endcode
03679 ///
03680 /// This routine is recursive, injecting the names of nested anonymous
03681 /// structs/unions into the owning context and scope as well.
03682 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
03683                                          DeclContext *Owner,
03684                                          RecordDecl *AnonRecord,
03685                                          AccessSpecifier AS,
03686                                          SmallVectorImpl<NamedDecl *> &Chaining,
03687                                          bool MSAnonStruct) {
03688   unsigned diagKind
03689     = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
03690                             : diag::err_anonymous_struct_member_redecl;
03691 
03692   bool Invalid = false;
03693 
03694   // Look every FieldDecl and IndirectFieldDecl with a name.
03695   for (auto *D : AnonRecord->decls()) {
03696     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
03697         cast<NamedDecl>(D)->getDeclName()) {
03698       ValueDecl *VD = cast<ValueDecl>(D);
03699       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
03700                                        VD->getLocation(), diagKind)) {
03701         // C++ [class.union]p2:
03702         //   The names of the members of an anonymous union shall be
03703         //   distinct from the names of any other entity in the
03704         //   scope in which the anonymous union is declared.
03705         Invalid = true;
03706       } else {
03707         // C++ [class.union]p2:
03708         //   For the purpose of name lookup, after the anonymous union
03709         //   definition, the members of the anonymous union are
03710         //   considered to have been defined in the scope in which the
03711         //   anonymous union is declared.
03712         unsigned OldChainingSize = Chaining.size();
03713         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
03714           for (auto *PI : IF->chain())
03715             Chaining.push_back(PI);
03716         else
03717           Chaining.push_back(VD);
03718 
03719         assert(Chaining.size() >= 2);
03720         NamedDecl **NamedChain =
03721           new (SemaRef.Context)NamedDecl*[Chaining.size()];
03722         for (unsigned i = 0; i < Chaining.size(); i++)
03723           NamedChain[i] = Chaining[i];
03724 
03725         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
03726             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
03727             VD->getType(), NamedChain, Chaining.size());
03728 
03729         for (const auto *Attr : VD->attrs())
03730           IndirectField->addAttr(Attr->clone(SemaRef.Context));
03731 
03732         IndirectField->setAccess(AS);
03733         IndirectField->setImplicit();
03734         SemaRef.PushOnScopeChains(IndirectField, S);
03735 
03736         // That includes picking up the appropriate access specifier.
03737         if (AS != AS_none) IndirectField->setAccess(AS);
03738 
03739         Chaining.resize(OldChainingSize);
03740       }
03741     }
03742   }
03743 
03744   return Invalid;
03745 }
03746 
03747 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
03748 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
03749 /// illegal input values are mapped to SC_None.
03750 static StorageClass
03751 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
03752   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
03753   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
03754          "Parser allowed 'typedef' as storage class VarDecl.");
03755   switch (StorageClassSpec) {
03756   case DeclSpec::SCS_unspecified:    return SC_None;
03757   case DeclSpec::SCS_extern:
03758     if (DS.isExternInLinkageSpec())
03759       return SC_None;
03760     return SC_Extern;
03761   case DeclSpec::SCS_static:         return SC_Static;
03762   case DeclSpec::SCS_auto:           return SC_Auto;
03763   case DeclSpec::SCS_register:       return SC_Register;
03764   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
03765     // Illegal SCSs map to None: error reporting is up to the caller.
03766   case DeclSpec::SCS_mutable:        // Fall through.
03767   case DeclSpec::SCS_typedef:        return SC_None;
03768   }
03769   llvm_unreachable("unknown storage class specifier");
03770 }
03771 
03772 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
03773   assert(Record->hasInClassInitializer());
03774 
03775   for (const auto *I : Record->decls()) {
03776     const auto *FD = dyn_cast<FieldDecl>(I);
03777     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
03778       FD = IFD->getAnonField();
03779     if (FD && FD->hasInClassInitializer())
03780       return FD->getLocation();
03781   }
03782 
03783   llvm_unreachable("couldn't find in-class initializer");
03784 }
03785 
03786 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
03787                                       SourceLocation DefaultInitLoc) {
03788   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
03789     return;
03790 
03791   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
03792   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
03793 }
03794 
03795 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
03796                                       CXXRecordDecl *AnonUnion) {
03797   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
03798     return;
03799 
03800   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
03801 }
03802 
03803 /// BuildAnonymousStructOrUnion - Handle the declaration of an
03804 /// anonymous structure or union. Anonymous unions are a C++ feature
03805 /// (C++ [class.union]) and a C11 feature; anonymous structures
03806 /// are a C11 feature and GNU C++ extension.
03807 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
03808                                         AccessSpecifier AS,
03809                                         RecordDecl *Record,
03810                                         const PrintingPolicy &Policy) {
03811   DeclContext *Owner = Record->getDeclContext();
03812 
03813   // Diagnose whether this anonymous struct/union is an extension.
03814   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
03815     Diag(Record->getLocation(), diag::ext_anonymous_union);
03816   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
03817     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
03818   else if (!Record->isUnion() && !getLangOpts().C11)
03819     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
03820 
03821   // C and C++ require different kinds of checks for anonymous
03822   // structs/unions.
03823   bool Invalid = false;
03824   if (getLangOpts().CPlusPlus) {
03825     const char *PrevSpec = nullptr;
03826     unsigned DiagID;
03827     if (Record->isUnion()) {
03828       // C++ [class.union]p6:
03829       //   Anonymous unions declared in a named namespace or in the
03830       //   global namespace shall be declared static.
03831       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
03832           (isa<TranslationUnitDecl>(Owner) ||
03833            (isa<NamespaceDecl>(Owner) &&
03834             cast<NamespaceDecl>(Owner)->getDeclName()))) {
03835         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
03836           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
03837   
03838         // Recover by adding 'static'.
03839         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
03840                                PrevSpec, DiagID, Policy);
03841       }
03842       // C++ [class.union]p6:
03843       //   A storage class is not allowed in a declaration of an
03844       //   anonymous union in a class scope.
03845       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
03846                isa<RecordDecl>(Owner)) {
03847         Diag(DS.getStorageClassSpecLoc(),
03848              diag::err_anonymous_union_with_storage_spec)
03849           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
03850   
03851         // Recover by removing the storage specifier.
03852         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 
03853                                SourceLocation(),
03854                                PrevSpec, DiagID, Context.getPrintingPolicy());
03855       }
03856     }
03857 
03858     // Ignore const/volatile/restrict qualifiers.
03859     if (DS.getTypeQualifiers()) {
03860       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
03861         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
03862           << Record->isUnion() << "const"
03863           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
03864       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
03865         Diag(DS.getVolatileSpecLoc(),
03866              diag::ext_anonymous_struct_union_qualified)
03867           << Record->isUnion() << "volatile"
03868           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
03869       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
03870         Diag(DS.getRestrictSpecLoc(),
03871              diag::ext_anonymous_struct_union_qualified)
03872           << Record->isUnion() << "restrict"
03873           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
03874       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
03875         Diag(DS.getAtomicSpecLoc(),
03876              diag::ext_anonymous_struct_union_qualified)
03877           << Record->isUnion() << "_Atomic"
03878           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
03879 
03880       DS.ClearTypeQualifiers();
03881     }
03882 
03883     // C++ [class.union]p2:
03884     //   The member-specification of an anonymous union shall only
03885     //   define non-static data members. [Note: nested types and
03886     //   functions cannot be declared within an anonymous union. ]
03887     for (auto *Mem : Record->decls()) {
03888       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
03889         // C++ [class.union]p3:
03890         //   An anonymous union shall not have private or protected
03891         //   members (clause 11).
03892         assert(FD->getAccess() != AS_none);
03893         if (FD->getAccess() != AS_public) {
03894           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
03895             << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
03896           Invalid = true;
03897         }
03898 
03899         // C++ [class.union]p1
03900         //   An object of a class with a non-trivial constructor, a non-trivial
03901         //   copy constructor, a non-trivial destructor, or a non-trivial copy
03902         //   assignment operator cannot be a member of a union, nor can an
03903         //   array of such objects.
03904         if (CheckNontrivialField(FD))
03905           Invalid = true;
03906       } else if (Mem->isImplicit()) {
03907         // Any implicit members are fine.
03908       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
03909         // This is a type that showed up in an
03910         // elaborated-type-specifier inside the anonymous struct or
03911         // union, but which actually declares a type outside of the
03912         // anonymous struct or union. It's okay.
03913       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
03914         if (!MemRecord->isAnonymousStructOrUnion() &&
03915             MemRecord->getDeclName()) {
03916           // Visual C++ allows type definition in anonymous struct or union.
03917           if (getLangOpts().MicrosoftExt)
03918             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
03919               << (int)Record->isUnion();
03920           else {
03921             // This is a nested type declaration.
03922             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
03923               << (int)Record->isUnion();
03924             Invalid = true;
03925           }
03926         } else {
03927           // This is an anonymous type definition within another anonymous type.
03928           // This is a popular extension, provided by Plan9, MSVC and GCC, but
03929           // not part of standard C++.
03930           Diag(MemRecord->getLocation(),
03931                diag::ext_anonymous_record_with_anonymous_type)
03932             << (int)Record->isUnion();
03933         }
03934       } else if (isa<AccessSpecDecl>(Mem)) {
03935         // Any access specifier is fine.
03936       } else if (isa<StaticAssertDecl>(Mem)) {
03937         // In C++1z, static_assert declarations are also fine.
03938       } else {
03939         // We have something that isn't a non-static data
03940         // member. Complain about it.
03941         unsigned DK = diag::err_anonymous_record_bad_member;
03942         if (isa<TypeDecl>(Mem))
03943           DK = diag::err_anonymous_record_with_type;
03944         else if (isa<FunctionDecl>(Mem))
03945           DK = diag::err_anonymous_record_with_function;
03946         else if (isa<VarDecl>(Mem))
03947           DK = diag::err_anonymous_record_with_static;
03948         
03949         // Visual C++ allows type definition in anonymous struct or union.
03950         if (getLangOpts().MicrosoftExt &&
03951             DK == diag::err_anonymous_record_with_type)
03952           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
03953             << (int)Record->isUnion();
03954         else {
03955           Diag(Mem->getLocation(), DK)
03956               << (int)Record->isUnion();
03957           Invalid = true;
03958         }
03959       }
03960     }
03961 
03962     // C++11 [class.union]p8 (DR1460):
03963     //   At most one variant member of a union may have a
03964     //   brace-or-equal-initializer.
03965     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
03966         Owner->isRecord())
03967       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
03968                                 cast<CXXRecordDecl>(Record));
03969   }
03970 
03971   if (!Record->isUnion() && !Owner->isRecord()) {
03972     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
03973       << (int)getLangOpts().CPlusPlus;
03974     Invalid = true;
03975   }
03976 
03977   // Mock up a declarator.
03978   Declarator Dc(DS, Declarator::MemberContext);
03979   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
03980   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
03981 
03982   // Create a declaration for this anonymous struct/union.
03983   NamedDecl *Anon = nullptr;
03984   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
03985     Anon = FieldDecl::Create(Context, OwningClass,
03986                              DS.getLocStart(),
03987                              Record->getLocation(),
03988                              /*IdentifierInfo=*/nullptr,
03989                              Context.getTypeDeclType(Record),
03990                              TInfo,
03991                              /*BitWidth=*/nullptr, /*Mutable=*/false,
03992                              /*InitStyle=*/ICIS_NoInit);
03993     Anon->setAccess(AS);
03994     if (getLangOpts().CPlusPlus)
03995       FieldCollector->Add(cast<FieldDecl>(Anon));
03996   } else {
03997     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
03998     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
03999     if (SCSpec == DeclSpec::SCS_mutable) {
04000       // mutable can only appear on non-static class members, so it's always
04001       // an error here
04002       Diag(Record->getLocation(), diag::err_mutable_nonmember);
04003       Invalid = true;
04004       SC = SC_None;
04005     }
04006 
04007     Anon = VarDecl::Create(Context, Owner,
04008                            DS.getLocStart(),
04009                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
04010                            Context.getTypeDeclType(Record),
04011                            TInfo, SC);
04012 
04013     // Default-initialize the implicit variable. This initialization will be
04014     // trivial in almost all cases, except if a union member has an in-class
04015     // initializer:
04016     //   union { int n = 0; };
04017     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
04018   }
04019   Anon->setImplicit();
04020 
04021   // Mark this as an anonymous struct/union type.
04022   Record->setAnonymousStructOrUnion(true);
04023 
04024   // Add the anonymous struct/union object to the current
04025   // context. We'll be referencing this object when we refer to one of
04026   // its members.
04027   Owner->addDecl(Anon);
04028 
04029   // Inject the members of the anonymous struct/union into the owning
04030   // context and into the identifier resolver chain for name lookup
04031   // purposes.
04032   SmallVector<NamedDecl*, 2> Chain;
04033   Chain.push_back(Anon);
04034 
04035   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
04036                                           Chain, false))
04037     Invalid = true;
04038 
04039   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
04040     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
04041       Decl *ManglingContextDecl;
04042       if (MangleNumberingContext *MCtx =
04043               getCurrentMangleNumberContext(NewVD->getDeclContext(),
04044                                             ManglingContextDecl)) {
04045         Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
04046         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
04047       }
04048     }
04049   }
04050 
04051   if (Invalid)
04052     Anon->setInvalidDecl();
04053 
04054   return Anon;
04055 }
04056 
04057 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
04058 /// Microsoft C anonymous structure.
04059 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
04060 /// Example:
04061 ///
04062 /// struct A { int a; };
04063 /// struct B { struct A; int b; };
04064 ///
04065 /// void foo() {
04066 ///   B var;
04067 ///   var.a = 3;
04068 /// }
04069 ///
04070 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
04071                                            RecordDecl *Record) {
04072   assert(Record && "expected a record!");
04073 
04074   // Mock up a declarator.
04075   Declarator Dc(DS, Declarator::TypeNameContext);
04076   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
04077   assert(TInfo && "couldn't build declarator info for anonymous struct");
04078 
04079   auto *ParentDecl = cast<RecordDecl>(CurContext);
04080   QualType RecTy = Context.getTypeDeclType(Record);
04081 
04082   // Create a declaration for this anonymous struct.
04083   NamedDecl *Anon = FieldDecl::Create(Context,
04084                              ParentDecl,
04085                              DS.getLocStart(),
04086                              DS.getLocStart(),
04087                              /*IdentifierInfo=*/nullptr,
04088                              RecTy,
04089                              TInfo,
04090                              /*BitWidth=*/nullptr, /*Mutable=*/false,
04091                              /*InitStyle=*/ICIS_NoInit);
04092   Anon->setImplicit();
04093 
04094   // Add the anonymous struct object to the current context.
04095   CurContext->addDecl(Anon);
04096 
04097   // Inject the members of the anonymous struct into the current
04098   // context and into the identifier resolver chain for name lookup
04099   // purposes.
04100   SmallVector<NamedDecl*, 2> Chain;
04101   Chain.push_back(Anon);
04102 
04103   RecordDecl *RecordDef = Record->getDefinition();
04104   if (RequireCompleteType(Anon->getLocation(), RecTy,
04105                           diag::err_field_incomplete) ||
04106       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
04107                                           AS_none, Chain, true)) {
04108     Anon->setInvalidDecl();
04109     ParentDecl->setInvalidDecl();
04110   }
04111 
04112   return Anon;
04113 }
04114 
04115 /// GetNameForDeclarator - Determine the full declaration name for the
04116 /// given Declarator.
04117 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
04118   return GetNameFromUnqualifiedId(D.getName());
04119 }
04120 
04121 /// \brief Retrieves the declaration name from a parsed unqualified-id.
04122 DeclarationNameInfo
04123 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
04124   DeclarationNameInfo NameInfo;
04125   NameInfo.setLoc(Name.StartLocation);
04126 
04127   switch (Name.getKind()) {
04128 
04129   case UnqualifiedId::IK_ImplicitSelfParam:
04130   case UnqualifiedId::IK_Identifier:
04131     NameInfo.setName(Name.Identifier);
04132     NameInfo.setLoc(Name.StartLocation);
04133     return NameInfo;
04134 
04135   case UnqualifiedId::IK_OperatorFunctionId:
04136     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
04137                                            Name.OperatorFunctionId.Operator));
04138     NameInfo.setLoc(Name.StartLocation);
04139     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
04140       = Name.OperatorFunctionId.SymbolLocations[0];
04141     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
04142       = Name.EndLocation.getRawEncoding();
04143     return NameInfo;
04144 
04145   case UnqualifiedId::IK_LiteralOperatorId:
04146     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
04147                                                            Name.Identifier));
04148     NameInfo.setLoc(Name.StartLocation);
04149     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
04150     return NameInfo;
04151 
04152   case UnqualifiedId::IK_ConversionFunctionId: {
04153     TypeSourceInfo *TInfo;
04154     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
04155     if (Ty.isNull())
04156       return DeclarationNameInfo();
04157     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
04158                                                Context.getCanonicalType(Ty)));
04159     NameInfo.setLoc(Name.StartLocation);
04160     NameInfo.setNamedTypeInfo(TInfo);
04161     return NameInfo;
04162   }
04163 
04164   case UnqualifiedId::IK_ConstructorName: {
04165     TypeSourceInfo *TInfo;
04166     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
04167     if (Ty.isNull())
04168       return DeclarationNameInfo();
04169     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
04170                                               Context.getCanonicalType(Ty)));
04171     NameInfo.setLoc(Name.StartLocation);
04172     NameInfo.setNamedTypeInfo(TInfo);
04173     return NameInfo;
04174   }
04175 
04176   case UnqualifiedId::IK_ConstructorTemplateId: {
04177     // In well-formed code, we can only have a constructor
04178     // template-id that refers to the current context, so go there
04179     // to find the actual type being constructed.
04180     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
04181     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
04182       return DeclarationNameInfo();
04183 
04184     // Determine the type of the class being constructed.
04185     QualType CurClassType = Context.getTypeDeclType(CurClass);
04186 
04187     // FIXME: Check two things: that the template-id names the same type as
04188     // CurClassType, and that the template-id does not occur when the name
04189     // was qualified.
04190 
04191     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
04192                                     Context.getCanonicalType(CurClassType)));
04193     NameInfo.setLoc(Name.StartLocation);
04194     // FIXME: should we retrieve TypeSourceInfo?
04195     NameInfo.setNamedTypeInfo(nullptr);
04196     return NameInfo;
04197   }
04198 
04199   case UnqualifiedId::IK_DestructorName: {
04200     TypeSourceInfo *TInfo;
04201     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
04202     if (Ty.isNull())
04203       return DeclarationNameInfo();
04204     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
04205                                               Context.getCanonicalType(Ty)));
04206     NameInfo.setLoc(Name.StartLocation);
04207     NameInfo.setNamedTypeInfo(TInfo);
04208     return NameInfo;
04209   }
04210 
04211   case UnqualifiedId::IK_TemplateId: {
04212     TemplateName TName = Name.TemplateId->Template.get();
04213     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
04214     return Context.getNameForTemplate(TName, TNameLoc);
04215   }
04216 
04217   } // switch (Name.getKind())
04218 
04219   llvm_unreachable("Unknown name kind");
04220 }
04221 
04222 static QualType getCoreType(QualType Ty) {
04223   do {
04224     if (Ty->isPointerType() || Ty->isReferenceType())
04225       Ty = Ty->getPointeeType();
04226     else if (Ty->isArrayType())
04227       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
04228     else
04229       return Ty.withoutLocalFastQualifiers();
04230   } while (true);
04231 }
04232 
04233 /// hasSimilarParameters - Determine whether the C++ functions Declaration
04234 /// and Definition have "nearly" matching parameters. This heuristic is
04235 /// used to improve diagnostics in the case where an out-of-line function
04236 /// definition doesn't match any declaration within the class or namespace.
04237 /// Also sets Params to the list of indices to the parameters that differ
04238 /// between the declaration and the definition. If hasSimilarParameters
04239 /// returns true and Params is empty, then all of the parameters match.
04240 static bool hasSimilarParameters(ASTContext &Context,
04241                                      FunctionDecl *Declaration,
04242                                      FunctionDecl *Definition,
04243                                      SmallVectorImpl<unsigned> &Params) {
04244   Params.clear();
04245   if (Declaration->param_size() != Definition->param_size())
04246     return false;
04247   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
04248     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
04249     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
04250 
04251     // The parameter types are identical
04252     if (Context.hasSameType(DefParamTy, DeclParamTy))
04253       continue;
04254 
04255     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
04256     QualType DefParamBaseTy = getCoreType(DefParamTy);
04257     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
04258     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
04259 
04260     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
04261         (DeclTyName && DeclTyName == DefTyName))
04262       Params.push_back(Idx);
04263     else  // The two parameters aren't even close
04264       return false;
04265   }
04266 
04267   return true;
04268 }
04269 
04270 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
04271 /// declarator needs to be rebuilt in the current instantiation.
04272 /// Any bits of declarator which appear before the name are valid for
04273 /// consideration here.  That's specifically the type in the decl spec
04274 /// and the base type in any member-pointer chunks.
04275 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
04276                                                     DeclarationName Name) {
04277   // The types we specifically need to rebuild are:
04278   //   - typenames, typeofs, and decltypes
04279   //   - types which will become injected class names
04280   // Of course, we also need to rebuild any type referencing such a
04281   // type.  It's safest to just say "dependent", but we call out a
04282   // few cases here.
04283 
04284   DeclSpec &DS = D.getMutableDeclSpec();
04285   switch (DS.getTypeSpecType()) {
04286   case DeclSpec::TST_typename:
04287   case DeclSpec::TST_typeofType:
04288   case DeclSpec::TST_underlyingType:
04289   case DeclSpec::TST_atomic: {
04290     // Grab the type from the parser.
04291     TypeSourceInfo *TSI = nullptr;
04292     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
04293     if (T.isNull() || !T->isDependentType()) break;
04294 
04295     // Make sure there's a type source info.  This isn't really much
04296     // of a waste; most dependent types should have type source info
04297     // attached already.
04298     if (!TSI)
04299       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
04300 
04301     // Rebuild the type in the current instantiation.
04302     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
04303     if (!TSI) return true;
04304 
04305     // Store the new type back in the decl spec.
04306     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
04307     DS.UpdateTypeRep(LocType);
04308     break;
04309   }
04310 
04311   case DeclSpec::TST_decltype:
04312   case DeclSpec::TST_typeofExpr: {
04313     Expr *E = DS.getRepAsExpr();
04314     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
04315     if (Result.isInvalid()) return true;
04316     DS.UpdateExprRep(Result.get());
04317     break;
04318   }
04319 
04320   default:
04321     // Nothing to do for these decl specs.
04322     break;
04323   }
04324 
04325   // It doesn't matter what order we do this in.
04326   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
04327     DeclaratorChunk &Chunk = D.getTypeObject(I);
04328 
04329     // The only type information in the declarator which can come
04330     // before the declaration name is the base type of a member
04331     // pointer.
04332     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
04333       continue;
04334 
04335     // Rebuild the scope specifier in-place.
04336     CXXScopeSpec &SS = Chunk.Mem.Scope();
04337     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
04338       return true;
04339   }
04340 
04341   return false;
04342 }
04343 
04344 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
04345   D.setFunctionDefinitionKind(FDK_Declaration);
04346   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
04347 
04348   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
04349       Dcl && Dcl->getDeclContext()->isFileContext())
04350     Dcl->setTopLevelDeclInObjCContainer();
04351 
04352   return Dcl;
04353 }
04354 
04355 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
04356 ///   If T is the name of a class, then each of the following shall have a 
04357 ///   name different from T:
04358 ///     - every static data member of class T;
04359 ///     - every member function of class T
04360 ///     - every member of class T that is itself a type;
04361 /// \returns true if the declaration name violates these rules.
04362 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
04363                                    DeclarationNameInfo NameInfo) {
04364   DeclarationName Name = NameInfo.getName();
04365 
04366   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 
04367     if (Record->getIdentifier() && Record->getDeclName() == Name) {
04368       Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
04369       return true;
04370     }
04371 
04372   return false;
04373 }
04374 
04375 /// \brief Diagnose a declaration whose declarator-id has the given 
04376 /// nested-name-specifier.
04377 ///
04378 /// \param SS The nested-name-specifier of the declarator-id.
04379 ///
04380 /// \param DC The declaration context to which the nested-name-specifier 
04381 /// resolves.
04382 ///
04383 /// \param Name The name of the entity being declared.
04384 ///
04385 /// \param Loc The location of the name of the entity being declared.
04386 ///
04387 /// \returns true if we cannot safely recover from this error, false otherwise.
04388 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
04389                                         DeclarationName Name,
04390                                         SourceLocation Loc) {
04391   DeclContext *Cur = CurContext;
04392   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
04393     Cur = Cur->getParent();
04394 
04395   // If the user provided a superfluous scope specifier that refers back to the
04396   // class in which the entity is already declared, diagnose and ignore it.
04397   //
04398   // class X {
04399   //   void X::f();
04400   // };
04401   //
04402   // Note, it was once ill-formed to give redundant qualification in all
04403   // contexts, but that rule was removed by DR482.
04404   if (Cur->Equals(DC)) {
04405     if (Cur->isRecord()) {
04406       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
04407                                       : diag::err_member_extra_qualification)
04408         << Name << FixItHint::CreateRemoval(SS.getRange());
04409       SS.clear();
04410     } else {
04411       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
04412     }
04413     return false;
04414   }
04415 
04416   // Check whether the qualifying scope encloses the scope of the original
04417   // declaration.
04418   if (!Cur->Encloses(DC)) {
04419     if (Cur->isRecord())
04420       Diag(Loc, diag::err_member_qualification)
04421         << Name << SS.getRange();
04422     else if (isa<TranslationUnitDecl>(DC))
04423       Diag(Loc, diag::err_invalid_declarator_global_scope)
04424         << Name << SS.getRange();
04425     else if (isa<FunctionDecl>(Cur))
04426       Diag(Loc, diag::err_invalid_declarator_in_function) 
04427         << Name << SS.getRange();
04428     else if (isa<BlockDecl>(Cur))
04429       Diag(Loc, diag::err_invalid_declarator_in_block) 
04430         << Name << SS.getRange();
04431     else
04432       Diag(Loc, diag::err_invalid_declarator_scope)
04433       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
04434     
04435     return true;
04436   }
04437 
04438   if (Cur->isRecord()) {
04439     // Cannot qualify members within a class.
04440     Diag(Loc, diag::err_member_qualification)
04441       << Name << SS.getRange();
04442     SS.clear();
04443     
04444     // C++ constructors and destructors with incorrect scopes can break
04445     // our AST invariants by having the wrong underlying types. If
04446     // that's the case, then drop this declaration entirely.
04447     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
04448          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
04449         !Context.hasSameType(Name.getCXXNameType(),
04450                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
04451       return true;
04452     
04453     return false;
04454   }
04455   
04456   // C++11 [dcl.meaning]p1:
04457   //   [...] "The nested-name-specifier of the qualified declarator-id shall
04458   //   not begin with a decltype-specifer"
04459   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
04460   while (SpecLoc.getPrefix())
04461     SpecLoc = SpecLoc.getPrefix();
04462   if (dyn_cast_or_null<DecltypeType>(
04463         SpecLoc.getNestedNameSpecifier()->getAsType()))
04464     Diag(Loc, diag::err_decltype_in_declarator)
04465       << SpecLoc.getTypeLoc().getSourceRange();
04466 
04467   return false;
04468 }
04469 
04470 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
04471                                   MultiTemplateParamsArg TemplateParamLists) {
04472   // TODO: consider using NameInfo for diagnostic.
04473   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
04474   DeclarationName Name = NameInfo.getName();
04475 
04476   // All of these full declarators require an identifier.  If it doesn't have
04477   // one, the ParsedFreeStandingDeclSpec action should be used.
04478   if (!Name) {
04479     if (!D.isInvalidType())  // Reject this if we think it is valid.
04480       Diag(D.getDeclSpec().getLocStart(),
04481            diag::err_declarator_need_ident)
04482         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
04483     return nullptr;
04484   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
04485     return nullptr;
04486 
04487   // The scope passed in may not be a decl scope.  Zip up the scope tree until
04488   // we find one that is.
04489   while ((S->getFlags() & Scope::DeclScope) == 0 ||
04490          (S->getFlags() & Scope::TemplateParamScope) != 0)
04491     S = S->getParent();
04492 
04493   DeclContext *DC = CurContext;
04494   if (D.getCXXScopeSpec().isInvalid())
04495     D.setInvalidType();
04496   else if (D.getCXXScopeSpec().isSet()) {
04497     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 
04498                                         UPPC_DeclarationQualifier))
04499       return nullptr;
04500 
04501     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
04502     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
04503     if (!DC || isa<EnumDecl>(DC)) {
04504       // If we could not compute the declaration context, it's because the
04505       // declaration context is dependent but does not refer to a class,
04506       // class template, or class template partial specialization. Complain
04507       // and return early, to avoid the coming semantic disaster.
04508       Diag(D.getIdentifierLoc(),
04509            diag::err_template_qualified_declarator_no_match)
04510         << D.getCXXScopeSpec().getScopeRep()
04511         << D.getCXXScopeSpec().getRange();
04512       return nullptr;
04513     }
04514     bool IsDependentContext = DC->isDependentContext();
04515 
04516     if (!IsDependentContext && 
04517         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
04518       return nullptr;
04519 
04520     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
04521       Diag(D.getIdentifierLoc(),
04522            diag::err_member_def_undefined_record)
04523         << Name << DC << D.getCXXScopeSpec().getRange();
04524       D.setInvalidType();
04525     } else if (!D.getDeclSpec().isFriendSpecified()) {
04526       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
04527                                       Name, D.getIdentifierLoc())) {
04528         if (DC->isRecord())
04529           return nullptr;
04530 
04531         D.setInvalidType();
04532       }
04533     }
04534 
04535     // Check whether we need to rebuild the type of the given
04536     // declaration in the current instantiation.
04537     if (EnteringContext && IsDependentContext &&
04538         TemplateParamLists.size() != 0) {
04539       ContextRAII SavedContext(*this, DC);
04540       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
04541         D.setInvalidType();
04542     }
04543   }
04544 
04545   if (DiagnoseClassNameShadow(DC, NameInfo))
04546     // If this is a typedef, we'll end up spewing multiple diagnostics.
04547     // Just return early; it's safer.
04548     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
04549       return nullptr;
04550 
04551   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
04552   QualType R = TInfo->getType();
04553 
04554   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
04555                                       UPPC_DeclarationType))
04556     D.setInvalidType();
04557 
04558   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
04559                         ForRedeclaration);
04560 
04561   // See if this is a redefinition of a variable in the same scope.
04562   if (!D.getCXXScopeSpec().isSet()) {
04563     bool IsLinkageLookup = false;
04564     bool CreateBuiltins = false;
04565 
04566     // If the declaration we're planning to build will be a function
04567     // or object with linkage, then look for another declaration with
04568     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
04569     //
04570     // If the declaration we're planning to build will be declared with
04571     // external linkage in the translation unit, create any builtin with
04572     // the same name.
04573     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
04574       /* Do nothing*/;
04575     else if (CurContext->isFunctionOrMethod() &&
04576              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
04577               R->isFunctionType())) {
04578       IsLinkageLookup = true;
04579       CreateBuiltins =
04580           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
04581     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
04582                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
04583       CreateBuiltins = true;
04584 
04585     if (IsLinkageLookup)
04586       Previous.clear(LookupRedeclarationWithLinkage);
04587 
04588     LookupName(Previous, S, CreateBuiltins);
04589   } else { // Something like "int foo::x;"
04590     LookupQualifiedName(Previous, DC);
04591 
04592     // C++ [dcl.meaning]p1:
04593     //   When the declarator-id is qualified, the declaration shall refer to a 
04594     //  previously declared member of the class or namespace to which the 
04595     //  qualifier refers (or, in the case of a namespace, of an element of the
04596     //  inline namespace set of that namespace (7.3.1)) or to a specialization
04597     //  thereof; [...] 
04598     //
04599     // Note that we already checked the context above, and that we do not have
04600     // enough information to make sure that Previous contains the declaration
04601     // we want to match. For example, given:
04602     //
04603     //   class X {
04604     //     void f();
04605     //     void f(float);
04606     //   };
04607     //
04608     //   void X::f(int) { } // ill-formed
04609     //
04610     // In this case, Previous will point to the overload set
04611     // containing the two f's declared in X, but neither of them
04612     // matches.
04613     
04614     // C++ [dcl.meaning]p1:
04615     //   [...] the member shall not merely have been introduced by a 
04616     //   using-declaration in the scope of the class or namespace nominated by 
04617     //   the nested-name-specifier of the declarator-id.
04618     RemoveUsingDecls(Previous);
04619   }
04620 
04621   if (Previous.isSingleResult() &&
04622       Previous.getFoundDecl()->isTemplateParameter()) {
04623     // Maybe we will complain about the shadowed template parameter.
04624     if (!D.isInvalidType())
04625       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
04626                                       Previous.getFoundDecl());
04627 
04628     // Just pretend that we didn't see the previous declaration.
04629     Previous.clear();
04630   }
04631 
04632   // In C++, the previous declaration we find might be a tag type
04633   // (class or enum). In this case, the new declaration will hide the
04634   // tag type. Note that this does does not apply if we're declaring a
04635   // typedef (C++ [dcl.typedef]p4).
04636   if (Previous.isSingleTagDecl() &&
04637       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
04638     Previous.clear();
04639 
04640   // Check that there are no default arguments other than in the parameters
04641   // of a function declaration (C++ only).
04642   if (getLangOpts().CPlusPlus)
04643     CheckExtraCXXDefaultArguments(D);
04644 
04645   NamedDecl *New;
04646 
04647   bool AddToScope = true;
04648   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
04649     if (TemplateParamLists.size()) {
04650       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
04651       return nullptr;
04652     }
04653 
04654     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
04655   } else if (R->isFunctionType()) {
04656     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
04657                                   TemplateParamLists,
04658                                   AddToScope);
04659   } else {
04660     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
04661                                   AddToScope);
04662   }
04663 
04664   if (!New)
04665     return nullptr;
04666 
04667   // If this has an identifier and is not an invalid redeclaration or 
04668   // function template specialization, add it to the scope stack.
04669   if (New->getDeclName() && AddToScope &&
04670        !(D.isRedeclaration() && New->isInvalidDecl())) {
04671     // Only make a locally-scoped extern declaration visible if it is the first
04672     // declaration of this entity. Qualified lookup for such an entity should
04673     // only find this declaration if there is no visible declaration of it.
04674     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
04675     PushOnScopeChains(New, S, AddToContext);
04676     if (!AddToContext)
04677       CurContext->addHiddenDecl(New);
04678   }
04679 
04680   return New;
04681 }
04682 
04683 /// Helper method to turn variable array types into constant array
04684 /// types in certain situations which would otherwise be errors (for
04685 /// GCC compatibility).
04686 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
04687                                                     ASTContext &Context,
04688                                                     bool &SizeIsNegative,
04689                                                     llvm::APSInt &Oversized) {
04690   // This method tries to turn a variable array into a constant
04691   // array even when the size isn't an ICE.  This is necessary
04692   // for compatibility with code that depends on gcc's buggy
04693   // constant expression folding, like struct {char x[(int)(char*)2];}
04694   SizeIsNegative = false;
04695   Oversized = 0;
04696   
04697   if (T->isDependentType())
04698     return QualType();
04699   
04700   QualifierCollector Qs;
04701   const Type *Ty = Qs.strip(T);
04702 
04703   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
04704     QualType Pointee = PTy->getPointeeType();
04705     QualType FixedType =
04706         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
04707                                             Oversized);
04708     if (FixedType.isNull()) return FixedType;
04709     FixedType = Context.getPointerType(FixedType);
04710     return Qs.apply(Context, FixedType);
04711   }
04712   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
04713     QualType Inner = PTy->getInnerType();
04714     QualType FixedType =
04715         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
04716                                             Oversized);
04717     if (FixedType.isNull()) return FixedType;
04718     FixedType = Context.getParenType(FixedType);
04719     return Qs.apply(Context, FixedType);
04720   }
04721 
04722   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
04723   if (!VLATy)
04724     return QualType();
04725   // FIXME: We should probably handle this case
04726   if (VLATy->getElementType()->isVariablyModifiedType())
04727     return QualType();
04728 
04729   llvm::APSInt Res;
04730   if (!VLATy->getSizeExpr() ||
04731       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
04732     return QualType();
04733 
04734   // Check whether the array size is negative.
04735   if (Res.isSigned() && Res.isNegative()) {
04736     SizeIsNegative = true;
04737     return QualType();
04738   }
04739 
04740   // Check whether the array is too large to be addressed.
04741   unsigned ActiveSizeBits
04742     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
04743                                               Res);
04744   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
04745     Oversized = Res;
04746     return QualType();
04747   }
04748   
04749   return Context.getConstantArrayType(VLATy->getElementType(),
04750                                       Res, ArrayType::Normal, 0);
04751 }
04752 
04753 static void
04754 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
04755   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
04756     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
04757     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
04758                                       DstPTL.getPointeeLoc());
04759     DstPTL.setStarLoc(SrcPTL.getStarLoc());
04760     return;
04761   }
04762   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
04763     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
04764     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
04765                                       DstPTL.getInnerLoc());
04766     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
04767     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
04768     return;
04769   }
04770   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
04771   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
04772   TypeLoc SrcElemTL = SrcATL.getElementLoc();
04773   TypeLoc DstElemTL = DstATL.getElementLoc();
04774   DstElemTL.initializeFullCopy(SrcElemTL);
04775   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
04776   DstATL.setSizeExpr(SrcATL.getSizeExpr());
04777   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
04778 }
04779 
04780 /// Helper method to turn variable array types into constant array
04781 /// types in certain situations which would otherwise be errors (for
04782 /// GCC compatibility).
04783 static TypeSourceInfo*
04784 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
04785                                               ASTContext &Context,
04786                                               bool &SizeIsNegative,
04787                                               llvm::APSInt &Oversized) {
04788   QualType FixedTy
04789     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
04790                                           SizeIsNegative, Oversized);
04791   if (FixedTy.isNull())
04792     return nullptr;
04793   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
04794   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
04795                                     FixedTInfo->getTypeLoc());
04796   return FixedTInfo;
04797 }
04798 
04799 /// \brief Register the given locally-scoped extern "C" declaration so
04800 /// that it can be found later for redeclarations. We include any extern "C"
04801 /// declaration that is not visible in the translation unit here, not just
04802 /// function-scope declarations.
04803 void
04804 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
04805   if (!getLangOpts().CPlusPlus &&
04806       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
04807     // Don't need to track declarations in the TU in C.
04808     return;
04809 
04810   // Note that we have a locally-scoped external with this name.
04811   // FIXME: There can be multiple such declarations if they are functions marked
04812   // __attribute__((overloadable)) declared in function scope in C.
04813   LocallyScopedExternCDecls[ND->getDeclName()] = ND;
04814 }
04815 
04816 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
04817   if (ExternalSource) {
04818     // Load locally-scoped external decls from the external source.
04819     // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
04820     SmallVector<NamedDecl *, 4> Decls;
04821     ExternalSource->ReadLocallyScopedExternCDecls(Decls);
04822     for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
04823       llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
04824         = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
04825       if (Pos == LocallyScopedExternCDecls.end())
04826         LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
04827     }
04828   }
04829 
04830   NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
04831   return D ? D->getMostRecentDecl() : nullptr;
04832 }
04833 
04834 /// \brief Diagnose function specifiers on a declaration of an identifier that
04835 /// does not identify a function.
04836 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
04837   // FIXME: We should probably indicate the identifier in question to avoid
04838   // confusion for constructs like "inline int a(), b;"
04839   if (DS.isInlineSpecified())
04840     Diag(DS.getInlineSpecLoc(),
04841          diag::err_inline_non_function);
04842 
04843   if (DS.isVirtualSpecified())
04844     Diag(DS.getVirtualSpecLoc(),
04845          diag::err_virtual_non_function);
04846 
04847   if (DS.isExplicitSpecified())
04848     Diag(DS.getExplicitSpecLoc(),
04849          diag::err_explicit_non_function);
04850 
04851   if (DS.isNoreturnSpecified())
04852     Diag(DS.getNoreturnSpecLoc(),
04853          diag::err_noreturn_non_function);
04854 }
04855 
04856 NamedDecl*
04857 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
04858                              TypeSourceInfo *TInfo, LookupResult &Previous) {
04859   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
04860   if (D.getCXXScopeSpec().isSet()) {
04861     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
04862       << D.getCXXScopeSpec().getRange();
04863     D.setInvalidType();
04864     // Pretend we didn't see the scope specifier.
04865     DC = CurContext;
04866     Previous.clear();
04867   }
04868 
04869   DiagnoseFunctionSpecifiers(D.getDeclSpec());
04870 
04871   if (D.getDeclSpec().isConstexprSpecified())
04872     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
04873       << 1;
04874 
04875   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
04876     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
04877       << D.getName().getSourceRange();
04878     return nullptr;
04879   }
04880 
04881   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
04882   if (!NewTD) return nullptr;
04883 
04884   // Handle attributes prior to checking for duplicates in MergeVarDecl
04885   ProcessDeclAttributes(S, NewTD, D);
04886 
04887   CheckTypedefForVariablyModifiedType(S, NewTD);
04888 
04889   bool Redeclaration = D.isRedeclaration();
04890   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
04891   D.setRedeclaration(Redeclaration);
04892   return ND;
04893 }
04894 
04895 void
04896 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
04897   // C99 6.7.7p2: If a typedef name specifies a variably modified type
04898   // then it shall have block scope.
04899   // Note that variably modified types must be fixed before merging the decl so
04900   // that redeclarations will match.
04901   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
04902   QualType T = TInfo->getType();
04903   if (T->isVariablyModifiedType()) {
04904     getCurFunction()->setHasBranchProtectedScope();
04905 
04906     if (S->getFnParent() == nullptr) {
04907       bool SizeIsNegative;
04908       llvm::APSInt Oversized;
04909       TypeSourceInfo *FixedTInfo =
04910         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
04911                                                       SizeIsNegative,
04912                                                       Oversized);
04913       if (FixedTInfo) {
04914         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
04915         NewTD->setTypeSourceInfo(FixedTInfo);
04916       } else {
04917         if (SizeIsNegative)
04918           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
04919         else if (T->isVariableArrayType())
04920           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
04921         else if (Oversized.getBoolValue())
04922           Diag(NewTD->getLocation(), diag::err_array_too_large) 
04923             << Oversized.toString(10);
04924         else
04925           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
04926         NewTD->setInvalidDecl();
04927       }
04928     }
04929   }
04930 }
04931 
04932 
04933 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
04934 /// declares a typedef-name, either using the 'typedef' type specifier or via
04935 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
04936 NamedDecl*
04937 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
04938                            LookupResult &Previous, bool &Redeclaration) {
04939   // Merge the decl with the existing one if appropriate. If the decl is
04940   // in an outer scope, it isn't the same thing.
04941   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
04942                        /*AllowInlineNamespace*/false);
04943   filterNonConflictingPreviousTypedefDecls(Context, NewTD, Previous);
04944   if (!Previous.empty()) {
04945     Redeclaration = true;
04946     MergeTypedefNameDecl(NewTD, Previous);
04947   }
04948 
04949   // If this is the C FILE type, notify the AST context.
04950   if (IdentifierInfo *II = NewTD->getIdentifier())
04951     if (!NewTD->isInvalidDecl() &&
04952         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
04953       if (II->isStr("FILE"))
04954         Context.setFILEDecl(NewTD);
04955       else if (II->isStr("jmp_buf"))
04956         Context.setjmp_bufDecl(NewTD);
04957       else if (II->isStr("sigjmp_buf"))
04958         Context.setsigjmp_bufDecl(NewTD);
04959       else if (II->isStr("ucontext_t"))
04960         Context.setucontext_tDecl(NewTD);
04961     }
04962 
04963   return NewTD;
04964 }
04965 
04966 /// \brief Determines whether the given declaration is an out-of-scope
04967 /// previous declaration.
04968 ///
04969 /// This routine should be invoked when name lookup has found a
04970 /// previous declaration (PrevDecl) that is not in the scope where a
04971 /// new declaration by the same name is being introduced. If the new
04972 /// declaration occurs in a local scope, previous declarations with
04973 /// linkage may still be considered previous declarations (C99
04974 /// 6.2.2p4-5, C++ [basic.link]p6).
04975 ///
04976 /// \param PrevDecl the previous declaration found by name
04977 /// lookup
04978 ///
04979 /// \param DC the context in which the new declaration is being
04980 /// declared.
04981 ///
04982 /// \returns true if PrevDecl is an out-of-scope previous declaration
04983 /// for a new delcaration with the same name.
04984 static bool
04985 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
04986                                 ASTContext &Context) {
04987   if (!PrevDecl)
04988     return false;
04989 
04990   if (!PrevDecl->hasLinkage())
04991     return false;
04992 
04993   if (Context.getLangOpts().CPlusPlus) {
04994     // C++ [basic.link]p6:
04995     //   If there is a visible declaration of an entity with linkage
04996     //   having the same name and type, ignoring entities declared
04997     //   outside the innermost enclosing namespace scope, the block
04998     //   scope declaration declares that same entity and receives the
04999     //   linkage of the previous declaration.
05000     DeclContext *OuterContext = DC->getRedeclContext();
05001     if (!OuterContext->isFunctionOrMethod())
05002       // This rule only applies to block-scope declarations.
05003       return false;
05004     
05005     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
05006     if (PrevOuterContext->isRecord())
05007       // We found a member function: ignore it.
05008       return false;
05009     
05010     // Find the innermost enclosing namespace for the new and
05011     // previous declarations.
05012     OuterContext = OuterContext->getEnclosingNamespaceContext();
05013     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
05014 
05015     // The previous declaration is in a different namespace, so it
05016     // isn't the same function.
05017     if (!OuterContext->Equals(PrevOuterContext))
05018       return false;
05019   }
05020 
05021   return true;
05022 }
05023 
05024 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
05025   CXXScopeSpec &SS = D.getCXXScopeSpec();
05026   if (!SS.isSet()) return;
05027   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
05028 }
05029 
05030 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
05031   QualType type = decl->getType();
05032   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
05033   if (lifetime == Qualifiers::OCL_Autoreleasing) {
05034     // Various kinds of declaration aren't allowed to be __autoreleasing.
05035     unsigned kind = -1U;
05036     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
05037       if (var->hasAttr<BlocksAttr>())
05038         kind = 0; // __block
05039       else if (!var->hasLocalStorage())
05040         kind = 1; // global
05041     } else if (isa<ObjCIvarDecl>(decl)) {
05042       kind = 3; // ivar
05043     } else if (isa<FieldDecl>(decl)) {
05044       kind = 2; // field
05045     }
05046 
05047     if (kind != -1U) {
05048       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
05049         << kind;
05050     }
05051   } else if (lifetime == Qualifiers::OCL_None) {
05052     // Try to infer lifetime.
05053     if (!type->isObjCLifetimeType())
05054       return false;
05055 
05056     lifetime = type->getObjCARCImplicitLifetime();
05057     type = Context.getLifetimeQualifiedType(type, lifetime);
05058     decl->setType(type);
05059   }
05060   
05061   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
05062     // Thread-local variables cannot have lifetime.
05063     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
05064         var->getTLSKind()) {
05065       Diag(var->getLocation(), diag::err_arc_thread_ownership)
05066         << var->getType();
05067       return true;
05068     }
05069   }
05070   
05071   return false;
05072 }
05073 
05074 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
05075   // Ensure that an auto decl is deduced otherwise the checks below might cache
05076   // the wrong linkage.
05077   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
05078 
05079   // 'weak' only applies to declarations with external linkage.
05080   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
05081     if (!ND.isExternallyVisible()) {
05082       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
05083       ND.dropAttr<WeakAttr>();
05084     }
05085   }
05086   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
05087     if (ND.isExternallyVisible()) {
05088       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
05089       ND.dropAttr<WeakRefAttr>();
05090     }
05091   }
05092 
05093   // 'selectany' only applies to externally visible varable declarations.
05094   // It does not apply to functions.
05095   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
05096     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
05097       S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
05098       ND.dropAttr<SelectAnyAttr>();
05099     }
05100   }
05101 
05102   // dll attributes require external linkage.
05103   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
05104     if (!ND.isExternallyVisible()) {
05105       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
05106         << &ND << Attr;
05107       ND.setInvalidDecl();
05108     }
05109   }
05110 }
05111 
05112 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
05113                                            NamedDecl *NewDecl,
05114                                            bool IsSpecialization) {
05115   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
05116     OldDecl = OldTD->getTemplatedDecl();
05117   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
05118     NewDecl = NewTD->getTemplatedDecl();
05119 
05120   if (!OldDecl || !NewDecl)
05121     return;
05122 
05123   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
05124   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
05125   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
05126   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
05127 
05128   // dllimport and dllexport are inheritable attributes so we have to exclude
05129   // inherited attribute instances.
05130   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
05131                     (NewExportAttr && !NewExportAttr->isInherited());
05132 
05133   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
05134   // the only exception being explicit specializations.
05135   // Implicitly generated declarations are also excluded for now because there
05136   // is no other way to switch these to use dllimport or dllexport.
05137   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
05138 
05139   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
05140     // If the declaration hasn't been used yet, allow with a warning for
05141     // free functions and global variables.
05142     bool JustWarn = false;
05143     if (!OldDecl->isUsed() && !OldDecl->isCXXClassMember()) {
05144       auto *VD = dyn_cast<VarDecl>(OldDecl);
05145       if (VD && !VD->getDescribedVarTemplate())
05146         JustWarn = true;
05147       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
05148       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
05149         JustWarn = true;
05150     }
05151 
05152     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
05153                                : diag::err_attribute_dll_redeclaration;
05154     S.Diag(NewDecl->getLocation(), DiagID)
05155         << NewDecl
05156         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
05157     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
05158     if (!JustWarn) {
05159       NewDecl->setInvalidDecl();
05160       return;
05161     }
05162   }
05163 
05164   // A redeclaration is not allowed to drop a dllimport attribute, the only
05165   // exceptions being inline function definitions, local extern declarations,
05166   // and qualified friend declarations.
05167   // NB: MSVC converts such a declaration to dllexport.
05168   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
05169   if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
05170     // Ignore static data because out-of-line definitions are diagnosed
05171     // separately.
05172     IsStaticDataMember = VD->isStaticDataMember();
05173   else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
05174     IsInline = FD->isInlined();
05175     IsQualifiedFriend = FD->getQualifier() &&
05176                         FD->getFriendObjectKind() == Decl::FOK_Declared;
05177   }
05178 
05179   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
05180       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
05181     S.Diag(NewDecl->getLocation(),
05182            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
05183       << NewDecl << OldImportAttr;
05184     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
05185     S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
05186     OldDecl->dropAttr<DLLImportAttr>();
05187     NewDecl->dropAttr<DLLImportAttr>();
05188   } else if (IsInline && OldImportAttr &&
05189              !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
05190     // In MinGW, seeing a function declared inline drops the dllimport attribute.
05191     OldDecl->dropAttr<DLLImportAttr>();
05192     NewDecl->dropAttr<DLLImportAttr>();
05193     S.Diag(NewDecl->getLocation(),
05194            diag::warn_dllimport_dropped_from_inline_function)
05195         << NewDecl << OldImportAttr;
05196   }
05197 }
05198 
05199 /// Given that we are within the definition of the given function,
05200 /// will that definition behave like C99's 'inline', where the
05201 /// definition is discarded except for optimization purposes?
05202 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
05203   // Try to avoid calling GetGVALinkageForFunction.
05204 
05205   // All cases of this require the 'inline' keyword.
05206   if (!FD->isInlined()) return false;
05207 
05208   // This is only possible in C++ with the gnu_inline attribute.
05209   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
05210     return false;
05211 
05212   // Okay, go ahead and call the relatively-more-expensive function.
05213 
05214 #ifndef NDEBUG
05215   // AST quite reasonably asserts that it's working on a function
05216   // definition.  We don't really have a way to tell it that we're
05217   // currently defining the function, so just lie to it in +Asserts
05218   // builds.  This is an awful hack.
05219   FD->setLazyBody(1);
05220 #endif
05221 
05222   bool isC99Inline =
05223       S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
05224 
05225 #ifndef NDEBUG
05226   FD->setLazyBody(0);
05227 #endif
05228 
05229   return isC99Inline;
05230 }
05231 
05232 /// Determine whether a variable is extern "C" prior to attaching
05233 /// an initializer. We can't just call isExternC() here, because that
05234 /// will also compute and cache whether the declaration is externally
05235 /// visible, which might change when we attach the initializer.
05236 ///
05237 /// This can only be used if the declaration is known to not be a
05238 /// redeclaration of an internal linkage declaration.
05239 ///
05240 /// For instance:
05241 ///
05242 ///   auto x = []{};
05243 ///
05244 /// Attaching the initializer here makes this declaration not externally
05245 /// visible, because its type has internal linkage.
05246 ///
05247 /// FIXME: This is a hack.
05248 template<typename T>
05249 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
05250   if (S.getLangOpts().CPlusPlus) {
05251     // In C++, the overloadable attribute negates the effects of extern "C".
05252     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
05253       return false;
05254   }
05255   return D->isExternC();
05256 }
05257 
05258 static bool shouldConsiderLinkage(const VarDecl *VD) {
05259   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
05260   if (DC->isFunctionOrMethod())
05261     return VD->hasExternalStorage();
05262   if (DC->isFileContext())
05263     return true;
05264   if (DC->isRecord())
05265     return false;
05266   llvm_unreachable("Unexpected context");
05267 }
05268 
05269 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
05270   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
05271   if (DC->isFileContext() || DC->isFunctionOrMethod())
05272     return true;
05273   if (DC->isRecord())
05274     return false;
05275   llvm_unreachable("Unexpected context");
05276 }
05277 
05278 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
05279                           AttributeList::Kind Kind) {
05280   for (const AttributeList *L = AttrList; L; L = L->getNext())
05281     if (L->getKind() == Kind)
05282       return true;
05283   return false;
05284 }
05285 
05286 static bool hasParsedAttr(Scope *S, const Declarator &PD,
05287                           AttributeList::Kind Kind) {
05288   // Check decl attributes on the DeclSpec.
05289   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
05290     return true;
05291 
05292   // Walk the declarator structure, checking decl attributes that were in a type
05293   // position to the decl itself.
05294   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
05295     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
05296       return true;
05297   }
05298 
05299   // Finally, check attributes on the decl itself.
05300   return hasParsedAttr(S, PD.getAttributes(), Kind);
05301 }
05302 
05303 /// Adjust the \c DeclContext for a function or variable that might be a
05304 /// function-local external declaration.
05305 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
05306   if (!DC->isFunctionOrMethod())
05307     return false;
05308 
05309   // If this is a local extern function or variable declared within a function
05310   // template, don't add it into the enclosing namespace scope until it is
05311   // instantiated; it might have a dependent type right now.
05312   if (DC->isDependentContext())
05313     return true;
05314 
05315   // C++11 [basic.link]p7:
05316   //   When a block scope declaration of an entity with linkage is not found to
05317   //   refer to some other declaration, then that entity is a member of the
05318   //   innermost enclosing namespace.
05319   //
05320   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
05321   // semantically-enclosing namespace, not a lexically-enclosing one.
05322   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
05323     DC = DC->getParent();
05324   return true;
05325 }
05326 
05327 NamedDecl *
05328 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
05329                               TypeSourceInfo *TInfo, LookupResult &Previous,
05330                               MultiTemplateParamsArg TemplateParamLists,
05331                               bool &AddToScope) {
05332   QualType R = TInfo->getType();
05333   DeclarationName Name = GetNameForDeclarator(D).getName();
05334 
05335   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
05336   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
05337 
05338   // dllimport globals without explicit storage class are treated as extern. We
05339   // have to change the storage class this early to get the right DeclContext.
05340   if (SC == SC_None && !DC->isRecord() &&
05341       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
05342       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
05343     SC = SC_Extern;
05344 
05345   DeclContext *OriginalDC = DC;
05346   bool IsLocalExternDecl = SC == SC_Extern &&
05347                            adjustContextForLocalExternDecl(DC);
05348 
05349   if (getLangOpts().OpenCL) {
05350     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
05351     QualType NR = R;
05352     while (NR->isPointerType()) {
05353       if (NR->isFunctionPointerType()) {
05354         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
05355         D.setInvalidType();
05356         break;
05357       }
05358       NR = NR->getPointeeType();
05359     }
05360 
05361     if (!getOpenCLOptions().cl_khr_fp16) {
05362       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
05363       // half array type (unless the cl_khr_fp16 extension is enabled).
05364       if (Context.getBaseElementType(R)->isHalfType()) {
05365         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
05366         D.setInvalidType();
05367       }
05368     }
05369   }
05370 
05371   if (SCSpec == DeclSpec::SCS_mutable) {
05372     // mutable can only appear on non-static class members, so it's always
05373     // an error here
05374     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
05375     D.setInvalidType();
05376     SC = SC_None;
05377   }
05378 
05379   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
05380       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
05381                               D.getDeclSpec().getStorageClassSpecLoc())) {
05382     // In C++11, the 'register' storage class specifier is deprecated.
05383     // Suppress the warning in system macros, it's used in macros in some
05384     // popular C system headers, such as in glibc's htonl() macro.
05385     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
05386          diag::warn_deprecated_register)
05387       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
05388   }
05389 
05390   IdentifierInfo *II = Name.getAsIdentifierInfo();
05391   if (!II) {
05392     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
05393       << Name;
05394     return nullptr;
05395   }
05396 
05397   DiagnoseFunctionSpecifiers(D.getDeclSpec());
05398 
05399   if (!DC->isRecord() && S->getFnParent() == nullptr) {
05400     // C99 6.9p2: The storage-class specifiers auto and register shall not
05401     // appear in the declaration specifiers in an external declaration.
05402     // Global Register+Asm is a GNU extension we support.
05403     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
05404       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
05405       D.setInvalidType();
05406     }
05407   }
05408 
05409   if (getLangOpts().OpenCL) {
05410     // Set up the special work-group-local storage class for variables in the
05411     // OpenCL __local address space.
05412     if (R.getAddressSpace() == LangAS::opencl_local) {
05413       SC = SC_OpenCLWorkGroupLocal;
05414     }
05415 
05416     // OpenCL v1.2 s6.9.b p4:
05417     // The sampler type cannot be used with the __local and __global address
05418     // space qualifiers.
05419     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
05420       R.getAddressSpace() == LangAS::opencl_global)) {
05421       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
05422     }
05423 
05424     // OpenCL 1.2 spec, p6.9 r:
05425     // The event type cannot be used to declare a program scope variable.
05426     // The event type cannot be used with the __local, __constant and __global
05427     // address space qualifiers.
05428     if (R->isEventT()) {
05429       if (S->getParent() == nullptr) {
05430         Diag(D.getLocStart(), diag::err_event_t_global_var);
05431         D.setInvalidType();
05432       }
05433 
05434       if (R.getAddressSpace()) {
05435         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
05436         D.setInvalidType();
05437       }
05438     }
05439   }
05440 
05441   bool IsExplicitSpecialization = false;
05442   bool IsVariableTemplateSpecialization = false;
05443   bool IsPartialSpecialization = false;
05444   bool IsVariableTemplate = false;
05445   VarDecl *NewVD = nullptr;
05446   VarTemplateDecl *NewTemplate = nullptr;
05447   TemplateParameterList *TemplateParams = nullptr;
05448   if (!getLangOpts().CPlusPlus) {
05449     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
05450                             D.getIdentifierLoc(), II,
05451                             R, TInfo, SC);
05452   
05453     if (D.isInvalidType())
05454       NewVD->setInvalidDecl();
05455   } else {
05456     bool Invalid = false;
05457 
05458     if (DC->isRecord() && !CurContext->isRecord()) {
05459       // This is an out-of-line definition of a static data member.
05460       switch (SC) {
05461       case SC_None:
05462         break;
05463       case SC_Static:
05464         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
05465              diag::err_static_out_of_line)
05466           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
05467         break;
05468       case SC_Auto:
05469       case SC_Register:
05470       case SC_Extern:
05471         // [dcl.stc] p2: The auto or register specifiers shall be applied only
05472         // to names of variables declared in a block or to function parameters.
05473         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
05474         // of class members
05475 
05476         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
05477              diag::err_storage_class_for_static_member)
05478           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
05479         break;
05480       case SC_PrivateExtern:
05481         llvm_unreachable("C storage class in c++!");
05482       case SC_OpenCLWorkGroupLocal:
05483         llvm_unreachable("OpenCL storage class in c++!");
05484       }
05485     }    
05486 
05487     if (SC == SC_Static && CurContext->isRecord()) {
05488       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
05489         if (RD->isLocalClass())
05490           Diag(D.getIdentifierLoc(),
05491                diag::err_static_data_member_not_allowed_in_local_class)
05492             << Name << RD->getDeclName();
05493 
05494         // C++98 [class.union]p1: If a union contains a static data member,
05495         // the program is ill-formed. C++11 drops this restriction.
05496         if (RD->isUnion())
05497           Diag(D.getIdentifierLoc(),
05498                getLangOpts().CPlusPlus11
05499                  ? diag::warn_cxx98_compat_static_data_member_in_union
05500                  : diag::ext_static_data_member_in_union) << Name;
05501         // We conservatively disallow static data members in anonymous structs.
05502         else if (!RD->getDeclName())
05503           Diag(D.getIdentifierLoc(),
05504                diag::err_static_data_member_not_allowed_in_anon_struct)
05505             << Name << RD->isUnion();
05506       }
05507     }
05508 
05509     // Match up the template parameter lists with the scope specifier, then
05510     // determine whether we have a template or a template specialization.
05511     TemplateParams = MatchTemplateParametersToScopeSpecifier(
05512         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
05513         D.getCXXScopeSpec(),
05514         D.getName().getKind() == UnqualifiedId::IK_TemplateId
05515             ? D.getName().TemplateId
05516             : nullptr,
05517         TemplateParamLists,
05518         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
05519 
05520     if (TemplateParams) {
05521       if (!TemplateParams->size() &&
05522           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
05523         // There is an extraneous 'template<>' for this variable. Complain
05524         // about it, but allow the declaration of the variable.
05525         Diag(TemplateParams->getTemplateLoc(),
05526              diag::err_template_variable_noparams)
05527           << II
05528           << SourceRange(TemplateParams->getTemplateLoc(),
05529                          TemplateParams->getRAngleLoc());
05530         TemplateParams = nullptr;
05531       } else {
05532         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
05533           // This is an explicit specialization or a partial specialization.
05534           // FIXME: Check that we can declare a specialization here.
05535           IsVariableTemplateSpecialization = true;
05536           IsPartialSpecialization = TemplateParams->size() > 0;
05537         } else { // if (TemplateParams->size() > 0)
05538           // This is a template declaration.
05539           IsVariableTemplate = true;
05540 
05541           // Check that we can declare a template here.
05542           if (CheckTemplateDeclScope(S, TemplateParams))
05543             return nullptr;
05544 
05545           // Only C++1y supports variable templates (N3651).
05546           Diag(D.getIdentifierLoc(),
05547                getLangOpts().CPlusPlus14
05548                    ? diag::warn_cxx11_compat_variable_template
05549                    : diag::ext_variable_template);
05550         }
05551       }
05552     } else {
05553       assert(D.getName().getKind() != UnqualifiedId::IK_TemplateId &&
05554              "should have a 'template<>' for this decl");
05555     }
05556 
05557     if (IsVariableTemplateSpecialization) {
05558       SourceLocation TemplateKWLoc =
05559           TemplateParamLists.size() > 0
05560               ? TemplateParamLists[0]->getTemplateLoc()
05561               : SourceLocation();
05562       DeclResult Res = ActOnVarTemplateSpecialization(
05563           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
05564           IsPartialSpecialization);
05565       if (Res.isInvalid())
05566         return nullptr;
05567       NewVD = cast<VarDecl>(Res.get());
05568       AddToScope = false;
05569     } else
05570       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
05571                               D.getIdentifierLoc(), II, R, TInfo, SC);
05572 
05573     // If this is supposed to be a variable template, create it as such.
05574     if (IsVariableTemplate) {
05575       NewTemplate =
05576           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
05577                                   TemplateParams, NewVD);
05578       NewVD->setDescribedVarTemplate(NewTemplate);
05579     }
05580 
05581     // If this decl has an auto type in need of deduction, make a note of the
05582     // Decl so we can diagnose uses of it in its own initializer.
05583     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
05584       ParsingInitForAutoVars.insert(NewVD);
05585 
05586     if (D.isInvalidType() || Invalid) {
05587       NewVD->setInvalidDecl();
05588       if (NewTemplate)
05589         NewTemplate->setInvalidDecl();
05590     }
05591 
05592     SetNestedNameSpecifier(NewVD, D);
05593 
05594     // If we have any template parameter lists that don't directly belong to
05595     // the variable (matching the scope specifier), store them.
05596     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
05597     if (TemplateParamLists.size() > VDTemplateParamLists)
05598       NewVD->setTemplateParameterListsInfo(
05599           Context, TemplateParamLists.size() - VDTemplateParamLists,
05600           TemplateParamLists.data());
05601 
05602     if (D.getDeclSpec().isConstexprSpecified())
05603       NewVD->setConstexpr(true);
05604   }
05605 
05606   // Set the lexical context. If the declarator has a C++ scope specifier, the
05607   // lexical context will be different from the semantic context.
05608   NewVD->setLexicalDeclContext(CurContext);
05609   if (NewTemplate)
05610     NewTemplate->setLexicalDeclContext(CurContext);
05611 
05612   if (IsLocalExternDecl)
05613     NewVD->setLocalExternDecl();
05614 
05615   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
05616     if (NewVD->hasLocalStorage()) {
05617       // C++11 [dcl.stc]p4:
05618       //   When thread_local is applied to a variable of block scope the
05619       //   storage-class-specifier static is implied if it does not appear
05620       //   explicitly.
05621       // Core issue: 'static' is not implied if the variable is declared
05622       //   'extern'.
05623       if (SCSpec == DeclSpec::SCS_unspecified &&
05624           TSCS == DeclSpec::TSCS_thread_local &&
05625           DC->isFunctionOrMethod())
05626         NewVD->setTSCSpec(TSCS);
05627       else
05628         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
05629              diag::err_thread_non_global)
05630           << DeclSpec::getSpecifierName(TSCS);
05631     } else if (!Context.getTargetInfo().isTLSSupported())
05632       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
05633            diag::err_thread_unsupported);
05634     else
05635       NewVD->setTSCSpec(TSCS);
05636   }
05637 
05638   // C99 6.7.4p3
05639   //   An inline definition of a function with external linkage shall
05640   //   not contain a definition of a modifiable object with static or
05641   //   thread storage duration...
05642   // We only apply this when the function is required to be defined
05643   // elsewhere, i.e. when the function is not 'extern inline'.  Note
05644   // that a local variable with thread storage duration still has to
05645   // be marked 'static'.  Also note that it's possible to get these
05646   // semantics in C++ using __attribute__((gnu_inline)).
05647   if (SC == SC_Static && S->getFnParent() != nullptr &&
05648       !NewVD->getType().isConstQualified()) {
05649     FunctionDecl *CurFD = getCurFunctionDecl();
05650     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
05651       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
05652            diag::warn_static_local_in_extern_inline);
05653       MaybeSuggestAddingStaticToDecl(CurFD);
05654     }
05655   }
05656 
05657   if (D.getDeclSpec().isModulePrivateSpecified()) {
05658     if (IsVariableTemplateSpecialization)
05659       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
05660           << (IsPartialSpecialization ? 1 : 0)
05661           << FixItHint::CreateRemoval(
05662                  D.getDeclSpec().getModulePrivateSpecLoc());
05663     else if (IsExplicitSpecialization)
05664       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
05665         << 2
05666         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
05667     else if (NewVD->hasLocalStorage())
05668       Diag(NewVD->getLocation(), diag::err_module_private_local)
05669         << 0 << NewVD->getDeclName()
05670         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
05671         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
05672     else {
05673       NewVD->setModulePrivate();
05674       if (NewTemplate)
05675         NewTemplate->setModulePrivate();
05676     }
05677   }
05678 
05679   // Handle attributes prior to checking for duplicates in MergeVarDecl
05680   ProcessDeclAttributes(S, NewVD, D);
05681 
05682   if (getLangOpts().CUDA) {
05683     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
05684     // storage [duration]."
05685     if (SC == SC_None && S->getFnParent() != nullptr &&
05686         (NewVD->hasAttr<CUDASharedAttr>() ||
05687          NewVD->hasAttr<CUDAConstantAttr>())) {
05688       NewVD->setStorageClass(SC_Static);
05689     }
05690   }
05691 
05692   // Ensure that dllimport globals without explicit storage class are treated as
05693   // extern. The storage class is set above using parsed attributes. Now we can
05694   // check the VarDecl itself.
05695   assert(!NewVD->hasAttr<DLLImportAttr>() ||
05696          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
05697          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
05698 
05699   // In auto-retain/release, infer strong retension for variables of
05700   // retainable type.
05701   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
05702     NewVD->setInvalidDecl();
05703 
05704   // Handle GNU asm-label extension (encoded as an attribute).
05705   if (Expr *E = (Expr*)D.getAsmLabel()) {
05706     // The parser guarantees this is a string.
05707     StringLiteral *SE = cast<StringLiteral>(E);
05708     StringRef Label = SE->getString();
05709     if (S->getFnParent() != nullptr) {
05710       switch (SC) {
05711       case SC_None:
05712       case SC_Auto:
05713         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
05714         break;
05715       case SC_Register:
05716         // Local Named register
05717         if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
05718           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
05719         break;
05720       case SC_Static:
05721       case SC_Extern:
05722       case SC_PrivateExtern:
05723       case SC_OpenCLWorkGroupLocal:
05724         break;
05725       }
05726     } else if (SC == SC_Register) {
05727       // Global Named register
05728       if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
05729         Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
05730       if (!R->isIntegralType(Context) && !R->isPointerType()) {
05731         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
05732         NewVD->setInvalidDecl(true);
05733       }
05734     }
05735 
05736     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
05737                                                 Context, Label, 0));
05738   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
05739     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
05740       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
05741     if (I != ExtnameUndeclaredIdentifiers.end()) {
05742       NewVD->addAttr(I->second);
05743       ExtnameUndeclaredIdentifiers.erase(I);
05744     }
05745   }
05746 
05747   // Diagnose shadowed variables before filtering for scope.
05748   if (D.getCXXScopeSpec().isEmpty())
05749     CheckShadow(S, NewVD, Previous);
05750 
05751   // Don't consider existing declarations that are in a different
05752   // scope and are out-of-semantic-context declarations (if the new
05753   // declaration has linkage).
05754   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
05755                        D.getCXXScopeSpec().isNotEmpty() ||
05756                        IsExplicitSpecialization ||
05757                        IsVariableTemplateSpecialization);
05758 
05759   // Check whether the previous declaration is in the same block scope. This
05760   // affects whether we merge types with it, per C++11 [dcl.array]p3.
05761   if (getLangOpts().CPlusPlus &&
05762       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
05763     NewVD->setPreviousDeclInSameBlockScope(
05764         Previous.isSingleResult() && !Previous.isShadowed() &&
05765         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
05766 
05767   if (!getLangOpts().CPlusPlus) {
05768     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
05769   } else {
05770     // If this is an explicit specialization of a static data member, check it.
05771     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
05772         CheckMemberSpecialization(NewVD, Previous))
05773       NewVD->setInvalidDecl();
05774 
05775     // Merge the decl with the existing one if appropriate.
05776     if (!Previous.empty()) {
05777       if (Previous.isSingleResult() &&
05778           isa<FieldDecl>(Previous.getFoundDecl()) &&
05779           D.getCXXScopeSpec().isSet()) {
05780         // The user tried to define a non-static data member
05781         // out-of-line (C++ [dcl.meaning]p1).
05782         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
05783           << D.getCXXScopeSpec().getRange();
05784         Previous.clear();
05785         NewVD->setInvalidDecl();
05786       }
05787     } else if (D.getCXXScopeSpec().isSet()) {
05788       // No previous declaration in the qualifying scope.
05789       Diag(D.getIdentifierLoc(), diag::err_no_member)
05790         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
05791         << D.getCXXScopeSpec().getRange();
05792       NewVD->setInvalidDecl();
05793     }
05794 
05795     if (!IsVariableTemplateSpecialization)
05796       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
05797 
05798     if (NewTemplate) {
05799       VarTemplateDecl *PrevVarTemplate =
05800           NewVD->getPreviousDecl()
05801               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
05802               : nullptr;
05803 
05804       // Check the template parameter list of this declaration, possibly
05805       // merging in the template parameter list from the previous variable
05806       // template declaration.
05807       if (CheckTemplateParameterList(
05808               TemplateParams,
05809               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
05810                               : nullptr,
05811               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
05812                DC->isDependentContext())
05813                   ? TPC_ClassTemplateMember
05814                   : TPC_VarTemplate))
05815         NewVD->setInvalidDecl();
05816 
05817       // If we are providing an explicit specialization of a static variable
05818       // template, make a note of that.
05819       if (PrevVarTemplate &&
05820           PrevVarTemplate->getInstantiatedFromMemberTemplate())
05821         PrevVarTemplate->setMemberSpecialization();
05822     }
05823   }
05824 
05825   ProcessPragmaWeak(S, NewVD);
05826 
05827   // If this is the first declaration of an extern C variable, update
05828   // the map of such variables.
05829   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
05830       isIncompleteDeclExternC(*this, NewVD))
05831     RegisterLocallyScopedExternCDecl(NewVD, S);
05832 
05833   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
05834     Decl *ManglingContextDecl;
05835     if (MangleNumberingContext *MCtx =
05836             getCurrentMangleNumberContext(NewVD->getDeclContext(),
05837                                           ManglingContextDecl)) {
05838       Context.setManglingNumber(
05839           NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
05840       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
05841     }
05842   }
05843 
05844   if (D.isRedeclaration() && !Previous.empty()) {
05845     checkDLLAttributeRedeclaration(
05846         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
05847         IsExplicitSpecialization);
05848   }
05849 
05850   if (NewTemplate) {
05851     if (NewVD->isInvalidDecl())
05852       NewTemplate->setInvalidDecl();
05853     ActOnDocumentableDecl(NewTemplate);
05854     return NewTemplate;
05855   }
05856 
05857   return NewVD;
05858 }
05859 
05860 /// \brief Diagnose variable or built-in function shadowing.  Implements
05861 /// -Wshadow.
05862 ///
05863 /// This method is called whenever a VarDecl is added to a "useful"
05864 /// scope.
05865 ///
05866 /// \param S the scope in which the shadowing name is being declared
05867 /// \param R the lookup of the name
05868 ///
05869 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
05870   // Return if warning is ignored.
05871   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
05872     return;
05873 
05874   // Don't diagnose declarations at file scope.
05875   if (D->hasGlobalStorage())
05876     return;
05877 
05878   DeclContext *NewDC = D->getDeclContext();
05879 
05880   // Only diagnose if we're shadowing an unambiguous field or variable.
05881   if (R.getResultKind() != LookupResult::Found)
05882     return;
05883 
05884   NamedDecl* ShadowedDecl = R.getFoundDecl();
05885   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
05886     return;
05887 
05888   // Fields are not shadowed by variables in C++ static methods.
05889   if (isa<FieldDecl>(ShadowedDecl))
05890     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
05891       if (MD->isStatic())
05892         return;
05893 
05894   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
05895     if (shadowedVar->isExternC()) {
05896       // For shadowing external vars, make sure that we point to the global
05897       // declaration, not a locally scoped extern declaration.
05898       for (auto I : shadowedVar->redecls())
05899         if (I->isFileVarDecl()) {
05900           ShadowedDecl = I;
05901           break;
05902         }
05903     }
05904 
05905   DeclContext *OldDC = ShadowedDecl->getDeclContext();
05906 
05907   // Only warn about certain kinds of shadowing for class members.
05908   if (NewDC && NewDC->isRecord()) {
05909     // In particular, don't warn about shadowing non-class members.
05910     if (!OldDC->isRecord())
05911       return;
05912 
05913     // TODO: should we warn about static data members shadowing
05914     // static data members from base classes?
05915     
05916     // TODO: don't diagnose for inaccessible shadowed members.
05917     // This is hard to do perfectly because we might friend the
05918     // shadowing context, but that's just a false negative.
05919   }
05920 
05921   // Determine what kind of declaration we're shadowing.
05922   unsigned Kind;
05923   if (isa<RecordDecl>(OldDC)) {
05924     if (isa<FieldDecl>(ShadowedDecl))
05925       Kind = 3; // field
05926     else
05927       Kind = 2; // static data member
05928   } else if (OldDC->isFileContext())
05929     Kind = 1; // global
05930   else
05931     Kind = 0; // local
05932 
05933   DeclarationName Name = R.getLookupName();
05934 
05935   // Emit warning and note.
05936   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
05937     return;
05938   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
05939   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
05940 }
05941 
05942 /// \brief Check -Wshadow without the advantage of a previous lookup.
05943 void Sema::CheckShadow(Scope *S, VarDecl *D) {
05944   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
05945     return;
05946 
05947   LookupResult R(*this, D->getDeclName(), D->getLocation(),
05948                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
05949   LookupName(R, S);
05950   CheckShadow(S, D, R);
05951 }
05952 
05953 /// Check for conflict between this global or extern "C" declaration and
05954 /// previous global or extern "C" declarations. This is only used in C++.
05955 template<typename T>
05956 static bool checkGlobalOrExternCConflict(
05957     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
05958   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
05959   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
05960 
05961   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
05962     // The common case: this global doesn't conflict with any extern "C"
05963     // declaration.
05964     return false;
05965   }
05966 
05967   if (Prev) {
05968     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
05969       // Both the old and new declarations have C language linkage. This is a
05970       // redeclaration.
05971       Previous.clear();
05972       Previous.addDecl(Prev);
05973       return true;
05974     }
05975 
05976     // This is a global, non-extern "C" declaration, and there is a previous
05977     // non-global extern "C" declaration. Diagnose if this is a variable
05978     // declaration.
05979     if (!isa<VarDecl>(ND))
05980       return false;
05981   } else {
05982     // The declaration is extern "C". Check for any declaration in the
05983     // translation unit which might conflict.
05984     if (IsGlobal) {
05985       // We have already performed the lookup into the translation unit.
05986       IsGlobal = false;
05987       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
05988            I != E; ++I) {
05989         if (isa<VarDecl>(*I)) {
05990           Prev = *I;
05991           break;
05992         }
05993       }
05994     } else {
05995       DeclContext::lookup_result R =
05996           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
05997       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
05998            I != E; ++I) {
05999         if (isa<VarDecl>(*I)) {
06000           Prev = *I;
06001           break;
06002         }
06003         // FIXME: If we have any other entity with this name in global scope,
06004         // the declaration is ill-formed, but that is a defect: it breaks the
06005         // 'stat' hack, for instance. Only variables can have mangled name
06006         // clashes with extern "C" declarations, so only they deserve a
06007         // diagnostic.
06008       }
06009     }
06010 
06011     if (!Prev)
06012       return false;
06013   }
06014 
06015   // Use the first declaration's location to ensure we point at something which
06016   // is lexically inside an extern "C" linkage-spec.
06017   assert(Prev && "should have found a previous declaration to diagnose");
06018   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
06019     Prev = FD->getFirstDecl();
06020   else
06021     Prev = cast<VarDecl>(Prev)->getFirstDecl();
06022 
06023   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
06024     << IsGlobal << ND;
06025   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
06026     << IsGlobal;
06027   return false;
06028 }
06029 
06030 /// Apply special rules for handling extern "C" declarations. Returns \c true
06031 /// if we have found that this is a redeclaration of some prior entity.
06032 ///
06033 /// Per C++ [dcl.link]p6:
06034 ///   Two declarations [for a function or variable] with C language linkage
06035 ///   with the same name that appear in different scopes refer to the same
06036 ///   [entity]. An entity with C language linkage shall not be declared with
06037 ///   the same name as an entity in global scope.
06038 template<typename T>
06039 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
06040                                                   LookupResult &Previous) {
06041   if (!S.getLangOpts().CPlusPlus) {
06042     // In C, when declaring a global variable, look for a corresponding 'extern'
06043     // variable declared in function scope. We don't need this in C++, because
06044     // we find local extern decls in the surrounding file-scope DeclContext.
06045     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
06046       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
06047         Previous.clear();
06048         Previous.addDecl(Prev);
06049         return true;
06050       }
06051     }
06052     return false;
06053   }
06054 
06055   // A declaration in the translation unit can conflict with an extern "C"
06056   // declaration.
06057   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
06058     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
06059 
06060   // An extern "C" declaration can conflict with a declaration in the
06061   // translation unit or can be a redeclaration of an extern "C" declaration
06062   // in another scope.
06063   if (isIncompleteDeclExternC(S,ND))
06064     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
06065 
06066   // Neither global nor extern "C": nothing to do.
06067   return false;
06068 }
06069 
06070 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
06071   // If the decl is already known invalid, don't check it.
06072   if (NewVD->isInvalidDecl())
06073     return;
06074 
06075   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
06076   QualType T = TInfo->getType();
06077 
06078   // Defer checking an 'auto' type until its initializer is attached.
06079   if (T->isUndeducedType())
06080     return;
06081 
06082   if (NewVD->hasAttrs())
06083     CheckAlignasUnderalignment(NewVD);
06084 
06085   if (T->isObjCObjectType()) {
06086     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
06087       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
06088     T = Context.getObjCObjectPointerType(T);
06089     NewVD->setType(T);
06090   }
06091 
06092   // Emit an error if an address space was applied to decl with local storage.
06093   // This includes arrays of objects with address space qualifiers, but not
06094   // automatic variables that point to other address spaces.
06095   // ISO/IEC TR 18037 S5.1.2
06096   if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
06097     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
06098     NewVD->setInvalidDecl();
06099     return;
06100   }
06101 
06102   // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
06103   // __constant address space.
06104   if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
06105       && T.getAddressSpace() != LangAS::opencl_constant
06106       && !T->isSamplerT()){
06107     Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
06108     NewVD->setInvalidDecl();
06109     return;
06110   }
06111   
06112   // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
06113   // scope.
06114   if ((getLangOpts().OpenCLVersion >= 120)
06115       && NewVD->isStaticLocal()) {
06116     Diag(NewVD->getLocation(), diag::err_static_function_scope);
06117     NewVD->setInvalidDecl();
06118     return;
06119   }
06120 
06121   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
06122       && !NewVD->hasAttr<BlocksAttr>()) {
06123     if (getLangOpts().getGC() != LangOptions::NonGC)
06124       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
06125     else {
06126       assert(!getLangOpts().ObjCAutoRefCount);
06127       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
06128     }
06129   }
06130   
06131   bool isVM = T->isVariablyModifiedType();
06132   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
06133       NewVD->hasAttr<BlocksAttr>())
06134     getCurFunction()->setHasBranchProtectedScope();
06135 
06136   if ((isVM && NewVD->hasLinkage()) ||
06137       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
06138     bool SizeIsNegative;
06139     llvm::APSInt Oversized;
06140     TypeSourceInfo *FixedTInfo =
06141       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
06142                                                     SizeIsNegative, Oversized);
06143     if (!FixedTInfo && T->isVariableArrayType()) {
06144       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
06145       // FIXME: This won't give the correct result for
06146       // int a[10][n];
06147       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
06148 
06149       if (NewVD->isFileVarDecl())
06150         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
06151         << SizeRange;
06152       else if (NewVD->isStaticLocal())
06153         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
06154         << SizeRange;
06155       else
06156         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
06157         << SizeRange;
06158       NewVD->setInvalidDecl();
06159       return;
06160     }
06161 
06162     if (!FixedTInfo) {
06163       if (NewVD->isFileVarDecl())
06164         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
06165       else
06166         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
06167       NewVD->setInvalidDecl();
06168       return;
06169     }
06170 
06171     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
06172     NewVD->setType(FixedTInfo->getType());
06173     NewVD->setTypeSourceInfo(FixedTInfo);
06174   }
06175 
06176   if (T->isVoidType()) {
06177     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
06178     //                    of objects and functions.
06179     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
06180       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
06181         << T;
06182       NewVD->setInvalidDecl();
06183       return;
06184     }
06185   }
06186 
06187   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
06188     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
06189     NewVD->setInvalidDecl();
06190     return;
06191   }
06192 
06193   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
06194     Diag(NewVD->getLocation(), diag::err_block_on_vm);
06195     NewVD->setInvalidDecl();
06196     return;
06197   }
06198 
06199   if (NewVD->isConstexpr() && !T->isDependentType() &&
06200       RequireLiteralType(NewVD->getLocation(), T,
06201                          diag::err_constexpr_var_non_literal)) {
06202     NewVD->setInvalidDecl();
06203     return;
06204   }
06205 }
06206 
06207 /// \brief Perform semantic checking on a newly-created variable
06208 /// declaration.
06209 ///
06210 /// This routine performs all of the type-checking required for a
06211 /// variable declaration once it has been built. It is used both to
06212 /// check variables after they have been parsed and their declarators
06213 /// have been translated into a declaration, and to check variables
06214 /// that have been instantiated from a template.
06215 ///
06216 /// Sets NewVD->isInvalidDecl() if an error was encountered.
06217 ///
06218 /// Returns true if the variable declaration is a redeclaration.
06219 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
06220   CheckVariableDeclarationType(NewVD);
06221 
06222   // If the decl is already known invalid, don't check it.
06223   if (NewVD->isInvalidDecl())
06224     return false;
06225 
06226   // If we did not find anything by this name, look for a non-visible
06227   // extern "C" declaration with the same name.
06228   if (Previous.empty() &&
06229       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
06230     Previous.setShadowed();
06231 
06232   // Filter out any non-conflicting previous declarations.
06233   filterNonConflictingPreviousDecls(Context, NewVD, Previous);
06234 
06235   if (!Previous.empty()) {
06236     MergeVarDecl(NewVD, Previous);
06237     return true;
06238   }
06239   return false;
06240 }
06241 
06242 /// \brief Data used with FindOverriddenMethod
06243 struct FindOverriddenMethodData {
06244   Sema *S;
06245   CXXMethodDecl *Method;
06246 };
06247 
06248 /// \brief Member lookup function that determines whether a given C++
06249 /// method overrides a method in a base class, to be used with
06250 /// CXXRecordDecl::lookupInBases().
06251 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
06252                                  CXXBasePath &Path,
06253                                  void *UserData) {
06254   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
06255 
06256   FindOverriddenMethodData *Data 
06257     = reinterpret_cast<FindOverriddenMethodData*>(UserData);
06258   
06259   DeclarationName Name = Data->Method->getDeclName();
06260   
06261   // FIXME: Do we care about other names here too?
06262   if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
06263     // We really want to find the base class destructor here.
06264     QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
06265     CanQualType CT = Data->S->Context.getCanonicalType(T);
06266     
06267     Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
06268   }    
06269   
06270   for (Path.Decls = BaseRecord->lookup(Name);
06271        !Path.Decls.empty();
06272        Path.Decls = Path.Decls.slice(1)) {
06273     NamedDecl *D = Path.Decls.front();
06274     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
06275       if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
06276         return true;
06277     }
06278   }
06279   
06280   return false;
06281 }
06282 
06283 namespace {
06284   enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
06285 }
06286 /// \brief Report an error regarding overriding, along with any relevant
06287 /// overriden methods.
06288 ///
06289 /// \param DiagID the primary error to report.
06290 /// \param MD the overriding method.
06291 /// \param OEK which overrides to include as notes.
06292 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
06293                             OverrideErrorKind OEK = OEK_All) {
06294   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
06295   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
06296                                       E = MD->end_overridden_methods();
06297        I != E; ++I) {
06298     // This check (& the OEK parameter) could be replaced by a predicate, but
06299     // without lambdas that would be overkill. This is still nicer than writing
06300     // out the diag loop 3 times.
06301     if ((OEK == OEK_All) ||
06302         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
06303         (OEK == OEK_Deleted && (*I)->isDeleted()))
06304       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
06305   }
06306 }
06307 
06308 /// AddOverriddenMethods - See if a method overrides any in the base classes,
06309 /// and if so, check that it's a valid override and remember it.
06310 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
06311   // Look for methods in base classes that this method might override.
06312   CXXBasePaths Paths;
06313   FindOverriddenMethodData Data;
06314   Data.Method = MD;
06315   Data.S = this;
06316   bool hasDeletedOverridenMethods = false;
06317   bool hasNonDeletedOverridenMethods = false;
06318   bool AddedAny = false;
06319   if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
06320     for (auto *I : Paths.found_decls()) {
06321       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
06322         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
06323         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
06324             !CheckOverridingFunctionAttributes(MD, OldMD) &&
06325             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
06326             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
06327           hasDeletedOverridenMethods |= OldMD->isDeleted();
06328           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
06329           AddedAny = true;
06330         }
06331       }
06332     }
06333   }
06334 
06335   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
06336     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
06337   }
06338   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
06339     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
06340   }
06341 
06342   return AddedAny;
06343 }
06344 
06345 namespace {
06346   // Struct for holding all of the extra arguments needed by
06347   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
06348   struct ActOnFDArgs {
06349     Scope *S;
06350     Declarator &D;
06351     MultiTemplateParamsArg TemplateParamLists;
06352     bool AddToScope;
06353   };
06354 }
06355 
06356 namespace {
06357 
06358 // Callback to only accept typo corrections that have a non-zero edit distance.
06359 // Also only accept corrections that have the same parent decl.
06360 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
06361  public:
06362   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
06363                             CXXRecordDecl *Parent)
06364       : Context(Context), OriginalFD(TypoFD),
06365         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
06366 
06367   bool ValidateCandidate(const TypoCorrection &candidate) override {
06368     if (candidate.getEditDistance() == 0)
06369       return false;
06370 
06371     SmallVector<unsigned, 1> MismatchedParams;
06372     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
06373                                           CDeclEnd = candidate.end();
06374          CDecl != CDeclEnd; ++CDecl) {
06375       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
06376 
06377       if (FD && !FD->hasBody() &&
06378           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
06379         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
06380           CXXRecordDecl *Parent = MD->getParent();
06381           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
06382             return true;
06383         } else if (!ExpectedParent) {
06384           return true;
06385         }
06386       }
06387     }
06388 
06389     return false;
06390   }
06391 
06392  private:
06393   ASTContext &Context;
06394   FunctionDecl *OriginalFD;
06395   CXXRecordDecl *ExpectedParent;
06396 };
06397 
06398 }
06399 
06400 /// \brief Generate diagnostics for an invalid function redeclaration.
06401 ///
06402 /// This routine handles generating the diagnostic messages for an invalid
06403 /// function redeclaration, including finding possible similar declarations
06404 /// or performing typo correction if there are no previous declarations with
06405 /// the same name.
06406 ///
06407 /// Returns a NamedDecl iff typo correction was performed and substituting in
06408 /// the new declaration name does not cause new errors.
06409 static NamedDecl *DiagnoseInvalidRedeclaration(
06410     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
06411     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
06412   DeclarationName Name = NewFD->getDeclName();
06413   DeclContext *NewDC = NewFD->getDeclContext();
06414   SmallVector<unsigned, 1> MismatchedParams;
06415   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
06416   TypoCorrection Correction;
06417   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
06418   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
06419                                    : diag::err_member_decl_does_not_match;
06420   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
06421                     IsLocalFriend ? Sema::LookupLocalFriendName
06422                                   : Sema::LookupOrdinaryName,
06423                     Sema::ForRedeclaration);
06424 
06425   NewFD->setInvalidDecl();
06426   if (IsLocalFriend)
06427     SemaRef.LookupName(Prev, S);
06428   else
06429     SemaRef.LookupQualifiedName(Prev, NewDC);
06430   assert(!Prev.isAmbiguous() &&
06431          "Cannot have an ambiguity in previous-declaration lookup");
06432   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
06433   if (!Prev.empty()) {
06434     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
06435          Func != FuncEnd; ++Func) {
06436       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
06437       if (FD &&
06438           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
06439         // Add 1 to the index so that 0 can mean the mismatch didn't
06440         // involve a parameter
06441         unsigned ParamNum =
06442             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
06443         NearMatches.push_back(std::make_pair(FD, ParamNum));
06444       }
06445     }
06446   // If the qualified name lookup yielded nothing, try typo correction
06447   } else if ((Correction = SemaRef.CorrectTypo(
06448                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
06449                   &ExtraArgs.D.getCXXScopeSpec(),
06450                   llvm::make_unique<DifferentNameValidatorCCC>(
06451                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
06452                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
06453     // Set up everything for the call to ActOnFunctionDeclarator
06454     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
06455                               ExtraArgs.D.getIdentifierLoc());
06456     Previous.clear();
06457     Previous.setLookupName(Correction.getCorrection());
06458     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
06459                                     CDeclEnd = Correction.end();
06460          CDecl != CDeclEnd; ++CDecl) {
06461       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
06462       if (FD && !FD->hasBody() &&
06463           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
06464         Previous.addDecl(FD);
06465       }
06466     }
06467     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
06468 
06469     NamedDecl *Result;
06470     // Retry building the function declaration with the new previous
06471     // declarations, and with errors suppressed.
06472     {
06473       // Trap errors.
06474       Sema::SFINAETrap Trap(SemaRef);
06475 
06476       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
06477       // pieces need to verify the typo-corrected C++ declaration and hopefully
06478       // eliminate the need for the parameter pack ExtraArgs.
06479       Result = SemaRef.ActOnFunctionDeclarator(
06480           ExtraArgs.S, ExtraArgs.D,
06481           Correction.getCorrectionDecl()->getDeclContext(),
06482           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
06483           ExtraArgs.AddToScope);
06484 
06485       if (Trap.hasErrorOccurred())
06486         Result = nullptr;
06487     }
06488 
06489     if (Result) {
06490       // Determine which correction we picked.
06491       Decl *Canonical = Result->getCanonicalDecl();
06492       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
06493            I != E; ++I)
06494         if ((*I)->getCanonicalDecl() == Canonical)
06495           Correction.setCorrectionDecl(*I);
06496 
06497       SemaRef.diagnoseTypo(
06498           Correction,
06499           SemaRef.PDiag(IsLocalFriend
06500                           ? diag::err_no_matching_local_friend_suggest
06501                           : diag::err_member_decl_does_not_match_suggest)
06502             << Name << NewDC << IsDefinition);
06503       return Result;
06504     }
06505 
06506     // Pretend the typo correction never occurred
06507     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
06508                               ExtraArgs.D.getIdentifierLoc());
06509     ExtraArgs.D.setRedeclaration(wasRedeclaration);
06510     Previous.clear();
06511     Previous.setLookupName(Name);
06512   }
06513 
06514   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
06515       << Name << NewDC << IsDefinition << NewFD->getLocation();
06516 
06517   bool NewFDisConst = false;
06518   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
06519     NewFDisConst = NewMD->isConst();
06520 
06521   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
06522        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
06523        NearMatch != NearMatchEnd; ++NearMatch) {
06524     FunctionDecl *FD = NearMatch->first;
06525     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
06526     bool FDisConst = MD && MD->isConst();
06527     bool IsMember = MD || !IsLocalFriend;
06528 
06529     // FIXME: These notes are poorly worded for the local friend case.
06530     if (unsigned Idx = NearMatch->second) {
06531       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
06532       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
06533       if (Loc.isInvalid()) Loc = FD->getLocation();
06534       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
06535                                  : diag::note_local_decl_close_param_match)
06536         << Idx << FDParam->getType()
06537         << NewFD->getParamDecl(Idx - 1)->getType();
06538     } else if (FDisConst != NewFDisConst) {
06539       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
06540           << NewFDisConst << FD->getSourceRange().getEnd();
06541     } else
06542       SemaRef.Diag(FD->getLocation(),
06543                    IsMember ? diag::note_member_def_close_match
06544                             : diag::note_local_decl_close_match);
06545   }
06546   return nullptr;
06547 }
06548 
06549 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
06550   switch (D.getDeclSpec().getStorageClassSpec()) {
06551   default: llvm_unreachable("Unknown storage class!");
06552   case DeclSpec::SCS_auto:
06553   case DeclSpec::SCS_register:
06554   case DeclSpec::SCS_mutable:
06555     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
06556                  diag::err_typecheck_sclass_func);
06557     D.setInvalidType();
06558     break;
06559   case DeclSpec::SCS_unspecified: break;
06560   case DeclSpec::SCS_extern:
06561     if (D.getDeclSpec().isExternInLinkageSpec())
06562       return SC_None;
06563     return SC_Extern;
06564   case DeclSpec::SCS_static: {
06565     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
06566       // C99 6.7.1p5:
06567       //   The declaration of an identifier for a function that has
06568       //   block scope shall have no explicit storage-class specifier
06569       //   other than extern
06570       // See also (C++ [dcl.stc]p4).
06571       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
06572                    diag::err_static_block_func);
06573       break;
06574     } else
06575       return SC_Static;
06576   }
06577   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
06578   }
06579 
06580   // No explicit storage class has already been returned
06581   return SC_None;
06582 }
06583 
06584 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
06585                                            DeclContext *DC, QualType &R,
06586                                            TypeSourceInfo *TInfo,
06587                                            StorageClass SC,
06588                                            bool &IsVirtualOkay) {
06589   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
06590   DeclarationName Name = NameInfo.getName();
06591 
06592   FunctionDecl *NewFD = nullptr;
06593   bool isInline = D.getDeclSpec().isInlineSpecified();
06594 
06595   if (!SemaRef.getLangOpts().CPlusPlus) {
06596     // Determine whether the function was written with a
06597     // prototype. This true when:
06598     //   - there is a prototype in the declarator, or
06599     //   - the type R of the function is some kind of typedef or other reference
06600     //     to a type name (which eventually refers to a function type).
06601     bool HasPrototype =
06602       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
06603       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
06604 
06605     NewFD = FunctionDecl::Create(SemaRef.Context, DC, 
06606                                  D.getLocStart(), NameInfo, R, 
06607                                  TInfo, SC, isInline, 
06608                                  HasPrototype, false);
06609     if (D.isInvalidType())
06610       NewFD->setInvalidDecl();
06611 
06612     // Set the lexical context.
06613     NewFD->setLexicalDeclContext(SemaRef.CurContext);
06614 
06615     return NewFD;
06616   }
06617 
06618   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
06619   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
06620 
06621   // Check that the return type is not an abstract class type.
06622   // For record types, this is done by the AbstractClassUsageDiagnoser once
06623   // the class has been completely parsed.
06624   if (!DC->isRecord() &&
06625       SemaRef.RequireNonAbstractType(
06626           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
06627           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
06628     D.setInvalidType();
06629 
06630   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
06631     // This is a C++ constructor declaration.
06632     assert(DC->isRecord() &&
06633            "Constructors can only be declared in a member context");
06634 
06635     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
06636     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
06637                                       D.getLocStart(), NameInfo,
06638                                       R, TInfo, isExplicit, isInline,
06639                                       /*isImplicitlyDeclared=*/false,
06640                                       isConstexpr);
06641 
06642   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
06643     // This is a C++ destructor declaration.
06644     if (DC->isRecord()) {
06645       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
06646       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
06647       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
06648                                         SemaRef.Context, Record,
06649                                         D.getLocStart(),
06650                                         NameInfo, R, TInfo, isInline,
06651                                         /*isImplicitlyDeclared=*/false);
06652 
06653       // If the class is complete, then we now create the implicit exception
06654       // specification. If the class is incomplete or dependent, we can't do
06655       // it yet.
06656       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
06657           Record->getDefinition() && !Record->isBeingDefined() &&
06658           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
06659         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
06660       }
06661 
06662       IsVirtualOkay = true;
06663       return NewDD;
06664 
06665     } else {
06666       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
06667       D.setInvalidType();
06668 
06669       // Create a FunctionDecl to satisfy the function definition parsing
06670       // code path.
06671       return FunctionDecl::Create(SemaRef.Context, DC,
06672                                   D.getLocStart(),
06673                                   D.getIdentifierLoc(), Name, R, TInfo,
06674                                   SC, isInline,
06675                                   /*hasPrototype=*/true, isConstexpr);
06676     }
06677 
06678   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
06679     if (!DC->isRecord()) {
06680       SemaRef.Diag(D.getIdentifierLoc(),
06681            diag::err_conv_function_not_member);
06682       return nullptr;
06683     }
06684 
06685     SemaRef.CheckConversionDeclarator(D, R, SC);
06686     IsVirtualOkay = true;
06687     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
06688                                      D.getLocStart(), NameInfo,
06689                                      R, TInfo, isInline, isExplicit,
06690                                      isConstexpr, SourceLocation());
06691 
06692   } else if (DC->isRecord()) {
06693     // If the name of the function is the same as the name of the record,
06694     // then this must be an invalid constructor that has a return type.
06695     // (The parser checks for a return type and makes the declarator a
06696     // constructor if it has no return type).
06697     if (Name.getAsIdentifierInfo() &&
06698         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
06699       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
06700         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
06701         << SourceRange(D.getIdentifierLoc());
06702       return nullptr;
06703     }
06704 
06705     // This is a C++ method declaration.
06706     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
06707                                                cast<CXXRecordDecl>(DC),
06708                                                D.getLocStart(), NameInfo, R,
06709                                                TInfo, SC, isInline,
06710                                                isConstexpr, SourceLocation());
06711     IsVirtualOkay = !Ret->isStatic();
06712     return Ret;
06713   } else {
06714     // Determine whether the function was written with a
06715     // prototype. This true when:
06716     //   - we're in C++ (where every function has a prototype),
06717     return FunctionDecl::Create(SemaRef.Context, DC,
06718                                 D.getLocStart(),
06719                                 NameInfo, R, TInfo, SC, isInline,
06720                                 true/*HasPrototype*/, isConstexpr);
06721   }
06722 }
06723 
06724 enum OpenCLParamType {
06725   ValidKernelParam,
06726   PtrPtrKernelParam,
06727   PtrKernelParam,
06728   PrivatePtrKernelParam,
06729   InvalidKernelParam,
06730   RecordKernelParam
06731 };
06732 
06733 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
06734   if (PT->isPointerType()) {
06735     QualType PointeeType = PT->getPointeeType();
06736     if (PointeeType->isPointerType())
06737       return PtrPtrKernelParam;
06738     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
06739                                               : PtrKernelParam;
06740   }
06741 
06742   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
06743   // be used as builtin types.
06744 
06745   if (PT->isImageType())
06746     return PtrKernelParam;
06747 
06748   if (PT->isBooleanType())
06749     return InvalidKernelParam;
06750 
06751   if (PT->isEventT())
06752     return InvalidKernelParam;
06753 
06754   if (PT->isHalfType())
06755     return InvalidKernelParam;
06756 
06757   if (PT->isRecordType())
06758     return RecordKernelParam;
06759 
06760   return ValidKernelParam;
06761 }
06762 
06763 static void checkIsValidOpenCLKernelParameter(
06764   Sema &S,
06765   Declarator &D,
06766   ParmVarDecl *Param,
06767   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
06768   QualType PT = Param->getType();
06769 
06770   // Cache the valid types we encounter to avoid rechecking structs that are
06771   // used again
06772   if (ValidTypes.count(PT.getTypePtr()))
06773     return;
06774 
06775   switch (getOpenCLKernelParameterType(PT)) {
06776   case PtrPtrKernelParam:
06777     // OpenCL v1.2 s6.9.a:
06778     // A kernel function argument cannot be declared as a
06779     // pointer to a pointer type.
06780     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
06781     D.setInvalidType();
06782     return;
06783 
06784   case PrivatePtrKernelParam:
06785     // OpenCL v1.2 s6.9.a:
06786     // A kernel function argument cannot be declared as a
06787     // pointer to the private address space.
06788     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
06789     D.setInvalidType();
06790     return;
06791 
06792     // OpenCL v1.2 s6.9.k:
06793     // Arguments to kernel functions in a program cannot be declared with the
06794     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
06795     // uintptr_t or a struct and/or union that contain fields declared to be
06796     // one of these built-in scalar types.
06797 
06798   case InvalidKernelParam:
06799     // OpenCL v1.2 s6.8 n:
06800     // A kernel function argument cannot be declared
06801     // of event_t type.
06802     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
06803     D.setInvalidType();
06804     return;
06805 
06806   case PtrKernelParam:
06807   case ValidKernelParam:
06808     ValidTypes.insert(PT.getTypePtr());
06809     return;
06810 
06811   case RecordKernelParam:
06812     break;
06813   }
06814 
06815   // Track nested structs we will inspect
06816   SmallVector<const Decl *, 4> VisitStack;
06817 
06818   // Track where we are in the nested structs. Items will migrate from
06819   // VisitStack to HistoryStack as we do the DFS for bad field.
06820   SmallVector<const FieldDecl *, 4> HistoryStack;
06821   HistoryStack.push_back(nullptr);
06822 
06823   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
06824   VisitStack.push_back(PD);
06825 
06826   assert(VisitStack.back() && "First decl null?");
06827 
06828   do {
06829     const Decl *Next = VisitStack.pop_back_val();
06830     if (!Next) {
06831       assert(!HistoryStack.empty());
06832       // Found a marker, we have gone up a level
06833       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
06834         ValidTypes.insert(Hist->getType().getTypePtr());
06835 
06836       continue;
06837     }
06838 
06839     // Adds everything except the original parameter declaration (which is not a
06840     // field itself) to the history stack.
06841     const RecordDecl *RD;
06842     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
06843       HistoryStack.push_back(Field);
06844       RD = Field->getType()->castAs<RecordType>()->getDecl();
06845     } else {
06846       RD = cast<RecordDecl>(Next);
06847     }
06848 
06849     // Add a null marker so we know when we've gone back up a level
06850     VisitStack.push_back(nullptr);
06851 
06852     for (const auto *FD : RD->fields()) {
06853       QualType QT = FD->getType();
06854 
06855       if (ValidTypes.count(QT.getTypePtr()))
06856         continue;
06857 
06858       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
06859       if (ParamType == ValidKernelParam)
06860         continue;
06861 
06862       if (ParamType == RecordKernelParam) {
06863         VisitStack.push_back(FD);
06864         continue;
06865       }
06866 
06867       // OpenCL v1.2 s6.9.p:
06868       // Arguments to kernel functions that are declared to be a struct or union
06869       // do not allow OpenCL objects to be passed as elements of the struct or
06870       // union.
06871       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
06872           ParamType == PrivatePtrKernelParam) {
06873         S.Diag(Param->getLocation(),
06874                diag::err_record_with_pointers_kernel_param)
06875           << PT->isUnionType()
06876           << PT;
06877       } else {
06878         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
06879       }
06880 
06881       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
06882         << PD->getDeclName();
06883 
06884       // We have an error, now let's go back up through history and show where
06885       // the offending field came from
06886       for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
06887              E = HistoryStack.end(); I != E; ++I) {
06888         const FieldDecl *OuterField = *I;
06889         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
06890           << OuterField->getType();
06891       }
06892 
06893       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
06894         << QT->isPointerType()
06895         << QT;
06896       D.setInvalidType();
06897       return;
06898     }
06899   } while (!VisitStack.empty());
06900 }
06901 
06902 NamedDecl*
06903 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
06904                               TypeSourceInfo *TInfo, LookupResult &Previous,
06905                               MultiTemplateParamsArg TemplateParamLists,
06906                               bool &AddToScope) {
06907   QualType R = TInfo->getType();
06908 
06909   assert(R.getTypePtr()->isFunctionType());
06910 
06911   // TODO: consider using NameInfo for diagnostic.
06912   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
06913   DeclarationName Name = NameInfo.getName();
06914   StorageClass SC = getFunctionStorageClass(*this, D);
06915 
06916   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
06917     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
06918          diag::err_invalid_thread)
06919       << DeclSpec::getSpecifierName(TSCS);
06920 
06921   if (D.isFirstDeclarationOfMember())
06922     adjustMemberFunctionCC(R, D.isStaticMember());
06923 
06924   bool isFriend = false;
06925   FunctionTemplateDecl *FunctionTemplate = nullptr;
06926   bool isExplicitSpecialization = false;
06927   bool isFunctionTemplateSpecialization = false;
06928 
06929   bool isDependentClassScopeExplicitSpecialization = false;
06930   bool HasExplicitTemplateArgs = false;
06931   TemplateArgumentListInfo TemplateArgs;
06932 
06933   bool isVirtualOkay = false;
06934 
06935   DeclContext *OriginalDC = DC;
06936   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
06937 
06938   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
06939                                               isVirtualOkay);
06940   if (!NewFD) return nullptr;
06941 
06942   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
06943     NewFD->setTopLevelDeclInObjCContainer();
06944 
06945   // Set the lexical context. If this is a function-scope declaration, or has a
06946   // C++ scope specifier, or is the object of a friend declaration, the lexical
06947   // context will be different from the semantic context.
06948   NewFD->setLexicalDeclContext(CurContext);
06949 
06950   if (IsLocalExternDecl)
06951     NewFD->setLocalExternDecl();
06952 
06953   if (getLangOpts().CPlusPlus) {
06954     bool isInline = D.getDeclSpec().isInlineSpecified();
06955     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
06956     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
06957     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
06958     isFriend = D.getDeclSpec().isFriendSpecified();
06959     if (isFriend && !isInline && D.isFunctionDefinition()) {
06960       // C++ [class.friend]p5
06961       //   A function can be defined in a friend declaration of a
06962       //   class . . . . Such a function is implicitly inline.
06963       NewFD->setImplicitlyInline();
06964     }
06965 
06966     // If this is a method defined in an __interface, and is not a constructor
06967     // or an overloaded operator, then set the pure flag (isVirtual will already
06968     // return true).
06969     if (const CXXRecordDecl *Parent =
06970           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
06971       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
06972         NewFD->setPure(true);
06973     }
06974 
06975     SetNestedNameSpecifier(NewFD, D);
06976     isExplicitSpecialization = false;
06977     isFunctionTemplateSpecialization = false;
06978     if (D.isInvalidType())
06979       NewFD->setInvalidDecl();
06980 
06981     // Match up the template parameter lists with the scope specifier, then
06982     // determine whether we have a template or a template specialization.
06983     bool Invalid = false;
06984     if (TemplateParameterList *TemplateParams =
06985             MatchTemplateParametersToScopeSpecifier(
06986                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
06987                 D.getCXXScopeSpec(),
06988                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
06989                     ? D.getName().TemplateId
06990                     : nullptr,
06991                 TemplateParamLists, isFriend, isExplicitSpecialization,
06992                 Invalid)) {
06993       if (TemplateParams->size() > 0) {
06994         // This is a function template
06995 
06996         // Check that we can declare a template here.
06997         if (CheckTemplateDeclScope(S, TemplateParams))
06998           return nullptr;
06999 
07000         // A destructor cannot be a template.
07001         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
07002           Diag(NewFD->getLocation(), diag::err_destructor_template);
07003           return nullptr;
07004         }
07005         
07006         // If we're adding a template to a dependent context, we may need to 
07007         // rebuilding some of the types used within the template parameter list,
07008         // now that we know what the current instantiation is.
07009         if (DC->isDependentContext()) {
07010           ContextRAII SavedContext(*this, DC);
07011           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
07012             Invalid = true;
07013         }
07014         
07015 
07016         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
07017                                                         NewFD->getLocation(),
07018                                                         Name, TemplateParams,
07019                                                         NewFD);
07020         FunctionTemplate->setLexicalDeclContext(CurContext);
07021         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
07022 
07023         // For source fidelity, store the other template param lists.
07024         if (TemplateParamLists.size() > 1) {
07025           NewFD->setTemplateParameterListsInfo(Context,
07026                                                TemplateParamLists.size() - 1,
07027                                                TemplateParamLists.data());
07028         }
07029       } else {
07030         // This is a function template specialization.
07031         isFunctionTemplateSpecialization = true;
07032         // For source fidelity, store all the template param lists.
07033         if (TemplateParamLists.size() > 0)
07034           NewFD->setTemplateParameterListsInfo(Context,
07035                                                TemplateParamLists.size(),
07036                                                TemplateParamLists.data());
07037 
07038         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
07039         if (isFriend) {
07040           // We want to remove the "template<>", found here.
07041           SourceRange RemoveRange = TemplateParams->getSourceRange();
07042 
07043           // If we remove the template<> and the name is not a
07044           // template-id, we're actually silently creating a problem:
07045           // the friend declaration will refer to an untemplated decl,
07046           // and clearly the user wants a template specialization.  So
07047           // we need to insert '<>' after the name.
07048           SourceLocation InsertLoc;
07049           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
07050             InsertLoc = D.getName().getSourceRange().getEnd();
07051             InsertLoc = getLocForEndOfToken(InsertLoc);
07052           }
07053 
07054           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
07055             << Name << RemoveRange
07056             << FixItHint::CreateRemoval(RemoveRange)
07057             << FixItHint::CreateInsertion(InsertLoc, "<>");
07058         }
07059       }
07060     }
07061     else {
07062       // All template param lists were matched against the scope specifier:
07063       // this is NOT (an explicit specialization of) a template.
07064       if (TemplateParamLists.size() > 0)
07065         // For source fidelity, store all the template param lists.
07066         NewFD->setTemplateParameterListsInfo(Context,
07067                                              TemplateParamLists.size(),
07068                                              TemplateParamLists.data());
07069     }
07070 
07071     if (Invalid) {
07072       NewFD->setInvalidDecl();
07073       if (FunctionTemplate)
07074         FunctionTemplate->setInvalidDecl();
07075     }
07076 
07077     // C++ [dcl.fct.spec]p5:
07078     //   The virtual specifier shall only be used in declarations of
07079     //   nonstatic class member functions that appear within a
07080     //   member-specification of a class declaration; see 10.3.
07081     //
07082     if (isVirtual && !NewFD->isInvalidDecl()) {
07083       if (!isVirtualOkay) {
07084         Diag(D.getDeclSpec().getVirtualSpecLoc(),
07085              diag::err_virtual_non_function);
07086       } else if (!CurContext->isRecord()) {
07087         // 'virtual' was specified outside of the class.
07088         Diag(D.getDeclSpec().getVirtualSpecLoc(), 
07089              diag::err_virtual_out_of_class)
07090           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
07091       } else if (NewFD->getDescribedFunctionTemplate()) {
07092         // C++ [temp.mem]p3:
07093         //  A member function template shall not be virtual.
07094         Diag(D.getDeclSpec().getVirtualSpecLoc(),
07095              diag::err_virtual_member_function_template)
07096           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
07097       } else {
07098         // Okay: Add virtual to the method.
07099         NewFD->setVirtualAsWritten(true);
07100       }
07101 
07102       if (getLangOpts().CPlusPlus14 &&
07103           NewFD->getReturnType()->isUndeducedType())
07104         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
07105     }
07106 
07107     if (getLangOpts().CPlusPlus14 &&
07108         (NewFD->isDependentContext() ||
07109          (isFriend && CurContext->isDependentContext())) &&
07110         NewFD->getReturnType()->isUndeducedType()) {
07111       // If the function template is referenced directly (for instance, as a
07112       // member of the current instantiation), pretend it has a dependent type.
07113       // This is not really justified by the standard, but is the only sane
07114       // thing to do.
07115       // FIXME: For a friend function, we have not marked the function as being
07116       // a friend yet, so 'isDependentContext' on the FD doesn't work.
07117       const FunctionProtoType *FPT =
07118           NewFD->getType()->castAs<FunctionProtoType>();
07119       QualType Result =
07120           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
07121       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
07122                                              FPT->getExtProtoInfo()));
07123     }
07124 
07125     // C++ [dcl.fct.spec]p3:
07126     //  The inline specifier shall not appear on a block scope function 
07127     //  declaration.
07128     if (isInline && !NewFD->isInvalidDecl()) {
07129       if (CurContext->isFunctionOrMethod()) {
07130         // 'inline' is not allowed on block scope function declaration.
07131         Diag(D.getDeclSpec().getInlineSpecLoc(), 
07132              diag::err_inline_declaration_block_scope) << Name
07133           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
07134       }
07135     }
07136 
07137     // C++ [dcl.fct.spec]p6:
07138     //  The explicit specifier shall be used only in the declaration of a
07139     //  constructor or conversion function within its class definition; 
07140     //  see 12.3.1 and 12.3.2.
07141     if (isExplicit && !NewFD->isInvalidDecl()) {
07142       if (!CurContext->isRecord()) {
07143         // 'explicit' was specified outside of the class.
07144         Diag(D.getDeclSpec().getExplicitSpecLoc(), 
07145              diag::err_explicit_out_of_class)
07146           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
07147       } else if (!isa<CXXConstructorDecl>(NewFD) && 
07148                  !isa<CXXConversionDecl>(NewFD)) {
07149         // 'explicit' was specified on a function that wasn't a constructor
07150         // or conversion function.
07151         Diag(D.getDeclSpec().getExplicitSpecLoc(),
07152              diag::err_explicit_non_ctor_or_conv_function)
07153           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
07154       }      
07155     }
07156 
07157     if (isConstexpr) {
07158       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
07159       // are implicitly inline.
07160       NewFD->setImplicitlyInline();
07161 
07162       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
07163       // be either constructors or to return a literal type. Therefore,
07164       // destructors cannot be declared constexpr.
07165       if (isa<CXXDestructorDecl>(NewFD))
07166         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
07167     }
07168 
07169     // If __module_private__ was specified, mark the function accordingly.
07170     if (D.getDeclSpec().isModulePrivateSpecified()) {
07171       if (isFunctionTemplateSpecialization) {
07172         SourceLocation ModulePrivateLoc
07173           = D.getDeclSpec().getModulePrivateSpecLoc();
07174         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
07175           << 0
07176           << FixItHint::CreateRemoval(ModulePrivateLoc);
07177       } else {
07178         NewFD->setModulePrivate();
07179         if (FunctionTemplate)
07180           FunctionTemplate->setModulePrivate();
07181       }
07182     }
07183 
07184     if (isFriend) {
07185       if (FunctionTemplate) {
07186         FunctionTemplate->setObjectOfFriendDecl();
07187         FunctionTemplate->setAccess(AS_public);
07188       }
07189       NewFD->setObjectOfFriendDecl();
07190       NewFD->setAccess(AS_public);
07191     }
07192 
07193     // If a function is defined as defaulted or deleted, mark it as such now.
07194     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
07195     // definition kind to FDK_Definition.
07196     switch (D.getFunctionDefinitionKind()) {
07197       case FDK_Declaration:
07198       case FDK_Definition:
07199         break;
07200         
07201       case FDK_Defaulted:
07202         NewFD->setDefaulted();
07203         break;
07204         
07205       case FDK_Deleted:
07206         NewFD->setDeletedAsWritten();
07207         break;
07208     }
07209 
07210     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
07211         D.isFunctionDefinition()) {
07212       // C++ [class.mfct]p2:
07213       //   A member function may be defined (8.4) in its class definition, in 
07214       //   which case it is an inline member function (7.1.2)
07215       NewFD->setImplicitlyInline();
07216     }
07217 
07218     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
07219         !CurContext->isRecord()) {
07220       // C++ [class.static]p1:
07221       //   A data or function member of a class may be declared static
07222       //   in a class definition, in which case it is a static member of
07223       //   the class.
07224 
07225       // Complain about the 'static' specifier if it's on an out-of-line
07226       // member function definition.
07227       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
07228            diag::err_static_out_of_line)
07229         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
07230     }
07231 
07232     // C++11 [except.spec]p15:
07233     //   A deallocation function with no exception-specification is treated
07234     //   as if it were specified with noexcept(true).
07235     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
07236     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
07237          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
07238         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
07239       NewFD->setType(Context.getFunctionType(
07240           FPT->getReturnType(), FPT->getParamTypes(),
07241           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
07242   }
07243 
07244   // Filter out previous declarations that don't match the scope.
07245   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
07246                        D.getCXXScopeSpec().isNotEmpty() ||
07247                        isExplicitSpecialization ||
07248                        isFunctionTemplateSpecialization);
07249 
07250   // Handle GNU asm-label extension (encoded as an attribute).
07251   if (Expr *E = (Expr*) D.getAsmLabel()) {
07252     // The parser guarantees this is a string.
07253     StringLiteral *SE = cast<StringLiteral>(E);
07254     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
07255                                                 SE->getString(), 0));
07256   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
07257     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
07258       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
07259     if (I != ExtnameUndeclaredIdentifiers.end()) {
07260       NewFD->addAttr(I->second);
07261       ExtnameUndeclaredIdentifiers.erase(I);
07262     }
07263   }
07264 
07265   // Copy the parameter declarations from the declarator D to the function
07266   // declaration NewFD, if they are available.  First scavenge them into Params.
07267   SmallVector<ParmVarDecl*, 16> Params;
07268   if (D.isFunctionDeclarator()) {
07269     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
07270 
07271     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
07272     // function that takes no arguments, not a function that takes a
07273     // single void argument.
07274     // We let through "const void" here because Sema::GetTypeForDeclarator
07275     // already checks for that case.
07276     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
07277       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
07278         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
07279         assert(Param->getDeclContext() != NewFD && "Was set before ?");
07280         Param->setDeclContext(NewFD);
07281         Params.push_back(Param);
07282 
07283         if (Param->isInvalidDecl())
07284           NewFD->setInvalidDecl();
07285       }
07286     }
07287 
07288   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
07289     // When we're declaring a function with a typedef, typeof, etc as in the
07290     // following example, we'll need to synthesize (unnamed)
07291     // parameters for use in the declaration.
07292     //
07293     // @code
07294     // typedef void fn(int);
07295     // fn f;
07296     // @endcode
07297 
07298     // Synthesize a parameter for each argument type.
07299     for (const auto &AI : FT->param_types()) {
07300       ParmVarDecl *Param =
07301           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
07302       Param->setScopeInfo(0, Params.size());
07303       Params.push_back(Param);
07304     }
07305   } else {
07306     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
07307            "Should not need args for typedef of non-prototype fn");
07308   }
07309 
07310   // Finally, we know we have the right number of parameters, install them.
07311   NewFD->setParams(Params);
07312 
07313   // Find all anonymous symbols defined during the declaration of this function
07314   // and add to NewFD. This lets us track decls such 'enum Y' in:
07315   //
07316   //   void f(enum Y {AA} x) {}
07317   //
07318   // which would otherwise incorrectly end up in the translation unit scope.
07319   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
07320   DeclsInPrototypeScope.clear();
07321 
07322   if (D.getDeclSpec().isNoreturnSpecified())
07323     NewFD->addAttr(
07324         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
07325                                        Context, 0));
07326 
07327   // Functions returning a variably modified type violate C99 6.7.5.2p2
07328   // because all functions have linkage.
07329   if (!NewFD->isInvalidDecl() &&
07330       NewFD->getReturnType()->isVariablyModifiedType()) {
07331     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
07332     NewFD->setInvalidDecl();
07333   }
07334 
07335   if (D.isFunctionDefinition() && CodeSegStack.CurrentValue &&
07336       !NewFD->hasAttr<SectionAttr>()) {
07337     NewFD->addAttr(
07338         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
07339                                     CodeSegStack.CurrentValue->getString(),
07340                                     CodeSegStack.CurrentPragmaLocation));
07341     if (UnifySection(CodeSegStack.CurrentValue->getString(),
07342                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
07343                          ASTContext::PSF_Read,
07344                      NewFD))
07345       NewFD->dropAttr<SectionAttr>();
07346   }
07347 
07348   // Handle attributes.
07349   ProcessDeclAttributes(S, NewFD, D);
07350 
07351   QualType RetType = NewFD->getReturnType();
07352   const CXXRecordDecl *Ret = RetType->isRecordType() ?
07353       RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
07354   if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
07355       Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
07356     const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
07357     // Attach WarnUnusedResult to functions returning types with that attribute.
07358     // Don't apply the attribute to that type's own non-static member functions
07359     // (to avoid warning on things like assignment operators)
07360     if (!MD || MD->getParent() != Ret)
07361       NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context));
07362   }
07363 
07364   if (getLangOpts().OpenCL) {
07365     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
07366     // type declaration will generate a compilation error.
07367     unsigned AddressSpace = RetType.getAddressSpace();
07368     if (AddressSpace == LangAS::opencl_local ||
07369         AddressSpace == LangAS::opencl_global ||
07370         AddressSpace == LangAS::opencl_constant) {
07371       Diag(NewFD->getLocation(),
07372            diag::err_opencl_return_value_with_address_space);
07373       NewFD->setInvalidDecl();
07374     }
07375   }
07376 
07377   if (!getLangOpts().CPlusPlus) {
07378     // Perform semantic checking on the function declaration.
07379     bool isExplicitSpecialization=false;
07380     if (!NewFD->isInvalidDecl() && NewFD->isMain())
07381       CheckMain(NewFD, D.getDeclSpec());
07382 
07383     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
07384       CheckMSVCRTEntryPoint(NewFD);
07385 
07386     if (!NewFD->isInvalidDecl())
07387       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
07388                                                   isExplicitSpecialization));
07389     else if (!Previous.empty())
07390       // Make graceful recovery from an invalid redeclaration.
07391       D.setRedeclaration(true);
07392     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
07393             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
07394            "previous declaration set still overloaded");
07395 
07396     // Diagnose no-prototype function declarations with calling conventions that
07397     // don't support variadic calls. Only do this in C and do it after merging
07398     // possibly prototyped redeclarations.
07399     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
07400     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
07401       CallingConv CC = FT->getExtInfo().getCC();
07402       if (!supportsVariadicCall(CC)) {
07403         // Windows system headers sometimes accidentally use stdcall without
07404         // (void) parameters, so we relax this to a warning.
07405         int DiagID =
07406             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
07407         Diag(NewFD->getLocation(), DiagID)
07408             << FunctionType::getNameForCallConv(CC);
07409       }
07410     }
07411   } else {
07412     // C++11 [replacement.functions]p3:
07413     //  The program's definitions shall not be specified as inline.
07414     //
07415     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
07416     //
07417     // Suppress the diagnostic if the function is __attribute__((used)), since
07418     // that forces an external definition to be emitted.
07419     if (D.getDeclSpec().isInlineSpecified() &&
07420         NewFD->isReplaceableGlobalAllocationFunction() &&
07421         !NewFD->hasAttr<UsedAttr>())
07422       Diag(D.getDeclSpec().getInlineSpecLoc(),
07423            diag::ext_operator_new_delete_declared_inline)
07424         << NewFD->getDeclName();
07425 
07426     // If the declarator is a template-id, translate the parser's template 
07427     // argument list into our AST format.
07428     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
07429       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
07430       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
07431       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
07432       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
07433                                          TemplateId->NumArgs);
07434       translateTemplateArguments(TemplateArgsPtr,
07435                                  TemplateArgs);
07436     
07437       HasExplicitTemplateArgs = true;
07438     
07439       if (NewFD->isInvalidDecl()) {
07440         HasExplicitTemplateArgs = false;
07441       } else if (FunctionTemplate) {
07442         // Function template with explicit template arguments.
07443         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
07444           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
07445 
07446         HasExplicitTemplateArgs = false;
07447       } else {
07448         assert((isFunctionTemplateSpecialization ||
07449                 D.getDeclSpec().isFriendSpecified()) &&
07450                "should have a 'template<>' for this decl");
07451         // "friend void foo<>(int);" is an implicit specialization decl.
07452         isFunctionTemplateSpecialization = true;
07453       }
07454     } else if (isFriend && isFunctionTemplateSpecialization) {
07455       // This combination is only possible in a recovery case;  the user
07456       // wrote something like:
07457       //   template <> friend void foo(int);
07458       // which we're recovering from as if the user had written:
07459       //   friend void foo<>(int);
07460       // Go ahead and fake up a template id.
07461       HasExplicitTemplateArgs = true;
07462       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
07463       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
07464     }
07465 
07466     // If it's a friend (and only if it's a friend), it's possible
07467     // that either the specialized function type or the specialized
07468     // template is dependent, and therefore matching will fail.  In
07469     // this case, don't check the specialization yet.
07470     bool InstantiationDependent = false;
07471     if (isFunctionTemplateSpecialization && isFriend &&
07472         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
07473          TemplateSpecializationType::anyDependentTemplateArguments(
07474             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
07475             InstantiationDependent))) {
07476       assert(HasExplicitTemplateArgs &&
07477              "friend function specialization without template args");
07478       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
07479                                                        Previous))
07480         NewFD->setInvalidDecl();
07481     } else if (isFunctionTemplateSpecialization) {
07482       if (CurContext->isDependentContext() && CurContext->isRecord() 
07483           && !isFriend) {
07484         isDependentClassScopeExplicitSpecialization = true;
07485         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 
07486           diag::ext_function_specialization_in_class :
07487           diag::err_function_specialization_in_class)
07488           << NewFD->getDeclName();
07489       } else if (CheckFunctionTemplateSpecialization(NewFD,
07490                                   (HasExplicitTemplateArgs ? &TemplateArgs
07491                                                            : nullptr),
07492                                                      Previous))
07493         NewFD->setInvalidDecl();
07494       
07495       // C++ [dcl.stc]p1:
07496       //   A storage-class-specifier shall not be specified in an explicit
07497       //   specialization (14.7.3)
07498       FunctionTemplateSpecializationInfo *Info =
07499           NewFD->getTemplateSpecializationInfo();
07500       if (Info && SC != SC_None) {
07501         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
07502           Diag(NewFD->getLocation(),
07503                diag::err_explicit_specialization_inconsistent_storage_class)
07504             << SC
07505             << FixItHint::CreateRemoval(
07506                                       D.getDeclSpec().getStorageClassSpecLoc());
07507             
07508         else
07509           Diag(NewFD->getLocation(), 
07510                diag::ext_explicit_specialization_storage_class)
07511             << FixItHint::CreateRemoval(
07512                                       D.getDeclSpec().getStorageClassSpecLoc());
07513       }
07514       
07515     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
07516       if (CheckMemberSpecialization(NewFD, Previous))
07517           NewFD->setInvalidDecl();
07518     }
07519 
07520     // Perform semantic checking on the function declaration.
07521     if (!isDependentClassScopeExplicitSpecialization) {
07522       if (!NewFD->isInvalidDecl() && NewFD->isMain())
07523         CheckMain(NewFD, D.getDeclSpec());
07524 
07525       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
07526         CheckMSVCRTEntryPoint(NewFD);
07527 
07528       if (!NewFD->isInvalidDecl())
07529         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
07530                                                     isExplicitSpecialization));
07531     }
07532 
07533     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
07534             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
07535            "previous declaration set still overloaded");
07536 
07537     NamedDecl *PrincipalDecl = (FunctionTemplate
07538                                 ? cast<NamedDecl>(FunctionTemplate)
07539                                 : NewFD);
07540 
07541     if (isFriend && D.isRedeclaration()) {
07542       AccessSpecifier Access = AS_public;
07543       if (!NewFD->isInvalidDecl())
07544         Access = NewFD->getPreviousDecl()->getAccess();
07545 
07546       NewFD->setAccess(Access);
07547       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
07548     }
07549 
07550     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
07551         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
07552       PrincipalDecl->setNonMemberOperator();
07553 
07554     // If we have a function template, check the template parameter
07555     // list. This will check and merge default template arguments.
07556     if (FunctionTemplate) {
07557       FunctionTemplateDecl *PrevTemplate = 
07558                                      FunctionTemplate->getPreviousDecl();
07559       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
07560                        PrevTemplate ? PrevTemplate->getTemplateParameters()
07561                                     : nullptr,
07562                             D.getDeclSpec().isFriendSpecified()
07563                               ? (D.isFunctionDefinition()
07564                                    ? TPC_FriendFunctionTemplateDefinition
07565                                    : TPC_FriendFunctionTemplate)
07566                               : (D.getCXXScopeSpec().isSet() && 
07567                                  DC && DC->isRecord() && 
07568                                  DC->isDependentContext())
07569                                   ? TPC_ClassTemplateMember
07570                                   : TPC_FunctionTemplate);
07571     }
07572 
07573     if (NewFD->isInvalidDecl()) {
07574       // Ignore all the rest of this.
07575     } else if (!D.isRedeclaration()) {
07576       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
07577                                        AddToScope };
07578       // Fake up an access specifier if it's supposed to be a class member.
07579       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
07580         NewFD->setAccess(AS_public);
07581 
07582       // Qualified decls generally require a previous declaration.
07583       if (D.getCXXScopeSpec().isSet()) {
07584         // ...with the major exception of templated-scope or
07585         // dependent-scope friend declarations.
07586 
07587         // TODO: we currently also suppress this check in dependent
07588         // contexts because (1) the parameter depth will be off when
07589         // matching friend templates and (2) we might actually be
07590         // selecting a friend based on a dependent factor.  But there
07591         // are situations where these conditions don't apply and we
07592         // can actually do this check immediately.
07593         if (isFriend &&
07594             (TemplateParamLists.size() ||
07595              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
07596              CurContext->isDependentContext())) {
07597           // ignore these
07598         } else {
07599           // The user tried to provide an out-of-line definition for a
07600           // function that is a member of a class or namespace, but there
07601           // was no such member function declared (C++ [class.mfct]p2,
07602           // C++ [namespace.memdef]p2). For example:
07603           //
07604           // class X {
07605           //   void f() const;
07606           // };
07607           //
07608           // void X::f() { } // ill-formed
07609           //
07610           // Complain about this problem, and attempt to suggest close
07611           // matches (e.g., those that differ only in cv-qualifiers and
07612           // whether the parameter types are references).
07613 
07614           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
07615                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
07616             AddToScope = ExtraArgs.AddToScope;
07617             return Result;
07618           }
07619         }
07620 
07621         // Unqualified local friend declarations are required to resolve
07622         // to something.
07623       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
07624         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
07625                 *this, Previous, NewFD, ExtraArgs, true, S)) {
07626           AddToScope = ExtraArgs.AddToScope;
07627           return Result;
07628         }
07629       }
07630 
07631     } else if (!D.isFunctionDefinition() &&
07632                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
07633                !isFriend && !isFunctionTemplateSpecialization &&
07634                !isExplicitSpecialization) {
07635       // An out-of-line member function declaration must also be a
07636       // definition (C++ [class.mfct]p2).
07637       // Note that this is not the case for explicit specializations of
07638       // function templates or member functions of class templates, per
07639       // C++ [temp.expl.spec]p2. We also allow these declarations as an 
07640       // extension for compatibility with old SWIG code which likes to 
07641       // generate them.
07642       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
07643         << D.getCXXScopeSpec().getRange();
07644     }
07645   }
07646 
07647   ProcessPragmaWeak(S, NewFD);
07648   checkAttributesAfterMerging(*this, *NewFD);
07649 
07650   AddKnownFunctionAttributes(NewFD);
07651 
07652   if (NewFD->hasAttr<OverloadableAttr>() && 
07653       !NewFD->getType()->getAs<FunctionProtoType>()) {
07654     Diag(NewFD->getLocation(),
07655          diag::err_attribute_overloadable_no_prototype)
07656       << NewFD;
07657 
07658     // Turn this into a variadic function with no parameters.
07659     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
07660     FunctionProtoType::ExtProtoInfo EPI(
07661         Context.getDefaultCallingConvention(true, false));
07662     EPI.Variadic = true;
07663     EPI.ExtInfo = FT->getExtInfo();
07664 
07665     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
07666     NewFD->setType(R);
07667   }
07668 
07669   // If there's a #pragma GCC visibility in scope, and this isn't a class
07670   // member, set the visibility of this function.
07671   if (!DC->isRecord() && NewFD->isExternallyVisible())
07672     AddPushedVisibilityAttribute(NewFD);
07673 
07674   // If there's a #pragma clang arc_cf_code_audited in scope, consider
07675   // marking the function.
07676   AddCFAuditedAttribute(NewFD);
07677 
07678   // If this is a function definition, check if we have to apply optnone due to
07679   // a pragma.
07680   if(D.isFunctionDefinition())
07681     AddRangeBasedOptnone(NewFD);
07682 
07683   // If this is the first declaration of an extern C variable, update
07684   // the map of such variables.
07685   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
07686       isIncompleteDeclExternC(*this, NewFD))
07687     RegisterLocallyScopedExternCDecl(NewFD, S);
07688 
07689   // Set this FunctionDecl's range up to the right paren.
07690   NewFD->setRangeEnd(D.getSourceRange().getEnd());
07691 
07692   if (D.isRedeclaration() && !Previous.empty()) {
07693     checkDLLAttributeRedeclaration(
07694         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
07695         isExplicitSpecialization || isFunctionTemplateSpecialization);
07696   }
07697 
07698   if (getLangOpts().CPlusPlus) {
07699     if (FunctionTemplate) {
07700       if (NewFD->isInvalidDecl())
07701         FunctionTemplate->setInvalidDecl();
07702       return FunctionTemplate;
07703     }
07704   }
07705 
07706   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
07707     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
07708     if ((getLangOpts().OpenCLVersion >= 120)
07709         && (SC == SC_Static)) {
07710       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
07711       D.setInvalidType();
07712     }
07713     
07714     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
07715     if (!NewFD->getReturnType()->isVoidType()) {
07716       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
07717       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
07718           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
07719                                 : FixItHint());
07720       D.setInvalidType();
07721     }
07722 
07723     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
07724     for (auto Param : NewFD->params())
07725       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
07726   }
07727 
07728   MarkUnusedFileScopedDecl(NewFD);
07729 
07730   if (getLangOpts().CUDA)
07731     if (IdentifierInfo *II = NewFD->getIdentifier())
07732       if (!NewFD->isInvalidDecl() &&
07733           NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
07734         if (II->isStr("cudaConfigureCall")) {
07735           if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
07736             Diag(NewFD->getLocation(), diag::err_config_scalar_return);
07737 
07738           Context.setcudaConfigureCallDecl(NewFD);
07739         }
07740       }
07741   
07742   // Here we have an function template explicit specialization at class scope.
07743   // The actually specialization will be postponed to template instatiation
07744   // time via the ClassScopeFunctionSpecializationDecl node.
07745   if (isDependentClassScopeExplicitSpecialization) {
07746     ClassScopeFunctionSpecializationDecl *NewSpec =
07747                          ClassScopeFunctionSpecializationDecl::Create(
07748                                 Context, CurContext, SourceLocation(), 
07749                                 cast<CXXMethodDecl>(NewFD),
07750                                 HasExplicitTemplateArgs, TemplateArgs);
07751     CurContext->addDecl(NewSpec);
07752     AddToScope = false;
07753   }
07754 
07755   return NewFD;
07756 }
07757 
07758 /// \brief Perform semantic checking of a new function declaration.
07759 ///
07760 /// Performs semantic analysis of the new function declaration
07761 /// NewFD. This routine performs all semantic checking that does not
07762 /// require the actual declarator involved in the declaration, and is
07763 /// used both for the declaration of functions as they are parsed
07764 /// (called via ActOnDeclarator) and for the declaration of functions
07765 /// that have been instantiated via C++ template instantiation (called
07766 /// via InstantiateDecl).
07767 ///
07768 /// \param IsExplicitSpecialization whether this new function declaration is
07769 /// an explicit specialization of the previous declaration.
07770 ///
07771 /// This sets NewFD->isInvalidDecl() to true if there was an error.
07772 ///
07773 /// \returns true if the function declaration is a redeclaration.
07774 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
07775                                     LookupResult &Previous,
07776                                     bool IsExplicitSpecialization) {
07777   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
07778          "Variably modified return types are not handled here");
07779 
07780   // Determine whether the type of this function should be merged with
07781   // a previous visible declaration. This never happens for functions in C++,
07782   // and always happens in C if the previous declaration was visible.
07783   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
07784                                !Previous.isShadowed();
07785 
07786   // Filter out any non-conflicting previous declarations.
07787   filterNonConflictingPreviousDecls(Context, NewFD, Previous);
07788 
07789   bool Redeclaration = false;
07790   NamedDecl *OldDecl = nullptr;
07791 
07792   // Merge or overload the declaration with an existing declaration of
07793   // the same name, if appropriate.
07794   if (!Previous.empty()) {
07795     // Determine whether NewFD is an overload of PrevDecl or
07796     // a declaration that requires merging. If it's an overload,
07797     // there's no more work to do here; we'll just add the new
07798     // function to the scope.
07799     if (!AllowOverloadingOfFunction(Previous, Context)) {
07800       NamedDecl *Candidate = Previous.getFoundDecl();
07801       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
07802         Redeclaration = true;
07803         OldDecl = Candidate;
07804       }
07805     } else {
07806       switch (CheckOverload(S, NewFD, Previous, OldDecl,
07807                             /*NewIsUsingDecl*/ false)) {
07808       case Ovl_Match:
07809         Redeclaration = true;
07810         break;
07811 
07812       case Ovl_NonFunction:
07813         Redeclaration = true;
07814         break;
07815 
07816       case Ovl_Overload:
07817         Redeclaration = false;
07818         break;
07819       }
07820 
07821       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
07822         // If a function name is overloadable in C, then every function
07823         // with that name must be marked "overloadable".
07824         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
07825           << Redeclaration << NewFD;
07826         NamedDecl *OverloadedDecl = nullptr;
07827         if (Redeclaration)
07828           OverloadedDecl = OldDecl;
07829         else if (!Previous.empty())
07830           OverloadedDecl = Previous.getRepresentativeDecl();
07831         if (OverloadedDecl)
07832           Diag(OverloadedDecl->getLocation(),
07833                diag::note_attribute_overloadable_prev_overload);
07834         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
07835       }
07836     }
07837   }
07838 
07839   // Check for a previous extern "C" declaration with this name.
07840   if (!Redeclaration &&
07841       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
07842     filterNonConflictingPreviousDecls(Context, NewFD, Previous);
07843     if (!Previous.empty()) {
07844       // This is an extern "C" declaration with the same name as a previous
07845       // declaration, and thus redeclares that entity...
07846       Redeclaration = true;
07847       OldDecl = Previous.getFoundDecl();
07848       MergeTypeWithPrevious = false;
07849 
07850       // ... except in the presence of __attribute__((overloadable)).
07851       if (OldDecl->hasAttr<OverloadableAttr>()) {
07852         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
07853           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
07854             << Redeclaration << NewFD;
07855           Diag(Previous.getFoundDecl()->getLocation(),
07856                diag::note_attribute_overloadable_prev_overload);
07857           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
07858         }
07859         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
07860           Redeclaration = false;
07861           OldDecl = nullptr;
07862         }
07863       }
07864     }
07865   }
07866 
07867   // C++11 [dcl.constexpr]p8:
07868   //   A constexpr specifier for a non-static member function that is not
07869   //   a constructor declares that member function to be const.
07870   //
07871   // This needs to be delayed until we know whether this is an out-of-line
07872   // definition of a static member function.
07873   //
07874   // This rule is not present in C++1y, so we produce a backwards
07875   // compatibility warning whenever it happens in C++11.
07876   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
07877   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
07878       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
07879       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
07880     CXXMethodDecl *OldMD = nullptr;
07881     if (OldDecl)
07882       OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction());
07883     if (!OldMD || !OldMD->isStatic()) {
07884       const FunctionProtoType *FPT =
07885         MD->getType()->castAs<FunctionProtoType>();
07886       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
07887       EPI.TypeQuals |= Qualifiers::Const;
07888       MD->setType(Context.getFunctionType(FPT->getReturnType(),
07889                                           FPT->getParamTypes(), EPI));
07890 
07891       // Warn that we did this, if we're not performing template instantiation.
07892       // In that case, we'll have warned already when the template was defined.
07893       if (ActiveTemplateInstantiations.empty()) {
07894         SourceLocation AddConstLoc;
07895         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
07896                 .IgnoreParens().getAs<FunctionTypeLoc>())
07897           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
07898 
07899         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
07900           << FixItHint::CreateInsertion(AddConstLoc, " const");
07901       }
07902     }
07903   }
07904 
07905   if (Redeclaration) {
07906     // NewFD and OldDecl represent declarations that need to be
07907     // merged.
07908     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
07909       NewFD->setInvalidDecl();
07910       return Redeclaration;
07911     }
07912 
07913     Previous.clear();
07914     Previous.addDecl(OldDecl);
07915 
07916     if (FunctionTemplateDecl *OldTemplateDecl
07917                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
07918       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
07919       FunctionTemplateDecl *NewTemplateDecl
07920         = NewFD->getDescribedFunctionTemplate();
07921       assert(NewTemplateDecl && "Template/non-template mismatch");
07922       if (CXXMethodDecl *Method 
07923             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
07924         Method->setAccess(OldTemplateDecl->getAccess());
07925         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
07926       }
07927       
07928       // If this is an explicit specialization of a member that is a function
07929       // template, mark it as a member specialization.
07930       if (IsExplicitSpecialization && 
07931           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
07932         NewTemplateDecl->setMemberSpecialization();
07933         assert(OldTemplateDecl->isMemberSpecialization());
07934       }
07935       
07936     } else {
07937       // This needs to happen first so that 'inline' propagates.
07938       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
07939 
07940       if (isa<CXXMethodDecl>(NewFD)) {
07941         // A valid redeclaration of a C++ method must be out-of-line,
07942         // but (unfortunately) it's not necessarily a definition
07943         // because of templates, which means that the previous
07944         // declaration is not necessarily from the class definition.
07945 
07946         // For just setting the access, that doesn't matter.
07947         CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
07948         NewFD->setAccess(oldMethod->getAccess());
07949 
07950         // Update the key-function state if necessary for this ABI.
07951         if (NewFD->isInlined() &&
07952             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
07953           // setNonKeyFunction needs to work with the original
07954           // declaration from the class definition, and isVirtual() is
07955           // just faster in that case, so map back to that now.
07956           oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
07957           if (oldMethod->isVirtual()) {
07958             Context.setNonKeyFunction(oldMethod);
07959           }
07960         }
07961       }
07962     }
07963   }
07964 
07965   // Semantic checking for this function declaration (in isolation).
07966 
07967   if (getLangOpts().CPlusPlus) {
07968     // C++-specific checks.
07969     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
07970       CheckConstructor(Constructor);
07971     } else if (CXXDestructorDecl *Destructor = 
07972                 dyn_cast<CXXDestructorDecl>(NewFD)) {
07973       CXXRecordDecl *Record = Destructor->getParent();
07974       QualType ClassType = Context.getTypeDeclType(Record);
07975       
07976       // FIXME: Shouldn't we be able to perform this check even when the class
07977       // type is dependent? Both gcc and edg can handle that.
07978       if (!ClassType->isDependentType()) {
07979         DeclarationName Name
07980           = Context.DeclarationNames.getCXXDestructorName(
07981                                         Context.getCanonicalType(ClassType));
07982         if (NewFD->getDeclName() != Name) {
07983           Diag(NewFD->getLocation(), diag::err_destructor_name);
07984           NewFD->setInvalidDecl();
07985           return Redeclaration;
07986         }
07987       }
07988     } else if (CXXConversionDecl *Conversion
07989                = dyn_cast<CXXConversionDecl>(NewFD)) {
07990       ActOnConversionDeclarator(Conversion);
07991     }
07992 
07993     // Find any virtual functions that this function overrides.
07994     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
07995       if (!Method->isFunctionTemplateSpecialization() && 
07996           !Method->getDescribedFunctionTemplate() &&
07997           Method->isCanonicalDecl()) {
07998         if (AddOverriddenMethods(Method->getParent(), Method)) {
07999           // If the function was marked as "static", we have a problem.
08000           if (NewFD->getStorageClass() == SC_Static) {
08001             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
08002           }
08003         }
08004       }
08005       
08006       if (Method->isStatic())
08007         checkThisInStaticMemberFunctionType(Method);
08008     }
08009 
08010     // Extra checking for C++ overloaded operators (C++ [over.oper]).
08011     if (NewFD->isOverloadedOperator() &&
08012         CheckOverloadedOperatorDeclaration(NewFD)) {
08013       NewFD->setInvalidDecl();
08014       return Redeclaration;
08015     }
08016 
08017     // Extra checking for C++0x literal operators (C++0x [over.literal]).
08018     if (NewFD->getLiteralIdentifier() &&
08019         CheckLiteralOperatorDeclaration(NewFD)) {
08020       NewFD->setInvalidDecl();
08021       return Redeclaration;
08022     }
08023 
08024     // In C++, check default arguments now that we have merged decls. Unless
08025     // the lexical context is the class, because in this case this is done
08026     // during delayed parsing anyway.
08027     if (!CurContext->isRecord())
08028       CheckCXXDefaultArguments(NewFD);
08029 
08030     // If this function declares a builtin function, check the type of this
08031     // declaration against the expected type for the builtin. 
08032     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
08033       ASTContext::GetBuiltinTypeError Error;
08034       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
08035       QualType T = Context.GetBuiltinType(BuiltinID, Error);
08036       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
08037         // The type of this function differs from the type of the builtin,
08038         // so forget about the builtin entirely.
08039         Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
08040       }
08041     }
08042 
08043     // If this function is declared as being extern "C", then check to see if 
08044     // the function returns a UDT (class, struct, or union type) that is not C
08045     // compatible, and if it does, warn the user.
08046     // But, issue any diagnostic on the first declaration only.
08047     if (NewFD->isExternC() && Previous.empty()) {
08048       QualType R = NewFD->getReturnType();
08049       if (R->isIncompleteType() && !R->isVoidType())
08050         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
08051             << NewFD << R;
08052       else if (!R.isPODType(Context) && !R->isVoidType() &&
08053                !R->isObjCObjectPointerType())
08054         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
08055     }
08056   }
08057   return Redeclaration;
08058 }
08059 
08060 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
08061   // C++11 [basic.start.main]p3:
08062   //   A program that [...] declares main to be inline, static or
08063   //   constexpr is ill-formed.
08064   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
08065   //   appear in a declaration of main.
08066   // static main is not an error under C99, but we should warn about it.
08067   // We accept _Noreturn main as an extension.
08068   if (FD->getStorageClass() == SC_Static)
08069     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 
08070          ? diag::err_static_main : diag::warn_static_main) 
08071       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
08072   if (FD->isInlineSpecified())
08073     Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 
08074       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
08075   if (DS.isNoreturnSpecified()) {
08076     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
08077     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
08078     Diag(NoreturnLoc, diag::ext_noreturn_main);
08079     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
08080       << FixItHint::CreateRemoval(NoreturnRange);
08081   }
08082   if (FD->isConstexpr()) {
08083     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
08084       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
08085     FD->setConstexpr(false);
08086   }
08087 
08088   if (getLangOpts().OpenCL) {
08089     Diag(FD->getLocation(), diag::err_opencl_no_main)
08090         << FD->hasAttr<OpenCLKernelAttr>();
08091     FD->setInvalidDecl();
08092     return;
08093   }
08094 
08095   QualType T = FD->getType();
08096   assert(T->isFunctionType() && "function decl is not of function type");
08097   const FunctionType* FT = T->castAs<FunctionType>();
08098 
08099   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
08100     // In C with GNU extensions we allow main() to have non-integer return
08101     // type, but we should warn about the extension, and we disable the
08102     // implicit-return-zero rule.
08103 
08104     // GCC in C mode accepts qualified 'int'.
08105     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
08106       FD->setHasImplicitReturnZero(true);
08107     else {
08108       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
08109       SourceRange RTRange = FD->getReturnTypeSourceRange();
08110       if (RTRange.isValid())
08111         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
08112             << FixItHint::CreateReplacement(RTRange, "int");
08113     }
08114   } else {
08115     // In C and C++, main magically returns 0 if you fall off the end;
08116     // set the flag which tells us that.
08117     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
08118 
08119     // All the standards say that main() should return 'int'.
08120     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
08121       FD->setHasImplicitReturnZero(true);
08122     else {
08123       // Otherwise, this is just a flat-out error.
08124       SourceRange RTRange = FD->getReturnTypeSourceRange();
08125       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
08126           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
08127                                 : FixItHint());
08128       FD->setInvalidDecl(true);
08129     }
08130   }
08131 
08132   // Treat protoless main() as nullary.
08133   if (isa<FunctionNoProtoType>(FT)) return;
08134 
08135   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
08136   unsigned nparams = FTP->getNumParams();
08137   assert(FD->getNumParams() == nparams);
08138 
08139   bool HasExtraParameters = (nparams > 3);
08140 
08141   // Darwin passes an undocumented fourth argument of type char**.  If
08142   // other platforms start sprouting these, the logic below will start
08143   // getting shifty.
08144   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
08145     HasExtraParameters = false;
08146 
08147   if (HasExtraParameters) {
08148     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
08149     FD->setInvalidDecl(true);
08150     nparams = 3;
08151   }
08152 
08153   // FIXME: a lot of the following diagnostics would be improved
08154   // if we had some location information about types.
08155 
08156   QualType CharPP =
08157     Context.getPointerType(Context.getPointerType(Context.CharTy));
08158   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
08159 
08160   for (unsigned i = 0; i < nparams; ++i) {
08161     QualType AT = FTP->getParamType(i);
08162 
08163     bool mismatch = true;
08164 
08165     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
08166       mismatch = false;
08167     else if (Expected[i] == CharPP) {
08168       // As an extension, the following forms are okay:
08169       //   char const **
08170       //   char const * const *
08171       //   char * const *
08172 
08173       QualifierCollector qs;
08174       const PointerType* PT;
08175       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
08176           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
08177           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
08178                               Context.CharTy)) {
08179         qs.removeConst();
08180         mismatch = !qs.empty();
08181       }
08182     }
08183 
08184     if (mismatch) {
08185       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
08186       // TODO: suggest replacing given type with expected type
08187       FD->setInvalidDecl(true);
08188     }
08189   }
08190 
08191   if (nparams == 1 && !FD->isInvalidDecl()) {
08192     Diag(FD->getLocation(), diag::warn_main_one_arg);
08193   }
08194   
08195   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
08196     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
08197     FD->setInvalidDecl();
08198   }
08199 }
08200 
08201 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
08202   QualType T = FD->getType();
08203   assert(T->isFunctionType() && "function decl is not of function type");
08204   const FunctionType *FT = T->castAs<FunctionType>();
08205 
08206   // Set an implicit return of 'zero' if the function can return some integral,
08207   // enumeration, pointer or nullptr type.
08208   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
08209       FT->getReturnType()->isAnyPointerType() ||
08210       FT->getReturnType()->isNullPtrType())
08211     // DllMain is exempt because a return value of zero means it failed.
08212     if (FD->getName() != "DllMain")
08213       FD->setHasImplicitReturnZero(true);
08214 
08215   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
08216     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
08217     FD->setInvalidDecl();
08218   }
08219 }
08220 
08221 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
08222   // FIXME: Need strict checking.  In C89, we need to check for
08223   // any assignment, increment, decrement, function-calls, or
08224   // commas outside of a sizeof.  In C99, it's the same list,
08225   // except that the aforementioned are allowed in unevaluated
08226   // expressions.  Everything else falls under the
08227   // "may accept other forms of constant expressions" exception.
08228   // (We never end up here for C++, so the constant expression
08229   // rules there don't matter.)
08230   const Expr *Culprit;
08231   if (Init->isConstantInitializer(Context, false, &Culprit))
08232     return false;
08233   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
08234     << Culprit->getSourceRange();
08235   return true;
08236 }
08237 
08238 namespace {
08239   // Visits an initialization expression to see if OrigDecl is evaluated in
08240   // its own initialization and throws a warning if it does.
08241   class SelfReferenceChecker
08242       : public EvaluatedExprVisitor<SelfReferenceChecker> {
08243     Sema &S;
08244     Decl *OrigDecl;
08245     bool isRecordType;
08246     bool isPODType;
08247     bool isReferenceType;
08248 
08249     bool isInitList;
08250     llvm::SmallVector<unsigned, 4> InitFieldIndex;
08251   public:
08252     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
08253 
08254     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
08255                                                     S(S), OrigDecl(OrigDecl) {
08256       isPODType = false;
08257       isRecordType = false;
08258       isReferenceType = false;
08259       isInitList = false;
08260       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
08261         isPODType = VD->getType().isPODType(S.Context);
08262         isRecordType = VD->getType()->isRecordType();
08263         isReferenceType = VD->getType()->isReferenceType();
08264       }
08265     }
08266 
08267     // For most expressions, just call the visitor.  For initializer lists,
08268     // track the index of the field being initialized since fields are
08269     // initialized in order allowing use of previously initialized fields.
08270     void CheckExpr(Expr *E) {
08271       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
08272       if (!InitList) {
08273         Visit(E);
08274         return;
08275       }
08276 
08277       // Track and increment the index here.
08278       isInitList = true;
08279       InitFieldIndex.push_back(0);
08280       for (auto Child : InitList->children()) {
08281         CheckExpr(cast<Expr>(Child));
08282         ++InitFieldIndex.back();
08283       }
08284       InitFieldIndex.pop_back();
08285     }
08286 
08287     // Returns true if MemberExpr is checked and no futher checking is needed.
08288     // Returns false if additional checking is required.
08289     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
08290       llvm::SmallVector<FieldDecl*, 4> Fields;
08291       Expr *Base = E;
08292       bool ReferenceField = false;
08293 
08294       // Get the field memebers used.
08295       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
08296         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
08297         if (!FD)
08298           return false;
08299         Fields.push_back(FD);
08300         if (FD->getType()->isReferenceType())
08301           ReferenceField = true;
08302         Base = ME->getBase()->IgnoreParenImpCasts();
08303       }
08304 
08305       // Keep checking only if the base Decl is the same.
08306       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
08307       if (!DRE || DRE->getDecl() != OrigDecl)
08308         return false;
08309 
08310       // A reference field can be bound to an unininitialized field.
08311       if (CheckReference && !ReferenceField)
08312         return true;
08313 
08314       // Convert FieldDecls to their index number.
08315       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
08316       for (auto I = Fields.rbegin(), E = Fields.rend(); I != E; ++I) {
08317         UsedFieldIndex.push_back((*I)->getFieldIndex());
08318       }
08319 
08320       // See if a warning is needed by checking the first difference in index
08321       // numbers.  If field being used has index less than the field being
08322       // initialized, then the use is safe.
08323       for (auto UsedIter = UsedFieldIndex.begin(),
08324                 UsedEnd = UsedFieldIndex.end(),
08325                 OrigIter = InitFieldIndex.begin(),
08326                 OrigEnd = InitFieldIndex.end();
08327            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
08328         if (*UsedIter < *OrigIter)
08329           return true;
08330         if (*UsedIter > *OrigIter)
08331           break;
08332       }
08333 
08334       // TODO: Add a different warning which will print the field names.
08335       HandleDeclRefExpr(DRE);
08336       return true;
08337     }
08338 
08339     // For most expressions, the cast is directly above the DeclRefExpr.
08340     // For conditional operators, the cast can be outside the conditional
08341     // operator if both expressions are DeclRefExpr's.
08342     void HandleValue(Expr *E) {
08343       E = E->IgnoreParens();
08344       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
08345         HandleDeclRefExpr(DRE);
08346         return;
08347       }
08348 
08349       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
08350         Visit(CO->getCond());
08351         HandleValue(CO->getTrueExpr());
08352         HandleValue(CO->getFalseExpr());
08353         return;
08354       }
08355 
08356       if (BinaryConditionalOperator *BCO =
08357               dyn_cast<BinaryConditionalOperator>(E)) {
08358         Visit(BCO->getCond());
08359         HandleValue(BCO->getFalseExpr());
08360         return;
08361       }
08362 
08363       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
08364         HandleValue(OVE->getSourceExpr());
08365         return;
08366       }
08367 
08368       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
08369         if (BO->getOpcode() == BO_Comma) {
08370           Visit(BO->getLHS());
08371           HandleValue(BO->getRHS());
08372           return;
08373         }
08374       }
08375 
08376       if (isa<MemberExpr>(E)) {
08377         if (isInitList) {
08378           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
08379                                       false /*CheckReference*/))
08380             return;
08381         }
08382 
08383         Expr *Base = E->IgnoreParenImpCasts();
08384         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
08385           // Check for static member variables and don't warn on them.
08386           if (!isa<FieldDecl>(ME->getMemberDecl()))
08387             return;
08388           Base = ME->getBase()->IgnoreParenImpCasts();
08389         }
08390         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
08391           HandleDeclRefExpr(DRE);
08392         return;
08393       }
08394 
08395       Visit(E);
08396     }
08397 
08398     // Reference types not handled in HandleValue are handled here since all
08399     // uses of references are bad, not just r-value uses.
08400     void VisitDeclRefExpr(DeclRefExpr *E) {
08401       if (isReferenceType)
08402         HandleDeclRefExpr(E);
08403     }
08404 
08405     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
08406       if (E->getCastKind() == CK_LValueToRValue) {
08407         HandleValue(E->getSubExpr());
08408         return;
08409       }
08410 
08411       Inherited::VisitImplicitCastExpr(E);
08412     }
08413 
08414     void VisitMemberExpr(MemberExpr *E) {
08415       if (isInitList) {
08416         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
08417           return;
08418       }
08419 
08420       // Don't warn on arrays since they can be treated as pointers.
08421       if (E->getType()->canDecayToPointerType()) return;
08422 
08423       // Warn when a non-static method call is followed by non-static member
08424       // field accesses, which is followed by a DeclRefExpr.
08425       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
08426       bool Warn = (MD && !MD->isStatic());
08427       Expr *Base = E->getBase()->IgnoreParenImpCasts();
08428       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
08429         if (!isa<FieldDecl>(ME->getMemberDecl()))
08430           Warn = false;
08431         Base = ME->getBase()->IgnoreParenImpCasts();
08432       }
08433 
08434       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
08435         if (Warn)
08436           HandleDeclRefExpr(DRE);
08437         return;
08438       }
08439 
08440       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
08441       // Visit that expression.
08442       Visit(Base);
08443     }
08444 
08445     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
08446       Expr *Callee = E->getCallee();
08447 
08448       if (isa<UnresolvedLookupExpr>(Callee))
08449         return Inherited::VisitCXXOperatorCallExpr(E);
08450 
08451       Visit(Callee);
08452       for (auto Arg: E->arguments())
08453         HandleValue(Arg->IgnoreParenImpCasts());
08454     }
08455 
08456     void VisitUnaryOperator(UnaryOperator *E) {
08457       // For POD record types, addresses of its own members are well-defined.
08458       if (E->getOpcode() == UO_AddrOf && isRecordType &&
08459           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
08460         if (!isPODType)
08461           HandleValue(E->getSubExpr());
08462         return;
08463       }
08464 
08465       if (E->isIncrementDecrementOp()) {
08466         HandleValue(E->getSubExpr());
08467         return;
08468       }
08469 
08470       Inherited::VisitUnaryOperator(E);
08471     }
08472 
08473     void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
08474 
08475     void VisitCXXConstructExpr(CXXConstructExpr *E) {
08476       if (E->getConstructor()->isCopyConstructor()) {
08477         Expr *ArgExpr = E->getArg(0);
08478         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
08479           if (ILE->getNumInits() == 1)
08480             ArgExpr = ILE->getInit(0);
08481         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
08482           if (ICE->getCastKind() == CK_NoOp)
08483             ArgExpr = ICE->getSubExpr();
08484         HandleValue(ArgExpr);
08485         return;
08486       }
08487       Inherited::VisitCXXConstructExpr(E);
08488     }
08489 
08490     void VisitCallExpr(CallExpr *E) {
08491       // Treat std::move as a use.
08492       if (E->getNumArgs() == 1) {
08493         if (FunctionDecl *FD = E->getDirectCallee()) {
08494           if (FD->getIdentifier() && FD->getIdentifier()->isStr("move")) {
08495             HandleValue(E->getArg(0));
08496             return;
08497           }
08498         }
08499       }
08500 
08501       Inherited::VisitCallExpr(E);
08502     }
08503 
08504     void VisitBinaryOperator(BinaryOperator *E) {
08505       if (E->isCompoundAssignmentOp()) {
08506         HandleValue(E->getLHS());
08507         Visit(E->getRHS());
08508         return;
08509       }
08510 
08511       Inherited::VisitBinaryOperator(E);
08512     }
08513 
08514     // A custom visitor for BinaryConditionalOperator is needed because the
08515     // regular visitor would check the condition and true expression separately
08516     // but both point to the same place giving duplicate diagnostics.
08517     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
08518       Visit(E->getCond());
08519       Visit(E->getFalseExpr());
08520     }
08521 
08522     void HandleDeclRefExpr(DeclRefExpr *DRE) {
08523       Decl* ReferenceDecl = DRE->getDecl();
08524       if (OrigDecl != ReferenceDecl) return;
08525       unsigned diag;
08526       if (isReferenceType) {
08527         diag = diag::warn_uninit_self_reference_in_reference_init;
08528       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
08529         diag = diag::warn_static_self_reference_in_init;
08530       } else {
08531         diag = diag::warn_uninit_self_reference_in_init;
08532       }
08533 
08534       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
08535                             S.PDiag(diag)
08536                               << DRE->getNameInfo().getName()
08537                               << OrigDecl->getLocation()
08538                               << DRE->getSourceRange());
08539     }
08540   };
08541 
08542   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
08543   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
08544                                  bool DirectInit) {
08545     // Parameters arguments are occassionially constructed with itself,
08546     // for instance, in recursive functions.  Skip them.
08547     if (isa<ParmVarDecl>(OrigDecl))
08548       return;
08549 
08550     E = E->IgnoreParens();
08551 
08552     // Skip checking T a = a where T is not a record or reference type.
08553     // Doing so is a way to silence uninitialized warnings.
08554     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
08555       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
08556         if (ICE->getCastKind() == CK_LValueToRValue)
08557           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
08558             if (DRE->getDecl() == OrigDecl)
08559               return;
08560 
08561     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
08562   }
08563 }
08564 
08565 /// AddInitializerToDecl - Adds the initializer Init to the
08566 /// declaration dcl. If DirectInit is true, this is C++ direct
08567 /// initialization rather than copy initialization.
08568 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
08569                                 bool DirectInit, bool TypeMayContainAuto) {
08570   // If there is no declaration, there was an error parsing it.  Just ignore
08571   // the initializer.
08572   if (!RealDecl || RealDecl->isInvalidDecl())
08573     return;
08574 
08575   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
08576     // With declarators parsed the way they are, the parser cannot
08577     // distinguish between a normal initializer and a pure-specifier.
08578     // Thus this grotesque test.
08579     IntegerLiteral *IL;
08580     if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
08581         Context.getCanonicalType(IL->getType()) == Context.IntTy)
08582       CheckPureMethod(Method, Init->getSourceRange());
08583     else {
08584       Diag(Method->getLocation(), diag::err_member_function_initialization)
08585         << Method->getDeclName() << Init->getSourceRange();
08586       Method->setInvalidDecl();
08587     }
08588     return;
08589   }
08590 
08591   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
08592   if (!VDecl) {
08593     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
08594     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
08595     RealDecl->setInvalidDecl();
08596     return;
08597   }
08598   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
08599 
08600   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
08601   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
08602     Expr *DeduceInit = Init;
08603     // Initializer could be a C++ direct-initializer. Deduction only works if it
08604     // contains exactly one expression.
08605     if (CXXDirectInit) {
08606       if (CXXDirectInit->getNumExprs() == 0) {
08607         // It isn't possible to write this directly, but it is possible to
08608         // end up in this situation with "auto x(some_pack...);"
08609         Diag(CXXDirectInit->getLocStart(),
08610              VDecl->isInitCapture() ? diag::err_init_capture_no_expression
08611                                     : diag::err_auto_var_init_no_expression)
08612           << VDecl->getDeclName() << VDecl->getType()
08613           << VDecl->getSourceRange();
08614         RealDecl->setInvalidDecl();
08615         return;
08616       } else if (CXXDirectInit->getNumExprs() > 1) {
08617         Diag(CXXDirectInit->getExpr(1)->getLocStart(),
08618              VDecl->isInitCapture()
08619                  ? diag::err_init_capture_multiple_expressions
08620                  : diag::err_auto_var_init_multiple_expressions)
08621           << VDecl->getDeclName() << VDecl->getType()
08622           << VDecl->getSourceRange();
08623         RealDecl->setInvalidDecl();
08624         return;
08625       } else {
08626         DeduceInit = CXXDirectInit->getExpr(0);
08627         if (isa<InitListExpr>(DeduceInit))
08628           Diag(CXXDirectInit->getLocStart(),
08629                diag::err_auto_var_init_paren_braces)
08630             << VDecl->getDeclName() << VDecl->getType()
08631             << VDecl->getSourceRange();
08632       }
08633     }
08634 
08635     // Expressions default to 'id' when we're in a debugger.
08636     bool DefaultedToAuto = false;
08637     if (getLangOpts().DebuggerCastResultToId &&
08638         Init->getType() == Context.UnknownAnyTy) {
08639       ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
08640       if (Result.isInvalid()) {
08641         VDecl->setInvalidDecl();
08642         return;
08643       }
08644       Init = Result.get();
08645       DefaultedToAuto = true;
08646     }
08647 
08648     QualType DeducedType;
08649     if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
08650             DAR_Failed)
08651       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
08652     if (DeducedType.isNull()) {
08653       RealDecl->setInvalidDecl();
08654       return;
08655     }
08656     VDecl->setType(DeducedType);
08657     assert(VDecl->isLinkageValid());
08658 
08659     // In ARC, infer lifetime.
08660     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
08661       VDecl->setInvalidDecl();
08662 
08663     // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
08664     // 'id' instead of a specific object type prevents most of our usual checks.
08665     // We only want to warn outside of template instantiations, though:
08666     // inside a template, the 'id' could have come from a parameter.
08667     if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
08668         DeducedType->isObjCIdType()) {
08669       SourceLocation Loc =
08670           VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
08671       Diag(Loc, diag::warn_auto_var_is_id)
08672         << VDecl->getDeclName() << DeduceInit->getSourceRange();
08673     }
08674 
08675     // If this is a redeclaration, check that the type we just deduced matches
08676     // the previously declared type.
08677     if (VarDecl *Old = VDecl->getPreviousDecl()) {
08678       // We never need to merge the type, because we cannot form an incomplete
08679       // array of auto, nor deduce such a type.
08680       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
08681     }
08682 
08683     // Check the deduced type is valid for a variable declaration.
08684     CheckVariableDeclarationType(VDecl);
08685     if (VDecl->isInvalidDecl())
08686       return;
08687   }
08688 
08689   // dllimport cannot be used on variable definitions.
08690   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
08691     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
08692     VDecl->setInvalidDecl();
08693     return;
08694   }
08695 
08696   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
08697     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
08698     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
08699     VDecl->setInvalidDecl();
08700     return;
08701   }
08702 
08703   if (!VDecl->getType()->isDependentType()) {
08704     // A definition must end up with a complete type, which means it must be
08705     // complete with the restriction that an array type might be completed by
08706     // the initializer; note that later code assumes this restriction.
08707     QualType BaseDeclType = VDecl->getType();
08708     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
08709       BaseDeclType = Array->getElementType();
08710     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
08711                             diag::err_typecheck_decl_incomplete_type)) {
08712       RealDecl->setInvalidDecl();
08713       return;
08714     }
08715 
08716     // The variable can not have an abstract class type.
08717     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
08718                                diag::err_abstract_type_in_decl,
08719                                AbstractVariableType))
08720       VDecl->setInvalidDecl();
08721   }
08722 
08723   const VarDecl *Def;
08724   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
08725     Diag(VDecl->getLocation(), diag::err_redefinition)
08726       << VDecl->getDeclName();
08727     Diag(Def->getLocation(), diag::note_previous_definition);
08728     VDecl->setInvalidDecl();
08729     return;
08730   }
08731 
08732   const VarDecl *PrevInit = nullptr;
08733   if (getLangOpts().CPlusPlus) {
08734     // C++ [class.static.data]p4
08735     //   If a static data member is of const integral or const
08736     //   enumeration type, its declaration in the class definition can
08737     //   specify a constant-initializer which shall be an integral
08738     //   constant expression (5.19). In that case, the member can appear
08739     //   in integral constant expressions. The member shall still be
08740     //   defined in a namespace scope if it is used in the program and the
08741     //   namespace scope definition shall not contain an initializer.
08742     //
08743     // We already performed a redefinition check above, but for static
08744     // data members we also need to check whether there was an in-class
08745     // declaration with an initializer.
08746     if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
08747       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
08748           << VDecl->getDeclName();
08749       Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0;
08750       return;
08751     }  
08752 
08753     if (VDecl->hasLocalStorage())
08754       getCurFunction()->setHasBranchProtectedScope();
08755 
08756     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
08757       VDecl->setInvalidDecl();
08758       return;
08759     }
08760   }
08761 
08762   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
08763   // a kernel function cannot be initialized."
08764   if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
08765     Diag(VDecl->getLocation(), diag::err_local_cant_init);
08766     VDecl->setInvalidDecl();
08767     return;
08768   }
08769 
08770   // Get the decls type and save a reference for later, since
08771   // CheckInitializerTypes may change it.
08772   QualType DclT = VDecl->getType(), SavT = DclT;
08773   
08774   // Expressions default to 'id' when we're in a debugger
08775   // and we are assigning it to a variable of Objective-C pointer type.
08776   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
08777       Init->getType() == Context.UnknownAnyTy) {
08778     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
08779     if (Result.isInvalid()) {
08780       VDecl->setInvalidDecl();
08781       return;
08782     }
08783     Init = Result.get();
08784   }
08785 
08786   // Perform the initialization.
08787   if (!VDecl->isInvalidDecl()) {
08788     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
08789     InitializationKind Kind
08790       = DirectInit ?
08791           CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
08792                                                            Init->getLocStart(),
08793                                                            Init->getLocEnd())
08794                         : InitializationKind::CreateDirectList(
08795                                                           VDecl->getLocation())
08796                    : InitializationKind::CreateCopy(VDecl->getLocation(),
08797                                                     Init->getLocStart());
08798 
08799     MultiExprArg Args = Init;
08800     if (CXXDirectInit)
08801       Args = MultiExprArg(CXXDirectInit->getExprs(),
08802                           CXXDirectInit->getNumExprs());
08803 
08804     InitializationSequence InitSeq(*this, Entity, Kind, Args);
08805     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
08806     if (Result.isInvalid()) {
08807       VDecl->setInvalidDecl();
08808       return;
08809     }
08810 
08811     Init = Result.getAs<Expr>();
08812   }
08813 
08814   // Check for self-references within variable initializers.
08815   // Variables declared within a function/method body (except for references)
08816   // are handled by a dataflow analysis.
08817   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
08818       VDecl->getType()->isReferenceType()) {
08819     CheckSelfReference(*this, RealDecl, Init, DirectInit);
08820   }
08821 
08822   // If the type changed, it means we had an incomplete type that was
08823   // completed by the initializer. For example:
08824   //   int ary[] = { 1, 3, 5 };
08825   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
08826   if (!VDecl->isInvalidDecl() && (DclT != SavT))
08827     VDecl->setType(DclT);
08828 
08829   if (!VDecl->isInvalidDecl()) {
08830     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
08831 
08832     if (VDecl->hasAttr<BlocksAttr>())
08833       checkRetainCycles(VDecl, Init);
08834 
08835     // It is safe to assign a weak reference into a strong variable.
08836     // Although this code can still have problems:
08837     //   id x = self.weakProp;
08838     //   id y = self.weakProp;
08839     // we do not warn to warn spuriously when 'x' and 'y' are on separate
08840     // paths through the function. This should be revisited if
08841     // -Wrepeated-use-of-weak is made flow-sensitive.
08842     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
08843         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
08844                          Init->getLocStart()))
08845         getCurFunction()->markSafeWeakUse(Init);
08846   }
08847 
08848   // The initialization is usually a full-expression.
08849   //
08850   // FIXME: If this is a braced initialization of an aggregate, it is not
08851   // an expression, and each individual field initializer is a separate
08852   // full-expression. For instance, in:
08853   //
08854   //   struct Temp { ~Temp(); };
08855   //   struct S { S(Temp); };
08856   //   struct T { S a, b; } t = { Temp(), Temp() }
08857   //
08858   // we should destroy the first Temp before constructing the second.
08859   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
08860                                           false,
08861                                           VDecl->isConstexpr());
08862   if (Result.isInvalid()) {
08863     VDecl->setInvalidDecl();
08864     return;
08865   }
08866   Init = Result.get();
08867 
08868   // Attach the initializer to the decl.
08869   VDecl->setInit(Init);
08870 
08871   if (VDecl->isLocalVarDecl()) {
08872     // C99 6.7.8p4: All the expressions in an initializer for an object that has
08873     // static storage duration shall be constant expressions or string literals.
08874     // C++ does not have this restriction.
08875     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
08876       const Expr *Culprit;
08877       if (VDecl->getStorageClass() == SC_Static)
08878         CheckForConstantInitializer(Init, DclT);
08879       // C89 is stricter than C99 for non-static aggregate types.
08880       // C89 6.5.7p3: All the expressions [...] in an initializer list
08881       // for an object that has aggregate or union type shall be
08882       // constant expressions.
08883       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
08884                isa<InitListExpr>(Init) &&
08885                !Init->isConstantInitializer(Context, false, &Culprit))
08886         Diag(Culprit->getExprLoc(),
08887              diag::ext_aggregate_init_not_constant)
08888           << Culprit->getSourceRange();
08889     }
08890   } else if (VDecl->isStaticDataMember() &&
08891              VDecl->getLexicalDeclContext()->isRecord()) {
08892     // This is an in-class initialization for a static data member, e.g.,
08893     //
08894     // struct S {
08895     //   static const int value = 17;
08896     // };
08897 
08898     // C++ [class.mem]p4:
08899     //   A member-declarator can contain a constant-initializer only
08900     //   if it declares a static member (9.4) of const integral or
08901     //   const enumeration type, see 9.4.2.
08902     //
08903     // C++11 [class.static.data]p3:
08904     //   If a non-volatile const static data member is of integral or
08905     //   enumeration type, its declaration in the class definition can
08906     //   specify a brace-or-equal-initializer in which every initalizer-clause
08907     //   that is an assignment-expression is a constant expression. A static
08908     //   data member of literal type can be declared in the class definition
08909     //   with the constexpr specifier; if so, its declaration shall specify a
08910     //   brace-or-equal-initializer in which every initializer-clause that is
08911     //   an assignment-expression is a constant expression.
08912 
08913     // Do nothing on dependent types.
08914     if (DclT->isDependentType()) {
08915 
08916     // Allow any 'static constexpr' members, whether or not they are of literal
08917     // type. We separately check that every constexpr variable is of literal
08918     // type.
08919     } else if (VDecl->isConstexpr()) {
08920 
08921     // Require constness.
08922     } else if (!DclT.isConstQualified()) {
08923       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
08924         << Init->getSourceRange();
08925       VDecl->setInvalidDecl();
08926 
08927     // We allow integer constant expressions in all cases.
08928     } else if (DclT->isIntegralOrEnumerationType()) {
08929       // Check whether the expression is a constant expression.
08930       SourceLocation Loc;
08931       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
08932         // In C++11, a non-constexpr const static data member with an
08933         // in-class initializer cannot be volatile.
08934         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
08935       else if (Init->isValueDependent())
08936         ; // Nothing to check.
08937       else if (Init->isIntegerConstantExpr(Context, &Loc))
08938         ; // Ok, it's an ICE!
08939       else if (Init->isEvaluatable(Context)) {
08940         // If we can constant fold the initializer through heroics, accept it,
08941         // but report this as a use of an extension for -pedantic.
08942         Diag(Loc, diag::ext_in_class_initializer_non_constant)
08943           << Init->getSourceRange();
08944       } else {
08945         // Otherwise, this is some crazy unknown case.  Report the issue at the
08946         // location provided by the isIntegerConstantExpr failed check.
08947         Diag(Loc, diag::err_in_class_initializer_non_constant)
08948           << Init->getSourceRange();
08949         VDecl->setInvalidDecl();
08950       }
08951 
08952     // We allow foldable floating-point constants as an extension.
08953     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
08954       // In C++98, this is a GNU extension. In C++11, it is not, but we support
08955       // it anyway and provide a fixit to add the 'constexpr'.
08956       if (getLangOpts().CPlusPlus11) {
08957         Diag(VDecl->getLocation(),
08958              diag::ext_in_class_initializer_float_type_cxx11)
08959             << DclT << Init->getSourceRange();
08960         Diag(VDecl->getLocStart(),
08961              diag::note_in_class_initializer_float_type_cxx11)
08962             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
08963       } else {
08964         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
08965           << DclT << Init->getSourceRange();
08966 
08967         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
08968           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
08969             << Init->getSourceRange();
08970           VDecl->setInvalidDecl();
08971         }
08972       }
08973 
08974     // Suggest adding 'constexpr' in C++11 for literal types.
08975     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
08976       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
08977         << DclT << Init->getSourceRange()
08978         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
08979       VDecl->setConstexpr(true);
08980 
08981     } else {
08982       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
08983         << DclT << Init->getSourceRange();
08984       VDecl->setInvalidDecl();
08985     }
08986   } else if (VDecl->isFileVarDecl()) {
08987     if (VDecl->getStorageClass() == SC_Extern &&
08988         (!getLangOpts().CPlusPlus ||
08989          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
08990            VDecl->isExternC())) &&
08991         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
08992       Diag(VDecl->getLocation(), diag::warn_extern_init);
08993 
08994     // C99 6.7.8p4. All file scoped initializers need to be constant.
08995     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
08996       CheckForConstantInitializer(Init, DclT);
08997   }
08998 
08999   // We will represent direct-initialization similarly to copy-initialization:
09000   //    int x(1);  -as-> int x = 1;
09001   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
09002   //
09003   // Clients that want to distinguish between the two forms, can check for
09004   // direct initializer using VarDecl::getInitStyle().
09005   // A major benefit is that clients that don't particularly care about which
09006   // exactly form was it (like the CodeGen) can handle both cases without
09007   // special case code.
09008 
09009   // C++ 8.5p11:
09010   // The form of initialization (using parentheses or '=') is generally
09011   // insignificant, but does matter when the entity being initialized has a
09012   // class type.
09013   if (CXXDirectInit) {
09014     assert(DirectInit && "Call-style initializer must be direct init.");
09015     VDecl->setInitStyle(VarDecl::CallInit);
09016   } else if (DirectInit) {
09017     // This must be list-initialization. No other way is direct-initialization.
09018     VDecl->setInitStyle(VarDecl::ListInit);
09019   }
09020 
09021   CheckCompleteVariableDeclaration(VDecl);
09022 }
09023 
09024 /// ActOnInitializerError - Given that there was an error parsing an
09025 /// initializer for the given declaration, try to return to some form
09026 /// of sanity.
09027 void Sema::ActOnInitializerError(Decl *D) {
09028   // Our main concern here is re-establishing invariants like "a
09029   // variable's type is either dependent or complete".
09030   if (!D || D->isInvalidDecl()) return;
09031 
09032   VarDecl *VD = dyn_cast<VarDecl>(D);
09033   if (!VD) return;
09034 
09035   // Auto types are meaningless if we can't make sense of the initializer.
09036   if (ParsingInitForAutoVars.count(D)) {
09037     D->setInvalidDecl();
09038     return;
09039   }
09040 
09041   QualType Ty = VD->getType();
09042   if (Ty->isDependentType()) return;
09043 
09044   // Require a complete type.
09045   if (RequireCompleteType(VD->getLocation(), 
09046                           Context.getBaseElementType(Ty),
09047                           diag::err_typecheck_decl_incomplete_type)) {
09048     VD->setInvalidDecl();
09049     return;
09050   }
09051 
09052   // Require a non-abstract type.
09053   if (RequireNonAbstractType(VD->getLocation(), Ty,
09054                              diag::err_abstract_type_in_decl,
09055                              AbstractVariableType)) {
09056     VD->setInvalidDecl();
09057     return;
09058   }
09059 
09060   // Don't bother complaining about constructors or destructors,
09061   // though.
09062 }
09063 
09064 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
09065                                   bool TypeMayContainAuto) {
09066   // If there is no declaration, there was an error parsing it. Just ignore it.
09067   if (!RealDecl)
09068     return;
09069 
09070   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
09071     QualType Type = Var->getType();
09072 
09073     // C++11 [dcl.spec.auto]p3
09074     if (TypeMayContainAuto && Type->getContainedAutoType()) {
09075       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
09076         << Var->getDeclName() << Type;
09077       Var->setInvalidDecl();
09078       return;
09079     }
09080 
09081     // C++11 [class.static.data]p3: A static data member can be declared with
09082     // the constexpr specifier; if so, its declaration shall specify
09083     // a brace-or-equal-initializer.
09084     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
09085     // the definition of a variable [...] or the declaration of a static data
09086     // member.
09087     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
09088       if (Var->isStaticDataMember())
09089         Diag(Var->getLocation(),
09090              diag::err_constexpr_static_mem_var_requires_init)
09091           << Var->getDeclName();
09092       else
09093         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
09094       Var->setInvalidDecl();
09095       return;
09096     }
09097 
09098     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
09099     // be initialized.
09100     if (!Var->isInvalidDecl() &&
09101         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
09102         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
09103       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
09104       Var->setInvalidDecl();
09105       return;
09106     }
09107 
09108     switch (Var->isThisDeclarationADefinition()) {
09109     case VarDecl::Definition:
09110       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
09111         break;
09112 
09113       // We have an out-of-line definition of a static data member
09114       // that has an in-class initializer, so we type-check this like
09115       // a declaration. 
09116       //
09117       // Fall through
09118       
09119     case VarDecl::DeclarationOnly:
09120       // It's only a declaration. 
09121 
09122       // Block scope. C99 6.7p7: If an identifier for an object is
09123       // declared with no linkage (C99 6.2.2p6), the type for the
09124       // object shall be complete.
09125       if (!Type->isDependentType() && Var->isLocalVarDecl() && 
09126           !Var->hasLinkage() && !Var->isInvalidDecl() &&
09127           RequireCompleteType(Var->getLocation(), Type,
09128                               diag::err_typecheck_decl_incomplete_type))
09129         Var->setInvalidDecl();
09130 
09131       // Make sure that the type is not abstract.
09132       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
09133           RequireNonAbstractType(Var->getLocation(), Type,
09134                                  diag::err_abstract_type_in_decl,
09135                                  AbstractVariableType))
09136         Var->setInvalidDecl();
09137       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
09138           Var->getStorageClass() == SC_PrivateExtern) {
09139         Diag(Var->getLocation(), diag::warn_private_extern);
09140         Diag(Var->getLocation(), diag::note_private_extern);
09141       }
09142         
09143       return;
09144 
09145     case VarDecl::TentativeDefinition:
09146       // File scope. C99 6.9.2p2: A declaration of an identifier for an
09147       // object that has file scope without an initializer, and without a
09148       // storage-class specifier or with the storage-class specifier "static",
09149       // constitutes a tentative definition. Note: A tentative definition with
09150       // external linkage is valid (C99 6.2.2p5).
09151       if (!Var->isInvalidDecl()) {
09152         if (const IncompleteArrayType *ArrayT
09153                                     = Context.getAsIncompleteArrayType(Type)) {
09154           if (RequireCompleteType(Var->getLocation(),
09155                                   ArrayT->getElementType(),
09156                                   diag::err_illegal_decl_array_incomplete_type))
09157             Var->setInvalidDecl();
09158         } else if (Var->getStorageClass() == SC_Static) {
09159           // C99 6.9.2p3: If the declaration of an identifier for an object is
09160           // a tentative definition and has internal linkage (C99 6.2.2p3), the
09161           // declared type shall not be an incomplete type.
09162           // NOTE: code such as the following
09163           //     static struct s;
09164           //     struct s { int a; };
09165           // is accepted by gcc. Hence here we issue a warning instead of
09166           // an error and we do not invalidate the static declaration.
09167           // NOTE: to avoid multiple warnings, only check the first declaration.
09168           if (Var->isFirstDecl())
09169             RequireCompleteType(Var->getLocation(), Type,
09170                                 diag::ext_typecheck_decl_incomplete_type);
09171         }
09172       }
09173 
09174       // Record the tentative definition; we're done.
09175       if (!Var->isInvalidDecl())
09176         TentativeDefinitions.push_back(Var);
09177       return;
09178     }
09179 
09180     // Provide a specific diagnostic for uninitialized variable
09181     // definitions with incomplete array type.
09182     if (Type->isIncompleteArrayType()) {
09183       Diag(Var->getLocation(),
09184            diag::err_typecheck_incomplete_array_needs_initializer);
09185       Var->setInvalidDecl();
09186       return;
09187     }
09188 
09189     // Provide a specific diagnostic for uninitialized variable
09190     // definitions with reference type.
09191     if (Type->isReferenceType()) {
09192       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
09193         << Var->getDeclName()
09194         << SourceRange(Var->getLocation(), Var->getLocation());
09195       Var->setInvalidDecl();
09196       return;
09197     }
09198 
09199     // Do not attempt to type-check the default initializer for a
09200     // variable with dependent type.
09201     if (Type->isDependentType())
09202       return;
09203 
09204     if (Var->isInvalidDecl())
09205       return;
09206 
09207     if (!Var->hasAttr<AliasAttr>()) {
09208       if (RequireCompleteType(Var->getLocation(),
09209                               Context.getBaseElementType(Type),
09210                               diag::err_typecheck_decl_incomplete_type)) {
09211         Var->setInvalidDecl();
09212         return;
09213       }
09214     }
09215 
09216     // The variable can not have an abstract class type.
09217     if (RequireNonAbstractType(Var->getLocation(), Type,
09218                                diag::err_abstract_type_in_decl,
09219                                AbstractVariableType)) {
09220       Var->setInvalidDecl();
09221       return;
09222     }
09223 
09224     // Check for jumps past the implicit initializer.  C++0x
09225     // clarifies that this applies to a "variable with automatic
09226     // storage duration", not a "local variable".
09227     // C++11 [stmt.dcl]p3
09228     //   A program that jumps from a point where a variable with automatic
09229     //   storage duration is not in scope to a point where it is in scope is
09230     //   ill-formed unless the variable has scalar type, class type with a
09231     //   trivial default constructor and a trivial destructor, a cv-qualified
09232     //   version of one of these types, or an array of one of the preceding
09233     //   types and is declared without an initializer.
09234     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
09235       if (const RecordType *Record
09236             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
09237         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
09238         // Mark the function for further checking even if the looser rules of
09239         // C++11 do not require such checks, so that we can diagnose
09240         // incompatibilities with C++98.
09241         if (!CXXRecord->isPOD())
09242           getCurFunction()->setHasBranchProtectedScope();
09243       }
09244     }
09245     
09246     // C++03 [dcl.init]p9:
09247     //   If no initializer is specified for an object, and the
09248     //   object is of (possibly cv-qualified) non-POD class type (or
09249     //   array thereof), the object shall be default-initialized; if
09250     //   the object is of const-qualified type, the underlying class
09251     //   type shall have a user-declared default
09252     //   constructor. Otherwise, if no initializer is specified for
09253     //   a non- static object, the object and its subobjects, if
09254     //   any, have an indeterminate initial value); if the object
09255     //   or any of its subobjects are of const-qualified type, the
09256     //   program is ill-formed.
09257     // C++0x [dcl.init]p11:
09258     //   If no initializer is specified for an object, the object is
09259     //   default-initialized; [...].
09260     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
09261     InitializationKind Kind
09262       = InitializationKind::CreateDefault(Var->getLocation());
09263 
09264     InitializationSequence InitSeq(*this, Entity, Kind, None);
09265     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
09266     if (Init.isInvalid())
09267       Var->setInvalidDecl();
09268     else if (Init.get()) {
09269       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
09270       // This is important for template substitution.
09271       Var->setInitStyle(VarDecl::CallInit);
09272     }
09273 
09274     CheckCompleteVariableDeclaration(Var);
09275   }
09276 }
09277 
09278 void Sema::ActOnCXXForRangeDecl(Decl *D) {
09279   VarDecl *VD = dyn_cast<VarDecl>(D);
09280   if (!VD) {
09281     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
09282     D->setInvalidDecl();
09283     return;
09284   }
09285 
09286   VD->setCXXForRangeDecl(true);
09287 
09288   // for-range-declaration cannot be given a storage class specifier.
09289   int Error = -1;
09290   switch (VD->getStorageClass()) {
09291   case SC_None:
09292     break;
09293   case SC_Extern:
09294     Error = 0;
09295     break;
09296   case SC_Static:
09297     Error = 1;
09298     break;
09299   case SC_PrivateExtern:
09300     Error = 2;
09301     break;
09302   case SC_Auto:
09303     Error = 3;
09304     break;
09305   case SC_Register:
09306     Error = 4;
09307     break;
09308   case SC_OpenCLWorkGroupLocal:
09309     llvm_unreachable("Unexpected storage class");
09310   }
09311   if (VD->isConstexpr())
09312     Error = 5;
09313   if (Error != -1) {
09314     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
09315       << VD->getDeclName() << Error;
09316     D->setInvalidDecl();
09317   }
09318 }
09319 
09320 StmtResult
09321 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
09322                                  IdentifierInfo *Ident,
09323                                  ParsedAttributes &Attrs,
09324                                  SourceLocation AttrEnd) {
09325   // C++1y [stmt.iter]p1:
09326   //   A range-based for statement of the form
09327   //      for ( for-range-identifier : for-range-initializer ) statement
09328   //   is equivalent to
09329   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
09330   DeclSpec DS(Attrs.getPool().getFactory());
09331 
09332   const char *PrevSpec;
09333   unsigned DiagID;
09334   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
09335                      getPrintingPolicy());
09336 
09337   Declarator D(DS, Declarator::ForContext);
09338   D.SetIdentifier(Ident, IdentLoc);
09339   D.takeAttributes(Attrs, AttrEnd);
09340 
09341   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
09342   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
09343                 EmptyAttrs, IdentLoc);
09344   Decl *Var = ActOnDeclarator(S, D);
09345   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
09346   FinalizeDeclaration(Var);
09347   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
09348                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
09349 }
09350 
09351 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
09352   if (var->isInvalidDecl()) return;
09353 
09354   // In ARC, don't allow jumps past the implicit initialization of a
09355   // local retaining variable.
09356   if (getLangOpts().ObjCAutoRefCount &&
09357       var->hasLocalStorage()) {
09358     switch (var->getType().getObjCLifetime()) {
09359     case Qualifiers::OCL_None:
09360     case Qualifiers::OCL_ExplicitNone:
09361     case Qualifiers::OCL_Autoreleasing:
09362       break;
09363 
09364     case Qualifiers::OCL_Weak:
09365     case Qualifiers::OCL_Strong:
09366       getCurFunction()->setHasBranchProtectedScope();
09367       break;
09368     }
09369   }
09370 
09371   // Warn about externally-visible variables being defined without a
09372   // prior declaration.  We only want to do this for global
09373   // declarations, but we also specifically need to avoid doing it for
09374   // class members because the linkage of an anonymous class can
09375   // change if it's later given a typedef name.
09376   if (var->isThisDeclarationADefinition() &&
09377       var->getDeclContext()->getRedeclContext()->isFileContext() &&
09378       var->isExternallyVisible() && var->hasLinkage() &&
09379       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
09380                                   var->getLocation())) {
09381     // Find a previous declaration that's not a definition.
09382     VarDecl *prev = var->getPreviousDecl();
09383     while (prev && prev->isThisDeclarationADefinition())
09384       prev = prev->getPreviousDecl();
09385 
09386     if (!prev)
09387       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
09388   }
09389 
09390   if (var->getTLSKind() == VarDecl::TLS_Static) {
09391     const Expr *Culprit;
09392     if (var->getType().isDestructedType()) {
09393       // GNU C++98 edits for __thread, [basic.start.term]p3:
09394       //   The type of an object with thread storage duration shall not
09395       //   have a non-trivial destructor.
09396       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
09397       if (getLangOpts().CPlusPlus11)
09398         Diag(var->getLocation(), diag::note_use_thread_local);
09399     } else if (getLangOpts().CPlusPlus && var->hasInit() &&
09400                !var->getInit()->isConstantInitializer(
09401                    Context, var->getType()->isReferenceType(), &Culprit)) {
09402       // GNU C++98 edits for __thread, [basic.start.init]p4:
09403       //   An object of thread storage duration shall not require dynamic
09404       //   initialization.
09405       // FIXME: Need strict checking here.
09406       Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
09407         << Culprit->getSourceRange();
09408       if (getLangOpts().CPlusPlus11)
09409         Diag(var->getLocation(), diag::note_use_thread_local);
09410     }
09411 
09412   }
09413 
09414   if (var->isThisDeclarationADefinition() &&
09415       ActiveTemplateInstantiations.empty()) {
09416     PragmaStack<StringLiteral *> *Stack = nullptr;
09417     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
09418     if (var->getType().isConstQualified())
09419       Stack = &ConstSegStack;
09420     else if (!var->getInit()) {
09421       Stack = &BSSSegStack;
09422       SectionFlags |= ASTContext::PSF_Write;
09423     } else {
09424       Stack = &DataSegStack;
09425       SectionFlags |= ASTContext::PSF_Write;
09426     }
09427     if (!var->hasAttr<SectionAttr>() && Stack->CurrentValue)
09428       var->addAttr(
09429           SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
09430                                       Stack->CurrentValue->getString(),
09431                                       Stack->CurrentPragmaLocation));
09432     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
09433       if (UnifySection(SA->getName(), SectionFlags, var))
09434         var->dropAttr<SectionAttr>();
09435 
09436     // Apply the init_seg attribute if this has an initializer.  If the
09437     // initializer turns out to not be dynamic, we'll end up ignoring this
09438     // attribute.
09439     if (CurInitSeg && var->getInit())
09440       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
09441                                                CurInitSegLoc));
09442   }
09443 
09444   // All the following checks are C++ only.
09445   if (!getLangOpts().CPlusPlus) return;
09446 
09447   QualType type = var->getType();
09448   if (type->isDependentType()) return;
09449 
09450   // __block variables might require us to capture a copy-initializer.
09451   if (var->hasAttr<BlocksAttr>()) {
09452     // It's currently invalid to ever have a __block variable with an
09453     // array type; should we diagnose that here?
09454 
09455     // Regardless, we don't want to ignore array nesting when
09456     // constructing this copy.
09457     if (type->isStructureOrClassType()) {
09458       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
09459       SourceLocation poi = var->getLocation();
09460       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
09461       ExprResult result
09462         = PerformMoveOrCopyInitialization(
09463             InitializedEntity::InitializeBlock(poi, type, false),
09464             var, var->getType(), varRef, /*AllowNRVO=*/true);
09465       if (!result.isInvalid()) {
09466         result = MaybeCreateExprWithCleanups(result);
09467         Expr *init = result.getAs<Expr>();
09468         Context.setBlockVarCopyInits(var, init);
09469       }
09470     }
09471   }
09472 
09473   Expr *Init = var->getInit();
09474   bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
09475   QualType baseType = Context.getBaseElementType(type);
09476 
09477   if (!var->getDeclContext()->isDependentContext() &&
09478       Init && !Init->isValueDependent()) {
09479     if (IsGlobal && !var->isConstexpr() &&
09480         !getDiagnostics().isIgnored(diag::warn_global_constructor,
09481                                     var->getLocation())) {
09482       // Warn about globals which don't have a constant initializer.  Don't
09483       // warn about globals with a non-trivial destructor because we already
09484       // warned about them.
09485       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
09486       if (!(RD && !RD->hasTrivialDestructor()) &&
09487           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
09488         Diag(var->getLocation(), diag::warn_global_constructor)
09489           << Init->getSourceRange();
09490     }
09491 
09492     if (var->isConstexpr()) {
09493       SmallVector<PartialDiagnosticAt, 8> Notes;
09494       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
09495         SourceLocation DiagLoc = var->getLocation();
09496         // If the note doesn't add any useful information other than a source
09497         // location, fold it into the primary diagnostic.
09498         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
09499               diag::note_invalid_subexpr_in_const_expr) {
09500           DiagLoc = Notes[0].first;
09501           Notes.clear();
09502         }
09503         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
09504           << var << Init->getSourceRange();
09505         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
09506           Diag(Notes[I].first, Notes[I].second);
09507       }
09508     } else if (var->isUsableInConstantExpressions(Context)) {
09509       // Check whether the initializer of a const variable of integral or
09510       // enumeration type is an ICE now, since we can't tell whether it was
09511       // initialized by a constant expression if we check later.
09512       var->checkInitIsICE();
09513     }
09514   }
09515 
09516   // Require the destructor.
09517   if (const RecordType *recordType = baseType->getAs<RecordType>())
09518     FinalizeVarWithDestructor(var, recordType);
09519 }
09520 
09521 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
09522 /// any semantic actions necessary after any initializer has been attached.
09523 void
09524 Sema::FinalizeDeclaration(Decl *ThisDecl) {
09525   // Note that we are no longer parsing the initializer for this declaration.
09526   ParsingInitForAutoVars.erase(ThisDecl);
09527 
09528   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
09529   if (!VD)
09530     return;
09531 
09532   checkAttributesAfterMerging(*this, *VD);
09533 
09534   // Static locals inherit dll attributes from their function.
09535   if (VD->isStaticLocal()) {
09536     if (FunctionDecl *FD =
09537             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
09538       if (Attr *A = getDLLAttr(FD)) {
09539         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
09540         NewAttr->setInherited(true);
09541         VD->addAttr(NewAttr);
09542       }
09543     }
09544   }
09545 
09546   // Grab the dllimport or dllexport attribute off of the VarDecl.
09547   const InheritableAttr *DLLAttr = getDLLAttr(VD);
09548 
09549   // Imported static data members cannot be defined out-of-line.
09550   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
09551     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
09552         VD->isThisDeclarationADefinition()) {
09553       // We allow definitions of dllimport class template static data members
09554       // with a warning.
09555       CXXRecordDecl *Context =
09556         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
09557       bool IsClassTemplateMember =
09558           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
09559           Context->getDescribedClassTemplate();
09560 
09561       Diag(VD->getLocation(),
09562            IsClassTemplateMember
09563                ? diag::warn_attribute_dllimport_static_field_definition
09564                : diag::err_attribute_dllimport_static_field_definition);
09565       Diag(IA->getLocation(), diag::note_attribute);
09566       if (!IsClassTemplateMember)
09567         VD->setInvalidDecl();
09568     }
09569   }
09570 
09571   // dllimport/dllexport variables cannot be thread local, their TLS index
09572   // isn't exported with the variable.
09573   if (DLLAttr && VD->getTLSKind()) {
09574     Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
09575                                                                   << DLLAttr;
09576     VD->setInvalidDecl();
09577   }
09578 
09579   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
09580     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
09581       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
09582       VD->dropAttr<UsedAttr>();
09583     }
09584   }
09585 
09586   if (!VD->isInvalidDecl() &&
09587       VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
09588     if (const VarDecl *Def = VD->getDefinition()) {
09589       if (Def->hasAttr<AliasAttr>()) {
09590         Diag(VD->getLocation(), diag::err_tentative_after_alias)
09591             << VD->getDeclName();
09592         Diag(Def->getLocation(), diag::note_previous_definition);
09593         VD->setInvalidDecl();
09594       }
09595     }
09596   }
09597 
09598   const DeclContext *DC = VD->getDeclContext();
09599   // If there's a #pragma GCC visibility in scope, and this isn't a class
09600   // member, set the visibility of this variable.
09601   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
09602     AddPushedVisibilityAttribute(VD);
09603 
09604   // FIXME: Warn on unused templates.
09605   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
09606       !isa<VarTemplatePartialSpecializationDecl>(VD))
09607     MarkUnusedFileScopedDecl(VD);
09608 
09609   // Now we have parsed the initializer and can update the table of magic
09610   // tag values.
09611   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
09612       !VD->getType()->isIntegralOrEnumerationType())
09613     return;
09614 
09615   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
09616     const Expr *MagicValueExpr = VD->getInit();
09617     if (!MagicValueExpr) {
09618       continue;
09619     }
09620     llvm::APSInt MagicValueInt;
09621     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
09622       Diag(I->getRange().getBegin(),
09623            diag::err_type_tag_for_datatype_not_ice)
09624         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
09625       continue;
09626     }
09627     if (MagicValueInt.getActiveBits() > 64) {
09628       Diag(I->getRange().getBegin(),
09629            diag::err_type_tag_for_datatype_too_large)
09630         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
09631       continue;
09632     }
09633     uint64_t MagicValue = MagicValueInt.getZExtValue();
09634     RegisterTypeTagForDatatype(I->getArgumentKind(),
09635                                MagicValue,
09636                                I->getMatchingCType(),
09637                                I->getLayoutCompatible(),
09638                                I->getMustBeNull());
09639   }
09640 }
09641 
09642 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
09643                                                    ArrayRef<Decl *> Group) {
09644   SmallVector<Decl*, 8> Decls;
09645 
09646   if (DS.isTypeSpecOwned())
09647     Decls.push_back(DS.getRepAsDecl());
09648 
09649   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
09650   for (unsigned i = 0, e = Group.size(); i != e; ++i)
09651     if (Decl *D = Group[i]) {
09652       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
09653         if (!FirstDeclaratorInGroup)
09654           FirstDeclaratorInGroup = DD;
09655       Decls.push_back(D);
09656     }
09657 
09658   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
09659     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
09660       HandleTagNumbering(*this, Tag, S);
09661       if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
09662         Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
09663     }
09664   }
09665 
09666   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
09667 }
09668 
09669 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
09670 /// group, performing any necessary semantic checking.
09671 Sema::DeclGroupPtrTy
09672 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
09673                            bool TypeMayContainAuto) {
09674   // C++0x [dcl.spec.auto]p7:
09675   //   If the type deduced for the template parameter U is not the same in each
09676   //   deduction, the program is ill-formed.
09677   // FIXME: When initializer-list support is added, a distinction is needed
09678   // between the deduced type U and the deduced type which 'auto' stands for.
09679   //   auto a = 0, b = { 1, 2, 3 };
09680   // is legal because the deduced type U is 'int' in both cases.
09681   if (TypeMayContainAuto && Group.size() > 1) {
09682     QualType Deduced;
09683     CanQualType DeducedCanon;
09684     VarDecl *DeducedDecl = nullptr;
09685     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
09686       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
09687         AutoType *AT = D->getType()->getContainedAutoType();
09688         // Don't reissue diagnostics when instantiating a template.
09689         if (AT && D->isInvalidDecl())
09690           break;
09691         QualType U = AT ? AT->getDeducedType() : QualType();
09692         if (!U.isNull()) {
09693           CanQualType UCanon = Context.getCanonicalType(U);
09694           if (Deduced.isNull()) {
09695             Deduced = U;
09696             DeducedCanon = UCanon;
09697             DeducedDecl = D;
09698           } else if (DeducedCanon != UCanon) {
09699             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
09700                  diag::err_auto_different_deductions)
09701               << (AT->isDecltypeAuto() ? 1 : 0)
09702               << Deduced << DeducedDecl->getDeclName()
09703               << U << D->getDeclName()
09704               << DeducedDecl->getInit()->getSourceRange()
09705               << D->getInit()->getSourceRange();
09706             D->setInvalidDecl();
09707             break;
09708           }
09709         }
09710       }
09711     }
09712   }
09713 
09714   ActOnDocumentableDecls(Group);
09715 
09716   return DeclGroupPtrTy::make(
09717       DeclGroupRef::Create(Context, Group.data(), Group.size()));
09718 }
09719 
09720 void Sema::ActOnDocumentableDecl(Decl *D) {
09721   ActOnDocumentableDecls(D);
09722 }
09723 
09724 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
09725   // Don't parse the comment if Doxygen diagnostics are ignored.
09726   if (Group.empty() || !Group[0])
09727    return;
09728 
09729   if (Diags.isIgnored(diag::warn_doc_param_not_found, Group[0]->getLocation()))
09730     return;
09731 
09732   if (Group.size() >= 2) {
09733     // This is a decl group.  Normally it will contain only declarations
09734     // produced from declarator list.  But in case we have any definitions or
09735     // additional declaration references:
09736     //   'typedef struct S {} S;'
09737     //   'typedef struct S *S;'
09738     //   'struct S *pS;'
09739     // FinalizeDeclaratorGroup adds these as separate declarations.
09740     Decl *MaybeTagDecl = Group[0];
09741     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
09742       Group = Group.slice(1);
09743     }
09744   }
09745 
09746   // See if there are any new comments that are not attached to a decl.
09747   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
09748   if (!Comments.empty() &&
09749       !Comments.back()->isAttached()) {
09750     // There is at least one comment that not attached to a decl.
09751     // Maybe it should be attached to one of these decls?
09752     //
09753     // Note that this way we pick up not only comments that precede the
09754     // declaration, but also comments that *follow* the declaration -- thanks to
09755     // the lookahead in the lexer: we've consumed the semicolon and looked
09756     // ahead through comments.
09757     for (unsigned i = 0, e = Group.size(); i != e; ++i)
09758       Context.getCommentForDecl(Group[i], &PP);
09759   }
09760 }
09761 
09762 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
09763 /// to introduce parameters into function prototype scope.
09764 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
09765   const DeclSpec &DS = D.getDeclSpec();
09766 
09767   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
09768 
09769   // C++03 [dcl.stc]p2 also permits 'auto'.
09770   StorageClass SC = SC_None;
09771   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
09772     SC = SC_Register;
09773   } else if (getLangOpts().CPlusPlus &&
09774              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
09775     SC = SC_Auto;
09776   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
09777     Diag(DS.getStorageClassSpecLoc(),
09778          diag::err_invalid_storage_class_in_func_decl);
09779     D.getMutableDeclSpec().ClearStorageClassSpecs();
09780   }
09781 
09782   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
09783     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
09784       << DeclSpec::getSpecifierName(TSCS);
09785   if (DS.isConstexprSpecified())
09786     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
09787       << 0;
09788 
09789   DiagnoseFunctionSpecifiers(DS);
09790 
09791   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
09792   QualType parmDeclType = TInfo->getType();
09793 
09794   if (getLangOpts().CPlusPlus) {
09795     // Check that there are no default arguments inside the type of this
09796     // parameter.
09797     CheckExtraCXXDefaultArguments(D);
09798     
09799     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
09800     if (D.getCXXScopeSpec().isSet()) {
09801       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
09802         << D.getCXXScopeSpec().getRange();
09803       D.getCXXScopeSpec().clear();
09804     }
09805   }
09806 
09807   // Ensure we have a valid name
09808   IdentifierInfo *II = nullptr;
09809   if (D.hasName()) {
09810     II = D.getIdentifier();
09811     if (!II) {
09812       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
09813         << GetNameForDeclarator(D).getName();
09814       D.setInvalidType(true);
09815     }
09816   }
09817 
09818   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
09819   if (II) {
09820     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
09821                    ForRedeclaration);
09822     LookupName(R, S);
09823     if (R.isSingleResult()) {
09824       NamedDecl *PrevDecl = R.getFoundDecl();
09825       if (PrevDecl->isTemplateParameter()) {
09826         // Maybe we will complain about the shadowed template parameter.
09827         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
09828         // Just pretend that we didn't see the previous declaration.
09829         PrevDecl = nullptr;
09830       } else if (S->isDeclScope(PrevDecl)) {
09831         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
09832         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
09833 
09834         // Recover by removing the name
09835         II = nullptr;
09836         D.SetIdentifier(nullptr, D.getIdentifierLoc());
09837         D.setInvalidType(true);
09838       }
09839     }
09840   }
09841 
09842   // Temporarily put parameter variables in the translation unit, not
09843   // the enclosing context.  This prevents them from accidentally
09844   // looking like class members in C++.
09845   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
09846                                     D.getLocStart(),
09847                                     D.getIdentifierLoc(), II,
09848                                     parmDeclType, TInfo,
09849                                     SC);
09850 
09851   if (D.isInvalidType())
09852     New->setInvalidDecl();
09853 
09854   assert(S->isFunctionPrototypeScope());
09855   assert(S->getFunctionPrototypeDepth() >= 1);
09856   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
09857                     S->getNextFunctionPrototypeIndex());
09858   
09859   // Add the parameter declaration into this scope.
09860   S->AddDecl(New);
09861   if (II)
09862     IdResolver.AddDecl(New);
09863 
09864   ProcessDeclAttributes(S, New, D);
09865 
09866   if (D.getDeclSpec().isModulePrivateSpecified())
09867     Diag(New->getLocation(), diag::err_module_private_local)
09868       << 1 << New->getDeclName()
09869       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
09870       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
09871 
09872   if (New->hasAttr<BlocksAttr>()) {
09873     Diag(New->getLocation(), diag::err_block_on_nonlocal);
09874   }
09875   return New;
09876 }
09877 
09878 /// \brief Synthesizes a variable for a parameter arising from a
09879 /// typedef.
09880 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
09881                                               SourceLocation Loc,
09882                                               QualType T) {
09883   /* FIXME: setting StartLoc == Loc.
09884      Would it be worth to modify callers so as to provide proper source
09885      location for the unnamed parameters, embedding the parameter's type? */
09886   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
09887                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
09888                                            SC_None, nullptr);
09889   Param->setImplicit();
09890   return Param;
09891 }
09892 
09893 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
09894                                     ParmVarDecl * const *ParamEnd) {
09895   // Don't diagnose unused-parameter errors in template instantiations; we
09896   // will already have done so in the template itself.
09897   if (!ActiveTemplateInstantiations.empty())
09898     return;
09899 
09900   for (; Param != ParamEnd; ++Param) {
09901     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
09902         !(*Param)->hasAttr<UnusedAttr>()) {
09903       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
09904         << (*Param)->getDeclName();
09905     }
09906   }
09907 }
09908 
09909 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
09910                                                   ParmVarDecl * const *ParamEnd,
09911                                                   QualType ReturnTy,
09912                                                   NamedDecl *D) {
09913   if (LangOpts.NumLargeByValueCopy == 0) // No check.
09914     return;
09915 
09916   // Warn if the return value is pass-by-value and larger than the specified
09917   // threshold.
09918   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
09919     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
09920     if (Size > LangOpts.NumLargeByValueCopy)
09921       Diag(D->getLocation(), diag::warn_return_value_size)
09922           << D->getDeclName() << Size;
09923   }
09924 
09925   // Warn if any parameter is pass-by-value and larger than the specified
09926   // threshold.
09927   for (; Param != ParamEnd; ++Param) {
09928     QualType T = (*Param)->getType();
09929     if (T->isDependentType() || !T.isPODType(Context))
09930       continue;
09931     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
09932     if (Size > LangOpts.NumLargeByValueCopy)
09933       Diag((*Param)->getLocation(), diag::warn_parameter_size)
09934           << (*Param)->getDeclName() << Size;
09935   }
09936 }
09937 
09938 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
09939                                   SourceLocation NameLoc, IdentifierInfo *Name,
09940                                   QualType T, TypeSourceInfo *TSInfo,
09941                                   StorageClass SC) {
09942   // In ARC, infer a lifetime qualifier for appropriate parameter types.
09943   if (getLangOpts().ObjCAutoRefCount &&
09944       T.getObjCLifetime() == Qualifiers::OCL_None &&
09945       T->isObjCLifetimeType()) {
09946 
09947     Qualifiers::ObjCLifetime lifetime;
09948 
09949     // Special cases for arrays:
09950     //   - if it's const, use __unsafe_unretained
09951     //   - otherwise, it's an error
09952     if (T->isArrayType()) {
09953       if (!T.isConstQualified()) {
09954         DelayedDiagnostics.add(
09955             sema::DelayedDiagnostic::makeForbiddenType(
09956             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
09957       }
09958       lifetime = Qualifiers::OCL_ExplicitNone;
09959     } else {
09960       lifetime = T->getObjCARCImplicitLifetime();
09961     }
09962     T = Context.getLifetimeQualifiedType(T, lifetime);
09963   }
09964 
09965   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
09966                                          Context.getAdjustedParameterType(T), 
09967                                          TSInfo, SC, nullptr);
09968 
09969   // Parameters can not be abstract class types.
09970   // For record types, this is done by the AbstractClassUsageDiagnoser once
09971   // the class has been completely parsed.
09972   if (!CurContext->isRecord() &&
09973       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
09974                              AbstractParamType))
09975     New->setInvalidDecl();
09976 
09977   // Parameter declarators cannot be interface types. All ObjC objects are
09978   // passed by reference.
09979   if (T->isObjCObjectType()) {
09980     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
09981     Diag(NameLoc,
09982          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
09983       << FixItHint::CreateInsertion(TypeEndLoc, "*");
09984     T = Context.getObjCObjectPointerType(T);
09985     New->setType(T);
09986   }
09987 
09988   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 
09989   // duration shall not be qualified by an address-space qualifier."
09990   // Since all parameters have automatic store duration, they can not have
09991   // an address space.
09992   if (T.getAddressSpace() != 0) {
09993     // OpenCL allows function arguments declared to be an array of a type
09994     // to be qualified with an address space.
09995     if (!(getLangOpts().OpenCL && T->isArrayType())) {
09996       Diag(NameLoc, diag::err_arg_with_address_space);
09997       New->setInvalidDecl();
09998     }
09999   }   
10000 
10001   return New;
10002 }
10003 
10004 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
10005                                            SourceLocation LocAfterDecls) {
10006   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10007 
10008   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
10009   // for a K&R function.
10010   if (!FTI.hasPrototype) {
10011     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
10012       --i;
10013       if (FTI.Params[i].Param == nullptr) {
10014         SmallString<256> Code;
10015         llvm::raw_svector_ostream(Code)
10016             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
10017         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
10018             << FTI.Params[i].Ident
10019             << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
10020 
10021         // Implicitly declare the argument as type 'int' for lack of a better
10022         // type.
10023         AttributeFactory attrs;
10024         DeclSpec DS(attrs);
10025         const char* PrevSpec; // unused
10026         unsigned DiagID; // unused
10027         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
10028                            DiagID, Context.getPrintingPolicy());
10029         // Use the identifier location for the type source range.
10030         DS.SetRangeStart(FTI.Params[i].IdentLoc);
10031         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
10032         Declarator ParamD(DS, Declarator::KNRTypeListContext);
10033         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
10034         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
10035       }
10036     }
10037   }
10038 }
10039 
10040 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
10041   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
10042   assert(D.isFunctionDeclarator() && "Not a function declarator!");
10043   Scope *ParentScope = FnBodyScope->getParent();
10044 
10045   D.setFunctionDefinitionKind(FDK_Definition);
10046   Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
10047   return ActOnStartOfFunctionDef(FnBodyScope, DP);
10048 }
10049 
10050 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) {
10051   Consumer.HandleInlineMethodDefinition(D);
10052 }
10053 
10054 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 
10055                              const FunctionDecl*& PossibleZeroParamPrototype) {
10056   // Don't warn about invalid declarations.
10057   if (FD->isInvalidDecl())
10058     return false;
10059 
10060   // Or declarations that aren't global.
10061   if (!FD->isGlobal())
10062     return false;
10063 
10064   // Don't warn about C++ member functions.
10065   if (isa<CXXMethodDecl>(FD))
10066     return false;
10067 
10068   // Don't warn about 'main'.
10069   if (FD->isMain())
10070     return false;
10071 
10072   // Don't warn about inline functions.
10073   if (FD->isInlined())
10074     return false;
10075 
10076   // Don't warn about function templates.
10077   if (FD->getDescribedFunctionTemplate())
10078     return false;
10079 
10080   // Don't warn about function template specializations.
10081   if (FD->isFunctionTemplateSpecialization())
10082     return false;
10083 
10084   // Don't warn for OpenCL kernels.
10085   if (FD->hasAttr<OpenCLKernelAttr>())
10086     return false;
10087 
10088   bool MissingPrototype = true;
10089   for (const FunctionDecl *Prev = FD->getPreviousDecl();
10090        Prev; Prev = Prev->getPreviousDecl()) {
10091     // Ignore any declarations that occur in function or method
10092     // scope, because they aren't visible from the header.
10093     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
10094       continue;
10095 
10096     MissingPrototype = !Prev->getType()->isFunctionProtoType();
10097     if (FD->getNumParams() == 0)
10098       PossibleZeroParamPrototype = Prev;
10099     break;
10100   }
10101 
10102   return MissingPrototype;
10103 }
10104 
10105 void
10106 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
10107                                    const FunctionDecl *EffectiveDefinition) {
10108   // Don't complain if we're in GNU89 mode and the previous definition
10109   // was an extern inline function.
10110   const FunctionDecl *Definition = EffectiveDefinition;
10111   if (!Definition)
10112     if (!FD->isDefined(Definition))
10113       return;
10114 
10115   if (canRedefineFunction(Definition, getLangOpts()))
10116     return;
10117 
10118   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
10119       Definition->getStorageClass() == SC_Extern)
10120     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
10121         << FD->getDeclName() << getLangOpts().CPlusPlus;
10122   else
10123     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
10124 
10125   Diag(Definition->getLocation(), diag::note_previous_definition);
10126   FD->setInvalidDecl();
10127 }
10128 
10129 
10130 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 
10131                                    Sema &S) {
10132   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
10133   
10134   LambdaScopeInfo *LSI = S.PushLambdaScope();
10135   LSI->CallOperator = CallOperator;
10136   LSI->Lambda = LambdaClass;
10137   LSI->ReturnType = CallOperator->getReturnType();
10138   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
10139 
10140   if (LCD == LCD_None)
10141     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
10142   else if (LCD == LCD_ByCopy)
10143     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
10144   else if (LCD == LCD_ByRef)
10145     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
10146   DeclarationNameInfo DNI = CallOperator->getNameInfo();
10147     
10148   LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 
10149   LSI->Mutable = !CallOperator->isConst();
10150 
10151   // Add the captures to the LSI so they can be noted as already
10152   // captured within tryCaptureVar. 
10153   auto I = LambdaClass->field_begin();
10154   for (const auto &C : LambdaClass->captures()) {
10155     if (C.capturesVariable()) {
10156       VarDecl *VD = C.getCapturedVar();
10157       if (VD->isInitCapture())
10158         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
10159       QualType CaptureType = VD->getType();
10160       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
10161       LSI->addCapture(VD, /*IsBlock*/false, ByRef, 
10162           /*RefersToEnclosingLocal*/true, C.getLocation(),
10163           /*EllipsisLoc*/C.isPackExpansion() 
10164                          ? C.getEllipsisLoc() : SourceLocation(),
10165           CaptureType, /*Expr*/ nullptr);
10166 
10167     } else if (C.capturesThis()) {
10168       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 
10169                               S.getCurrentThisType(), /*Expr*/ nullptr);
10170     } else {
10171       LSI->addVLATypeCapture(C.getLocation(), I->getType());
10172     }
10173     ++I;
10174   }
10175 }
10176 
10177 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
10178   // Clear the last template instantiation error context.
10179   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
10180   
10181   if (!D)
10182     return D;
10183   FunctionDecl *FD = nullptr;
10184 
10185   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
10186     FD = FunTmpl->getTemplatedDecl();
10187   else
10188     FD = cast<FunctionDecl>(D);
10189   // If we are instantiating a generic lambda call operator, push
10190   // a LambdaScopeInfo onto the function stack.  But use the information
10191   // that's already been calculated (ActOnLambdaExpr) to prime the current 
10192   // LambdaScopeInfo.  
10193   // When the template operator is being specialized, the LambdaScopeInfo,
10194   // has to be properly restored so that tryCaptureVariable doesn't try
10195   // and capture any new variables. In addition when calculating potential
10196   // captures during transformation of nested lambdas, it is necessary to 
10197   // have the LSI properly restored. 
10198   if (isGenericLambdaCallOperatorSpecialization(FD)) {
10199     assert(ActiveTemplateInstantiations.size() &&
10200       "There should be an active template instantiation on the stack " 
10201       "when instantiating a generic lambda!");
10202     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
10203   }
10204   else
10205     // Enter a new function scope
10206     PushFunctionScope();
10207 
10208   // See if this is a redefinition.
10209   if (!FD->isLateTemplateParsed())
10210     CheckForFunctionRedefinition(FD);
10211 
10212   // Builtin functions cannot be defined.
10213   if (unsigned BuiltinID = FD->getBuiltinID()) {
10214     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
10215         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
10216       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
10217       FD->setInvalidDecl();
10218     }
10219   }
10220 
10221   // The return type of a function definition must be complete
10222   // (C99 6.9.1p3, C++ [dcl.fct]p6).
10223   QualType ResultType = FD->getReturnType();
10224   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
10225       !FD->isInvalidDecl() &&
10226       RequireCompleteType(FD->getLocation(), ResultType,
10227                           diag::err_func_def_incomplete_result))
10228     FD->setInvalidDecl();
10229 
10230   // GNU warning -Wmissing-prototypes:
10231   //   Warn if a global function is defined without a previous
10232   //   prototype declaration. This warning is issued even if the
10233   //   definition itself provides a prototype. The aim is to detect
10234   //   global functions that fail to be declared in header files.
10235   const FunctionDecl *PossibleZeroParamPrototype = nullptr;
10236   if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
10237     Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
10238 
10239     if (PossibleZeroParamPrototype) {
10240       // We found a declaration that is not a prototype,
10241       // but that could be a zero-parameter prototype
10242       if (TypeSourceInfo *TI =
10243               PossibleZeroParamPrototype->getTypeSourceInfo()) {
10244         TypeLoc TL = TI->getTypeLoc();
10245         if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
10246           Diag(PossibleZeroParamPrototype->getLocation(),
10247                diag::note_declaration_not_a_prototype)
10248             << PossibleZeroParamPrototype
10249             << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
10250       }
10251     }
10252   }
10253 
10254   if (FnBodyScope)
10255     PushDeclContext(FnBodyScope, FD);
10256 
10257   // Check the validity of our function parameters
10258   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
10259                            /*CheckParameterNames=*/true);
10260 
10261   // Introduce our parameters into the function scope
10262   for (auto Param : FD->params()) {
10263     Param->setOwningFunction(FD);
10264 
10265     // If this has an identifier, add it to the scope stack.
10266     if (Param->getIdentifier() && FnBodyScope) {
10267       CheckShadow(FnBodyScope, Param);
10268 
10269       PushOnScopeChains(Param, FnBodyScope);
10270     }
10271   }
10272 
10273   // If we had any tags defined in the function prototype,
10274   // introduce them into the function scope.
10275   if (FnBodyScope) {
10276     for (ArrayRef<NamedDecl *>::iterator
10277              I = FD->getDeclsInPrototypeScope().begin(),
10278              E = FD->getDeclsInPrototypeScope().end();
10279          I != E; ++I) {
10280       NamedDecl *D = *I;
10281 
10282       // Some of these decls (like enums) may have been pinned to the translation unit
10283       // for lack of a real context earlier. If so, remove from the translation unit
10284       // and reattach to the current context.
10285       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
10286         // Is the decl actually in the context?
10287         for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
10288           if (DI == D) {  
10289             Context.getTranslationUnitDecl()->removeDecl(D);
10290             break;
10291           }
10292         }
10293         // Either way, reassign the lexical decl context to our FunctionDecl.
10294         D->setLexicalDeclContext(CurContext);
10295       }
10296 
10297       // If the decl has a non-null name, make accessible in the current scope.
10298       if (!D->getName().empty())
10299         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
10300 
10301       // Similarly, dive into enums and fish their constants out, making them
10302       // accessible in this scope.
10303       if (auto *ED = dyn_cast<EnumDecl>(D)) {
10304         for (auto *EI : ED->enumerators())
10305           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
10306       }
10307     }
10308   }
10309 
10310   // Ensure that the function's exception specification is instantiated.
10311   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
10312     ResolveExceptionSpec(D->getLocation(), FPT);
10313 
10314   // dllimport cannot be applied to non-inline function definitions.
10315   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
10316       !FD->isTemplateInstantiation()) {
10317     assert(!FD->hasAttr<DLLExportAttr>());
10318     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
10319     FD->setInvalidDecl();
10320     return D;
10321   }
10322   // We want to attach documentation to original Decl (which might be
10323   // a function template).
10324   ActOnDocumentableDecl(D);
10325   if (getCurLexicalContext()->isObjCContainer() &&
10326       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
10327       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
10328     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
10329     
10330   return D;
10331 }
10332 
10333 /// \brief Given the set of return statements within a function body,
10334 /// compute the variables that are subject to the named return value 
10335 /// optimization.
10336 ///
10337 /// Each of the variables that is subject to the named return value 
10338 /// optimization will be marked as NRVO variables in the AST, and any
10339 /// return statement that has a marked NRVO variable as its NRVO candidate can
10340 /// use the named return value optimization.
10341 ///
10342 /// This function applies a very simplistic algorithm for NRVO: if every return
10343 /// statement in the scope of a variable has the same NRVO candidate, that
10344 /// candidate is an NRVO variable.
10345 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
10346   ReturnStmt **Returns = Scope->Returns.data();
10347 
10348   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
10349     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
10350       if (!NRVOCandidate->isNRVOVariable())
10351         Returns[I]->setNRVOCandidate(nullptr);
10352     }
10353   }
10354 }
10355 
10356 bool Sema::canDelayFunctionBody(const Declarator &D) {
10357   // We can't delay parsing the body of a constexpr function template (yet).
10358   if (D.getDeclSpec().isConstexprSpecified())
10359     return false;
10360 
10361   // We can't delay parsing the body of a function template with a deduced
10362   // return type (yet).
10363   if (D.getDeclSpec().containsPlaceholderType()) {
10364     // If the placeholder introduces a non-deduced trailing return type,
10365     // we can still delay parsing it.
10366     if (D.getNumTypeObjects()) {
10367       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
10368       if (Outer.Kind == DeclaratorChunk::Function &&
10369           Outer.Fun.hasTrailingReturnType()) {
10370         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
10371         return Ty.isNull() || !Ty->isUndeducedType();
10372       }
10373     }
10374     return false;
10375   }
10376 
10377   return true;
10378 }
10379 
10380 bool Sema::canSkipFunctionBody(Decl *D) {
10381   // We cannot skip the body of a function (or function template) which is
10382   // constexpr, since we may need to evaluate its body in order to parse the
10383   // rest of the file.
10384   // We cannot skip the body of a function with an undeduced return type,
10385   // because any callers of that function need to know the type.
10386   if (const FunctionDecl *FD = D->getAsFunction())
10387     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
10388       return false;
10389   return Consumer.shouldSkipFunctionBody(D);
10390 }
10391 
10392 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
10393   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
10394     FD->setHasSkippedBody();
10395   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
10396     MD->setHasSkippedBody();
10397   return ActOnFinishFunctionBody(Decl, nullptr);
10398 }
10399 
10400 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
10401   return ActOnFinishFunctionBody(D, BodyArg, false);
10402 }
10403 
10404 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
10405                                     bool IsInstantiation) {
10406   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
10407 
10408   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10409   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
10410 
10411   if (FD) {
10412     FD->setBody(Body);
10413 
10414     if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body &&
10415         !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
10416       // If the function has a deduced result type but contains no 'return'
10417       // statements, the result type as written must be exactly 'auto', and
10418       // the deduced result type is 'void'.
10419       if (!FD->getReturnType()->getAs<AutoType>()) {
10420         Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
10421             << FD->getReturnType();
10422         FD->setInvalidDecl();
10423       } else {
10424         // Substitute 'void' for the 'auto' in the type.
10425         TypeLoc ResultType = getReturnTypeLoc(FD);
10426         Context.adjustDeducedFunctionResultType(
10427             FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
10428       }
10429     }
10430 
10431     // The only way to be included in UndefinedButUsed is if there is an
10432     // ODR use before the definition. Avoid the expensive map lookup if this
10433     // is the first declaration.
10434     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
10435       if (!FD->isExternallyVisible())
10436         UndefinedButUsed.erase(FD);
10437       else if (FD->isInlined() &&
10438                (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
10439                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
10440         UndefinedButUsed.erase(FD);
10441     }
10442 
10443     // If the function implicitly returns zero (like 'main') or is naked,
10444     // don't complain about missing return statements.
10445     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
10446       WP.disableCheckFallThrough();
10447 
10448     // MSVC permits the use of pure specifier (=0) on function definition,
10449     // defined at class scope, warn about this non-standard construct.
10450     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
10451       Diag(FD->getLocation(), diag::ext_pure_function_definition);
10452 
10453     if (!FD->isInvalidDecl()) {
10454       // Don't diagnose unused parameters of defaulted or deleted functions.
10455       if (Body)
10456         DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
10457       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
10458                                              FD->getReturnType(), FD);
10459 
10460       // If this is a constructor, we need a vtable.
10461       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
10462         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
10463       
10464       // Try to apply the named return value optimization. We have to check
10465       // if we can do this here because lambdas keep return statements around
10466       // to deduce an implicit return type.
10467       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
10468           !FD->isDependentContext())
10469         computeNRVO(Body, getCurFunction());
10470     }
10471     
10472     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
10473            "Function parsing confused");
10474   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
10475     assert(MD == getCurMethodDecl() && "Method parsing confused");
10476     MD->setBody(Body);
10477     if (!MD->isInvalidDecl()) {
10478       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
10479       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
10480                                              MD->getReturnType(), MD);
10481 
10482       if (Body)
10483         computeNRVO(Body, getCurFunction());
10484     }
10485     if (getCurFunction()->ObjCShouldCallSuper) {
10486       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
10487         << MD->getSelector().getAsString();
10488       getCurFunction()->ObjCShouldCallSuper = false;
10489     }
10490     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
10491       const ObjCMethodDecl *InitMethod = nullptr;
10492       bool isDesignated =
10493           MD->isDesignatedInitializerForTheInterface(&InitMethod);
10494       assert(isDesignated && InitMethod);
10495       (void)isDesignated;
10496 
10497       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
10498         auto IFace = MD->getClassInterface();
10499         if (!IFace)
10500           return false;
10501         auto SuperD = IFace->getSuperClass();
10502         if (!SuperD)
10503           return false;
10504         return SuperD->getIdentifier() ==
10505             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
10506       };
10507       // Don't issue this warning for unavailable inits or direct subclasses
10508       // of NSObject.
10509       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
10510         Diag(MD->getLocation(),
10511              diag::warn_objc_designated_init_missing_super_call);
10512         Diag(InitMethod->getLocation(),
10513              diag::note_objc_designated_init_marked_here);
10514       }
10515       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
10516     }
10517     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
10518       // Don't issue this warning for unavaialable inits.
10519       if (!MD->isUnavailable())
10520         Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call);
10521       getCurFunction()->ObjCWarnForNoInitDelegation = false;
10522     }
10523   } else {
10524     return nullptr;
10525   }
10526 
10527   assert(!getCurFunction()->ObjCShouldCallSuper &&
10528          "This should only be set for ObjC methods, which should have been "
10529          "handled in the block above.");
10530 
10531   // Verify and clean out per-function state.
10532   if (Body) {
10533     // C++ constructors that have function-try-blocks can't have return
10534     // statements in the handlers of that block. (C++ [except.handle]p14)
10535     // Verify this.
10536     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
10537       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
10538     
10539     // Verify that gotos and switch cases don't jump into scopes illegally.
10540     if (getCurFunction()->NeedsScopeChecking() &&
10541         !PP.isCodeCompletionEnabled())
10542       DiagnoseInvalidJumps(Body);
10543 
10544     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
10545       if (!Destructor->getParent()->isDependentType())
10546         CheckDestructor(Destructor);
10547 
10548       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10549                                              Destructor->getParent());
10550     }
10551     
10552     // If any errors have occurred, clear out any temporaries that may have
10553     // been leftover. This ensures that these temporaries won't be picked up for
10554     // deletion in some later function.
10555     if (getDiagnostics().hasErrorOccurred() ||
10556         getDiagnostics().getSuppressAllDiagnostics()) {
10557       DiscardCleanupsInEvaluationContext();
10558     }
10559     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
10560         !isa<FunctionTemplateDecl>(dcl)) {
10561       // Since the body is valid, issue any analysis-based warnings that are
10562       // enabled.
10563       ActivePolicy = &WP;
10564     }
10565 
10566     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
10567         (!CheckConstexprFunctionDecl(FD) ||
10568          !CheckConstexprFunctionBody(FD, Body)))
10569       FD->setInvalidDecl();
10570 
10571     if (FD && FD->hasAttr<NakedAttr>()) {
10572       for (const Stmt *S : Body->children()) {
10573         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
10574           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
10575           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
10576           FD->setInvalidDecl();
10577           break;
10578         }
10579       }
10580     }
10581 
10582     assert(ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects
10583            && "Leftover temporaries in function");
10584     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
10585     assert(MaybeODRUseExprs.empty() &&
10586            "Leftover expressions for odr-use checking");
10587   }
10588   
10589   if (!IsInstantiation)
10590     PopDeclContext();
10591 
10592   PopFunctionScopeInfo(ActivePolicy, dcl);
10593   // If any errors have occurred, clear out any temporaries that may have
10594   // been leftover. This ensures that these temporaries won't be picked up for
10595   // deletion in some later function.
10596   if (getDiagnostics().hasErrorOccurred()) {
10597     DiscardCleanupsInEvaluationContext();
10598   }
10599 
10600   return dcl;
10601 }
10602 
10603 
10604 /// When we finish delayed parsing of an attribute, we must attach it to the
10605 /// relevant Decl.
10606 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
10607                                        ParsedAttributes &Attrs) {
10608   // Always attach attributes to the underlying decl.
10609   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
10610     D = TD->getTemplatedDecl();
10611   ProcessDeclAttributeList(S, D, Attrs.getList());  
10612   
10613   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
10614     if (Method->isStatic())
10615       checkThisInStaticMemberFunctionAttributes(Method);
10616 }
10617 
10618 
10619 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
10620 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
10621 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
10622                                           IdentifierInfo &II, Scope *S) {
10623   // Before we produce a declaration for an implicitly defined
10624   // function, see whether there was a locally-scoped declaration of
10625   // this name as a function or variable. If so, use that
10626   // (non-visible) declaration, and complain about it.
10627   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
10628     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
10629     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
10630     return ExternCPrev;
10631   }
10632 
10633   // Extension in C99.  Legal in C90, but warn about it.
10634   unsigned diag_id;
10635   if (II.getName().startswith("__builtin_"))
10636     diag_id = diag::warn_builtin_unknown;
10637   else if (getLangOpts().C99)
10638     diag_id = diag::ext_implicit_function_decl;
10639   else
10640     diag_id = diag::warn_implicit_function_decl;
10641   Diag(Loc, diag_id) << &II;
10642 
10643   // Because typo correction is expensive, only do it if the implicit
10644   // function declaration is going to be treated as an error.
10645   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
10646     TypoCorrection Corrected;
10647     if (S &&
10648         (Corrected = CorrectTypo(
10649              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
10650              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
10651       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
10652                    /*ErrorRecovery*/false);
10653   }
10654 
10655   // Set a Declarator for the implicit definition: int foo();
10656   const char *Dummy;
10657   AttributeFactory attrFactory;
10658   DeclSpec DS(attrFactory);
10659   unsigned DiagID;
10660   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
10661                                   Context.getPrintingPolicy());
10662   (void)Error; // Silence warning.
10663   assert(!Error && "Error setting up implicit decl!");
10664   SourceLocation NoLoc;
10665   Declarator D(DS, Declarator::BlockContext);
10666   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
10667                                              /*IsAmbiguous=*/false,
10668                                              /*LParenLoc=*/NoLoc,
10669                                              /*Params=*/nullptr,
10670                                              /*NumParams=*/0,
10671                                              /*EllipsisLoc=*/NoLoc,
10672                                              /*RParenLoc=*/NoLoc,
10673                                              /*TypeQuals=*/0,
10674                                              /*RefQualifierIsLvalueRef=*/true,
10675                                              /*RefQualifierLoc=*/NoLoc,
10676                                              /*ConstQualifierLoc=*/NoLoc,
10677                                              /*VolatileQualifierLoc=*/NoLoc,
10678                                              /*RestrictQualifierLoc=*/NoLoc,
10679                                              /*MutableLoc=*/NoLoc,
10680                                              EST_None,
10681                                              /*ESpecLoc=*/NoLoc,
10682                                              /*Exceptions=*/nullptr,
10683                                              /*ExceptionRanges=*/nullptr,
10684                                              /*NumExceptions=*/0,
10685                                              /*NoexceptExpr=*/nullptr,
10686                                              /*ExceptionSpecTokens=*/nullptr,
10687                                              Loc, Loc, D),
10688                 DS.getAttributes(),
10689                 SourceLocation());
10690   D.SetIdentifier(&II, Loc);
10691 
10692   // Insert this function into translation-unit scope.
10693 
10694   DeclContext *PrevDC = CurContext;
10695   CurContext = Context.getTranslationUnitDecl();
10696 
10697   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
10698   FD->setImplicit();
10699 
10700   CurContext = PrevDC;
10701 
10702   AddKnownFunctionAttributes(FD);
10703 
10704   return FD;
10705 }
10706 
10707 /// \brief Adds any function attributes that we know a priori based on
10708 /// the declaration of this function.
10709 ///
10710 /// These attributes can apply both to implicitly-declared builtins
10711 /// (like __builtin___printf_chk) or to library-declared functions
10712 /// like NSLog or printf.
10713 ///
10714 /// We need to check for duplicate attributes both here and where user-written
10715 /// attributes are applied to declarations.
10716 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
10717   if (FD->isInvalidDecl())
10718     return;
10719 
10720   // If this is a built-in function, map its builtin attributes to
10721   // actual attributes.
10722   if (unsigned BuiltinID = FD->getBuiltinID()) {
10723     // Handle printf-formatting attributes.
10724     unsigned FormatIdx;
10725     bool HasVAListArg;
10726     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
10727       if (!FD->hasAttr<FormatAttr>()) {
10728         const char *fmt = "printf";
10729         unsigned int NumParams = FD->getNumParams();
10730         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10731             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10732           fmt = "NSString";
10733         FD->addAttr(FormatAttr::CreateImplicit(Context,
10734                                                &Context.Idents.get(fmt),
10735                                                FormatIdx+1,
10736                                                HasVAListArg ? 0 : FormatIdx+2,
10737                                                FD->getLocation()));
10738       }
10739     }
10740     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10741                                              HasVAListArg)) {
10742      if (!FD->hasAttr<FormatAttr>())
10743        FD->addAttr(FormatAttr::CreateImplicit(Context,
10744                                               &Context.Idents.get("scanf"),
10745                                               FormatIdx+1,
10746                                               HasVAListArg ? 0 : FormatIdx+2,
10747                                               FD->getLocation()));
10748     }
10749 
10750     // Mark const if we don't care about errno and that is the only
10751     // thing preventing the function from being const. This allows
10752     // IRgen to use LLVM intrinsics for such functions.
10753     if (!getLangOpts().MathErrno &&
10754         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
10755       if (!FD->hasAttr<ConstAttr>())
10756         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
10757     }
10758 
10759     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
10760         !FD->hasAttr<ReturnsTwiceAttr>())
10761       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
10762                                          FD->getLocation()));
10763     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
10764       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
10765     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
10766       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
10767   }
10768 
10769   IdentifierInfo *Name = FD->getIdentifier();
10770   if (!Name)
10771     return;
10772   if ((!getLangOpts().CPlusPlus &&
10773        FD->getDeclContext()->isTranslationUnit()) ||
10774       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
10775        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
10776        LinkageSpecDecl::lang_c)) {
10777     // Okay: this could be a libc/libm/Objective-C function we know
10778     // about.
10779   } else
10780     return;
10781 
10782   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
10783     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
10784     // target-specific builtins, perhaps?
10785     if (!FD->hasAttr<FormatAttr>())
10786       FD->addAttr(FormatAttr::CreateImplicit(Context,
10787                                              &Context.Idents.get("printf"), 2,
10788                                              Name->isStr("vasprintf") ? 0 : 3,
10789                                              FD->getLocation()));
10790   }
10791 
10792   if (Name->isStr("__CFStringMakeConstantString")) {
10793     // We already have a __builtin___CFStringMakeConstantString,
10794     // but builds that use -fno-constant-cfstrings don't go through that.
10795     if (!FD->hasAttr<FormatArgAttr>())
10796       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
10797                                                 FD->getLocation()));
10798   }
10799 }
10800 
10801 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
10802                                     TypeSourceInfo *TInfo) {
10803   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
10804   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
10805 
10806   if (!TInfo) {
10807     assert(D.isInvalidType() && "no declarator info for valid type");
10808     TInfo = Context.getTrivialTypeSourceInfo(T);
10809   }
10810 
10811   // Scope manipulation handled by caller.
10812   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
10813                                            D.getLocStart(),
10814                                            D.getIdentifierLoc(),
10815                                            D.getIdentifier(),
10816                                            TInfo);
10817 
10818   // Bail out immediately if we have an invalid declaration.
10819   if (D.isInvalidType()) {
10820     NewTD->setInvalidDecl();
10821     return NewTD;
10822   }
10823   
10824   if (D.getDeclSpec().isModulePrivateSpecified()) {
10825     if (CurContext->isFunctionOrMethod())
10826       Diag(NewTD->getLocation(), diag::err_module_private_local)
10827         << 2 << NewTD->getDeclName()
10828         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10829         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10830     else
10831       NewTD->setModulePrivate();
10832   }
10833   
10834   // C++ [dcl.typedef]p8:
10835   //   If the typedef declaration defines an unnamed class (or
10836   //   enum), the first typedef-name declared by the declaration
10837   //   to be that class type (or enum type) is used to denote the
10838   //   class type (or enum type) for linkage purposes only.
10839   // We need to check whether the type was declared in the declaration.
10840   switch (D.getDeclSpec().getTypeSpecType()) {
10841   case TST_enum:
10842   case TST_struct:
10843   case TST_interface:
10844   case TST_union:
10845   case TST_class: {
10846     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10847 
10848     // Do nothing if the tag is not anonymous or already has an
10849     // associated typedef (from an earlier typedef in this decl group).
10850     if (tagFromDeclSpec->getIdentifier()) break;
10851     if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
10852 
10853     // A well-formed anonymous tag must always be a TUK_Definition.
10854     assert(tagFromDeclSpec->isThisDeclarationADefinition());
10855 
10856     // The type must match the tag exactly;  no qualifiers allowed.
10857     if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10858       break;
10859 
10860     // If we've already computed linkage for the anonymous tag, then
10861     // adding a typedef name for the anonymous decl can change that
10862     // linkage, which might be a serious problem.  Diagnose this as
10863     // unsupported and ignore the typedef name.  TODO: we should
10864     // pursue this as a language defect and establish a formal rule
10865     // for how to handle it.
10866     if (tagFromDeclSpec->hasLinkageBeenComputed()) {
10867       Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage);
10868 
10869       SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
10870       tagLoc = getLocForEndOfToken(tagLoc);
10871 
10872       llvm::SmallString<40> textToInsert;
10873       textToInsert += ' ';
10874       textToInsert += D.getIdentifier()->getName();
10875       Diag(tagLoc, diag::note_typedef_changes_linkage)
10876         << FixItHint::CreateInsertion(tagLoc, textToInsert);
10877       break;
10878     }
10879 
10880     // Otherwise, set this is the anon-decl typedef for the tag.
10881     tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
10882     break;
10883   }
10884     
10885   default:
10886     break;
10887   }
10888 
10889   return NewTD;
10890 }
10891 
10892 
10893 /// \brief Check that this is a valid underlying type for an enum declaration.
10894 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10895   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10896   QualType T = TI->getType();
10897 
10898   if (T->isDependentType())
10899     return false;
10900 
10901   if (const BuiltinType *BT = T->getAs<BuiltinType>())
10902     if (BT->isInteger())
10903       return false;
10904 
10905   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10906   return true;
10907 }
10908 
10909 /// Check whether this is a valid redeclaration of a previous enumeration.
10910 /// \return true if the redeclaration was invalid.
10911 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10912                                   QualType EnumUnderlyingTy,
10913                                   const EnumDecl *Prev) {
10914   bool IsFixed = !EnumUnderlyingTy.isNull();
10915 
10916   if (IsScoped != Prev->isScoped()) {
10917     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10918       << Prev->isScoped();
10919     Diag(Prev->getLocation(), diag::note_previous_declaration);
10920     return true;
10921   }
10922 
10923   if (IsFixed && Prev->isFixed()) {
10924     if (!EnumUnderlyingTy->isDependentType() &&
10925         !Prev->getIntegerType()->isDependentType() &&
10926         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
10927                                         Prev->getIntegerType())) {
10928       // TODO: Highlight the underlying type of the redeclaration.
10929       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10930         << EnumUnderlyingTy << Prev->getIntegerType();
10931       Diag(Prev->getLocation(), diag::note_previous_declaration)
10932           << Prev->getIntegerTypeRange();
10933       return true;
10934     }
10935   } else if (IsFixed != Prev->isFixed()) {
10936     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10937       << Prev->isFixed();
10938     Diag(Prev->getLocation(), diag::note_previous_declaration);
10939     return true;
10940   }
10941 
10942   return false;
10943 }
10944 
10945 /// \brief Get diagnostic %select index for tag kind for
10946 /// redeclaration diagnostic message.
10947 /// WARNING: Indexes apply to particular diagnostics only!
10948 ///
10949 /// \returns diagnostic %select index.
10950 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
10951   switch (Tag) {
10952   case TTK_Struct: return 0;
10953   case TTK_Interface: return 1;
10954   case TTK_Class:  return 2;
10955   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
10956   }
10957 }
10958 
10959 /// \brief Determine if tag kind is a class-key compatible with
10960 /// class for redeclaration (class, struct, or __interface).
10961 ///
10962 /// \returns true iff the tag kind is compatible.
10963 static bool isClassCompatTagKind(TagTypeKind Tag)
10964 {
10965   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10966 }
10967 
10968 /// \brief Determine whether a tag with a given kind is acceptable
10969 /// as a redeclaration of the given tag declaration.
10970 ///
10971 /// \returns true if the new tag kind is acceptable, false otherwise.
10972 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
10973                                         TagTypeKind NewTag, bool isDefinition,
10974                                         SourceLocation NewTagLoc,
10975                                         const IdentifierInfo &Name) {
10976   // C++ [dcl.type.elab]p3:
10977   //   The class-key or enum keyword present in the
10978   //   elaborated-type-specifier shall agree in kind with the
10979   //   declaration to which the name in the elaborated-type-specifier
10980   //   refers. This rule also applies to the form of
10981   //   elaborated-type-specifier that declares a class-name or
10982   //   friend class since it can be construed as referring to the
10983   //   definition of the class. Thus, in any
10984   //   elaborated-type-specifier, the enum keyword shall be used to
10985   //   refer to an enumeration (7.2), the union class-key shall be
10986   //   used to refer to a union (clause 9), and either the class or
10987   //   struct class-key shall be used to refer to a class (clause 9)
10988   //   declared using the class or struct class-key.
10989   TagTypeKind OldTag = Previous->getTagKind();
10990   if (!isDefinition || !isClassCompatTagKind(NewTag))
10991     if (OldTag == NewTag)
10992       return true;
10993 
10994   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
10995     // Warn about the struct/class tag mismatch.
10996     bool isTemplate = false;
10997     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10998       isTemplate = Record->getDescribedClassTemplate();
10999 
11000     if (!ActiveTemplateInstantiations.empty()) {
11001       // In a template instantiation, do not offer fix-its for tag mismatches
11002       // since they usually mess up the template instead of fixing the problem.
11003       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11004         << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
11005         << getRedeclDiagFromTagKind(OldTag);
11006       return true;
11007     }
11008 
11009     if (isDefinition) {
11010       // On definitions, check previous tags and issue a fix-it for each
11011       // one that doesn't match the current tag.
11012       if (Previous->getDefinition()) {
11013         // Don't suggest fix-its for redefinitions.
11014         return true;
11015       }
11016 
11017       bool previousMismatch = false;
11018       for (auto I : Previous->redecls()) {
11019         if (I->getTagKind() != NewTag) {
11020           if (!previousMismatch) {
11021             previousMismatch = true;
11022             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
11023               << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
11024               << getRedeclDiagFromTagKind(I->getTagKind());
11025           }
11026           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
11027             << getRedeclDiagFromTagKind(NewTag)
11028             << FixItHint::CreateReplacement(I->getInnerLocStart(),
11029                  TypeWithKeyword::getTagTypeKindName(NewTag));
11030         }
11031       }
11032       return true;
11033     }
11034 
11035     // Check for a previous definition.  If current tag and definition
11036     // are same type, do nothing.  If no definition, but disagree with
11037     // with previous tag type, give a warning, but no fix-it.
11038     const TagDecl *Redecl = Previous->getDefinition() ?
11039                             Previous->getDefinition() : Previous;
11040     if (Redecl->getTagKind() == NewTag) {
11041       return true;
11042     }
11043 
11044     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11045       << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
11046       << getRedeclDiagFromTagKind(OldTag);
11047     Diag(Redecl->getLocation(), diag::note_previous_use);
11048 
11049     // If there is a previous definition, suggest a fix-it.
11050     if (Previous->getDefinition()) {
11051         Diag(NewTagLoc, diag::note_struct_class_suggestion)
11052           << getRedeclDiagFromTagKind(Redecl->getTagKind())
11053           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
11054                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
11055     }
11056 
11057     return true;
11058   }
11059   return false;
11060 }
11061 
11062 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
11063 /// from an outer enclosing namespace or file scope inside a friend declaration.
11064 /// This should provide the commented out code in the following snippet:
11065 ///   namespace N {
11066 ///     struct X;
11067 ///     namespace M {
11068 ///       struct Y { friend struct /*N::*/ X; };
11069 ///     }
11070 ///   }
11071 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
11072                                          SourceLocation NameLoc) {
11073   // While the decl is in a namespace, do repeated lookup of that name and see
11074   // if we get the same namespace back.  If we do not, continue until
11075   // translation unit scope, at which point we have a fully qualified NNS.
11076   SmallVector<IdentifierInfo *, 4> Namespaces;
11077   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11078   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
11079     // This tag should be declared in a namespace, which can only be enclosed by
11080     // other namespaces.  Bail if there's an anonymous namespace in the chain.
11081     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
11082     if (!Namespace || Namespace->isAnonymousNamespace())
11083       return FixItHint();
11084     IdentifierInfo *II = Namespace->getIdentifier();
11085     Namespaces.push_back(II);
11086     NamedDecl *Lookup = SemaRef.LookupSingleName(
11087         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
11088     if (Lookup == Namespace)
11089       break;
11090   }
11091 
11092   // Once we have all the namespaces, reverse them to go outermost first, and
11093   // build an NNS.
11094   SmallString<64> Insertion;
11095   llvm::raw_svector_ostream OS(Insertion);
11096   if (DC->isTranslationUnit())
11097     OS << "::";
11098   std::reverse(Namespaces.begin(), Namespaces.end());
11099   for (auto *II : Namespaces)
11100     OS << II->getName() << "::";
11101   OS.flush();
11102   return FixItHint::CreateInsertion(NameLoc, Insertion);
11103 }
11104 
11105 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
11106 /// former case, Name will be non-null.  In the later case, Name will be null.
11107 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
11108 /// reference/declaration/definition of a tag.
11109 ///
11110 /// IsTypeSpecifier is true if this is a type-specifier (or
11111 /// trailing-type-specifier) other than one in an alias-declaration.
11112 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11113                      SourceLocation KWLoc, CXXScopeSpec &SS,
11114                      IdentifierInfo *Name, SourceLocation NameLoc,
11115                      AttributeList *Attr, AccessSpecifier AS,
11116                      SourceLocation ModulePrivateLoc,
11117                      MultiTemplateParamsArg TemplateParameterLists,
11118                      bool &OwnedDecl, bool &IsDependent,
11119                      SourceLocation ScopedEnumKWLoc,
11120                      bool ScopedEnumUsesClassTag,
11121                      TypeResult UnderlyingType,
11122                      bool IsTypeSpecifier) {
11123   // If this is not a definition, it must have a name.
11124   IdentifierInfo *OrigName = Name;
11125   assert((Name != nullptr || TUK == TUK_Definition) &&
11126          "Nameless record must be a definition!");
11127   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
11128 
11129   OwnedDecl = false;
11130   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11131   bool ScopedEnum = ScopedEnumKWLoc.isValid();
11132 
11133   // FIXME: Check explicit specializations more carefully.
11134   bool isExplicitSpecialization = false;
11135   bool Invalid = false;
11136 
11137   // We only need to do this matching if we have template parameters
11138   // or a scope specifier, which also conveniently avoids this work
11139   // for non-C++ cases.
11140   if (TemplateParameterLists.size() > 0 ||
11141       (SS.isNotEmpty() && TUK != TUK_Reference)) {
11142     if (TemplateParameterList *TemplateParams =
11143             MatchTemplateParametersToScopeSpecifier(
11144                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
11145                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
11146       if (Kind == TTK_Enum) {
11147         Diag(KWLoc, diag::err_enum_template);
11148         return nullptr;
11149       }
11150 
11151       if (TemplateParams->size() > 0) {
11152         // This is a declaration or definition of a class template (which may
11153         // be a member of another template).
11154 
11155         if (Invalid)
11156           return nullptr;
11157 
11158         OwnedDecl = false;
11159         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
11160                                                SS, Name, NameLoc, Attr,
11161                                                TemplateParams, AS,
11162                                                ModulePrivateLoc,
11163                                                /*FriendLoc*/SourceLocation(),
11164                                                TemplateParameterLists.size()-1,
11165                                                TemplateParameterLists.data());
11166         return Result.get();
11167       } else {
11168         // The "template<>" header is extraneous.
11169         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11170           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11171         isExplicitSpecialization = true;
11172       }
11173     }
11174   }
11175 
11176   // Figure out the underlying type if this a enum declaration. We need to do
11177   // this early, because it's needed to detect if this is an incompatible
11178   // redeclaration.
11179   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
11180 
11181   if (Kind == TTK_Enum) {
11182     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
11183       // No underlying type explicitly specified, or we failed to parse the
11184       // type, default to int.
11185       EnumUnderlying = Context.IntTy.getTypePtr();
11186     else if (UnderlyingType.get()) {
11187       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
11188       // integral type; any cv-qualification is ignored.
11189       TypeSourceInfo *TI = nullptr;
11190       GetTypeFromParser(UnderlyingType.get(), &TI);
11191       EnumUnderlying = TI;
11192 
11193       if (CheckEnumUnderlyingType(TI))
11194         // Recover by falling back to int.
11195         EnumUnderlying = Context.IntTy.getTypePtr();
11196 
11197       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
11198                                           UPPC_FixedUnderlyingType))
11199         EnumUnderlying = Context.IntTy.getTypePtr();
11200 
11201     } else if (getLangOpts().MSVCCompat)
11202       // Microsoft enums are always of int type.
11203       EnumUnderlying = Context.IntTy.getTypePtr();
11204   }
11205 
11206   DeclContext *SearchDC = CurContext;
11207   DeclContext *DC = CurContext;
11208   bool isStdBadAlloc = false;
11209 
11210   RedeclarationKind Redecl = ForRedeclaration;
11211   if (TUK == TUK_Friend || TUK == TUK_Reference)
11212     Redecl = NotForRedeclaration;
11213 
11214   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
11215   if (Name && SS.isNotEmpty()) {
11216     // We have a nested-name tag ('struct foo::bar').
11217 
11218     // Check for invalid 'foo::'.
11219     if (SS.isInvalid()) {
11220       Name = nullptr;
11221       goto CreateNewDecl;
11222     }
11223 
11224     // If this is a friend or a reference to a class in a dependent
11225     // context, don't try to make a decl for it.
11226     if (TUK == TUK_Friend || TUK == TUK_Reference) {
11227       DC = computeDeclContext(SS, false);
11228       if (!DC) {
11229         IsDependent = true;
11230         return nullptr;
11231       }
11232     } else {
11233       DC = computeDeclContext(SS, true);
11234       if (!DC) {
11235         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
11236           << SS.getRange();
11237         return nullptr;
11238       }
11239     }
11240 
11241     if (RequireCompleteDeclContext(SS, DC))
11242       return nullptr;
11243 
11244     SearchDC = DC;
11245     // Look-up name inside 'foo::'.
11246     LookupQualifiedName(Previous, DC);
11247 
11248     if (Previous.isAmbiguous())
11249       return nullptr;
11250 
11251     if (Previous.empty()) {
11252       // Name lookup did not find anything. However, if the
11253       // nested-name-specifier refers to the current instantiation,
11254       // and that current instantiation has any dependent base
11255       // classes, we might find something at instantiation time: treat
11256       // this as a dependent elaborated-type-specifier.
11257       // But this only makes any sense for reference-like lookups.
11258       if (Previous.wasNotFoundInCurrentInstantiation() &&
11259           (TUK == TUK_Reference || TUK == TUK_Friend)) {
11260         IsDependent = true;
11261         return nullptr;
11262       }
11263 
11264       // A tag 'foo::bar' must already exist.
11265       Diag(NameLoc, diag::err_not_tag_in_scope) 
11266         << Kind << Name << DC << SS.getRange();
11267       Name = nullptr;
11268       Invalid = true;
11269       goto CreateNewDecl;
11270     }
11271   } else if (Name) {
11272     // If this is a named struct, check to see if there was a previous forward
11273     // declaration or definition.
11274     // FIXME: We're looking into outer scopes here, even when we
11275     // shouldn't be. Doing so can result in ambiguities that we
11276     // shouldn't be diagnosing.
11277     LookupName(Previous, S);
11278 
11279     // When declaring or defining a tag, ignore ambiguities introduced
11280     // by types using'ed into this scope.
11281     if (Previous.isAmbiguous() && 
11282         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
11283       LookupResult::Filter F = Previous.makeFilter();
11284       while (F.hasNext()) {
11285         NamedDecl *ND = F.next();
11286         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
11287           F.erase();
11288       }
11289       F.done();
11290     }
11291 
11292     // C++11 [namespace.memdef]p3:
11293     //   If the name in a friend declaration is neither qualified nor
11294     //   a template-id and the declaration is a function or an
11295     //   elaborated-type-specifier, the lookup to determine whether
11296     //   the entity has been previously declared shall not consider
11297     //   any scopes outside the innermost enclosing namespace.
11298     //
11299     // MSVC doesn't implement the above rule for types, so a friend tag
11300     // declaration may be a redeclaration of a type declared in an enclosing
11301     // scope.  They do implement this rule for friend functions.
11302     //
11303     // Does it matter that this should be by scope instead of by
11304     // semantic context?
11305     if (!Previous.empty() && TUK == TUK_Friend) {
11306       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
11307       LookupResult::Filter F = Previous.makeFilter();
11308       bool FriendSawTagOutsideEnclosingNamespace = false;
11309       while (F.hasNext()) {
11310         NamedDecl *ND = F.next();
11311         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11312         if (DC->isFileContext() &&
11313             !EnclosingNS->Encloses(ND->getDeclContext())) {
11314           if (getLangOpts().MSVCCompat)
11315             FriendSawTagOutsideEnclosingNamespace = true;
11316           else
11317             F.erase();
11318         }
11319       }
11320       F.done();
11321 
11322       // Diagnose this MSVC extension in the easy case where lookup would have
11323       // unambiguously found something outside the enclosing namespace.
11324       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
11325         NamedDecl *ND = Previous.getFoundDecl();
11326         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
11327             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
11328       }
11329     }
11330 
11331     // Note:  there used to be some attempt at recovery here.
11332     if (Previous.isAmbiguous())
11333       return nullptr;
11334 
11335     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
11336       // FIXME: This makes sure that we ignore the contexts associated
11337       // with C structs, unions, and enums when looking for a matching
11338       // tag declaration or definition. See the similar lookup tweak
11339       // in Sema::LookupName; is there a better way to deal with this?
11340       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
11341         SearchDC = SearchDC->getParent();
11342     }
11343   }
11344 
11345   if (Previous.isSingleResult() &&
11346       Previous.getFoundDecl()->isTemplateParameter()) {
11347     // Maybe we will complain about the shadowed template parameter.
11348     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
11349     // Just pretend that we didn't see the previous declaration.
11350     Previous.clear();
11351   }
11352 
11353   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
11354       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
11355     // This is a declaration of or a reference to "std::bad_alloc".
11356     isStdBadAlloc = true;
11357     
11358     if (Previous.empty() && StdBadAlloc) {
11359       // std::bad_alloc has been implicitly declared (but made invisible to
11360       // name lookup). Fill in this implicit declaration as the previous 
11361       // declaration, so that the declarations get chained appropriately.
11362       Previous.addDecl(getStdBadAlloc());
11363     }
11364   }
11365 
11366   // If we didn't find a previous declaration, and this is a reference
11367   // (or friend reference), move to the correct scope.  In C++, we
11368   // also need to do a redeclaration lookup there, just in case
11369   // there's a shadow friend decl.
11370   if (Name && Previous.empty() &&
11371       (TUK == TUK_Reference || TUK == TUK_Friend)) {
11372     if (Invalid) goto CreateNewDecl;
11373     assert(SS.isEmpty());
11374 
11375     if (TUK == TUK_Reference) {
11376       // C++ [basic.scope.pdecl]p5:
11377       //   -- for an elaborated-type-specifier of the form
11378       //
11379       //          class-key identifier
11380       //
11381       //      if the elaborated-type-specifier is used in the
11382       //      decl-specifier-seq or parameter-declaration-clause of a
11383       //      function defined in namespace scope, the identifier is
11384       //      declared as a class-name in the namespace that contains
11385       //      the declaration; otherwise, except as a friend
11386       //      declaration, the identifier is declared in the smallest
11387       //      non-class, non-function-prototype scope that contains the
11388       //      declaration.
11389       //
11390       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
11391       // C structs and unions.
11392       //
11393       // It is an error in C++ to declare (rather than define) an enum
11394       // type, including via an elaborated type specifier.  We'll
11395       // diagnose that later; for now, declare the enum in the same
11396       // scope as we would have picked for any other tag type.
11397       //
11398       // GNU C also supports this behavior as part of its incomplete
11399       // enum types extension, while GNU C++ does not.
11400       //
11401       // Find the context where we'll be declaring the tag.
11402       // FIXME: We would like to maintain the current DeclContext as the
11403       // lexical context,
11404       while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
11405         SearchDC = SearchDC->getParent();
11406 
11407       // Find the scope where we'll be declaring the tag.
11408       while (S->isClassScope() ||
11409              (getLangOpts().CPlusPlus &&
11410               S->isFunctionPrototypeScope()) ||
11411              ((S->getFlags() & Scope::DeclScope) == 0) ||
11412              (S->getEntity() && S->getEntity()->isTransparentContext()))
11413         S = S->getParent();
11414     } else {
11415       assert(TUK == TUK_Friend);
11416       // C++ [namespace.memdef]p3:
11417       //   If a friend declaration in a non-local class first declares a
11418       //   class or function, the friend class or function is a member of
11419       //   the innermost enclosing namespace.
11420       SearchDC = SearchDC->getEnclosingNamespaceContext();
11421     }
11422 
11423     // In C++, we need to do a redeclaration lookup to properly
11424     // diagnose some problems.
11425     if (getLangOpts().CPlusPlus) {
11426       Previous.setRedeclarationKind(ForRedeclaration);
11427       LookupQualifiedName(Previous, SearchDC);
11428     }
11429   }
11430 
11431   if (!Previous.empty()) {
11432     NamedDecl *PrevDecl = Previous.getFoundDecl();
11433     NamedDecl *DirectPrevDecl =
11434         getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl;
11435 
11436     // It's okay to have a tag decl in the same scope as a typedef
11437     // which hides a tag decl in the same scope.  Finding this
11438     // insanity with a redeclaration lookup can only actually happen
11439     // in C++.
11440     //
11441     // This is also okay for elaborated-type-specifiers, which is
11442     // technically forbidden by the current standard but which is
11443     // okay according to the likely resolution of an open issue;
11444     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
11445     if (getLangOpts().CPlusPlus) {
11446       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
11447         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
11448           TagDecl *Tag = TT->getDecl();
11449           if (Tag->getDeclName() == Name &&
11450               Tag->getDeclContext()->getRedeclContext()
11451                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
11452             PrevDecl = Tag;
11453             Previous.clear();
11454             Previous.addDecl(Tag);
11455             Previous.resolveKind();
11456           }
11457         }
11458       }
11459     }
11460 
11461     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
11462       // If this is a use of a previous tag, or if the tag is already declared
11463       // in the same scope (so that the definition/declaration completes or
11464       // rementions the tag), reuse the decl.
11465       if (TUK == TUK_Reference || TUK == TUK_Friend ||
11466           isDeclInScope(DirectPrevDecl, SearchDC, S,
11467                         SS.isNotEmpty() || isExplicitSpecialization)) {
11468         // Make sure that this wasn't declared as an enum and now used as a
11469         // struct or something similar.
11470         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
11471                                           TUK == TUK_Definition, KWLoc,
11472                                           *Name)) {
11473           bool SafeToContinue
11474             = (PrevTagDecl->getTagKind() != TTK_Enum &&
11475                Kind != TTK_Enum);
11476           if (SafeToContinue)
11477             Diag(KWLoc, diag::err_use_with_wrong_tag)
11478               << Name
11479               << FixItHint::CreateReplacement(SourceRange(KWLoc),
11480                                               PrevTagDecl->getKindName());
11481           else
11482             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
11483           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
11484 
11485           if (SafeToContinue)
11486             Kind = PrevTagDecl->getTagKind();
11487           else {
11488             // Recover by making this an anonymous redefinition.
11489             Name = nullptr;
11490             Previous.clear();
11491             Invalid = true;
11492           }
11493         }
11494 
11495         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
11496           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
11497 
11498           // If this is an elaborated-type-specifier for a scoped enumeration,
11499           // the 'class' keyword is not necessary and not permitted.
11500           if (TUK == TUK_Reference || TUK == TUK_Friend) {
11501             if (ScopedEnum)
11502               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
11503                 << PrevEnum->isScoped()
11504                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
11505             return PrevTagDecl;
11506           }
11507 
11508           QualType EnumUnderlyingTy;
11509           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
11510             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
11511           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
11512             EnumUnderlyingTy = QualType(T, 0);
11513 
11514           // All conflicts with previous declarations are recovered by
11515           // returning the previous declaration, unless this is a definition,
11516           // in which case we want the caller to bail out.
11517           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
11518                                      ScopedEnum, EnumUnderlyingTy, PrevEnum))
11519             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
11520         }
11521 
11522         // C++11 [class.mem]p1:
11523         //   A member shall not be declared twice in the member-specification,
11524         //   except that a nested class or member class template can be declared
11525         //   and then later defined.
11526         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
11527             S->isDeclScope(PrevDecl)) {
11528           Diag(NameLoc, diag::ext_member_redeclared);
11529           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
11530         }
11531 
11532         if (!Invalid) {
11533           // If this is a use, just return the declaration we found, unless
11534           // we have attributes.
11535 
11536           // FIXME: In the future, return a variant or some other clue
11537           // for the consumer of this Decl to know it doesn't own it.
11538           // For our current ASTs this shouldn't be a problem, but will
11539           // need to be changed with DeclGroups.
11540           if (!Attr &&
11541               ((TUK == TUK_Reference &&
11542                 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt))
11543                || TUK == TUK_Friend))
11544             return PrevTagDecl;
11545 
11546           // Diagnose attempts to redefine a tag.
11547           if (TUK == TUK_Definition) {
11548             if (TagDecl *Def = PrevTagDecl->getDefinition()) {
11549               // If we're defining a specialization and the previous definition
11550               // is from an implicit instantiation, don't emit an error
11551               // here; we'll catch this in the general case below.
11552               bool IsExplicitSpecializationAfterInstantiation = false;
11553               if (isExplicitSpecialization) {
11554                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
11555                   IsExplicitSpecializationAfterInstantiation =
11556                     RD->getTemplateSpecializationKind() !=
11557                     TSK_ExplicitSpecialization;
11558                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
11559                   IsExplicitSpecializationAfterInstantiation =
11560                     ED->getTemplateSpecializationKind() !=
11561                     TSK_ExplicitSpecialization;
11562               }
11563 
11564               if (!IsExplicitSpecializationAfterInstantiation) {
11565                 // A redeclaration in function prototype scope in C isn't
11566                 // visible elsewhere, so merely issue a warning.
11567                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
11568                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
11569                 else
11570                   Diag(NameLoc, diag::err_redefinition) << Name;
11571                 Diag(Def->getLocation(), diag::note_previous_definition);
11572                 // If this is a redefinition, recover by making this
11573                 // struct be anonymous, which will make any later
11574                 // references get the previous definition.
11575                 Name = nullptr;
11576                 Previous.clear();
11577                 Invalid = true;
11578               }
11579             } else {
11580               // If the type is currently being defined, complain
11581               // about a nested redefinition.
11582               const TagType *Tag
11583                 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
11584               if (Tag->isBeingDefined()) {
11585                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
11586                 Diag(PrevTagDecl->getLocation(),
11587                      diag::note_previous_definition);
11588                 Name = nullptr;
11589                 Previous.clear();
11590                 Invalid = true;
11591               }
11592             }
11593 
11594             // Okay, this is definition of a previously declared or referenced
11595             // tag. We're going to create a new Decl for it.
11596           }
11597 
11598           // Okay, we're going to make a redeclaration.  If this is some kind
11599           // of reference, make sure we build the redeclaration in the same DC
11600           // as the original, and ignore the current access specifier.
11601           if (TUK == TUK_Friend || TUK == TUK_Reference) {
11602             SearchDC = PrevTagDecl->getDeclContext();
11603             AS = AS_none;
11604           }
11605         }
11606         // If we get here we have (another) forward declaration or we
11607         // have a definition.  Just create a new decl.
11608 
11609       } else {
11610         // If we get here, this is a definition of a new tag type in a nested
11611         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
11612         // new decl/type.  We set PrevDecl to NULL so that the entities
11613         // have distinct types.
11614         Previous.clear();
11615       }
11616       // If we get here, we're going to create a new Decl. If PrevDecl
11617       // is non-NULL, it's a definition of the tag declared by
11618       // PrevDecl. If it's NULL, we have a new definition.
11619 
11620 
11621     // Otherwise, PrevDecl is not a tag, but was found with tag
11622     // lookup.  This is only actually possible in C++, where a few
11623     // things like templates still live in the tag namespace.
11624     } else {
11625       // Use a better diagnostic if an elaborated-type-specifier
11626       // found the wrong kind of type on the first
11627       // (non-redeclaration) lookup.
11628       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
11629           !Previous.isForRedeclaration()) {
11630         unsigned Kind = 0;
11631         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
11632         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11633         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
11634         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
11635         Diag(PrevDecl->getLocation(), diag::note_declared_at);
11636         Invalid = true;
11637 
11638       // Otherwise, only diagnose if the declaration is in scope.
11639       } else if (!isDeclInScope(PrevDecl, SearchDC, S,
11640                                 SS.isNotEmpty() || isExplicitSpecialization)) {
11641         // do nothing
11642 
11643       // Diagnose implicit declarations introduced by elaborated types.
11644       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
11645         unsigned Kind = 0;
11646         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
11647         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11648         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
11649         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
11650         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11651         Invalid = true;
11652 
11653       // Otherwise it's a declaration.  Call out a particularly common
11654       // case here.
11655       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
11656         unsigned Kind = 0;
11657         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
11658         Diag(NameLoc, diag::err_tag_definition_of_typedef)
11659           << Name << Kind << TND->getUnderlyingType();
11660         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11661         Invalid = true;
11662 
11663       // Otherwise, diagnose.
11664       } else {
11665         // The tag name clashes with something else in the target scope,
11666         // issue an error and recover by making this tag be anonymous.
11667         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
11668         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11669         Name = nullptr;
11670         Invalid = true;
11671       }
11672 
11673       // The existing declaration isn't relevant to us; we're in a
11674       // new scope, so clear out the previous declaration.
11675       Previous.clear();
11676     }
11677   }
11678 
11679 CreateNewDecl:
11680 
11681   TagDecl *PrevDecl = nullptr;
11682   if (Previous.isSingleResult())
11683     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
11684 
11685   // If there is an identifier, use the location of the identifier as the
11686   // location of the decl, otherwise use the location of the struct/union
11687   // keyword.
11688   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
11689 
11690   // Otherwise, create a new declaration. If there is a previous
11691   // declaration of the same entity, the two will be linked via
11692   // PrevDecl.
11693   TagDecl *New;
11694 
11695   bool IsForwardReference = false;
11696   if (Kind == TTK_Enum) {
11697     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11698     // enum X { A, B, C } D;    D should chain to X.
11699     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
11700                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
11701                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
11702     // If this is an undefined enum, warn.
11703     if (TUK != TUK_Definition && !Invalid) {
11704       TagDecl *Def;
11705       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
11706           cast<EnumDecl>(New)->isFixed()) {
11707         // C++0x: 7.2p2: opaque-enum-declaration.
11708         // Conflicts are diagnosed above. Do nothing.
11709       }
11710       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
11711         Diag(Loc, diag::ext_forward_ref_enum_def)
11712           << New;
11713         Diag(Def->getLocation(), diag::note_previous_definition);
11714       } else {
11715         unsigned DiagID = diag::ext_forward_ref_enum;
11716         if (getLangOpts().MSVCCompat)
11717           DiagID = diag::ext_ms_forward_ref_enum;
11718         else if (getLangOpts().CPlusPlus)
11719           DiagID = diag::err_forward_ref_enum;
11720         Diag(Loc, DiagID);
11721         
11722         // If this is a forward-declared reference to an enumeration, make a 
11723         // note of it; we won't actually be introducing the declaration into
11724         // the declaration context.
11725         if (TUK == TUK_Reference)
11726           IsForwardReference = true;
11727       }
11728     }
11729 
11730     if (EnumUnderlying) {
11731       EnumDecl *ED = cast<EnumDecl>(New);
11732       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
11733         ED->setIntegerTypeSourceInfo(TI);
11734       else
11735         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
11736       ED->setPromotionType(ED->getIntegerType());
11737     }
11738 
11739   } else {
11740     // struct/union/class
11741 
11742     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11743     // struct X { int A; } D;    D should chain to X.
11744     if (getLangOpts().CPlusPlus) {
11745       // FIXME: Look for a way to use RecordDecl for simple structs.
11746       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
11747                                   cast_or_null<CXXRecordDecl>(PrevDecl));
11748 
11749       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
11750         StdBadAlloc = cast<CXXRecordDecl>(New);
11751     } else
11752       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
11753                                cast_or_null<RecordDecl>(PrevDecl));
11754   }
11755 
11756   // C++11 [dcl.type]p3:
11757   //   A type-specifier-seq shall not define a class or enumeration [...].
11758   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
11759     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
11760       << Context.getTagDeclType(New);
11761     Invalid = true;
11762   }
11763 
11764   // Maybe add qualifier info.
11765   if (SS.isNotEmpty()) {
11766     if (SS.isSet()) {
11767       // If this is either a declaration or a definition, check the 
11768       // nested-name-specifier against the current context. We don't do this
11769       // for explicit specializations, because they have similar checking
11770       // (with more specific diagnostics) in the call to 
11771       // CheckMemberSpecialization, below.
11772       if (!isExplicitSpecialization &&
11773           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
11774           diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
11775         Invalid = true;
11776 
11777       New->setQualifierInfo(SS.getWithLocInContext(Context));
11778       if (TemplateParameterLists.size() > 0) {
11779         New->setTemplateParameterListsInfo(Context,
11780                                            TemplateParameterLists.size(),
11781                                            TemplateParameterLists.data());
11782       }
11783     }
11784     else
11785       Invalid = true;
11786   }
11787 
11788   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
11789     // Add alignment attributes if necessary; these attributes are checked when
11790     // the ASTContext lays out the structure.
11791     //
11792     // It is important for implementing the correct semantics that this
11793     // happen here (in act on tag decl). The #pragma pack stack is
11794     // maintained as a result of parser callbacks which can occur at
11795     // many points during the parsing of a struct declaration (because
11796     // the #pragma tokens are effectively skipped over during the
11797     // parsing of the struct).
11798     if (TUK == TUK_Definition) {
11799       AddAlignmentAttributesForRecord(RD);
11800       AddMsStructLayoutForRecord(RD);
11801     }
11802   }
11803 
11804   if (ModulePrivateLoc.isValid()) {
11805     if (isExplicitSpecialization)
11806       Diag(New->getLocation(), diag::err_module_private_specialization)
11807         << 2
11808         << FixItHint::CreateRemoval(ModulePrivateLoc);
11809     // __module_private__ does not apply to local classes. However, we only
11810     // diagnose this as an error when the declaration specifiers are
11811     // freestanding. Here, we just ignore the __module_private__.
11812     else if (!SearchDC->isFunctionOrMethod())
11813       New->setModulePrivate();
11814   }
11815 
11816   // If this is a specialization of a member class (of a class template),
11817   // check the specialization.
11818   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
11819     Invalid = true;
11820 
11821   // If we're declaring or defining a tag in function prototype scope in C,
11822   // note that this type can only be used within the function and add it to
11823   // the list of decls to inject into the function definition scope.
11824   if ((Name || Kind == TTK_Enum) &&
11825       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
11826     if (getLangOpts().CPlusPlus) {
11827       // C++ [dcl.fct]p6:
11828       //   Types shall not be defined in return or parameter types.
11829       if (TUK == TUK_Definition && !IsTypeSpecifier) {
11830         Diag(Loc, diag::err_type_defined_in_param_type)
11831             << Name;
11832         Invalid = true;
11833       }
11834     } else {
11835       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
11836     }
11837     DeclsInPrototypeScope.push_back(New);
11838   }
11839 
11840   if (Invalid)
11841     New->setInvalidDecl();
11842 
11843   if (Attr)
11844     ProcessDeclAttributeList(S, New, Attr);
11845 
11846   // Set the lexical context. If the tag has a C++ scope specifier, the
11847   // lexical context will be different from the semantic context.
11848   New->setLexicalDeclContext(CurContext);
11849 
11850   // Mark this as a friend decl if applicable.
11851   // In Microsoft mode, a friend declaration also acts as a forward
11852   // declaration so we always pass true to setObjectOfFriendDecl to make
11853   // the tag name visible.
11854   if (TUK == TUK_Friend)
11855     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
11856 
11857   // Set the access specifier.
11858   if (!Invalid && SearchDC->isRecord())
11859     SetMemberAccessSpecifier(New, PrevDecl, AS);
11860 
11861   if (TUK == TUK_Definition)
11862     New->startDefinition();
11863 
11864   // If this has an identifier, add it to the scope stack.
11865   if (TUK == TUK_Friend) {
11866     // We might be replacing an existing declaration in the lookup tables;
11867     // if so, borrow its access specifier.
11868     if (PrevDecl)
11869       New->setAccess(PrevDecl->getAccess());
11870 
11871     DeclContext *DC = New->getDeclContext()->getRedeclContext();
11872     DC->makeDeclVisibleInContext(New);
11873     if (Name) // can be null along some error paths
11874       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11875         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
11876   } else if (Name) {
11877     S = getNonFieldDeclScope(S);
11878     PushOnScopeChains(New, S, !IsForwardReference);
11879     if (IsForwardReference)
11880       SearchDC->makeDeclVisibleInContext(New);
11881 
11882   } else {
11883     CurContext->addDecl(New);
11884   }
11885 
11886   // If this is the C FILE type, notify the AST context.
11887   if (IdentifierInfo *II = New->getIdentifier())
11888     if (!New->isInvalidDecl() &&
11889         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
11890         II->isStr("FILE"))
11891       Context.setFILEDecl(New);
11892 
11893   if (PrevDecl)
11894     mergeDeclAttributes(New, PrevDecl);
11895 
11896   // If there's a #pragma GCC visibility in scope, set the visibility of this
11897   // record.
11898   AddPushedVisibilityAttribute(New);
11899 
11900   OwnedDecl = true;
11901   // In C++, don't return an invalid declaration. We can't recover well from
11902   // the cases where we make the type anonymous.
11903   return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
11904 }
11905 
11906 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
11907   AdjustDeclIfTemplate(TagD);
11908   TagDecl *Tag = cast<TagDecl>(TagD);
11909   
11910   // Enter the tag context.
11911   PushDeclContext(S, Tag);
11912 
11913   ActOnDocumentableDecl(TagD);
11914 
11915   // If there's a #pragma GCC visibility in scope, set the visibility of this
11916   // record.
11917   AddPushedVisibilityAttribute(Tag);
11918 }
11919 
11920 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
11921   assert(isa<ObjCContainerDecl>(IDecl) && 
11922          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11923   DeclContext *OCD = cast<DeclContext>(IDecl);
11924   assert(getContainingDC(OCD) == CurContext &&
11925       "The next DeclContext should be lexically contained in the current one.");
11926   CurContext = OCD;
11927   return IDecl;
11928 }
11929 
11930 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
11931                                            SourceLocation FinalLoc,
11932                                            bool IsFinalSpelledSealed,
11933                                            SourceLocation LBraceLoc) {
11934   AdjustDeclIfTemplate(TagD);
11935   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
11936 
11937   FieldCollector->StartClass();
11938 
11939   if (!Record->getIdentifier())
11940     return;
11941 
11942   if (FinalLoc.isValid())
11943     Record->addAttr(new (Context)
11944                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11945 
11946   // C++ [class]p2:
11947   //   [...] The class-name is also inserted into the scope of the
11948   //   class itself; this is known as the injected-class-name. For
11949   //   purposes of access checking, the injected-class-name is treated
11950   //   as if it were a public member name.
11951   CXXRecordDecl *InjectedClassName
11952     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11953                             Record->getLocStart(), Record->getLocation(),
11954                             Record->getIdentifier(),
11955                             /*PrevDecl=*/nullptr,
11956                             /*DelayTypeCreation=*/true);
11957   Context.getTypeDeclType(InjectedClassName, Record);
11958   InjectedClassName->setImplicit();
11959   InjectedClassName->setAccess(AS_public);
11960   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11961       InjectedClassName->setDescribedClassTemplate(Template);
11962   PushOnScopeChains(InjectedClassName, S);
11963   assert(InjectedClassName->isInjectedClassName() &&
11964          "Broken injected-class-name");
11965 }
11966 
11967 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
11968                                     SourceLocation RBraceLoc) {
11969   AdjustDeclIfTemplate(TagD);
11970   TagDecl *Tag = cast<TagDecl>(TagD);
11971   Tag->setRBraceLoc(RBraceLoc);
11972 
11973   // Make sure we "complete" the definition even it is invalid.
11974   if (Tag->isBeingDefined()) {
11975     assert(Tag->isInvalidDecl() && "We should already have completed it");
11976     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11977       RD->completeDefinition();
11978   }
11979 
11980   if (isa<CXXRecordDecl>(Tag))
11981     FieldCollector->FinishClass();
11982 
11983   // Exit this scope of this tag's definition.
11984   PopDeclContext();
11985 
11986   if (getCurLexicalContext()->isObjCContainer() &&
11987       Tag->getDeclContext()->isFileContext())
11988     Tag->setTopLevelDeclInObjCContainer();
11989 
11990   // Notify the consumer that we've defined a tag.
11991   if (!Tag->isInvalidDecl())
11992     Consumer.HandleTagDeclDefinition(Tag);
11993 }
11994 
11995 void Sema::ActOnObjCContainerFinishDefinition() {
11996   // Exit this scope of this interface definition.
11997   PopDeclContext();
11998 }
11999 
12000 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
12001   assert(DC == CurContext && "Mismatch of container contexts");
12002   OriginalLexicalContext = DC;
12003   ActOnObjCContainerFinishDefinition();
12004 }
12005 
12006 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
12007   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
12008   OriginalLexicalContext = nullptr;
12009 }
12010 
12011 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
12012   AdjustDeclIfTemplate(TagD);
12013   TagDecl *Tag = cast<TagDecl>(TagD);
12014   Tag->setInvalidDecl();
12015 
12016   // Make sure we "complete" the definition even it is invalid.
12017   if (Tag->isBeingDefined()) {
12018     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12019       RD->completeDefinition();
12020   }
12021 
12022   // We're undoing ActOnTagStartDefinition here, not
12023   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
12024   // the FieldCollector.
12025 
12026   PopDeclContext();  
12027 }
12028 
12029 // Note that FieldName may be null for anonymous bitfields.
12030 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
12031                                 IdentifierInfo *FieldName,
12032                                 QualType FieldTy, bool IsMsStruct,
12033                                 Expr *BitWidth, bool *ZeroWidth) {
12034   // Default to true; that shouldn't confuse checks for emptiness
12035   if (ZeroWidth)
12036     *ZeroWidth = true;
12037 
12038   // C99 6.7.2.1p4 - verify the field type.
12039   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
12040   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
12041     // Handle incomplete types with specific error.
12042     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
12043       return ExprError();
12044     if (FieldName)
12045       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
12046         << FieldName << FieldTy << BitWidth->getSourceRange();
12047     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
12048       << FieldTy << BitWidth->getSourceRange();
12049   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
12050                                              UPPC_BitFieldWidth))
12051     return ExprError();
12052 
12053   // If the bit-width is type- or value-dependent, don't try to check
12054   // it now.
12055   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
12056     return BitWidth;
12057 
12058   llvm::APSInt Value;
12059   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
12060   if (ICE.isInvalid())
12061     return ICE;
12062   BitWidth = ICE.get();
12063 
12064   if (Value != 0 && ZeroWidth)
12065     *ZeroWidth = false;
12066 
12067   // Zero-width bitfield is ok for anonymous field.
12068   if (Value == 0 && FieldName)
12069     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
12070 
12071   if (Value.isSigned() && Value.isNegative()) {
12072     if (FieldName)
12073       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
12074                << FieldName << Value.toString(10);
12075     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
12076       << Value.toString(10);
12077   }
12078 
12079   if (!FieldTy->isDependentType()) {
12080     uint64_t TypeSize = Context.getTypeSize(FieldTy);
12081     if (Value.getZExtValue() > TypeSize) {
12082       if (!getLangOpts().CPlusPlus || IsMsStruct ||
12083           Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12084         if (FieldName) 
12085           return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
12086             << FieldName << (unsigned)Value.getZExtValue() 
12087             << (unsigned)TypeSize;
12088         
12089         return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
12090           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
12091       }
12092       
12093       if (FieldName)
12094         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
12095           << FieldName << (unsigned)Value.getZExtValue() 
12096           << (unsigned)TypeSize;
12097       else
12098         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
12099           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;        
12100     }
12101   }
12102 
12103   return BitWidth;
12104 }
12105 
12106 /// ActOnField - Each field of a C struct/union is passed into this in order
12107 /// to create a FieldDecl object for it.
12108 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
12109                        Declarator &D, Expr *BitfieldWidth) {
12110   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
12111                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
12112                                /*InitStyle=*/ICIS_NoInit, AS_public);
12113   return Res;
12114 }
12115 
12116 /// HandleField - Analyze a field of a C struct or a C++ data member.
12117 ///
12118 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
12119                              SourceLocation DeclStart,
12120                              Declarator &D, Expr *BitWidth,
12121                              InClassInitStyle InitStyle,
12122                              AccessSpecifier AS) {
12123   IdentifierInfo *II = D.getIdentifier();
12124   SourceLocation Loc = DeclStart;
12125   if (II) Loc = D.getIdentifierLoc();
12126 
12127   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12128   QualType T = TInfo->getType();
12129   if (getLangOpts().CPlusPlus) {
12130     CheckExtraCXXDefaultArguments(D);
12131 
12132     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12133                                         UPPC_DataMemberType)) {
12134       D.setInvalidType();
12135       T = Context.IntTy;
12136       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12137     }
12138   }
12139 
12140   // TR 18037 does not allow fields to be declared with address spaces.
12141   if (T.getQualifiers().hasAddressSpace()) {
12142     Diag(Loc, diag::err_field_with_address_space);
12143     D.setInvalidType();
12144   }
12145 
12146   // OpenCL 1.2 spec, s6.9 r:
12147   // The event type cannot be used to declare a structure or union field.
12148   if (LangOpts.OpenCL && T->isEventT()) {
12149     Diag(Loc, diag::err_event_t_struct_field);
12150     D.setInvalidType();
12151   }
12152 
12153   DiagnoseFunctionSpecifiers(D.getDeclSpec());
12154 
12155   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12156     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12157          diag::err_invalid_thread)
12158       << DeclSpec::getSpecifierName(TSCS);
12159 
12160   // Check to see if this name was declared as a member previously
12161   NamedDecl *PrevDecl = nullptr;
12162   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12163   LookupName(Previous, S);
12164   switch (Previous.getResultKind()) {
12165     case LookupResult::Found:
12166     case LookupResult::FoundUnresolvedValue:
12167       PrevDecl = Previous.getAsSingle<NamedDecl>();
12168       break;
12169       
12170     case LookupResult::FoundOverloaded:
12171       PrevDecl = Previous.getRepresentativeDecl();
12172       break;
12173       
12174     case LookupResult::NotFound:
12175     case LookupResult::NotFoundInCurrentInstantiation:
12176     case LookupResult::Ambiguous:
12177       break;
12178   }
12179   Previous.suppressDiagnostics();
12180 
12181   if (PrevDecl && PrevDecl->isTemplateParameter()) {
12182     // Maybe we will complain about the shadowed template parameter.
12183     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12184     // Just pretend that we didn't see the previous declaration.
12185     PrevDecl = nullptr;
12186   }
12187 
12188   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12189     PrevDecl = nullptr;
12190 
12191   bool Mutable
12192     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
12193   SourceLocation TSSL = D.getLocStart();
12194   FieldDecl *NewFD
12195     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
12196                      TSSL, AS, PrevDecl, &D);
12197 
12198   if (NewFD->isInvalidDecl())
12199     Record->setInvalidDecl();
12200 
12201   if (D.getDeclSpec().isModulePrivateSpecified())
12202     NewFD->setModulePrivate();
12203   
12204   if (NewFD->isInvalidDecl() && PrevDecl) {
12205     // Don't introduce NewFD into scope; there's already something
12206     // with the same name in the same scope.
12207   } else if (II) {
12208     PushOnScopeChains(NewFD, S);
12209   } else
12210     Record->addDecl(NewFD);
12211 
12212   return NewFD;
12213 }
12214 
12215 /// \brief Build a new FieldDecl and check its well-formedness.
12216 ///
12217 /// This routine builds a new FieldDecl given the fields name, type,
12218 /// record, etc. \p PrevDecl should refer to any previous declaration
12219 /// with the same name and in the same scope as the field to be
12220 /// created.
12221 ///
12222 /// \returns a new FieldDecl.
12223 ///
12224 /// \todo The Declarator argument is a hack. It will be removed once
12225 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
12226                                 TypeSourceInfo *TInfo,
12227                                 RecordDecl *Record, SourceLocation Loc,
12228                                 bool Mutable, Expr *BitWidth,
12229                                 InClassInitStyle InitStyle,
12230                                 SourceLocation TSSL,
12231                                 AccessSpecifier AS, NamedDecl *PrevDecl,
12232                                 Declarator *D) {
12233   IdentifierInfo *II = Name.getAsIdentifierInfo();
12234   bool InvalidDecl = false;
12235   if (D) InvalidDecl = D->isInvalidType();
12236 
12237   // If we receive a broken type, recover by assuming 'int' and
12238   // marking this declaration as invalid.
12239   if (T.isNull()) {
12240     InvalidDecl = true;
12241     T = Context.IntTy;
12242   }
12243 
12244   QualType EltTy = Context.getBaseElementType(T);
12245   if (!EltTy->isDependentType()) {
12246     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
12247       // Fields of incomplete type force their record to be invalid.
12248       Record->setInvalidDecl();
12249       InvalidDecl = true;
12250     } else {
12251       NamedDecl *Def;
12252       EltTy->isIncompleteType(&Def);
12253       if (Def && Def->isInvalidDecl()) {
12254         Record->setInvalidDecl();
12255         InvalidDecl = true;
12256       }
12257     }
12258   }
12259 
12260   // OpenCL v1.2 s6.9.c: bitfields are not supported.
12261   if (BitWidth && getLangOpts().OpenCL) {
12262     Diag(Loc, diag::err_opencl_bitfields);
12263     InvalidDecl = true;
12264   }
12265 
12266   // C99 6.7.2.1p8: A member of a structure or union may have any type other
12267   // than a variably modified type.
12268   if (!InvalidDecl && T->isVariablyModifiedType()) {
12269     bool SizeIsNegative;
12270     llvm::APSInt Oversized;
12271 
12272     TypeSourceInfo *FixedTInfo =
12273       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
12274                                                     SizeIsNegative,
12275                                                     Oversized);
12276     if (FixedTInfo) {
12277       Diag(Loc, diag::warn_illegal_constant_array_size);
12278       TInfo = FixedTInfo;
12279       T = FixedTInfo->getType();
12280     } else {
12281       if (SizeIsNegative)
12282         Diag(Loc, diag::err_typecheck_negative_array_size);
12283       else if (Oversized.getBoolValue())
12284         Diag(Loc, diag::err_array_too_large)
12285           << Oversized.toString(10);
12286       else
12287         Diag(Loc, diag::err_typecheck_field_variable_size);
12288       InvalidDecl = true;
12289     }
12290   }
12291 
12292   // Fields can not have abstract class types
12293   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
12294                                              diag::err_abstract_type_in_decl,
12295                                              AbstractFieldType))
12296     InvalidDecl = true;
12297 
12298   bool ZeroWidth = false;
12299   // If this is declared as a bit-field, check the bit-field.
12300   if (!InvalidDecl && BitWidth) {
12301     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
12302                               &ZeroWidth).get();
12303     if (!BitWidth) {
12304       InvalidDecl = true;
12305       BitWidth = nullptr;
12306       ZeroWidth = false;
12307     }
12308   }
12309 
12310   // Check that 'mutable' is consistent with the type of the declaration.
12311   if (!InvalidDecl && Mutable) {
12312     unsigned DiagID = 0;
12313     if (T->isReferenceType())
12314       DiagID = diag::err_mutable_reference;
12315     else if (T.isConstQualified())
12316       DiagID = diag::err_mutable_const;
12317 
12318     if (DiagID) {
12319       SourceLocation ErrLoc = Loc;
12320       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
12321         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
12322       Diag(ErrLoc, DiagID);
12323       Mutable = false;
12324       InvalidDecl = true;
12325     }
12326   }
12327 
12328   // C++11 [class.union]p8 (DR1460):
12329   //   At most one variant member of a union may have a
12330   //   brace-or-equal-initializer.
12331   if (InitStyle != ICIS_NoInit)
12332     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
12333 
12334   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
12335                                        BitWidth, Mutable, InitStyle);
12336   if (InvalidDecl)
12337     NewFD->setInvalidDecl();
12338 
12339   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
12340     Diag(Loc, diag::err_duplicate_member) << II;
12341     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12342     NewFD->setInvalidDecl();
12343   }
12344 
12345   if (!InvalidDecl && getLangOpts().CPlusPlus) {
12346     if (Record->isUnion()) {
12347       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
12348         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
12349         if (RDecl->getDefinition()) {
12350           // C++ [class.union]p1: An object of a class with a non-trivial
12351           // constructor, a non-trivial copy constructor, a non-trivial
12352           // destructor, or a non-trivial copy assignment operator
12353           // cannot be a member of a union, nor can an array of such
12354           // objects.
12355           if (CheckNontrivialField(NewFD))
12356             NewFD->setInvalidDecl();
12357         }
12358       }
12359 
12360       // C++ [class.union]p1: If a union contains a member of reference type,
12361       // the program is ill-formed, except when compiling with MSVC extensions
12362       // enabled.
12363       if (EltTy->isReferenceType()) {
12364         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
12365                                     diag::ext_union_member_of_reference_type :
12366                                     diag::err_union_member_of_reference_type)
12367           << NewFD->getDeclName() << EltTy;
12368         if (!getLangOpts().MicrosoftExt)
12369           NewFD->setInvalidDecl();
12370       }
12371     }
12372   }
12373 
12374   // FIXME: We need to pass in the attributes given an AST
12375   // representation, not a parser representation.
12376   if (D) {
12377     // FIXME: The current scope is almost... but not entirely... correct here.
12378     ProcessDeclAttributes(getCurScope(), NewFD, *D);
12379 
12380     if (NewFD->hasAttrs())
12381       CheckAlignasUnderalignment(NewFD);
12382   }
12383 
12384   // In auto-retain/release, infer strong retension for fields of
12385   // retainable type.
12386   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
12387     NewFD->setInvalidDecl();
12388 
12389   if (T.isObjCGCWeak())
12390     Diag(Loc, diag::warn_attribute_weak_on_field);
12391 
12392   NewFD->setAccess(AS);
12393   return NewFD;
12394 }
12395 
12396 bool Sema::CheckNontrivialField(FieldDecl *FD) {
12397   assert(FD);
12398   assert(getLangOpts().CPlusPlus && "valid check only for C++");
12399 
12400   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
12401     return false;
12402 
12403   QualType EltTy = Context.getBaseElementType(FD->getType());
12404   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
12405     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
12406     if (RDecl->getDefinition()) {
12407       // We check for copy constructors before constructors
12408       // because otherwise we'll never get complaints about
12409       // copy constructors.
12410 
12411       CXXSpecialMember member = CXXInvalid;
12412       // We're required to check for any non-trivial constructors. Since the
12413       // implicit default constructor is suppressed if there are any
12414       // user-declared constructors, we just need to check that there is a
12415       // trivial default constructor and a trivial copy constructor. (We don't
12416       // worry about move constructors here, since this is a C++98 check.)
12417       if (RDecl->hasNonTrivialCopyConstructor())
12418         member = CXXCopyConstructor;
12419       else if (!RDecl->hasTrivialDefaultConstructor())
12420         member = CXXDefaultConstructor;
12421       else if (RDecl->hasNonTrivialCopyAssignment())
12422         member = CXXCopyAssignment;
12423       else if (RDecl->hasNonTrivialDestructor())
12424         member = CXXDestructor;
12425 
12426       if (member != CXXInvalid) {
12427         if (!getLangOpts().CPlusPlus11 &&
12428             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
12429           // Objective-C++ ARC: it is an error to have a non-trivial field of
12430           // a union. However, system headers in Objective-C programs 
12431           // occasionally have Objective-C lifetime objects within unions,
12432           // and rather than cause the program to fail, we make those 
12433           // members unavailable.
12434           SourceLocation Loc = FD->getLocation();
12435           if (getSourceManager().isInSystemHeader(Loc)) {
12436             if (!FD->hasAttr<UnavailableAttr>())
12437               FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12438                                   "this system field has retaining ownership",
12439                                   Loc));
12440             return false;
12441           }
12442         }
12443 
12444         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
12445                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
12446                diag::err_illegal_union_or_anon_struct_member)
12447           << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
12448         DiagnoseNontrivial(RDecl, member);
12449         return !getLangOpts().CPlusPlus11;
12450       }
12451     }
12452   }
12453 
12454   return false;
12455 }
12456 
12457 /// TranslateIvarVisibility - Translate visibility from a token ID to an
12458 ///  AST enum value.
12459 static ObjCIvarDecl::AccessControl
12460 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
12461   switch (ivarVisibility) {
12462   default: llvm_unreachable("Unknown visitibility kind");
12463   case tok::objc_private: return ObjCIvarDecl::Private;
12464   case tok::objc_public: return ObjCIvarDecl::Public;
12465   case tok::objc_protected: return ObjCIvarDecl::Protected;
12466   case tok::objc_package: return ObjCIvarDecl::Package;
12467   }
12468 }
12469 
12470 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
12471 /// in order to create an IvarDecl object for it.
12472 Decl *Sema::ActOnIvar(Scope *S,
12473                                 SourceLocation DeclStart,
12474                                 Declarator &D, Expr *BitfieldWidth,
12475                                 tok::ObjCKeywordKind Visibility) {
12476 
12477   IdentifierInfo *II = D.getIdentifier();
12478   Expr *BitWidth = (Expr*)BitfieldWidth;
12479   SourceLocation Loc = DeclStart;
12480   if (II) Loc = D.getIdentifierLoc();
12481 
12482   // FIXME: Unnamed fields can be handled in various different ways, for
12483   // example, unnamed unions inject all members into the struct namespace!
12484 
12485   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12486   QualType T = TInfo->getType();
12487 
12488   if (BitWidth) {
12489     // 6.7.2.1p3, 6.7.2.1p4
12490     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
12491     if (!BitWidth)
12492       D.setInvalidType();
12493   } else {
12494     // Not a bitfield.
12495 
12496     // validate II.
12497 
12498   }
12499   if (T->isReferenceType()) {
12500     Diag(Loc, diag::err_ivar_reference_type);
12501     D.setInvalidType();
12502   }
12503   // C99 6.7.2.1p8: A member of a structure or union may have any type other
12504   // than a variably modified type.
12505   else if (T->isVariablyModifiedType()) {
12506     Diag(Loc, diag::err_typecheck_ivar_variable_size);
12507     D.setInvalidType();
12508   }
12509 
12510   // Get the visibility (access control) for this ivar.
12511   ObjCIvarDecl::AccessControl ac =
12512     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
12513                                         : ObjCIvarDecl::None;
12514   // Must set ivar's DeclContext to its enclosing interface.
12515   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
12516   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
12517     return nullptr;
12518   ObjCContainerDecl *EnclosingContext;
12519   if (ObjCImplementationDecl *IMPDecl =
12520       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
12521     if (LangOpts.ObjCRuntime.isFragile()) {
12522     // Case of ivar declared in an implementation. Context is that of its class.
12523       EnclosingContext = IMPDecl->getClassInterface();
12524       assert(EnclosingContext && "Implementation has no class interface!");
12525     }
12526     else
12527       EnclosingContext = EnclosingDecl;
12528   } else {
12529     if (ObjCCategoryDecl *CDecl = 
12530         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
12531       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
12532         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
12533         return nullptr;
12534       }
12535     }
12536     EnclosingContext = EnclosingDecl;
12537   }
12538 
12539   // Construct the decl.
12540   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
12541                                              DeclStart, Loc, II, T,
12542                                              TInfo, ac, (Expr *)BitfieldWidth);
12543 
12544   if (II) {
12545     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
12546                                            ForRedeclaration);
12547     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
12548         && !isa<TagDecl>(PrevDecl)) {
12549       Diag(Loc, diag::err_duplicate_member) << II;
12550       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12551       NewID->setInvalidDecl();
12552     }
12553   }
12554 
12555   // Process attributes attached to the ivar.
12556   ProcessDeclAttributes(S, NewID, D);
12557 
12558   if (D.isInvalidType())
12559     NewID->setInvalidDecl();
12560 
12561   // In ARC, infer 'retaining' for ivars of retainable type.
12562   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
12563     NewID->setInvalidDecl();
12564 
12565   if (D.getDeclSpec().isModulePrivateSpecified())
12566     NewID->setModulePrivate();
12567   
12568   if (II) {
12569     // FIXME: When interfaces are DeclContexts, we'll need to add
12570     // these to the interface.
12571     S->AddDecl(NewID);
12572     IdResolver.AddDecl(NewID);
12573   }
12574   
12575   if (LangOpts.ObjCRuntime.isNonFragile() &&
12576       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
12577     Diag(Loc, diag::warn_ivars_in_interface);
12578   
12579   return NewID;
12580 }
12581 
12582 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 
12583 /// class and class extensions. For every class \@interface and class 
12584 /// extension \@interface, if the last ivar is a bitfield of any type, 
12585 /// then add an implicit `char :0` ivar to the end of that interface.
12586 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
12587                              SmallVectorImpl<Decl *> &AllIvarDecls) {
12588   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
12589     return;
12590   
12591   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
12592   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
12593   
12594   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
12595     return;
12596   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
12597   if (!ID) {
12598     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
12599       if (!CD->IsClassExtension())
12600         return;
12601     }
12602     // No need to add this to end of @implementation.
12603     else
12604       return;
12605   }
12606   // All conditions are met. Add a new bitfield to the tail end of ivars.
12607   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
12608   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
12609 
12610   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
12611                               DeclLoc, DeclLoc, nullptr,
12612                               Context.CharTy, 
12613                               Context.getTrivialTypeSourceInfo(Context.CharTy,
12614                                                                DeclLoc),
12615                               ObjCIvarDecl::Private, BW,
12616                               true);
12617   AllIvarDecls.push_back(Ivar);
12618 }
12619 
12620 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
12621                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
12622                        SourceLocation RBrac, AttributeList *Attr) {
12623   assert(EnclosingDecl && "missing record or interface decl");
12624 
12625   // If this is an Objective-C @implementation or category and we have
12626   // new fields here we should reset the layout of the interface since
12627   // it will now change.
12628   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
12629     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
12630     switch (DC->getKind()) {
12631     default: break;
12632     case Decl::ObjCCategory:
12633       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
12634       break;
12635     case Decl::ObjCImplementation:
12636       Context.
12637         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
12638       break;
12639     }
12640   }
12641   
12642   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
12643 
12644   // Start counting up the number of named members; make sure to include
12645   // members of anonymous structs and unions in the total.
12646   unsigned NumNamedMembers = 0;
12647   if (Record) {
12648     for (const auto *I : Record->decls()) {
12649       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
12650         if (IFD->getDeclName())
12651           ++NumNamedMembers;
12652     }
12653   }
12654 
12655   // Verify that all the fields are okay.
12656   SmallVector<FieldDecl*, 32> RecFields;
12657 
12658   bool ARCErrReported = false;
12659   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
12660        i != end; ++i) {
12661     FieldDecl *FD = cast<FieldDecl>(*i);
12662 
12663     // Get the type for the field.
12664     const Type *FDTy = FD->getType().getTypePtr();
12665 
12666     if (!FD->isAnonymousStructOrUnion()) {
12667       // Remember all fields written by the user.
12668       RecFields.push_back(FD);
12669     }
12670 
12671     // If the field is already invalid for some reason, don't emit more
12672     // diagnostics about it.
12673     if (FD->isInvalidDecl()) {
12674       EnclosingDecl->setInvalidDecl();
12675       continue;
12676     }
12677 
12678     // C99 6.7.2.1p2:
12679     //   A structure or union shall not contain a member with
12680     //   incomplete or function type (hence, a structure shall not
12681     //   contain an instance of itself, but may contain a pointer to
12682     //   an instance of itself), except that the last member of a
12683     //   structure with more than one named member may have incomplete
12684     //   array type; such a structure (and any union containing,
12685     //   possibly recursively, a member that is such a structure)
12686     //   shall not be a member of a structure or an element of an
12687     //   array.
12688     if (FDTy->isFunctionType()) {
12689       // Field declared as a function.
12690       Diag(FD->getLocation(), diag::err_field_declared_as_function)
12691         << FD->getDeclName();
12692       FD->setInvalidDecl();
12693       EnclosingDecl->setInvalidDecl();
12694       continue;
12695     } else if (FDTy->isIncompleteArrayType() && Record && 
12696                ((i + 1 == Fields.end() && !Record->isUnion()) ||
12697                 ((getLangOpts().MicrosoftExt ||
12698                   getLangOpts().CPlusPlus) &&
12699                  (i + 1 == Fields.end() || Record->isUnion())))) {
12700       // Flexible array member.
12701       // Microsoft and g++ is more permissive regarding flexible array.
12702       // It will accept flexible array in union and also
12703       // as the sole element of a struct/class.
12704       unsigned DiagID = 0;
12705       if (Record->isUnion())
12706         DiagID = getLangOpts().MicrosoftExt
12707                      ? diag::ext_flexible_array_union_ms
12708                      : getLangOpts().CPlusPlus
12709                            ? diag::ext_flexible_array_union_gnu
12710                            : diag::err_flexible_array_union;
12711       else if (Fields.size() == 1)
12712         DiagID = getLangOpts().MicrosoftExt
12713                      ? diag::ext_flexible_array_empty_aggregate_ms
12714                      : getLangOpts().CPlusPlus
12715                            ? diag::ext_flexible_array_empty_aggregate_gnu
12716                            : NumNamedMembers < 1
12717                                  ? diag::err_flexible_array_empty_aggregate
12718                                  : 0;
12719 
12720       if (DiagID)
12721         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
12722                                         << Record->getTagKind();
12723       // While the layout of types that contain virtual bases is not specified
12724       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
12725       // virtual bases after the derived members.  This would make a flexible
12726       // array member declared at the end of an object not adjacent to the end
12727       // of the type.
12728       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
12729         if (RD->getNumVBases() != 0)
12730           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
12731             << FD->getDeclName() << Record->getTagKind();
12732       if (!getLangOpts().C99)
12733         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
12734           << FD->getDeclName() << Record->getTagKind();
12735 
12736       // If the element type has a non-trivial destructor, we would not
12737       // implicitly destroy the elements, so disallow it for now.
12738       //
12739       // FIXME: GCC allows this. We should probably either implicitly delete
12740       // the destructor of the containing class, or just allow this.
12741       QualType BaseElem = Context.getBaseElementType(FD->getType());
12742       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
12743         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
12744           << FD->getDeclName() << FD->getType();
12745         FD->setInvalidDecl();
12746         EnclosingDecl->setInvalidDecl();
12747         continue;
12748       }
12749       // Okay, we have a legal flexible array member at the end of the struct.
12750       Record->setHasFlexibleArrayMember(true);
12751     } else if (!FDTy->isDependentType() &&
12752                RequireCompleteType(FD->getLocation(), FD->getType(),
12753                                    diag::err_field_incomplete)) {
12754       // Incomplete type
12755       FD->setInvalidDecl();
12756       EnclosingDecl->setInvalidDecl();
12757       continue;
12758     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
12759       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
12760         // A type which contains a flexible array member is considered to be a
12761         // flexible array member.
12762         Record->setHasFlexibleArrayMember(true);
12763         if (!Record->isUnion()) {
12764           // If this is a struct/class and this is not the last element, reject
12765           // it.  Note that GCC supports variable sized arrays in the middle of
12766           // structures.
12767           if (i + 1 != Fields.end())
12768             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
12769               << FD->getDeclName() << FD->getType();
12770           else {
12771             // We support flexible arrays at the end of structs in
12772             // other structs as an extension.
12773             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
12774               << FD->getDeclName();
12775           }
12776         }
12777       }
12778       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
12779           RequireNonAbstractType(FD->getLocation(), FD->getType(),
12780                                  diag::err_abstract_type_in_decl,
12781                                  AbstractIvarType)) {
12782         // Ivars can not have abstract class types
12783         FD->setInvalidDecl();
12784       }
12785       if (Record && FDTTy->getDecl()->hasObjectMember())
12786         Record->setHasObjectMember(true);
12787       if (Record && FDTTy->getDecl()->hasVolatileMember())
12788         Record->setHasVolatileMember(true);
12789     } else if (FDTy->isObjCObjectType()) {
12790       /// A field cannot be an Objective-c object
12791       Diag(FD->getLocation(), diag::err_statically_allocated_object)
12792         << FixItHint::CreateInsertion(FD->getLocation(), "*");
12793       QualType T = Context.getObjCObjectPointerType(FD->getType());
12794       FD->setType(T);
12795     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
12796                (!getLangOpts().CPlusPlus || Record->isUnion())) {
12797       // It's an error in ARC if a field has lifetime.
12798       // We don't want to report this in a system header, though,
12799       // so we just make the field unavailable.
12800       // FIXME: that's really not sufficient; we need to make the type
12801       // itself invalid to, say, initialize or copy.
12802       QualType T = FD->getType();
12803       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
12804       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
12805         SourceLocation loc = FD->getLocation();
12806         if (getSourceManager().isInSystemHeader(loc)) {
12807           if (!FD->hasAttr<UnavailableAttr>()) {
12808             FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12809                               "this system field has retaining ownership",
12810                               loc));
12811           }
12812         } else {
12813           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 
12814             << T->isBlockPointerType() << Record->getTagKind();
12815         }
12816         ARCErrReported = true;
12817       }
12818     } else if (getLangOpts().ObjC1 &&
12819                getLangOpts().getGC() != LangOptions::NonGC &&
12820                Record && !Record->hasObjectMember()) {
12821       if (FD->getType()->isObjCObjectPointerType() ||
12822           FD->getType().isObjCGCStrong())
12823         Record->setHasObjectMember(true);
12824       else if (Context.getAsArrayType(FD->getType())) {
12825         QualType BaseType = Context.getBaseElementType(FD->getType());
12826         if (BaseType->isRecordType() && 
12827             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
12828           Record->setHasObjectMember(true);
12829         else if (BaseType->isObjCObjectPointerType() ||
12830                  BaseType.isObjCGCStrong())
12831                Record->setHasObjectMember(true);
12832       }
12833     }
12834     if (Record && FD->getType().isVolatileQualified())
12835       Record->setHasVolatileMember(true);
12836     // Keep track of the number of named members.
12837     if (FD->getIdentifier())
12838       ++NumNamedMembers;
12839   }
12840 
12841   // Okay, we successfully defined 'Record'.
12842   if (Record) {
12843     bool Completed = false;
12844     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12845       if (!CXXRecord->isInvalidDecl()) {
12846         // Set access bits correctly on the directly-declared conversions.
12847         for (CXXRecordDecl::conversion_iterator
12848                I = CXXRecord->conversion_begin(),
12849                E = CXXRecord->conversion_end(); I != E; ++I)
12850           I.setAccess((*I)->getAccess());
12851         
12852         if (!CXXRecord->isDependentType()) {
12853           if (CXXRecord->hasUserDeclaredDestructor()) {
12854             // Adjust user-defined destructor exception spec.
12855             if (getLangOpts().CPlusPlus11)
12856               AdjustDestructorExceptionSpec(CXXRecord,
12857                                             CXXRecord->getDestructor());
12858           }
12859 
12860           // Add any implicitly-declared members to this class.
12861           AddImplicitlyDeclaredMembersToClass(CXXRecord);
12862 
12863           // If we have virtual base classes, we may end up finding multiple 
12864           // final overriders for a given virtual function. Check for this 
12865           // problem now.
12866           if (CXXRecord->getNumVBases()) {
12867             CXXFinalOverriderMap FinalOverriders;
12868             CXXRecord->getFinalOverriders(FinalOverriders);
12869             
12870             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 
12871                                              MEnd = FinalOverriders.end();
12872                  M != MEnd; ++M) {
12873               for (OverridingMethods::iterator SO = M->second.begin(), 
12874                                             SOEnd = M->second.end();
12875                    SO != SOEnd; ++SO) {
12876                 assert(SO->second.size() > 0 && 
12877                        "Virtual function without overridding functions?");
12878                 if (SO->second.size() == 1)
12879                   continue;
12880                 
12881                 // C++ [class.virtual]p2:
12882                 //   In a derived class, if a virtual member function of a base
12883                 //   class subobject has more than one final overrider the
12884                 //   program is ill-formed.
12885                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
12886                   << (const NamedDecl *)M->first << Record;
12887                 Diag(M->first->getLocation(), 
12888                      diag::note_overridden_virtual_function);
12889                 for (OverridingMethods::overriding_iterator 
12890                           OM = SO->second.begin(), 
12891                        OMEnd = SO->second.end();
12892                      OM != OMEnd; ++OM)
12893                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
12894                     << (const NamedDecl *)M->first << OM->Method->getParent();
12895                 
12896                 Record->setInvalidDecl();
12897               }
12898             }
12899             CXXRecord->completeDefinition(&FinalOverriders);
12900             Completed = true;
12901           }
12902         }
12903       }
12904     }
12905     
12906     if (!Completed)
12907       Record->completeDefinition();
12908 
12909     if (Record->hasAttrs()) {
12910       CheckAlignasUnderalignment(Record);
12911 
12912       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
12913         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
12914                                            IA->getRange(), IA->getBestCase(),
12915                                            IA->getSemanticSpelling());
12916     }
12917 
12918     // Check if the structure/union declaration is a type that can have zero
12919     // size in C. For C this is a language extension, for C++ it may cause
12920     // compatibility problems.
12921     bool CheckForZeroSize;
12922     if (!getLangOpts().CPlusPlus) {
12923       CheckForZeroSize = true;
12924     } else {
12925       // For C++ filter out types that cannot be referenced in C code.
12926       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12927       CheckForZeroSize =
12928           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12929           !CXXRecord->isDependentType() &&
12930           CXXRecord->isCLike();
12931     }
12932     if (CheckForZeroSize) {
12933       bool ZeroSize = true;
12934       bool IsEmpty = true;
12935       unsigned NonBitFields = 0;
12936       for (RecordDecl::field_iterator I = Record->field_begin(),
12937                                       E = Record->field_end();
12938            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12939         IsEmpty = false;
12940         if (I->isUnnamedBitfield()) {
12941           if (I->getBitWidthValue(Context) > 0)
12942             ZeroSize = false;
12943         } else {
12944           ++NonBitFields;
12945           QualType FieldType = I->getType();
12946           if (FieldType->isIncompleteType() ||
12947               !Context.getTypeSizeInChars(FieldType).isZero())
12948             ZeroSize = false;
12949         }
12950       }
12951 
12952       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
12953       // allowed in C++, but warn if its declaration is inside
12954       // extern "C" block.
12955       if (ZeroSize) {
12956         Diag(RecLoc, getLangOpts().CPlusPlus ?
12957                          diag::warn_zero_size_struct_union_in_extern_c :
12958                          diag::warn_zero_size_struct_union_compat)
12959           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
12960       }
12961 
12962       // Structs without named members are extension in C (C99 6.7.2.1p7),
12963       // but are accepted by GCC.
12964       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
12965         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
12966                                diag::ext_no_named_members_in_struct_union)
12967           << Record->isUnion();
12968       }
12969     }
12970   } else {
12971     ObjCIvarDecl **ClsFields =
12972       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
12973     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
12974       ID->setEndOfDefinitionLoc(RBrac);
12975       // Add ivar's to class's DeclContext.
12976       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12977         ClsFields[i]->setLexicalDeclContext(ID);
12978         ID->addDecl(ClsFields[i]);
12979       }
12980       // Must enforce the rule that ivars in the base classes may not be
12981       // duplicates.
12982       if (ID->getSuperClass())
12983         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
12984     } else if (ObjCImplementationDecl *IMPDecl =
12985                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
12986       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
12987       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12988         // Ivar declared in @implementation never belongs to the implementation.
12989         // Only it is in implementation's lexical context.
12990         ClsFields[I]->setLexicalDeclContext(IMPDecl);
12991       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
12992       IMPDecl->setIvarLBraceLoc(LBrac);
12993       IMPDecl->setIvarRBraceLoc(RBrac);
12994     } else if (ObjCCategoryDecl *CDecl = 
12995                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
12996       // case of ivars in class extension; all other cases have been
12997       // reported as errors elsewhere.
12998       // FIXME. Class extension does not have a LocEnd field.
12999       // CDecl->setLocEnd(RBrac);
13000       // Add ivar's to class extension's DeclContext.
13001       // Diagnose redeclaration of private ivars.
13002       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
13003       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13004         if (IDecl) {
13005           if (const ObjCIvarDecl *ClsIvar = 
13006               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
13007             Diag(ClsFields[i]->getLocation(), 
13008                  diag::err_duplicate_ivar_declaration); 
13009             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
13010             continue;
13011           }
13012           for (const auto *Ext : IDecl->known_extensions()) {
13013             if (const ObjCIvarDecl *ClsExtIvar
13014                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
13015               Diag(ClsFields[i]->getLocation(), 
13016                    diag::err_duplicate_ivar_declaration); 
13017               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
13018               continue;
13019             }
13020           }
13021         }
13022         ClsFields[i]->setLexicalDeclContext(CDecl);
13023         CDecl->addDecl(ClsFields[i]);
13024       }
13025       CDecl->setIvarLBraceLoc(LBrac);
13026       CDecl->setIvarRBraceLoc(RBrac);
13027     }
13028   }
13029 
13030   if (Attr)
13031     ProcessDeclAttributeList(S, Record, Attr);
13032 }
13033 
13034 /// \brief Determine whether the given integral value is representable within
13035 /// the given type T.
13036 static bool isRepresentableIntegerValue(ASTContext &Context,
13037                                         llvm::APSInt &Value,
13038                                         QualType T) {
13039   assert(T->isIntegralType(Context) && "Integral type required!");
13040   unsigned BitWidth = Context.getIntWidth(T);
13041   
13042   if (Value.isUnsigned() || Value.isNonNegative()) {
13043     if (T->isSignedIntegerOrEnumerationType()) 
13044       --BitWidth;
13045     return Value.getActiveBits() <= BitWidth;
13046   }  
13047   return Value.getMinSignedBits() <= BitWidth;
13048 }
13049 
13050 // \brief Given an integral type, return the next larger integral type
13051 // (or a NULL type of no such type exists).
13052 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
13053   // FIXME: Int128/UInt128 support, which also needs to be introduced into 
13054   // enum checking below.
13055   assert(T->isIntegralType(Context) && "Integral type required!");
13056   const unsigned NumTypes = 4;
13057   QualType SignedIntegralTypes[NumTypes] = { 
13058     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
13059   };
13060   QualType UnsignedIntegralTypes[NumTypes] = { 
13061     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 
13062     Context.UnsignedLongLongTy
13063   };
13064   
13065   unsigned BitWidth = Context.getTypeSize(T);
13066   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
13067                                                         : UnsignedIntegralTypes;
13068   for (unsigned I = 0; I != NumTypes; ++I)
13069     if (Context.getTypeSize(Types[I]) > BitWidth)
13070       return Types[I];
13071   
13072   return QualType();
13073 }
13074 
13075 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
13076                                           EnumConstantDecl *LastEnumConst,
13077                                           SourceLocation IdLoc,
13078                                           IdentifierInfo *Id,
13079                                           Expr *Val) {
13080   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
13081   llvm::APSInt EnumVal(IntWidth);
13082   QualType EltTy;
13083 
13084   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
13085     Val = nullptr;
13086 
13087   if (Val)
13088     Val = DefaultLvalueConversion(Val).get();
13089 
13090   if (Val) {
13091     if (Enum->isDependentType() || Val->isTypeDependent())
13092       EltTy = Context.DependentTy;
13093     else {
13094       SourceLocation ExpLoc;
13095       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
13096           !getLangOpts().MSVCCompat) {
13097         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
13098         // constant-expression in the enumerator-definition shall be a converted
13099         // constant expression of the underlying type.
13100         EltTy = Enum->getIntegerType();
13101         ExprResult Converted =
13102           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
13103                                            CCEK_Enumerator);
13104         if (Converted.isInvalid())
13105           Val = nullptr;
13106         else
13107           Val = Converted.get();
13108       } else if (!Val->isValueDependent() &&
13109                  !(Val = VerifyIntegerConstantExpression(Val,
13110                                                          &EnumVal).get())) {
13111         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
13112       } else {
13113         if (Enum->isFixed()) {
13114           EltTy = Enum->getIntegerType();
13115 
13116           // In Obj-C and Microsoft mode, require the enumeration value to be
13117           // representable in the underlying type of the enumeration. In C++11,
13118           // we perform a non-narrowing conversion as part of converted constant
13119           // expression checking.
13120           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13121             if (getLangOpts().MSVCCompat) {
13122               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
13123               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13124             } else
13125               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
13126           } else
13127             Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13128         } else if (getLangOpts().CPlusPlus) {
13129           // C++11 [dcl.enum]p5:
13130           //   If the underlying type is not fixed, the type of each enumerator
13131           //   is the type of its initializing value:
13132           //     - If an initializer is specified for an enumerator, the 
13133           //       initializing value has the same type as the expression.
13134           EltTy = Val->getType();
13135         } else {
13136           // C99 6.7.2.2p2:
13137           //   The expression that defines the value of an enumeration constant
13138           //   shall be an integer constant expression that has a value
13139           //   representable as an int.
13140 
13141           // Complain if the value is not representable in an int.
13142           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
13143             Diag(IdLoc, diag::ext_enum_value_not_int)
13144               << EnumVal.toString(10) << Val->getSourceRange()
13145               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
13146           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
13147             // Force the type of the expression to 'int'.
13148             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
13149           }
13150           EltTy = Val->getType();
13151         }
13152       }
13153     }
13154   }
13155 
13156   if (!Val) {
13157     if (Enum->isDependentType())
13158       EltTy = Context.DependentTy;
13159     else if (!LastEnumConst) {
13160       // C++0x [dcl.enum]p5:
13161       //   If the underlying type is not fixed, the type of each enumerator
13162       //   is the type of its initializing value:
13163       //     - If no initializer is specified for the first enumerator, the 
13164       //       initializing value has an unspecified integral type.
13165       //
13166       // GCC uses 'int' for its unspecified integral type, as does 
13167       // C99 6.7.2.2p3.
13168       if (Enum->isFixed()) {
13169         EltTy = Enum->getIntegerType();
13170       }
13171       else {
13172         EltTy = Context.IntTy;
13173       }
13174     } else {
13175       // Assign the last value + 1.
13176       EnumVal = LastEnumConst->getInitVal();
13177       ++EnumVal;
13178       EltTy = LastEnumConst->getType();
13179 
13180       // Check for overflow on increment.
13181       if (EnumVal < LastEnumConst->getInitVal()) {
13182         // C++0x [dcl.enum]p5:
13183         //   If the underlying type is not fixed, the type of each enumerator
13184         //   is the type of its initializing value:
13185         //
13186         //     - Otherwise the type of the initializing value is the same as
13187         //       the type of the initializing value of the preceding enumerator
13188         //       unless the incremented value is not representable in that type,
13189         //       in which case the type is an unspecified integral type 
13190         //       sufficient to contain the incremented value. If no such type
13191         //       exists, the program is ill-formed.
13192         QualType T = getNextLargerIntegralType(Context, EltTy);
13193         if (T.isNull() || Enum->isFixed()) {
13194           // There is no integral type larger enough to represent this 
13195           // value. Complain, then allow the value to wrap around.
13196           EnumVal = LastEnumConst->getInitVal();
13197           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
13198           ++EnumVal;
13199           if (Enum->isFixed())
13200             // When the underlying type is fixed, this is ill-formed.
13201             Diag(IdLoc, diag::err_enumerator_wrapped)
13202               << EnumVal.toString(10)
13203               << EltTy;
13204           else
13205             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
13206               << EnumVal.toString(10);
13207         } else {
13208           EltTy = T;
13209         }
13210         
13211         // Retrieve the last enumerator's value, extent that type to the
13212         // type that is supposed to be large enough to represent the incremented
13213         // value, then increment.
13214         EnumVal = LastEnumConst->getInitVal();
13215         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13216         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
13217         ++EnumVal;        
13218         
13219         // If we're not in C++, diagnose the overflow of enumerator values,
13220         // which in C99 means that the enumerator value is not representable in
13221         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
13222         // permits enumerator values that are representable in some larger
13223         // integral type.
13224         if (!getLangOpts().CPlusPlus && !T.isNull())
13225           Diag(IdLoc, diag::warn_enum_value_overflow);
13226       } else if (!getLangOpts().CPlusPlus &&
13227                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13228         // Enforce C99 6.7.2.2p2 even when we compute the next value.
13229         Diag(IdLoc, diag::ext_enum_value_not_int)
13230           << EnumVal.toString(10) << 1;
13231       }
13232     }
13233   }
13234 
13235   if (!EltTy->isDependentType()) {
13236     // Make the enumerator value match the signedness and size of the 
13237     // enumerator's type.
13238     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
13239     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13240   }
13241   
13242   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
13243                                   Val, EnumVal);
13244 }
13245 
13246 
13247 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
13248                               SourceLocation IdLoc, IdentifierInfo *Id,
13249                               AttributeList *Attr,
13250                               SourceLocation EqualLoc, Expr *Val) {
13251   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
13252   EnumConstantDecl *LastEnumConst =
13253     cast_or_null<EnumConstantDecl>(lastEnumConst);
13254 
13255   // The scope passed in may not be a decl scope.  Zip up the scope tree until
13256   // we find one that is.
13257   S = getNonFieldDeclScope(S);
13258 
13259   // Verify that there isn't already something declared with this name in this
13260   // scope.
13261   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
13262                                          ForRedeclaration);
13263   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13264     // Maybe we will complain about the shadowed template parameter.
13265     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
13266     // Just pretend that we didn't see the previous declaration.
13267     PrevDecl = nullptr;
13268   }
13269 
13270   if (PrevDecl) {
13271     // When in C++, we may get a TagDecl with the same name; in this case the
13272     // enum constant will 'hide' the tag.
13273     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
13274            "Received TagDecl when not in C++!");
13275     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
13276       if (isa<EnumConstantDecl>(PrevDecl))
13277         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
13278       else
13279         Diag(IdLoc, diag::err_redefinition) << Id;
13280       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13281       return nullptr;
13282     }
13283   }
13284 
13285   // C++ [class.mem]p15:
13286   // If T is the name of a class, then each of the following shall have a name 
13287   // different from T:
13288   // - every enumerator of every member of class T that is an unscoped 
13289   // enumerated type
13290   if (CXXRecordDecl *Record
13291                       = dyn_cast<CXXRecordDecl>(
13292                              TheEnumDecl->getDeclContext()->getRedeclContext()))
13293     if (!TheEnumDecl->isScoped() && 
13294         Record->getIdentifier() && Record->getIdentifier() == Id)
13295       Diag(IdLoc, diag::err_member_name_of_class) << Id;
13296   
13297   EnumConstantDecl *New =
13298     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
13299 
13300   if (New) {
13301     // Process attributes.
13302     if (Attr) ProcessDeclAttributeList(S, New, Attr);
13303 
13304     // Register this decl in the current scope stack.
13305     New->setAccess(TheEnumDecl->getAccess());
13306     PushOnScopeChains(New, S);
13307   }
13308 
13309   ActOnDocumentableDecl(New);
13310 
13311   return New;
13312 }
13313 
13314 // Returns true when the enum initial expression does not trigger the
13315 // duplicate enum warning.  A few common cases are exempted as follows:
13316 // Element2 = Element1
13317 // Element2 = Element1 + 1
13318 // Element2 = Element1 - 1
13319 // Where Element2 and Element1 are from the same enum.
13320 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
13321   Expr *InitExpr = ECD->getInitExpr();
13322   if (!InitExpr)
13323     return true;
13324   InitExpr = InitExpr->IgnoreImpCasts();
13325 
13326   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
13327     if (!BO->isAdditiveOp())
13328       return true;
13329     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
13330     if (!IL)
13331       return true;
13332     if (IL->getValue() != 1)
13333       return true;
13334 
13335     InitExpr = BO->getLHS();
13336   }
13337 
13338   // This checks if the elements are from the same enum.
13339   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
13340   if (!DRE)
13341     return true;
13342 
13343   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
13344   if (!EnumConstant)
13345     return true;
13346 
13347   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
13348       Enum)
13349     return true;
13350 
13351   return false;
13352 }
13353 
13354 struct DupKey {
13355   int64_t val;
13356   bool isTombstoneOrEmptyKey;
13357   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
13358     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
13359 };
13360 
13361 static DupKey GetDupKey(const llvm::APSInt& Val) {
13362   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
13363                 false);
13364 }
13365 
13366 struct DenseMapInfoDupKey {
13367   static DupKey getEmptyKey() { return DupKey(0, true); }
13368   static DupKey getTombstoneKey() { return DupKey(1, true); }
13369   static unsigned getHashValue(const DupKey Key) {
13370     return (unsigned)(Key.val * 37);
13371   }
13372   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
13373     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
13374            LHS.val == RHS.val;
13375   }
13376 };
13377 
13378 // Emits a warning when an element is implicitly set a value that
13379 // a previous element has already been set to.
13380 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
13381                                         EnumDecl *Enum,
13382                                         QualType EnumType) {
13383   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
13384     return;
13385   // Avoid anonymous enums
13386   if (!Enum->getIdentifier())
13387     return;
13388 
13389   // Only check for small enums.
13390   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
13391     return;
13392 
13393   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
13394   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
13395 
13396   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
13397   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
13398           ValueToVectorMap;
13399 
13400   DuplicatesVector DupVector;
13401   ValueToVectorMap EnumMap;
13402 
13403   // Populate the EnumMap with all values represented by enum constants without
13404   // an initialier.
13405   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13406     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
13407 
13408     // Null EnumConstantDecl means a previous diagnostic has been emitted for
13409     // this constant.  Skip this enum since it may be ill-formed.
13410     if (!ECD) {
13411       return;
13412     }
13413 
13414     if (ECD->getInitExpr())
13415       continue;
13416 
13417     DupKey Key = GetDupKey(ECD->getInitVal());
13418     DeclOrVector &Entry = EnumMap[Key];
13419 
13420     // First time encountering this value.
13421     if (Entry.isNull())
13422       Entry = ECD;
13423   }
13424 
13425   // Create vectors for any values that has duplicates.
13426   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13427     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
13428     if (!ValidDuplicateEnum(ECD, Enum))
13429       continue;
13430 
13431     DupKey Key = GetDupKey(ECD->getInitVal());
13432 
13433     DeclOrVector& Entry = EnumMap[Key];
13434     if (Entry.isNull())
13435       continue;
13436 
13437     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
13438       // Ensure constants are different.
13439       if (D == ECD)
13440         continue;
13441 
13442       // Create new vector and push values onto it.
13443       ECDVector *Vec = new ECDVector();
13444       Vec->push_back(D);
13445       Vec->push_back(ECD);
13446 
13447       // Update entry to point to the duplicates vector.
13448       Entry = Vec;
13449 
13450       // Store the vector somewhere we can consult later for quick emission of
13451       // diagnostics.
13452       DupVector.push_back(Vec);
13453       continue;
13454     }
13455 
13456     ECDVector *Vec = Entry.get<ECDVector*>();
13457     // Make sure constants are not added more than once.
13458     if (*Vec->begin() == ECD)
13459       continue;
13460 
13461     Vec->push_back(ECD);
13462   }
13463 
13464   // Emit diagnostics.
13465   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
13466                                   DupVectorEnd = DupVector.end();
13467        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
13468     ECDVector *Vec = *DupVectorIter;
13469     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
13470 
13471     // Emit warning for one enum constant.
13472     ECDVector::iterator I = Vec->begin();
13473     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
13474       << (*I)->getName() << (*I)->getInitVal().toString(10)
13475       << (*I)->getSourceRange();
13476     ++I;
13477 
13478     // Emit one note for each of the remaining enum constants with
13479     // the same value.
13480     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
13481       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
13482         << (*I)->getName() << (*I)->getInitVal().toString(10)
13483         << (*I)->getSourceRange();
13484     delete Vec;
13485   }
13486 }
13487 
13488 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
13489                          SourceLocation RBraceLoc, Decl *EnumDeclX,
13490                          ArrayRef<Decl *> Elements,
13491                          Scope *S, AttributeList *Attr) {
13492   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
13493   QualType EnumType = Context.getTypeDeclType(Enum);
13494 
13495   if (Attr)
13496     ProcessDeclAttributeList(S, Enum, Attr);
13497 
13498   if (Enum->isDependentType()) {
13499     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13500       EnumConstantDecl *ECD =
13501         cast_or_null<EnumConstantDecl>(Elements[i]);
13502       if (!ECD) continue;
13503 
13504       ECD->setType(EnumType);
13505     }
13506 
13507     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
13508     return;
13509   }
13510 
13511   // TODO: If the result value doesn't fit in an int, it must be a long or long
13512   // long value.  ISO C does not support this, but GCC does as an extension,
13513   // emit a warning.
13514   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
13515   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
13516   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
13517 
13518   // Verify that all the values are okay, compute the size of the values, and
13519   // reverse the list.
13520   unsigned NumNegativeBits = 0;
13521   unsigned NumPositiveBits = 0;
13522 
13523   // Keep track of whether all elements have type int.
13524   bool AllElementsInt = true;
13525 
13526   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13527     EnumConstantDecl *ECD =
13528       cast_or_null<EnumConstantDecl>(Elements[i]);
13529     if (!ECD) continue;  // Already issued a diagnostic.
13530 
13531     const llvm::APSInt &InitVal = ECD->getInitVal();
13532 
13533     // Keep track of the size of positive and negative values.
13534     if (InitVal.isUnsigned() || InitVal.isNonNegative())
13535       NumPositiveBits = std::max(NumPositiveBits,
13536                                  (unsigned)InitVal.getActiveBits());
13537     else
13538       NumNegativeBits = std::max(NumNegativeBits,
13539                                  (unsigned)InitVal.getMinSignedBits());
13540 
13541     // Keep track of whether every enum element has type int (very commmon).
13542     if (AllElementsInt)
13543       AllElementsInt = ECD->getType() == Context.IntTy;
13544   }
13545 
13546   // Figure out the type that should be used for this enum.
13547   QualType BestType;
13548   unsigned BestWidth;
13549 
13550   // C++0x N3000 [conv.prom]p3:
13551   //   An rvalue of an unscoped enumeration type whose underlying
13552   //   type is not fixed can be converted to an rvalue of the first
13553   //   of the following types that can represent all the values of
13554   //   the enumeration: int, unsigned int, long int, unsigned long
13555   //   int, long long int, or unsigned long long int.
13556   // C99 6.4.4.3p2:
13557   //   An identifier declared as an enumeration constant has type int.
13558   // The C99 rule is modified by a gcc extension 
13559   QualType BestPromotionType;
13560 
13561   bool Packed = Enum->hasAttr<PackedAttr>();
13562   // -fshort-enums is the equivalent to specifying the packed attribute on all
13563   // enum definitions.
13564   if (LangOpts.ShortEnums)
13565     Packed = true;
13566 
13567   if (Enum->isFixed()) {
13568     BestType = Enum->getIntegerType();
13569     if (BestType->isPromotableIntegerType())
13570       BestPromotionType = Context.getPromotedIntegerType(BestType);
13571     else
13572       BestPromotionType = BestType;
13573     // We don't need to set BestWidth, because BestType is going to be the type
13574     // of the enumerators, but we do anyway because otherwise some compilers
13575     // warn that it might be used uninitialized.
13576     BestWidth = CharWidth;
13577   }
13578   else if (NumNegativeBits) {
13579     // If there is a negative value, figure out the smallest integer type (of
13580     // int/long/longlong) that fits.
13581     // If it's packed, check also if it fits a char or a short.
13582     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
13583       BestType = Context.SignedCharTy;
13584       BestWidth = CharWidth;
13585     } else if (Packed && NumNegativeBits <= ShortWidth &&
13586                NumPositiveBits < ShortWidth) {
13587       BestType = Context.ShortTy;
13588       BestWidth = ShortWidth;
13589     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
13590       BestType = Context.IntTy;
13591       BestWidth = IntWidth;
13592     } else {
13593       BestWidth = Context.getTargetInfo().getLongWidth();
13594 
13595       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
13596         BestType = Context.LongTy;
13597       } else {
13598         BestWidth = Context.getTargetInfo().getLongLongWidth();
13599 
13600         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
13601           Diag(Enum->getLocation(), diag::ext_enum_too_large);
13602         BestType = Context.LongLongTy;
13603       }
13604     }
13605     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
13606   } else {
13607     // If there is no negative value, figure out the smallest type that fits
13608     // all of the enumerator values.
13609     // If it's packed, check also if it fits a char or a short.
13610     if (Packed && NumPositiveBits <= CharWidth) {
13611       BestType = Context.UnsignedCharTy;
13612       BestPromotionType = Context.IntTy;
13613       BestWidth = CharWidth;
13614     } else if (Packed && NumPositiveBits <= ShortWidth) {
13615       BestType = Context.UnsignedShortTy;
13616       BestPromotionType = Context.IntTy;
13617       BestWidth = ShortWidth;
13618     } else if (NumPositiveBits <= IntWidth) {
13619       BestType = Context.UnsignedIntTy;
13620       BestWidth = IntWidth;
13621       BestPromotionType
13622         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
13623                            ? Context.UnsignedIntTy : Context.IntTy;
13624     } else if (NumPositiveBits <=
13625                (BestWidth = Context.getTargetInfo().getLongWidth())) {
13626       BestType = Context.UnsignedLongTy;
13627       BestPromotionType
13628         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
13629                            ? Context.UnsignedLongTy : Context.LongTy;
13630     } else {
13631       BestWidth = Context.getTargetInfo().getLongLongWidth();
13632       assert(NumPositiveBits <= BestWidth &&
13633              "How could an initializer get larger than ULL?");
13634       BestType = Context.UnsignedLongLongTy;
13635       BestPromotionType
13636         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
13637                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
13638     }
13639   }
13640 
13641   // Loop over all of the enumerator constants, changing their types to match
13642   // the type of the enum if needed.
13643   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13644     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
13645     if (!ECD) continue;  // Already issued a diagnostic.
13646 
13647     // Standard C says the enumerators have int type, but we allow, as an
13648     // extension, the enumerators to be larger than int size.  If each
13649     // enumerator value fits in an int, type it as an int, otherwise type it the
13650     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
13651     // that X has type 'int', not 'unsigned'.
13652 
13653     // Determine whether the value fits into an int.
13654     llvm::APSInt InitVal = ECD->getInitVal();
13655 
13656     // If it fits into an integer type, force it.  Otherwise force it to match
13657     // the enum decl type.
13658     QualType NewTy;
13659     unsigned NewWidth;
13660     bool NewSign;
13661     if (!getLangOpts().CPlusPlus &&
13662         !Enum->isFixed() &&
13663         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
13664       NewTy = Context.IntTy;
13665       NewWidth = IntWidth;
13666       NewSign = true;
13667     } else if (ECD->getType() == BestType) {
13668       // Already the right type!
13669       if (getLangOpts().CPlusPlus)
13670         // C++ [dcl.enum]p4: Following the closing brace of an
13671         // enum-specifier, each enumerator has the type of its
13672         // enumeration.
13673         ECD->setType(EnumType);
13674       continue;
13675     } else {
13676       NewTy = BestType;
13677       NewWidth = BestWidth;
13678       NewSign = BestType->isSignedIntegerOrEnumerationType();
13679     }
13680 
13681     // Adjust the APSInt value.
13682     InitVal = InitVal.extOrTrunc(NewWidth);
13683     InitVal.setIsSigned(NewSign);
13684     ECD->setInitVal(InitVal);
13685 
13686     // Adjust the Expr initializer and type.
13687     if (ECD->getInitExpr() &&
13688         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
13689       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
13690                                                 CK_IntegralCast,
13691                                                 ECD->getInitExpr(),
13692                                                 /*base paths*/ nullptr,
13693                                                 VK_RValue));
13694     if (getLangOpts().CPlusPlus)
13695       // C++ [dcl.enum]p4: Following the closing brace of an
13696       // enum-specifier, each enumerator has the type of its
13697       // enumeration.
13698       ECD->setType(EnumType);
13699     else
13700       ECD->setType(NewTy);
13701   }
13702 
13703   Enum->completeDefinition(BestType, BestPromotionType,
13704                            NumPositiveBits, NumNegativeBits);
13705 
13706   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
13707 
13708   // Now that the enum type is defined, ensure it's not been underaligned.
13709   if (Enum->hasAttrs())
13710     CheckAlignasUnderalignment(Enum);
13711 }
13712 
13713 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
13714                                   SourceLocation StartLoc,
13715                                   SourceLocation EndLoc) {
13716   StringLiteral *AsmString = cast<StringLiteral>(expr);
13717 
13718   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
13719                                                    AsmString, StartLoc,
13720                                                    EndLoc);
13721   CurContext->addDecl(New);
13722   return New;
13723 }
13724 
13725 static void checkModuleImportContext(Sema &S, Module *M,
13726                                      SourceLocation ImportLoc,
13727                                      DeclContext *DC) {
13728   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
13729     switch (LSD->getLanguage()) {
13730     case LinkageSpecDecl::lang_c:
13731       if (!M->IsExternC) {
13732         S.Diag(ImportLoc, diag::err_module_import_in_extern_c)
13733           << M->getFullModuleName();
13734         S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c);
13735         return;
13736       }
13737       break;
13738     case LinkageSpecDecl::lang_cxx:
13739       break;
13740     }
13741     DC = LSD->getParent();
13742   }
13743 
13744   while (isa<LinkageSpecDecl>(DC))
13745     DC = DC->getParent();
13746   if (!isa<TranslationUnitDecl>(DC)) {
13747     S.Diag(ImportLoc, diag::err_module_import_not_at_top_level)
13748       << M->getFullModuleName() << DC;
13749     S.Diag(cast<Decl>(DC)->getLocStart(),
13750            diag::note_module_import_not_at_top_level)
13751       << DC;
13752   }
13753 }
13754 
13755 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 
13756                                    SourceLocation ImportLoc, 
13757                                    ModuleIdPath Path) {
13758   Module *Mod =
13759       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
13760                                    /*IsIncludeDirective=*/false);
13761   if (!Mod)
13762     return true;
13763 
13764   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
13765 
13766   // FIXME: we should support importing a submodule within a different submodule
13767   // of the same top-level module. Until we do, make it an error rather than
13768   // silently ignoring the import.
13769   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
13770     Diag(ImportLoc, diag::err_module_self_import)
13771         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
13772   else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule)
13773     Diag(ImportLoc, diag::err_module_import_in_implementation)
13774         << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule;
13775 
13776   SmallVector<SourceLocation, 2> IdentifierLocs;
13777   Module *ModCheck = Mod;
13778   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
13779     // If we've run out of module parents, just drop the remaining identifiers.
13780     // We need the length to be consistent.
13781     if (!ModCheck)
13782       break;
13783     ModCheck = ModCheck->Parent;
13784     
13785     IdentifierLocs.push_back(Path[I].second);
13786   }
13787 
13788   ImportDecl *Import = ImportDecl::Create(Context, 
13789                                           Context.getTranslationUnitDecl(),
13790                                           AtLoc.isValid()? AtLoc : ImportLoc, 
13791                                           Mod, IdentifierLocs);
13792   Context.getTranslationUnitDecl()->addDecl(Import);
13793   return Import;
13794 }
13795 
13796 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
13797   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
13798 
13799   // FIXME: Should we synthesize an ImportDecl here?
13800   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
13801                                       /*Complain=*/true);
13802 }
13803 
13804 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
13805                                                       Module *Mod) {
13806   // Bail if we're not allowed to implicitly import a module here.
13807   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
13808     return;
13809 
13810   // Create the implicit import declaration.
13811   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
13812   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
13813                                                    Loc, Mod, Loc);
13814   TU->addDecl(ImportD);
13815   Consumer.HandleImplicitImportDecl(ImportD);
13816 
13817   // Make the module visible.
13818   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
13819                                       /*Complain=*/false);
13820 }
13821 
13822 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
13823                                       IdentifierInfo* AliasName,
13824                                       SourceLocation PragmaLoc,
13825                                       SourceLocation NameLoc,
13826                                       SourceLocation AliasNameLoc) {
13827   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
13828                                     LookupOrdinaryName);
13829   AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context,
13830                                                     AliasName->getName(), 0);
13831 
13832   if (PrevDecl) 
13833     PrevDecl->addAttr(Attr);
13834   else 
13835     (void)ExtnameUndeclaredIdentifiers.insert(
13836       std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
13837 }
13838 
13839 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
13840                              SourceLocation PragmaLoc,
13841                              SourceLocation NameLoc) {
13842   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
13843 
13844   if (PrevDecl) {
13845     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
13846   } else {
13847     (void)WeakUndeclaredIdentifiers.insert(
13848       std::pair<IdentifierInfo*,WeakInfo>
13849         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
13850   }
13851 }
13852 
13853 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
13854                                 IdentifierInfo* AliasName,
13855                                 SourceLocation PragmaLoc,
13856                                 SourceLocation NameLoc,
13857                                 SourceLocation AliasNameLoc) {
13858   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
13859                                     LookupOrdinaryName);
13860   WeakInfo W = WeakInfo(Name, NameLoc);
13861 
13862   if (PrevDecl) {
13863     if (!PrevDecl->hasAttr<AliasAttr>())
13864       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
13865         DeclApplyPragmaWeak(TUScope, ND, W);
13866   } else {
13867     (void)WeakUndeclaredIdentifiers.insert(
13868       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
13869   }
13870 }
13871 
13872 Decl *Sema::getObjCDeclContext() const {
13873   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
13874 }
13875 
13876 AvailabilityResult Sema::getCurContextAvailability() const {
13877   const Decl *D = cast<Decl>(getCurObjCLexicalContext());
13878   // If we are within an Objective-C method, we should consult
13879   // both the availability of the method as well as the
13880   // enclosing class.  If the class is (say) deprecated,
13881   // the entire method is considered deprecated from the
13882   // purpose of checking if the current context is deprecated.
13883   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
13884     AvailabilityResult R = MD->getAvailability();
13885     if (R != AR_Available)
13886       return R;
13887     D = MD->getClassInterface();
13888   }
13889   // If we are within an Objective-c @implementation, it
13890   // gets the same availability context as the @interface.
13891   else if (const ObjCImplementationDecl *ID =
13892             dyn_cast<ObjCImplementationDecl>(D)) {
13893     D = ID->getClassInterface();
13894   }
13895   // Recover from user error.
13896   return D ? D->getAvailability() : AR_Available;
13897 }