1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/CommentDiagnostic.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Parse/ParseDiagnostic.h"
37 #include "clang/Sema/CXXFieldCollector.h"
38 #include "clang/Sema/DeclSpec.h"
39 #include "clang/Sema/DelayedDiagnostic.h"
40 #include "clang/Sema/Initialization.h"
41 #include "clang/Sema/Lookup.h"
42 #include "clang/Sema/ParsedTemplate.h"
43 #include "clang/Sema/Scope.h"
44 #include "clang/Sema/ScopeInfo.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/Triple.h"
48 #include <algorithm>
49 #include <cstring>
50 #include <functional>
51 using namespace clang;
52 using namespace sema;
53 
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59 
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62 
63 namespace {
64 
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66  public:
67   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
68                        bool AllowTemplates=false)
69       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70         AllowClassTemplates(AllowTemplates) {
71     WantExpressionKeywords = false;
72     WantCXXNamedCasts = false;
73     WantRemainingKeywords = false;
74   }
75 
76   bool ValidateCandidate(const TypoCorrection &candidate) override {
77     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
78       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
79       bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
80       return (IsType || AllowedTemplate) &&
81              (AllowInvalidDecl || !ND->isInvalidDecl());
82     }
83     return !WantClassName && candidate.isKeyword();
84   }
85 
86  private:
87   bool AllowInvalidDecl;
88   bool WantClassName;
89   bool AllowClassTemplates;
90 };
91 
92 }
93 
94 /// \brief Determine whether the token kind starts a simple-type-specifier.
95 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
96   switch (Kind) {
97   // FIXME: Take into account the current language when deciding whether a
98   // token kind is a valid type specifier
99   case tok::kw_short:
100   case tok::kw_long:
101   case tok::kw___int64:
102   case tok::kw___int128:
103   case tok::kw_signed:
104   case tok::kw_unsigned:
105   case tok::kw_void:
106   case tok::kw_char:
107   case tok::kw_int:
108   case tok::kw_half:
109   case tok::kw_float:
110   case tok::kw_double:
111   case tok::kw_wchar_t:
112   case tok::kw_bool:
113   case tok::kw___underlying_type:
114     return true;
115 
116   case tok::annot_typename:
117   case tok::kw_char16_t:
118   case tok::kw_char32_t:
119   case tok::kw_typeof:
120   case tok::annot_decltype:
121   case tok::kw_decltype:
122     return getLangOpts().CPlusPlus;
123 
124   default:
125     break;
126   }
127 
128   return false;
129 }
130 
131 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
132                                                       const IdentifierInfo &II,
133                                                       SourceLocation NameLoc) {
134   // Find the first parent class template context, if any.
135   // FIXME: Perform the lookup in all enclosing class templates.
136   const CXXRecordDecl *RD = nullptr;
137   for (DeclContext *DC = S.CurContext; DC; DC = DC->getParent()) {
138     RD = dyn_cast<CXXRecordDecl>(DC);
139     if (RD && RD->getDescribedClassTemplate())
140       break;
141   }
142   if (!RD)
143     return ParsedType();
144 
145   // Look for type decls in dependent base classes that have known primary
146   // templates.
147   bool FoundTypeDecl = false;
148   for (const auto &Base : RD->bases()) {
149     auto *TST = Base.getType()->getAs<TemplateSpecializationType>();
150     if (!TST || !TST->isDependentType())
151       continue;
152     auto *TD = TST->getTemplateName().getAsTemplateDecl();
153     if (!TD)
154       continue;
155     auto *BasePrimaryTemplate =
156         dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
157     if (!BasePrimaryTemplate)
158       continue;
159     // FIXME: Allow lookup into non-dependent bases of dependent bases, possibly
160     // by calling or integrating with the main LookupQualifiedName mechanism.
161     for (NamedDecl *ND : BasePrimaryTemplate->lookup(&II)) {
162       if (FoundTypeDecl)
163         return ParsedType();
164       FoundTypeDecl = isa<TypeDecl>(ND);
165       if (!FoundTypeDecl)
166         return ParsedType();
167     }
168   }
169   if (!FoundTypeDecl)
170     return ParsedType();
171 
172   // We found some types in dependent base classes.  Recover as if the user
173   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
174   // lookup during template instantiation.
175   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
176 
177   ASTContext &Context = S.Context;
178   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
179                                           cast<Type>(Context.getRecordType(RD)));
180   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
181 
182   CXXScopeSpec SS;
183   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
184 
185   TypeLocBuilder Builder;
186   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
187   DepTL.setNameLoc(NameLoc);
188   DepTL.setElaboratedKeywordLoc(SourceLocation());
189   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
190   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
191 }
192 
193 /// \brief If the identifier refers to a type name within this scope,
194 /// return the declaration of that type.
195 ///
196 /// This routine performs ordinary name lookup of the identifier II
197 /// within the given scope, with optional C++ scope specifier SS, to
198 /// determine whether the name refers to a type. If so, returns an
199 /// opaque pointer (actually a QualType) corresponding to that
200 /// type. Otherwise, returns NULL.
201 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
202                              Scope *S, CXXScopeSpec *SS,
203                              bool isClassName, bool HasTrailingDot,
204                              ParsedType ObjectTypePtr,
205                              bool IsCtorOrDtorName,
206                              bool WantNontrivialTypeSourceInfo,
207                              IdentifierInfo **CorrectedII) {
208   // Determine where we will perform name lookup.
209   DeclContext *LookupCtx = nullptr;
210   if (ObjectTypePtr) {
211     QualType ObjectType = ObjectTypePtr.get();
212     if (ObjectType->isRecordType())
213       LookupCtx = computeDeclContext(ObjectType);
214   } else if (SS && SS->isNotEmpty()) {
215     LookupCtx = computeDeclContext(*SS, false);
216 
217     if (!LookupCtx) {
218       if (isDependentScopeSpecifier(*SS)) {
219         // C++ [temp.res]p3:
220         //   A qualified-id that refers to a type and in which the
221         //   nested-name-specifier depends on a template-parameter (14.6.2)
222         //   shall be prefixed by the keyword typename to indicate that the
223         //   qualified-id denotes a type, forming an
224         //   elaborated-type-specifier (7.1.5.3).
225         //
226         // We therefore do not perform any name lookup if the result would
227         // refer to a member of an unknown specialization.
228         if (!isClassName && !IsCtorOrDtorName)
229           return ParsedType();
230 
231         // We know from the grammar that this name refers to a type,
232         // so build a dependent node to describe the type.
233         if (WantNontrivialTypeSourceInfo)
234           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
235 
236         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
237         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
238                                        II, NameLoc);
239         return ParsedType::make(T);
240       }
241 
242       return ParsedType();
243     }
244 
245     if (!LookupCtx->isDependentContext() &&
246         RequireCompleteDeclContext(*SS, LookupCtx))
247       return ParsedType();
248   }
249 
250   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
251   // lookup for class-names.
252   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
253                                       LookupOrdinaryName;
254   LookupResult Result(*this, &II, NameLoc, Kind);
255   if (LookupCtx) {
256     // Perform "qualified" name lookup into the declaration context we
257     // computed, which is either the type of the base of a member access
258     // expression or the declaration context associated with a prior
259     // nested-name-specifier.
260     LookupQualifiedName(Result, LookupCtx);
261 
262     if (ObjectTypePtr && Result.empty()) {
263       // C++ [basic.lookup.classref]p3:
264       //   If the unqualified-id is ~type-name, the type-name is looked up
265       //   in the context of the entire postfix-expression. If the type T of
266       //   the object expression is of a class type C, the type-name is also
267       //   looked up in the scope of class C. At least one of the lookups shall
268       //   find a name that refers to (possibly cv-qualified) T.
269       LookupName(Result, S);
270     }
271   } else {
272     // Perform unqualified name lookup.
273     LookupName(Result, S);
274 
275     // For unqualified lookup in a class template in MSVC mode, look into
276     // dependent base classes where the primary class template is known.
277     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
278       if (ParsedType TypeInBase =
279               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
280         return TypeInBase;
281     }
282   }
283 
284   NamedDecl *IIDecl = nullptr;
285   switch (Result.getResultKind()) {
286   case LookupResult::NotFound:
287   case LookupResult::NotFoundInCurrentInstantiation:
288     if (CorrectedII) {
289       TypeNameValidatorCCC Validator(true, isClassName);
290       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
291                                               Kind, S, SS, Validator,
292                                               CTK_ErrorRecovery);
293       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
294       TemplateTy Template;
295       bool MemberOfUnknownSpecialization;
296       UnqualifiedId TemplateName;
297       TemplateName.setIdentifier(NewII, NameLoc);
298       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
299       CXXScopeSpec NewSS, *NewSSPtr = SS;
300       if (SS && NNS) {
301         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
302         NewSSPtr = &NewSS;
303       }
304       if (Correction && (NNS || NewII != &II) &&
305           // Ignore a correction to a template type as the to-be-corrected
306           // identifier is not a template (typo correction for template names
307           // is handled elsewhere).
308           !(getLangOpts().CPlusPlus && NewSSPtr &&
309             isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
310                            false, Template, MemberOfUnknownSpecialization))) {
311         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
312                                     isClassName, HasTrailingDot, ObjectTypePtr,
313                                     IsCtorOrDtorName,
314                                     WantNontrivialTypeSourceInfo);
315         if (Ty) {
316           diagnoseTypo(Correction,
317                        PDiag(diag::err_unknown_type_or_class_name_suggest)
318                          << Result.getLookupName() << isClassName);
319           if (SS && NNS)
320             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
321           *CorrectedII = NewII;
322           return Ty;
323         }
324       }
325     }
326     // If typo correction failed or was not performed, fall through
327   case LookupResult::FoundOverloaded:
328   case LookupResult::FoundUnresolvedValue:
329     Result.suppressDiagnostics();
330     return ParsedType();
331 
332   case LookupResult::Ambiguous:
333     // Recover from type-hiding ambiguities by hiding the type.  We'll
334     // do the lookup again when looking for an object, and we can
335     // diagnose the error then.  If we don't do this, then the error
336     // about hiding the type will be immediately followed by an error
337     // that only makes sense if the identifier was treated like a type.
338     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
339       Result.suppressDiagnostics();
340       return ParsedType();
341     }
342 
343     // Look to see if we have a type anywhere in the list of results.
344     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
345          Res != ResEnd; ++Res) {
346       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
347         if (!IIDecl ||
348             (*Res)->getLocation().getRawEncoding() <
349               IIDecl->getLocation().getRawEncoding())
350           IIDecl = *Res;
351       }
352     }
353 
354     if (!IIDecl) {
355       // None of the entities we found is a type, so there is no way
356       // to even assume that the result is a type. In this case, don't
357       // complain about the ambiguity. The parser will either try to
358       // perform this lookup again (e.g., as an object name), which
359       // will produce the ambiguity, or will complain that it expected
360       // a type name.
361       Result.suppressDiagnostics();
362       return ParsedType();
363     }
364 
365     // We found a type within the ambiguous lookup; diagnose the
366     // ambiguity and then return that type. This might be the right
367     // answer, or it might not be, but it suppresses any attempt to
368     // perform the name lookup again.
369     break;
370 
371   case LookupResult::Found:
372     IIDecl = Result.getFoundDecl();
373     break;
374   }
375 
376   assert(IIDecl && "Didn't find decl");
377 
378   QualType T;
379   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
380     DiagnoseUseOfDecl(IIDecl, NameLoc);
381 
382     T = Context.getTypeDeclType(TD);
383     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
384 
385     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
386     // constructor or destructor name (in such a case, the scope specifier
387     // will be attached to the enclosing Expr or Decl node).
388     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
389       if (WantNontrivialTypeSourceInfo) {
390         // Construct a type with type-source information.
391         TypeLocBuilder Builder;
392         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
393 
394         T = getElaboratedType(ETK_None, *SS, T);
395         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
396         ElabTL.setElaboratedKeywordLoc(SourceLocation());
397         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
398         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
399       } else {
400         T = getElaboratedType(ETK_None, *SS, T);
401       }
402     }
403   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
404     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
405     if (!HasTrailingDot)
406       T = Context.getObjCInterfaceType(IDecl);
407   }
408 
409   if (T.isNull()) {
410     // If it's not plausibly a type, suppress diagnostics.
411     Result.suppressDiagnostics();
412     return ParsedType();
413   }
414   return ParsedType::make(T);
415 }
416 
417 // Builds a fake NNS for the given decl context.
418 static NestedNameSpecifier *
419 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
420   for (;; DC = DC->getLookupParent()) {
421     DC = DC->getPrimaryContext();
422     auto *ND = dyn_cast<NamespaceDecl>(DC);
423     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
424       return NestedNameSpecifier::Create(Context, nullptr, ND);
425     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
426       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
427                                          RD->getTypeForDecl());
428     else if (isa<TranslationUnitDecl>(DC))
429       return NestedNameSpecifier::GlobalSpecifier(Context);
430   }
431   llvm_unreachable("something isn't in TU scope?");
432 }
433 
434 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
435                                                 SourceLocation NameLoc) {
436   // Accepting an undeclared identifier as a default argument for a template
437   // type parameter is a Microsoft extension.
438   Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
439 
440   // Build a fake DependentNameType that will perform lookup into CurContext at
441   // instantiation time.  The name specifier isn't dependent, so template
442   // instantiation won't transform it.  It will retry the lookup, however.
443   NestedNameSpecifier *NNS =
444       synthesizeCurrentNestedNameSpecifier(Context, CurContext);
445   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
446 
447   // Build type location information.  We synthesized the qualifier, so we have
448   // to build a fake NestedNameSpecifierLoc.
449   NestedNameSpecifierLocBuilder NNSLocBuilder;
450   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
451   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
452 
453   TypeLocBuilder Builder;
454   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
455   DepTL.setNameLoc(NameLoc);
456   DepTL.setElaboratedKeywordLoc(SourceLocation());
457   DepTL.setQualifierLoc(QualifierLoc);
458   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
459 }
460 
461 /// isTagName() - This method is called *for error recovery purposes only*
462 /// to determine if the specified name is a valid tag name ("struct foo").  If
463 /// so, this returns the TST for the tag corresponding to it (TST_enum,
464 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
465 /// cases in C where the user forgot to specify the tag.
466 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
467   // Do a tag name lookup in this scope.
468   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
469   LookupName(R, S, false);
470   R.suppressDiagnostics();
471   if (R.getResultKind() == LookupResult::Found)
472     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
473       switch (TD->getTagKind()) {
474       case TTK_Struct: return DeclSpec::TST_struct;
475       case TTK_Interface: return DeclSpec::TST_interface;
476       case TTK_Union:  return DeclSpec::TST_union;
477       case TTK_Class:  return DeclSpec::TST_class;
478       case TTK_Enum:   return DeclSpec::TST_enum;
479       }
480     }
481 
482   return DeclSpec::TST_unspecified;
483 }
484 
485 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
486 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
487 /// then downgrade the missing typename error to a warning.
488 /// This is needed for MSVC compatibility; Example:
489 /// @code
490 /// template<class T> class A {
491 /// public:
492 ///   typedef int TYPE;
493 /// };
494 /// template<class T> class B : public A<T> {
495 /// public:
496 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
497 /// };
498 /// @endcode
499 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
500   if (CurContext->isRecord()) {
501     const Type *Ty = SS->getScopeRep()->getAsType();
502 
503     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
504     for (const auto &Base : RD->bases())
505       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
506         return true;
507     return S->isFunctionPrototypeScope();
508   }
509   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
510 }
511 
512 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
513                                    SourceLocation IILoc,
514                                    Scope *S,
515                                    CXXScopeSpec *SS,
516                                    ParsedType &SuggestedType,
517                                    bool AllowClassTemplates) {
518   // We don't have anything to suggest (yet).
519   SuggestedType = ParsedType();
520 
521   // There may have been a typo in the name of the type. Look up typo
522   // results, in case we have something that we can suggest.
523   TypeNameValidatorCCC Validator(false, false, AllowClassTemplates);
524   if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
525                                              LookupOrdinaryName, S, SS,
526                                              Validator, CTK_ErrorRecovery)) {
527     if (Corrected.isKeyword()) {
528       // We corrected to a keyword.
529       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
530       II = Corrected.getCorrectionAsIdentifierInfo();
531     } else {
532       // We found a similarly-named type or interface; suggest that.
533       if (!SS || !SS->isSet()) {
534         diagnoseTypo(Corrected,
535                      PDiag(diag::err_unknown_typename_suggest) << II);
536       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
537         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
538         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
539                                 II->getName().equals(CorrectedStr);
540         diagnoseTypo(Corrected,
541                      PDiag(diag::err_unknown_nested_typename_suggest)
542                        << II << DC << DroppedSpecifier << SS->getRange());
543       } else {
544         llvm_unreachable("could not have corrected a typo here");
545       }
546 
547       CXXScopeSpec tmpSS;
548       if (Corrected.getCorrectionSpecifier())
549         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
550                           SourceRange(IILoc));
551       SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
552                                   IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
553                                   false, ParsedType(),
554                                   /*IsCtorOrDtorName=*/false,
555                                   /*NonTrivialTypeSourceInfo=*/true);
556     }
557     return;
558   }
559 
560   if (getLangOpts().CPlusPlus) {
561     // See if II is a class template that the user forgot to pass arguments to.
562     UnqualifiedId Name;
563     Name.setIdentifier(II, IILoc);
564     CXXScopeSpec EmptySS;
565     TemplateTy TemplateResult;
566     bool MemberOfUnknownSpecialization;
567     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
568                        Name, ParsedType(), true, TemplateResult,
569                        MemberOfUnknownSpecialization) == TNK_Type_template) {
570       TemplateName TplName = TemplateResult.get();
571       Diag(IILoc, diag::err_template_missing_args) << TplName;
572       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
573         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
574           << TplDecl->getTemplateParameters()->getSourceRange();
575       }
576       return;
577     }
578   }
579 
580   // FIXME: Should we move the logic that tries to recover from a missing tag
581   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
582 
583   if (!SS || (!SS->isSet() && !SS->isInvalid()))
584     Diag(IILoc, diag::err_unknown_typename) << II;
585   else if (DeclContext *DC = computeDeclContext(*SS, false))
586     Diag(IILoc, diag::err_typename_nested_not_found)
587       << II << DC << SS->getRange();
588   else if (isDependentScopeSpecifier(*SS)) {
589     unsigned DiagID = diag::err_typename_missing;
590     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
591       DiagID = diag::ext_typename_missing;
592 
593     Diag(SS->getRange().getBegin(), DiagID)
594       << SS->getScopeRep() << II->getName()
595       << SourceRange(SS->getRange().getBegin(), IILoc)
596       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
597     SuggestedType = ActOnTypenameType(S, SourceLocation(),
598                                       *SS, *II, IILoc).get();
599   } else {
600     assert(SS && SS->isInvalid() &&
601            "Invalid scope specifier has already been diagnosed");
602   }
603 }
604 
605 /// \brief Determine whether the given result set contains either a type name
606 /// or
607 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
608   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
609                        NextToken.is(tok::less);
610 
611   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
612     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
613       return true;
614 
615     if (CheckTemplate && isa<TemplateDecl>(*I))
616       return true;
617   }
618 
619   return false;
620 }
621 
622 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
623                                     Scope *S, CXXScopeSpec &SS,
624                                     IdentifierInfo *&Name,
625                                     SourceLocation NameLoc) {
626   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
627   SemaRef.LookupParsedName(R, S, &SS);
628   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
629     StringRef FixItTagName;
630     switch (Tag->getTagKind()) {
631       case TTK_Class:
632         FixItTagName = "class ";
633         break;
634 
635       case TTK_Enum:
636         FixItTagName = "enum ";
637         break;
638 
639       case TTK_Struct:
640         FixItTagName = "struct ";
641         break;
642 
643       case TTK_Interface:
644         FixItTagName = "__interface ";
645         break;
646 
647       case TTK_Union:
648         FixItTagName = "union ";
649         break;
650     }
651 
652     StringRef TagName = FixItTagName.drop_back();
653     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
654       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
655       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
656 
657     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
658          I != IEnd; ++I)
659       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
660         << Name << TagName;
661 
662     // Replace lookup results with just the tag decl.
663     Result.clear(Sema::LookupTagName);
664     SemaRef.LookupParsedName(Result, S, &SS);
665     return true;
666   }
667 
668   return false;
669 }
670 
671 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
672 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
673                                   QualType T, SourceLocation NameLoc) {
674   ASTContext &Context = S.Context;
675 
676   TypeLocBuilder Builder;
677   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
678 
679   T = S.getElaboratedType(ETK_None, SS, T);
680   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
681   ElabTL.setElaboratedKeywordLoc(SourceLocation());
682   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
683   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
684 }
685 
686 Sema::NameClassification Sema::ClassifyName(Scope *S,
687                                             CXXScopeSpec &SS,
688                                             IdentifierInfo *&Name,
689                                             SourceLocation NameLoc,
690                                             const Token &NextToken,
691                                             bool IsAddressOfOperand,
692                                             CorrectionCandidateCallback *CCC) {
693   DeclarationNameInfo NameInfo(Name, NameLoc);
694   ObjCMethodDecl *CurMethod = getCurMethodDecl();
695 
696   if (NextToken.is(tok::coloncolon)) {
697     BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
698                                 QualType(), false, SS, nullptr, false);
699   }
700 
701   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
702   LookupParsedName(Result, S, &SS, !CurMethod);
703 
704   // For unqualified lookup in a class template in MSVC mode, look into
705   // dependent base classes where the primary class template is known.
706   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
707     if (ParsedType TypeInBase =
708             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
709       return TypeInBase;
710   }
711 
712   // Perform lookup for Objective-C instance variables (including automatically
713   // synthesized instance variables), if we're in an Objective-C method.
714   // FIXME: This lookup really, really needs to be folded in to the normal
715   // unqualified lookup mechanism.
716   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
717     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
718     if (E.get() || E.isInvalid())
719       return E;
720   }
721 
722   bool SecondTry = false;
723   bool IsFilteredTemplateName = false;
724 
725 Corrected:
726   switch (Result.getResultKind()) {
727   case LookupResult::NotFound:
728     // If an unqualified-id is followed by a '(', then we have a function
729     // call.
730     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
731       // In C++, this is an ADL-only call.
732       // FIXME: Reference?
733       if (getLangOpts().CPlusPlus)
734         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
735 
736       // C90 6.3.2.2:
737       //   If the expression that precedes the parenthesized argument list in a
738       //   function call consists solely of an identifier, and if no
739       //   declaration is visible for this identifier, the identifier is
740       //   implicitly declared exactly as if, in the innermost block containing
741       //   the function call, the declaration
742       //
743       //     extern int identifier ();
744       //
745       //   appeared.
746       //
747       // We also allow this in C99 as an extension.
748       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
749         Result.addDecl(D);
750         Result.resolveKind();
751         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
752       }
753     }
754 
755     // In C, we first see whether there is a tag type by the same name, in
756     // which case it's likely that the user just forget to write "enum",
757     // "struct", or "union".
758     if (!getLangOpts().CPlusPlus && !SecondTry &&
759         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
760       break;
761     }
762 
763     // Perform typo correction to determine if there is another name that is
764     // close to this name.
765     if (!SecondTry && CCC) {
766       SecondTry = true;
767       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
768                                                  Result.getLookupKind(), S,
769                                                  &SS, *CCC,
770                                                  CTK_ErrorRecovery)) {
771         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
772         unsigned QualifiedDiag = diag::err_no_member_suggest;
773 
774         NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
775         NamedDecl *UnderlyingFirstDecl
776           = FirstDecl? FirstDecl->getUnderlyingDecl() : nullptr;
777         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
778             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
779           UnqualifiedDiag = diag::err_no_template_suggest;
780           QualifiedDiag = diag::err_no_member_template_suggest;
781         } else if (UnderlyingFirstDecl &&
782                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
783                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
784                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
785           UnqualifiedDiag = diag::err_unknown_typename_suggest;
786           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
787         }
788 
789         if (SS.isEmpty()) {
790           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
791         } else {// FIXME: is this even reachable? Test it.
792           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
793           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
794                                   Name->getName().equals(CorrectedStr);
795           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
796                                     << Name << computeDeclContext(SS, false)
797                                     << DroppedSpecifier << SS.getRange());
798         }
799 
800         // Update the name, so that the caller has the new name.
801         Name = Corrected.getCorrectionAsIdentifierInfo();
802 
803         // Typo correction corrected to a keyword.
804         if (Corrected.isKeyword())
805           return Name;
806 
807         // Also update the LookupResult...
808         // FIXME: This should probably go away at some point
809         Result.clear();
810         Result.setLookupName(Corrected.getCorrection());
811         if (FirstDecl)
812           Result.addDecl(FirstDecl);
813 
814         // If we found an Objective-C instance variable, let
815         // LookupInObjCMethod build the appropriate expression to
816         // reference the ivar.
817         // FIXME: This is a gross hack.
818         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
819           Result.clear();
820           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
821           return E;
822         }
823 
824         goto Corrected;
825       }
826     }
827 
828     // We failed to correct; just fall through and let the parser deal with it.
829     Result.suppressDiagnostics();
830     return NameClassification::Unknown();
831 
832   case LookupResult::NotFoundInCurrentInstantiation: {
833     // We performed name lookup into the current instantiation, and there were
834     // dependent bases, so we treat this result the same way as any other
835     // dependent nested-name-specifier.
836 
837     // C++ [temp.res]p2:
838     //   A name used in a template declaration or definition and that is
839     //   dependent on a template-parameter is assumed not to name a type
840     //   unless the applicable name lookup finds a type name or the name is
841     //   qualified by the keyword typename.
842     //
843     // FIXME: If the next token is '<', we might want to ask the parser to
844     // perform some heroics to see if we actually have a
845     // template-argument-list, which would indicate a missing 'template'
846     // keyword here.
847     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
848                                       NameInfo, IsAddressOfOperand,
849                                       /*TemplateArgs=*/nullptr);
850   }
851 
852   case LookupResult::Found:
853   case LookupResult::FoundOverloaded:
854   case LookupResult::FoundUnresolvedValue:
855     break;
856 
857   case LookupResult::Ambiguous:
858     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
859         hasAnyAcceptableTemplateNames(Result)) {
860       // C++ [temp.local]p3:
861       //   A lookup that finds an injected-class-name (10.2) can result in an
862       //   ambiguity in certain cases (for example, if it is found in more than
863       //   one base class). If all of the injected-class-names that are found
864       //   refer to specializations of the same class template, and if the name
865       //   is followed by a template-argument-list, the reference refers to the
866       //   class template itself and not a specialization thereof, and is not
867       //   ambiguous.
868       //
869       // This filtering can make an ambiguous result into an unambiguous one,
870       // so try again after filtering out template names.
871       FilterAcceptableTemplateNames(Result);
872       if (!Result.isAmbiguous()) {
873         IsFilteredTemplateName = true;
874         break;
875       }
876     }
877 
878     // Diagnose the ambiguity and return an error.
879     return NameClassification::Error();
880   }
881 
882   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
883       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
884     // C++ [temp.names]p3:
885     //   After name lookup (3.4) finds that a name is a template-name or that
886     //   an operator-function-id or a literal- operator-id refers to a set of
887     //   overloaded functions any member of which is a function template if
888     //   this is followed by a <, the < is always taken as the delimiter of a
889     //   template-argument-list and never as the less-than operator.
890     if (!IsFilteredTemplateName)
891       FilterAcceptableTemplateNames(Result);
892 
893     if (!Result.empty()) {
894       bool IsFunctionTemplate;
895       bool IsVarTemplate;
896       TemplateName Template;
897       if (Result.end() - Result.begin() > 1) {
898         IsFunctionTemplate = true;
899         Template = Context.getOverloadedTemplateName(Result.begin(),
900                                                      Result.end());
901       } else {
902         TemplateDecl *TD
903           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
904         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
905         IsVarTemplate = isa<VarTemplateDecl>(TD);
906 
907         if (SS.isSet() && !SS.isInvalid())
908           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
909                                                     /*TemplateKeyword=*/false,
910                                                       TD);
911         else
912           Template = TemplateName(TD);
913       }
914 
915       if (IsFunctionTemplate) {
916         // Function templates always go through overload resolution, at which
917         // point we'll perform the various checks (e.g., accessibility) we need
918         // to based on which function we selected.
919         Result.suppressDiagnostics();
920 
921         return NameClassification::FunctionTemplate(Template);
922       }
923 
924       return IsVarTemplate ? NameClassification::VarTemplate(Template)
925                            : NameClassification::TypeTemplate(Template);
926     }
927   }
928 
929   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
930   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
931     DiagnoseUseOfDecl(Type, NameLoc);
932     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
933     QualType T = Context.getTypeDeclType(Type);
934     if (SS.isNotEmpty())
935       return buildNestedType(*this, SS, T, NameLoc);
936     return ParsedType::make(T);
937   }
938 
939   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
940   if (!Class) {
941     // FIXME: It's unfortunate that we don't have a Type node for handling this.
942     if (ObjCCompatibleAliasDecl *Alias =
943             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
944       Class = Alias->getClassInterface();
945   }
946 
947   if (Class) {
948     DiagnoseUseOfDecl(Class, NameLoc);
949 
950     if (NextToken.is(tok::period)) {
951       // Interface. <something> is parsed as a property reference expression.
952       // Just return "unknown" as a fall-through for now.
953       Result.suppressDiagnostics();
954       return NameClassification::Unknown();
955     }
956 
957     QualType T = Context.getObjCInterfaceType(Class);
958     return ParsedType::make(T);
959   }
960 
961   // We can have a type template here if we're classifying a template argument.
962   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
963     return NameClassification::TypeTemplate(
964         TemplateName(cast<TemplateDecl>(FirstDecl)));
965 
966   // Check for a tag type hidden by a non-type decl in a few cases where it
967   // seems likely a type is wanted instead of the non-type that was found.
968   bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
969   if ((NextToken.is(tok::identifier) ||
970        (NextIsOp &&
971         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
972       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
973     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
974     DiagnoseUseOfDecl(Type, NameLoc);
975     QualType T = Context.getTypeDeclType(Type);
976     if (SS.isNotEmpty())
977       return buildNestedType(*this, SS, T, NameLoc);
978     return ParsedType::make(T);
979   }
980 
981   if (FirstDecl->isCXXClassMember())
982     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
983                                            nullptr);
984 
985   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
986   return BuildDeclarationNameExpr(SS, Result, ADL);
987 }
988 
989 // Determines the context to return to after temporarily entering a
990 // context.  This depends in an unnecessarily complicated way on the
991 // exact ordering of callbacks from the parser.
992 DeclContext *Sema::getContainingDC(DeclContext *DC) {
993 
994   // Functions defined inline within classes aren't parsed until we've
995   // finished parsing the top-level class, so the top-level class is
996   // the context we'll need to return to.
997   // A Lambda call operator whose parent is a class must not be treated
998   // as an inline member function.  A Lambda can be used legally
999   // either as an in-class member initializer or a default argument.  These
1000   // are parsed once the class has been marked complete and so the containing
1001   // context would be the nested class (when the lambda is defined in one);
1002   // If the class is not complete, then the lambda is being used in an
1003   // ill-formed fashion (such as to specify the width of a bit-field, or
1004   // in an array-bound) - in which case we still want to return the
1005   // lexically containing DC (which could be a nested class).
1006   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1007     DC = DC->getLexicalParent();
1008 
1009     // A function not defined within a class will always return to its
1010     // lexical context.
1011     if (!isa<CXXRecordDecl>(DC))
1012       return DC;
1013 
1014     // A C++ inline method/friend is parsed *after* the topmost class
1015     // it was declared in is fully parsed ("complete");  the topmost
1016     // class is the context we need to return to.
1017     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1018       DC = RD;
1019 
1020     // Return the declaration context of the topmost class the inline method is
1021     // declared in.
1022     return DC;
1023   }
1024 
1025   return DC->getLexicalParent();
1026 }
1027 
1028 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1029   assert(getContainingDC(DC) == CurContext &&
1030       "The next DeclContext should be lexically contained in the current one.");
1031   CurContext = DC;
1032   S->setEntity(DC);
1033 }
1034 
1035 void Sema::PopDeclContext() {
1036   assert(CurContext && "DeclContext imbalance!");
1037 
1038   CurContext = getContainingDC(CurContext);
1039   assert(CurContext && "Popped translation unit!");
1040 }
1041 
1042 /// EnterDeclaratorContext - Used when we must lookup names in the context
1043 /// of a declarator's nested name specifier.
1044 ///
1045 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1046   // C++0x [basic.lookup.unqual]p13:
1047   //   A name used in the definition of a static data member of class
1048   //   X (after the qualified-id of the static member) is looked up as
1049   //   if the name was used in a member function of X.
1050   // C++0x [basic.lookup.unqual]p14:
1051   //   If a variable member of a namespace is defined outside of the
1052   //   scope of its namespace then any name used in the definition of
1053   //   the variable member (after the declarator-id) is looked up as
1054   //   if the definition of the variable member occurred in its
1055   //   namespace.
1056   // Both of these imply that we should push a scope whose context
1057   // is the semantic context of the declaration.  We can't use
1058   // PushDeclContext here because that context is not necessarily
1059   // lexically contained in the current context.  Fortunately,
1060   // the containing scope should have the appropriate information.
1061 
1062   assert(!S->getEntity() && "scope already has entity");
1063 
1064 #ifndef NDEBUG
1065   Scope *Ancestor = S->getParent();
1066   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1067   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1068 #endif
1069 
1070   CurContext = DC;
1071   S->setEntity(DC);
1072 }
1073 
1074 void Sema::ExitDeclaratorContext(Scope *S) {
1075   assert(S->getEntity() == CurContext && "Context imbalance!");
1076 
1077   // Switch back to the lexical context.  The safety of this is
1078   // enforced by an assert in EnterDeclaratorContext.
1079   Scope *Ancestor = S->getParent();
1080   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1081   CurContext = Ancestor->getEntity();
1082 
1083   // We don't need to do anything with the scope, which is going to
1084   // disappear.
1085 }
1086 
1087 
1088 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1089   // We assume that the caller has already called
1090   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1091   FunctionDecl *FD = D->getAsFunction();
1092   if (!FD)
1093     return;
1094 
1095   // Same implementation as PushDeclContext, but enters the context
1096   // from the lexical parent, rather than the top-level class.
1097   assert(CurContext == FD->getLexicalParent() &&
1098     "The next DeclContext should be lexically contained in the current one.");
1099   CurContext = FD;
1100   S->setEntity(CurContext);
1101 
1102   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1103     ParmVarDecl *Param = FD->getParamDecl(P);
1104     // If the parameter has an identifier, then add it to the scope
1105     if (Param->getIdentifier()) {
1106       S->AddDecl(Param);
1107       IdResolver.AddDecl(Param);
1108     }
1109   }
1110 }
1111 
1112 
1113 void Sema::ActOnExitFunctionContext() {
1114   // Same implementation as PopDeclContext, but returns to the lexical parent,
1115   // rather than the top-level class.
1116   assert(CurContext && "DeclContext imbalance!");
1117   CurContext = CurContext->getLexicalParent();
1118   assert(CurContext && "Popped translation unit!");
1119 }
1120 
1121 
1122 /// \brief Determine whether we allow overloading of the function
1123 /// PrevDecl with another declaration.
1124 ///
1125 /// This routine determines whether overloading is possible, not
1126 /// whether some new function is actually an overload. It will return
1127 /// true in C++ (where we can always provide overloads) or, as an
1128 /// extension, in C when the previous function is already an
1129 /// overloaded function declaration or has the "overloadable"
1130 /// attribute.
1131 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1132                                        ASTContext &Context) {
1133   if (Context.getLangOpts().CPlusPlus)
1134     return true;
1135 
1136   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1137     return true;
1138 
1139   return (Previous.getResultKind() == LookupResult::Found
1140           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1141 }
1142 
1143 /// Add this decl to the scope shadowed decl chains.
1144 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1145   // Move up the scope chain until we find the nearest enclosing
1146   // non-transparent context. The declaration will be introduced into this
1147   // scope.
1148   while (S->getEntity() && S->getEntity()->isTransparentContext())
1149     S = S->getParent();
1150 
1151   // Add scoped declarations into their context, so that they can be
1152   // found later. Declarations without a context won't be inserted
1153   // into any context.
1154   if (AddToContext)
1155     CurContext->addDecl(D);
1156 
1157   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1158   // are function-local declarations.
1159   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1160       !D->getDeclContext()->getRedeclContext()->Equals(
1161         D->getLexicalDeclContext()->getRedeclContext()) &&
1162       !D->getLexicalDeclContext()->isFunctionOrMethod())
1163     return;
1164 
1165   // Template instantiations should also not be pushed into scope.
1166   if (isa<FunctionDecl>(D) &&
1167       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1168     return;
1169 
1170   // If this replaces anything in the current scope,
1171   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1172                                IEnd = IdResolver.end();
1173   for (; I != IEnd; ++I) {
1174     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1175       S->RemoveDecl(*I);
1176       IdResolver.RemoveDecl(*I);
1177 
1178       // Should only need to replace one decl.
1179       break;
1180     }
1181   }
1182 
1183   S->AddDecl(D);
1184 
1185   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1186     // Implicitly-generated labels may end up getting generated in an order that
1187     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1188     // the label at the appropriate place in the identifier chain.
1189     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1190       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1191       if (IDC == CurContext) {
1192         if (!S->isDeclScope(*I))
1193           continue;
1194       } else if (IDC->Encloses(CurContext))
1195         break;
1196     }
1197 
1198     IdResolver.InsertDeclAfter(I, D);
1199   } else {
1200     IdResolver.AddDecl(D);
1201   }
1202 }
1203 
1204 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1205   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1206     TUScope->AddDecl(D);
1207 }
1208 
1209 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1210                          bool AllowInlineNamespace) {
1211   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1212 }
1213 
1214 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1215   DeclContext *TargetDC = DC->getPrimaryContext();
1216   do {
1217     if (DeclContext *ScopeDC = S->getEntity())
1218       if (ScopeDC->getPrimaryContext() == TargetDC)
1219         return S;
1220   } while ((S = S->getParent()));
1221 
1222   return nullptr;
1223 }
1224 
1225 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1226                                             DeclContext*,
1227                                             ASTContext&);
1228 
1229 /// Filters out lookup results that don't fall within the given scope
1230 /// as determined by isDeclInScope.
1231 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1232                                 bool ConsiderLinkage,
1233                                 bool AllowInlineNamespace) {
1234   LookupResult::Filter F = R.makeFilter();
1235   while (F.hasNext()) {
1236     NamedDecl *D = F.next();
1237 
1238     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1239       continue;
1240 
1241     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1242       continue;
1243 
1244     F.erase();
1245   }
1246 
1247   F.done();
1248 }
1249 
1250 static bool isUsingDecl(NamedDecl *D) {
1251   return isa<UsingShadowDecl>(D) ||
1252          isa<UnresolvedUsingTypenameDecl>(D) ||
1253          isa<UnresolvedUsingValueDecl>(D);
1254 }
1255 
1256 /// Removes using shadow declarations from the lookup results.
1257 static void RemoveUsingDecls(LookupResult &R) {
1258   LookupResult::Filter F = R.makeFilter();
1259   while (F.hasNext())
1260     if (isUsingDecl(F.next()))
1261       F.erase();
1262 
1263   F.done();
1264 }
1265 
1266 /// \brief Check for this common pattern:
1267 /// @code
1268 /// class S {
1269 ///   S(const S&); // DO NOT IMPLEMENT
1270 ///   void operator=(const S&); // DO NOT IMPLEMENT
1271 /// };
1272 /// @endcode
1273 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1274   // FIXME: Should check for private access too but access is set after we get
1275   // the decl here.
1276   if (D->doesThisDeclarationHaveABody())
1277     return false;
1278 
1279   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1280     return CD->isCopyConstructor();
1281   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1282     return Method->isCopyAssignmentOperator();
1283   return false;
1284 }
1285 
1286 // We need this to handle
1287 //
1288 // typedef struct {
1289 //   void *foo() { return 0; }
1290 // } A;
1291 //
1292 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1293 // for example. If 'A', foo will have external linkage. If we have '*A',
1294 // foo will have no linkage. Since we can't know until we get to the end
1295 // of the typedef, this function finds out if D might have non-external linkage.
1296 // Callers should verify at the end of the TU if it D has external linkage or
1297 // not.
1298 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1299   const DeclContext *DC = D->getDeclContext();
1300   while (!DC->isTranslationUnit()) {
1301     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1302       if (!RD->hasNameForLinkage())
1303         return true;
1304     }
1305     DC = DC->getParent();
1306   }
1307 
1308   return !D->isExternallyVisible();
1309 }
1310 
1311 // FIXME: This needs to be refactored; some other isInMainFile users want
1312 // these semantics.
1313 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1314   if (S.TUKind != TU_Complete)
1315     return false;
1316   return S.SourceMgr.isInMainFile(Loc);
1317 }
1318 
1319 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1320   assert(D);
1321 
1322   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1323     return false;
1324 
1325   // Ignore all entities declared within templates, and out-of-line definitions
1326   // of members of class templates.
1327   if (D->getDeclContext()->isDependentContext() ||
1328       D->getLexicalDeclContext()->isDependentContext())
1329     return false;
1330 
1331   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1332     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1333       return false;
1334 
1335     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1336       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1337         return false;
1338     } else {
1339       // 'static inline' functions are defined in headers; don't warn.
1340       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1341         return false;
1342     }
1343 
1344     if (FD->doesThisDeclarationHaveABody() &&
1345         Context.DeclMustBeEmitted(FD))
1346       return false;
1347   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1348     // Constants and utility variables are defined in headers with internal
1349     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1350     // like "inline".)
1351     if (!isMainFileLoc(*this, VD->getLocation()))
1352       return false;
1353 
1354     if (Context.DeclMustBeEmitted(VD))
1355       return false;
1356 
1357     if (VD->isStaticDataMember() &&
1358         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1359       return false;
1360   } else {
1361     return false;
1362   }
1363 
1364   // Only warn for unused decls internal to the translation unit.
1365   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1366   // for inline functions defined in the main source file, for instance.
1367   return mightHaveNonExternalLinkage(D);
1368 }
1369 
1370 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1371   if (!D)
1372     return;
1373 
1374   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1375     const FunctionDecl *First = FD->getFirstDecl();
1376     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1377       return; // First should already be in the vector.
1378   }
1379 
1380   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1381     const VarDecl *First = VD->getFirstDecl();
1382     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1383       return; // First should already be in the vector.
1384   }
1385 
1386   if (ShouldWarnIfUnusedFileScopedDecl(D))
1387     UnusedFileScopedDecls.push_back(D);
1388 }
1389 
1390 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1391   if (D->isInvalidDecl())
1392     return false;
1393 
1394   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1395       D->hasAttr<ObjCPreciseLifetimeAttr>())
1396     return false;
1397 
1398   if (isa<LabelDecl>(D))
1399     return true;
1400 
1401   // Except for labels, we only care about unused decls that are local to
1402   // functions.
1403   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1404   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1405     // For dependent types, the diagnostic is deferred.
1406     WithinFunction =
1407         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1408   if (!WithinFunction)
1409     return false;
1410 
1411   if (isa<TypedefNameDecl>(D))
1412     return true;
1413 
1414   // White-list anything that isn't a local variable.
1415   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1416     return false;
1417 
1418   // Types of valid local variables should be complete, so this should succeed.
1419   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1420 
1421     // White-list anything with an __attribute__((unused)) type.
1422     QualType Ty = VD->getType();
1423 
1424     // Only look at the outermost level of typedef.
1425     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1426       if (TT->getDecl()->hasAttr<UnusedAttr>())
1427         return false;
1428     }
1429 
1430     // If we failed to complete the type for some reason, or if the type is
1431     // dependent, don't diagnose the variable.
1432     if (Ty->isIncompleteType() || Ty->isDependentType())
1433       return false;
1434 
1435     if (const TagType *TT = Ty->getAs<TagType>()) {
1436       const TagDecl *Tag = TT->getDecl();
1437       if (Tag->hasAttr<UnusedAttr>())
1438         return false;
1439 
1440       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1441         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1442           return false;
1443 
1444         if (const Expr *Init = VD->getInit()) {
1445           if (const ExprWithCleanups *Cleanups =
1446                   dyn_cast<ExprWithCleanups>(Init))
1447             Init = Cleanups->getSubExpr();
1448           const CXXConstructExpr *Construct =
1449             dyn_cast<CXXConstructExpr>(Init);
1450           if (Construct && !Construct->isElidable()) {
1451             CXXConstructorDecl *CD = Construct->getConstructor();
1452             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1453               return false;
1454           }
1455         }
1456       }
1457     }
1458 
1459     // TODO: __attribute__((unused)) templates?
1460   }
1461 
1462   return true;
1463 }
1464 
1465 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1466                                      FixItHint &Hint) {
1467   if (isa<LabelDecl>(D)) {
1468     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1469                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1470     if (AfterColon.isInvalid())
1471       return;
1472     Hint = FixItHint::CreateRemoval(CharSourceRange::
1473                                     getCharRange(D->getLocStart(), AfterColon));
1474   }
1475   return;
1476 }
1477 
1478 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1479   if (D->getTypeForDecl()->isDependentType())
1480     return;
1481 
1482   for (auto *TmpD : D->decls()) {
1483     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1484       DiagnoseUnusedDecl(T);
1485     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1486       DiagnoseUnusedNestedTypedefs(R);
1487   }
1488 }
1489 
1490 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1491 /// unless they are marked attr(unused).
1492 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1493   if (!ShouldDiagnoseUnusedDecl(D))
1494     return;
1495 
1496   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1497     // typedefs can be referenced later on, so the diagnostics are emitted
1498     // at end-of-translation-unit.
1499     UnusedLocalTypedefNameCandidates.insert(TD);
1500     return;
1501   }
1502 
1503   FixItHint Hint;
1504   GenerateFixForUnusedDecl(D, Context, Hint);
1505 
1506   unsigned DiagID;
1507   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1508     DiagID = diag::warn_unused_exception_param;
1509   else if (isa<LabelDecl>(D))
1510     DiagID = diag::warn_unused_label;
1511   else
1512     DiagID = diag::warn_unused_variable;
1513 
1514   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1515 }
1516 
1517 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1518   // Verify that we have no forward references left.  If so, there was a goto
1519   // or address of a label taken, but no definition of it.  Label fwd
1520   // definitions are indicated with a null substmt which is also not a resolved
1521   // MS inline assembly label name.
1522   bool Diagnose = false;
1523   if (L->isMSAsmLabel())
1524     Diagnose = !L->isResolvedMSAsmLabel();
1525   else
1526     Diagnose = L->getStmt() == nullptr;
1527   if (Diagnose)
1528     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1529 }
1530 
1531 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1532   S->mergeNRVOIntoParent();
1533 
1534   if (S->decl_empty()) return;
1535   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1536          "Scope shouldn't contain decls!");
1537 
1538   for (auto *TmpD : S->decls()) {
1539     assert(TmpD && "This decl didn't get pushed??");
1540 
1541     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1542     NamedDecl *D = cast<NamedDecl>(TmpD);
1543 
1544     if (!D->getDeclName()) continue;
1545 
1546     // Diagnose unused variables in this scope.
1547     if (!S->hasUnrecoverableErrorOccurred()) {
1548       DiagnoseUnusedDecl(D);
1549       if (const auto *RD = dyn_cast<RecordDecl>(D))
1550         DiagnoseUnusedNestedTypedefs(RD);
1551     }
1552 
1553     // If this was a forward reference to a label, verify it was defined.
1554     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1555       CheckPoppedLabel(LD, *this);
1556 
1557     // Remove this name from our lexical scope.
1558     IdResolver.RemoveDecl(D);
1559   }
1560 }
1561 
1562 /// \brief Look for an Objective-C class in the translation unit.
1563 ///
1564 /// \param Id The name of the Objective-C class we're looking for. If
1565 /// typo-correction fixes this name, the Id will be updated
1566 /// to the fixed name.
1567 ///
1568 /// \param IdLoc The location of the name in the translation unit.
1569 ///
1570 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1571 /// if there is no class with the given name.
1572 ///
1573 /// \returns The declaration of the named Objective-C class, or NULL if the
1574 /// class could not be found.
1575 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1576                                               SourceLocation IdLoc,
1577                                               bool DoTypoCorrection) {
1578   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1579   // creation from this context.
1580   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1581 
1582   if (!IDecl && DoTypoCorrection) {
1583     // Perform typo correction at the given location, but only if we
1584     // find an Objective-C class name.
1585     DeclFilterCCC<ObjCInterfaceDecl> Validator;
1586     if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1587                                        LookupOrdinaryName, TUScope, nullptr,
1588                                        Validator, CTK_ErrorRecovery)) {
1589       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1590       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1591       Id = IDecl->getIdentifier();
1592     }
1593   }
1594   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1595   // This routine must always return a class definition, if any.
1596   if (Def && Def->getDefinition())
1597       Def = Def->getDefinition();
1598   return Def;
1599 }
1600 
1601 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1602 /// from S, where a non-field would be declared. This routine copes
1603 /// with the difference between C and C++ scoping rules in structs and
1604 /// unions. For example, the following code is well-formed in C but
1605 /// ill-formed in C++:
1606 /// @code
1607 /// struct S6 {
1608 ///   enum { BAR } e;
1609 /// };
1610 ///
1611 /// void test_S6() {
1612 ///   struct S6 a;
1613 ///   a.e = BAR;
1614 /// }
1615 /// @endcode
1616 /// For the declaration of BAR, this routine will return a different
1617 /// scope. The scope S will be the scope of the unnamed enumeration
1618 /// within S6. In C++, this routine will return the scope associated
1619 /// with S6, because the enumeration's scope is a transparent
1620 /// context but structures can contain non-field names. In C, this
1621 /// routine will return the translation unit scope, since the
1622 /// enumeration's scope is a transparent context and structures cannot
1623 /// contain non-field names.
1624 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1625   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1626          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1627          (S->isClassScope() && !getLangOpts().CPlusPlus))
1628     S = S->getParent();
1629   return S;
1630 }
1631 
1632 /// \brief Looks up the declaration of "struct objc_super" and
1633 /// saves it for later use in building builtin declaration of
1634 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1635 /// pre-existing declaration exists no action takes place.
1636 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1637                                         IdentifierInfo *II) {
1638   if (!II->isStr("objc_msgSendSuper"))
1639     return;
1640   ASTContext &Context = ThisSema.Context;
1641 
1642   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1643                       SourceLocation(), Sema::LookupTagName);
1644   ThisSema.LookupName(Result, S);
1645   if (Result.getResultKind() == LookupResult::Found)
1646     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1647       Context.setObjCSuperType(Context.getTagDeclType(TD));
1648 }
1649 
1650 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1651   switch (Error) {
1652   case ASTContext::GE_None:
1653     return "";
1654   case ASTContext::GE_Missing_stdio:
1655     return "stdio.h";
1656   case ASTContext::GE_Missing_setjmp:
1657     return "setjmp.h";
1658   case ASTContext::GE_Missing_ucontext:
1659     return "ucontext.h";
1660   }
1661   llvm_unreachable("unhandled error kind");
1662 }
1663 
1664 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1665 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1666 /// if we're creating this built-in in anticipation of redeclaring the
1667 /// built-in.
1668 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1669                                      Scope *S, bool ForRedeclaration,
1670                                      SourceLocation Loc) {
1671   LookupPredefedObjCSuperType(*this, S, II);
1672 
1673   ASTContext::GetBuiltinTypeError Error;
1674   QualType R = Context.GetBuiltinType(ID, Error);
1675   if (Error) {
1676     if (ForRedeclaration)
1677       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1678           << getHeaderName(Error)
1679           << Context.BuiltinInfo.GetName(ID);
1680     return nullptr;
1681   }
1682 
1683   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
1684     Diag(Loc, diag::ext_implicit_lib_function_decl)
1685       << Context.BuiltinInfo.GetName(ID)
1686       << R;
1687     if (Context.BuiltinInfo.getHeaderName(ID) &&
1688         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1689       Diag(Loc, diag::note_include_header_or_declare)
1690           << Context.BuiltinInfo.getHeaderName(ID)
1691           << Context.BuiltinInfo.GetName(ID);
1692   }
1693 
1694   DeclContext *Parent = Context.getTranslationUnitDecl();
1695   if (getLangOpts().CPlusPlus) {
1696     LinkageSpecDecl *CLinkageDecl =
1697         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1698                                 LinkageSpecDecl::lang_c, false);
1699     CLinkageDecl->setImplicit();
1700     Parent->addDecl(CLinkageDecl);
1701     Parent = CLinkageDecl;
1702   }
1703 
1704   FunctionDecl *New = FunctionDecl::Create(Context,
1705                                            Parent,
1706                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1707                                            SC_Extern,
1708                                            false,
1709                                            /*hasPrototype=*/true);
1710   New->setImplicit();
1711 
1712   // Create Decl objects for each parameter, adding them to the
1713   // FunctionDecl.
1714   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1715     SmallVector<ParmVarDecl*, 16> Params;
1716     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1717       ParmVarDecl *parm =
1718           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1719                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1720                               SC_None, nullptr);
1721       parm->setScopeInfo(0, i);
1722       Params.push_back(parm);
1723     }
1724     New->setParams(Params);
1725   }
1726 
1727   AddKnownFunctionAttributes(New);
1728   RegisterLocallyScopedExternCDecl(New, S);
1729 
1730   // TUScope is the translation-unit scope to insert this function into.
1731   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1732   // relate Scopes to DeclContexts, and probably eliminate CurContext
1733   // entirely, but we're not there yet.
1734   DeclContext *SavedContext = CurContext;
1735   CurContext = Parent;
1736   PushOnScopeChains(New, TUScope);
1737   CurContext = SavedContext;
1738   return New;
1739 }
1740 
1741 /// \brief Filter out any previous declarations that the given declaration
1742 /// should not consider because they are not permitted to conflict, e.g.,
1743 /// because they come from hidden sub-modules and do not refer to the same
1744 /// entity.
1745 static void filterNonConflictingPreviousDecls(ASTContext &context,
1746                                               NamedDecl *decl,
1747                                               LookupResult &previous){
1748   // This is only interesting when modules are enabled.
1749   if (!context.getLangOpts().Modules)
1750     return;
1751 
1752   // Empty sets are uninteresting.
1753   if (previous.empty())
1754     return;
1755 
1756   LookupResult::Filter filter = previous.makeFilter();
1757   while (filter.hasNext()) {
1758     NamedDecl *old = filter.next();
1759 
1760     // Non-hidden declarations are never ignored.
1761     if (!old->isHidden())
1762       continue;
1763 
1764     if (!old->isExternallyVisible())
1765       filter.erase();
1766   }
1767 
1768   filter.done();
1769 }
1770 
1771 /// Typedef declarations don't have linkage, but they still denote the same
1772 /// entity if their types are the same.
1773 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1774 /// isSameEntity.
1775 static void filterNonConflictingPreviousTypedefDecls(ASTContext &Context,
1776                                                      TypedefNameDecl *Decl,
1777                                                      LookupResult &Previous) {
1778   // This is only interesting when modules are enabled.
1779   if (!Context.getLangOpts().Modules)
1780     return;
1781 
1782   // Empty sets are uninteresting.
1783   if (Previous.empty())
1784     return;
1785 
1786   LookupResult::Filter Filter = Previous.makeFilter();
1787   while (Filter.hasNext()) {
1788     NamedDecl *Old = Filter.next();
1789 
1790     // Non-hidden declarations are never ignored.
1791     if (!Old->isHidden())
1792       continue;
1793 
1794     // Declarations of the same entity are not ignored, even if they have
1795     // different linkages.
1796     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old))
1797       if (Context.hasSameType(OldTD->getUnderlyingType(),
1798                               Decl->getUnderlyingType()))
1799         continue;
1800 
1801     if (!Old->isExternallyVisible())
1802       Filter.erase();
1803   }
1804 
1805   Filter.done();
1806 }
1807 
1808 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1809   QualType OldType;
1810   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1811     OldType = OldTypedef->getUnderlyingType();
1812   else
1813     OldType = Context.getTypeDeclType(Old);
1814   QualType NewType = New->getUnderlyingType();
1815 
1816   if (NewType->isVariablyModifiedType()) {
1817     // Must not redefine a typedef with a variably-modified type.
1818     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1819     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1820       << Kind << NewType;
1821     if (Old->getLocation().isValid())
1822       Diag(Old->getLocation(), diag::note_previous_definition);
1823     New->setInvalidDecl();
1824     return true;
1825   }
1826 
1827   if (OldType != NewType &&
1828       !OldType->isDependentType() &&
1829       !NewType->isDependentType() &&
1830       !Context.hasSameType(OldType, NewType)) {
1831     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1832     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1833       << Kind << NewType << OldType;
1834     if (Old->getLocation().isValid())
1835       Diag(Old->getLocation(), diag::note_previous_definition);
1836     New->setInvalidDecl();
1837     return true;
1838   }
1839   return false;
1840 }
1841 
1842 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1843 /// same name and scope as a previous declaration 'Old'.  Figure out
1844 /// how to resolve this situation, merging decls or emitting
1845 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1846 ///
1847 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
1848   // If the new decl is known invalid already, don't bother doing any
1849   // merging checks.
1850   if (New->isInvalidDecl()) return;
1851 
1852   // Allow multiple definitions for ObjC built-in typedefs.
1853   // FIXME: Verify the underlying types are equivalent!
1854   if (getLangOpts().ObjC1) {
1855     const IdentifierInfo *TypeID = New->getIdentifier();
1856     switch (TypeID->getLength()) {
1857     default: break;
1858     case 2:
1859       {
1860         if (!TypeID->isStr("id"))
1861           break;
1862         QualType T = New->getUnderlyingType();
1863         if (!T->isPointerType())
1864           break;
1865         if (!T->isVoidPointerType()) {
1866           QualType PT = T->getAs<PointerType>()->getPointeeType();
1867           if (!PT->isStructureType())
1868             break;
1869         }
1870         Context.setObjCIdRedefinitionType(T);
1871         // Install the built-in type for 'id', ignoring the current definition.
1872         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1873         return;
1874       }
1875     case 5:
1876       if (!TypeID->isStr("Class"))
1877         break;
1878       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1879       // Install the built-in type for 'Class', ignoring the current definition.
1880       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1881       return;
1882     case 3:
1883       if (!TypeID->isStr("SEL"))
1884         break;
1885       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1886       // Install the built-in type for 'SEL', ignoring the current definition.
1887       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1888       return;
1889     }
1890     // Fall through - the typedef name was not a builtin type.
1891   }
1892 
1893   // Verify the old decl was also a type.
1894   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1895   if (!Old) {
1896     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1897       << New->getDeclName();
1898 
1899     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1900     if (OldD->getLocation().isValid())
1901       Diag(OldD->getLocation(), diag::note_previous_definition);
1902 
1903     return New->setInvalidDecl();
1904   }
1905 
1906   // If the old declaration is invalid, just give up here.
1907   if (Old->isInvalidDecl())
1908     return New->setInvalidDecl();
1909 
1910   // If the typedef types are not identical, reject them in all languages and
1911   // with any extensions enabled.
1912   if (isIncompatibleTypedef(Old, New))
1913     return;
1914 
1915   // The types match.  Link up the redeclaration chain and merge attributes if
1916   // the old declaration was a typedef.
1917   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
1918     New->setPreviousDecl(Typedef);
1919     mergeDeclAttributes(New, Old);
1920   }
1921 
1922   if (getLangOpts().MicrosoftExt)
1923     return;
1924 
1925   if (getLangOpts().CPlusPlus) {
1926     // C++ [dcl.typedef]p2:
1927     //   In a given non-class scope, a typedef specifier can be used to
1928     //   redefine the name of any type declared in that scope to refer
1929     //   to the type to which it already refers.
1930     if (!isa<CXXRecordDecl>(CurContext))
1931       return;
1932 
1933     // C++0x [dcl.typedef]p4:
1934     //   In a given class scope, a typedef specifier can be used to redefine
1935     //   any class-name declared in that scope that is not also a typedef-name
1936     //   to refer to the type to which it already refers.
1937     //
1938     // This wording came in via DR424, which was a correction to the
1939     // wording in DR56, which accidentally banned code like:
1940     //
1941     //   struct S {
1942     //     typedef struct A { } A;
1943     //   };
1944     //
1945     // in the C++03 standard. We implement the C++0x semantics, which
1946     // allow the above but disallow
1947     //
1948     //   struct S {
1949     //     typedef int I;
1950     //     typedef int I;
1951     //   };
1952     //
1953     // since that was the intent of DR56.
1954     if (!isa<TypedefNameDecl>(Old))
1955       return;
1956 
1957     Diag(New->getLocation(), diag::err_redefinition)
1958       << New->getDeclName();
1959     Diag(Old->getLocation(), diag::note_previous_definition);
1960     return New->setInvalidDecl();
1961   }
1962 
1963   // Modules always permit redefinition of typedefs, as does C11.
1964   if (getLangOpts().Modules || getLangOpts().C11)
1965     return;
1966 
1967   // If we have a redefinition of a typedef in C, emit a warning.  This warning
1968   // is normally mapped to an error, but can be controlled with
1969   // -Wtypedef-redefinition.  If either the original or the redefinition is
1970   // in a system header, don't emit this for compatibility with GCC.
1971   if (getDiagnostics().getSuppressSystemWarnings() &&
1972       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1973        Context.getSourceManager().isInSystemHeader(New->getLocation())))
1974     return;
1975 
1976   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
1977     << New->getDeclName();
1978   Diag(Old->getLocation(), diag::note_previous_definition);
1979   return;
1980 }
1981 
1982 /// DeclhasAttr - returns true if decl Declaration already has the target
1983 /// attribute.
1984 static bool DeclHasAttr(const Decl *D, const Attr *A) {
1985   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1986   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
1987   for (const auto *i : D->attrs())
1988     if (i->getKind() == A->getKind()) {
1989       if (Ann) {
1990         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
1991           return true;
1992         continue;
1993       }
1994       // FIXME: Don't hardcode this check
1995       if (OA && isa<OwnershipAttr>(i))
1996         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
1997       return true;
1998     }
1999 
2000   return false;
2001 }
2002 
2003 static bool isAttributeTargetADefinition(Decl *D) {
2004   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2005     return VD->isThisDeclarationADefinition();
2006   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2007     return TD->isCompleteDefinition() || TD->isBeingDefined();
2008   return true;
2009 }
2010 
2011 /// Merge alignment attributes from \p Old to \p New, taking into account the
2012 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2013 ///
2014 /// \return \c true if any attributes were added to \p New.
2015 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2016   // Look for alignas attributes on Old, and pick out whichever attribute
2017   // specifies the strictest alignment requirement.
2018   AlignedAttr *OldAlignasAttr = nullptr;
2019   AlignedAttr *OldStrictestAlignAttr = nullptr;
2020   unsigned OldAlign = 0;
2021   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2022     // FIXME: We have no way of representing inherited dependent alignments
2023     // in a case like:
2024     //   template<int A, int B> struct alignas(A) X;
2025     //   template<int A, int B> struct alignas(B) X {};
2026     // For now, we just ignore any alignas attributes which are not on the
2027     // definition in such a case.
2028     if (I->isAlignmentDependent())
2029       return false;
2030 
2031     if (I->isAlignas())
2032       OldAlignasAttr = I;
2033 
2034     unsigned Align = I->getAlignment(S.Context);
2035     if (Align > OldAlign) {
2036       OldAlign = Align;
2037       OldStrictestAlignAttr = I;
2038     }
2039   }
2040 
2041   // Look for alignas attributes on New.
2042   AlignedAttr *NewAlignasAttr = nullptr;
2043   unsigned NewAlign = 0;
2044   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2045     if (I->isAlignmentDependent())
2046       return false;
2047 
2048     if (I->isAlignas())
2049       NewAlignasAttr = I;
2050 
2051     unsigned Align = I->getAlignment(S.Context);
2052     if (Align > NewAlign)
2053       NewAlign = Align;
2054   }
2055 
2056   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2057     // Both declarations have 'alignas' attributes. We require them to match.
2058     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2059     // fall short. (If two declarations both have alignas, they must both match
2060     // every definition, and so must match each other if there is a definition.)
2061 
2062     // If either declaration only contains 'alignas(0)' specifiers, then it
2063     // specifies the natural alignment for the type.
2064     if (OldAlign == 0 || NewAlign == 0) {
2065       QualType Ty;
2066       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2067         Ty = VD->getType();
2068       else
2069         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2070 
2071       if (OldAlign == 0)
2072         OldAlign = S.Context.getTypeAlign(Ty);
2073       if (NewAlign == 0)
2074         NewAlign = S.Context.getTypeAlign(Ty);
2075     }
2076 
2077     if (OldAlign != NewAlign) {
2078       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2079         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2080         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2081       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2082     }
2083   }
2084 
2085   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2086     // C++11 [dcl.align]p6:
2087     //   if any declaration of an entity has an alignment-specifier,
2088     //   every defining declaration of that entity shall specify an
2089     //   equivalent alignment.
2090     // C11 6.7.5/7:
2091     //   If the definition of an object does not have an alignment
2092     //   specifier, any other declaration of that object shall also
2093     //   have no alignment specifier.
2094     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2095       << OldAlignasAttr;
2096     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2097       << OldAlignasAttr;
2098   }
2099 
2100   bool AnyAdded = false;
2101 
2102   // Ensure we have an attribute representing the strictest alignment.
2103   if (OldAlign > NewAlign) {
2104     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2105     Clone->setInherited(true);
2106     New->addAttr(Clone);
2107     AnyAdded = true;
2108   }
2109 
2110   // Ensure we have an alignas attribute if the old declaration had one.
2111   if (OldAlignasAttr && !NewAlignasAttr &&
2112       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2113     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2114     Clone->setInherited(true);
2115     New->addAttr(Clone);
2116     AnyAdded = true;
2117   }
2118 
2119   return AnyAdded;
2120 }
2121 
2122 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2123                                const InheritableAttr *Attr, bool Override) {
2124   InheritableAttr *NewAttr = nullptr;
2125   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2126   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2127     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2128                                       AA->getIntroduced(), AA->getDeprecated(),
2129                                       AA->getObsoleted(), AA->getUnavailable(),
2130                                       AA->getMessage(), Override,
2131                                       AttrSpellingListIndex);
2132   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2133     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2134                                     AttrSpellingListIndex);
2135   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2136     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2137                                         AttrSpellingListIndex);
2138   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2139     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2140                                    AttrSpellingListIndex);
2141   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2142     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2143                                    AttrSpellingListIndex);
2144   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2145     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2146                                 FA->getFormatIdx(), FA->getFirstArg(),
2147                                 AttrSpellingListIndex);
2148   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2149     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2150                                  AttrSpellingListIndex);
2151   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2152     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2153                                        AttrSpellingListIndex,
2154                                        IA->getSemanticSpelling());
2155   else if (isa<AlignedAttr>(Attr))
2156     // AlignedAttrs are handled separately, because we need to handle all
2157     // such attributes on a declaration at the same time.
2158     NewAttr = nullptr;
2159   else if (isa<DeprecatedAttr>(Attr) && Override)
2160     NewAttr = nullptr;
2161   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2162     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2163 
2164   if (NewAttr) {
2165     NewAttr->setInherited(true);
2166     D->addAttr(NewAttr);
2167     return true;
2168   }
2169 
2170   return false;
2171 }
2172 
2173 static const Decl *getDefinition(const Decl *D) {
2174   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2175     return TD->getDefinition();
2176   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2177     const VarDecl *Def = VD->getDefinition();
2178     if (Def)
2179       return Def;
2180     return VD->getActingDefinition();
2181   }
2182   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2183     const FunctionDecl* Def;
2184     if (FD->isDefined(Def))
2185       return Def;
2186   }
2187   return nullptr;
2188 }
2189 
2190 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2191   for (const auto *Attribute : D->attrs())
2192     if (Attribute->getKind() == Kind)
2193       return true;
2194   return false;
2195 }
2196 
2197 /// checkNewAttributesAfterDef - If we already have a definition, check that
2198 /// there are no new attributes in this declaration.
2199 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2200   if (!New->hasAttrs())
2201     return;
2202 
2203   const Decl *Def = getDefinition(Old);
2204   if (!Def || Def == New)
2205     return;
2206 
2207   AttrVec &NewAttributes = New->getAttrs();
2208   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2209     const Attr *NewAttribute = NewAttributes[I];
2210 
2211     if (isa<AliasAttr>(NewAttribute)) {
2212       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2213         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2214       else {
2215         VarDecl *VD = cast<VarDecl>(New);
2216         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2217                                 VarDecl::TentativeDefinition
2218                             ? diag::err_alias_after_tentative
2219                             : diag::err_redefinition;
2220         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2221         S.Diag(Def->getLocation(), diag::note_previous_definition);
2222         VD->setInvalidDecl();
2223       }
2224       ++I;
2225       continue;
2226     }
2227 
2228     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2229       // Tentative definitions are only interesting for the alias check above.
2230       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2231         ++I;
2232         continue;
2233       }
2234     }
2235 
2236     if (hasAttribute(Def, NewAttribute->getKind())) {
2237       ++I;
2238       continue; // regular attr merging will take care of validating this.
2239     }
2240 
2241     if (isa<C11NoReturnAttr>(NewAttribute)) {
2242       // C's _Noreturn is allowed to be added to a function after it is defined.
2243       ++I;
2244       continue;
2245     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2246       if (AA->isAlignas()) {
2247         // C++11 [dcl.align]p6:
2248         //   if any declaration of an entity has an alignment-specifier,
2249         //   every defining declaration of that entity shall specify an
2250         //   equivalent alignment.
2251         // C11 6.7.5/7:
2252         //   If the definition of an object does not have an alignment
2253         //   specifier, any other declaration of that object shall also
2254         //   have no alignment specifier.
2255         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2256           << AA;
2257         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2258           << AA;
2259         NewAttributes.erase(NewAttributes.begin() + I);
2260         --E;
2261         continue;
2262       }
2263     }
2264 
2265     S.Diag(NewAttribute->getLocation(),
2266            diag::warn_attribute_precede_definition);
2267     S.Diag(Def->getLocation(), diag::note_previous_definition);
2268     NewAttributes.erase(NewAttributes.begin() + I);
2269     --E;
2270   }
2271 }
2272 
2273 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2274 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2275                                AvailabilityMergeKind AMK) {
2276   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2277     UsedAttr *NewAttr = OldAttr->clone(Context);
2278     NewAttr->setInherited(true);
2279     New->addAttr(NewAttr);
2280   }
2281 
2282   if (!Old->hasAttrs() && !New->hasAttrs())
2283     return;
2284 
2285   // attributes declared post-definition are currently ignored
2286   checkNewAttributesAfterDef(*this, New, Old);
2287 
2288   if (!Old->hasAttrs())
2289     return;
2290 
2291   bool foundAny = New->hasAttrs();
2292 
2293   // Ensure that any moving of objects within the allocated map is done before
2294   // we process them.
2295   if (!foundAny) New->setAttrs(AttrVec());
2296 
2297   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2298     bool Override = false;
2299     // Ignore deprecated/unavailable/availability attributes if requested.
2300     if (isa<DeprecatedAttr>(I) ||
2301         isa<UnavailableAttr>(I) ||
2302         isa<AvailabilityAttr>(I)) {
2303       switch (AMK) {
2304       case AMK_None:
2305         continue;
2306 
2307       case AMK_Redeclaration:
2308         break;
2309 
2310       case AMK_Override:
2311         Override = true;
2312         break;
2313       }
2314     }
2315 
2316     // Already handled.
2317     if (isa<UsedAttr>(I))
2318       continue;
2319 
2320     if (mergeDeclAttribute(*this, New, I, Override))
2321       foundAny = true;
2322   }
2323 
2324   if (mergeAlignedAttrs(*this, New, Old))
2325     foundAny = true;
2326 
2327   if (!foundAny) New->dropAttrs();
2328 }
2329 
2330 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2331 /// to the new one.
2332 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2333                                      const ParmVarDecl *oldDecl,
2334                                      Sema &S) {
2335   // C++11 [dcl.attr.depend]p2:
2336   //   The first declaration of a function shall specify the
2337   //   carries_dependency attribute for its declarator-id if any declaration
2338   //   of the function specifies the carries_dependency attribute.
2339   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2340   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2341     S.Diag(CDA->getLocation(),
2342            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2343     // Find the first declaration of the parameter.
2344     // FIXME: Should we build redeclaration chains for function parameters?
2345     const FunctionDecl *FirstFD =
2346       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2347     const ParmVarDecl *FirstVD =
2348       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2349     S.Diag(FirstVD->getLocation(),
2350            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2351   }
2352 
2353   if (!oldDecl->hasAttrs())
2354     return;
2355 
2356   bool foundAny = newDecl->hasAttrs();
2357 
2358   // Ensure that any moving of objects within the allocated map is
2359   // done before we process them.
2360   if (!foundAny) newDecl->setAttrs(AttrVec());
2361 
2362   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2363     if (!DeclHasAttr(newDecl, I)) {
2364       InheritableAttr *newAttr =
2365         cast<InheritableParamAttr>(I->clone(S.Context));
2366       newAttr->setInherited(true);
2367       newDecl->addAttr(newAttr);
2368       foundAny = true;
2369     }
2370   }
2371 
2372   if (!foundAny) newDecl->dropAttrs();
2373 }
2374 
2375 namespace {
2376 
2377 /// Used in MergeFunctionDecl to keep track of function parameters in
2378 /// C.
2379 struct GNUCompatibleParamWarning {
2380   ParmVarDecl *OldParm;
2381   ParmVarDecl *NewParm;
2382   QualType PromotedType;
2383 };
2384 
2385 }
2386 
2387 /// getSpecialMember - get the special member enum for a method.
2388 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2389   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2390     if (Ctor->isDefaultConstructor())
2391       return Sema::CXXDefaultConstructor;
2392 
2393     if (Ctor->isCopyConstructor())
2394       return Sema::CXXCopyConstructor;
2395 
2396     if (Ctor->isMoveConstructor())
2397       return Sema::CXXMoveConstructor;
2398   } else if (isa<CXXDestructorDecl>(MD)) {
2399     return Sema::CXXDestructor;
2400   } else if (MD->isCopyAssignmentOperator()) {
2401     return Sema::CXXCopyAssignment;
2402   } else if (MD->isMoveAssignmentOperator()) {
2403     return Sema::CXXMoveAssignment;
2404   }
2405 
2406   return Sema::CXXInvalid;
2407 }
2408 
2409 // Determine whether the previous declaration was a definition, implicit
2410 // declaration, or a declaration.
2411 template <typename T>
2412 static std::pair<diag::kind, SourceLocation>
2413 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2414   diag::kind PrevDiag;
2415   SourceLocation OldLocation = Old->getLocation();
2416   if (Old->isThisDeclarationADefinition())
2417     PrevDiag = diag::note_previous_definition;
2418   else if (Old->isImplicit()) {
2419     PrevDiag = diag::note_previous_implicit_declaration;
2420     if (OldLocation.isInvalid())
2421       OldLocation = New->getLocation();
2422   } else
2423     PrevDiag = diag::note_previous_declaration;
2424   return std::make_pair(PrevDiag, OldLocation);
2425 }
2426 
2427 /// canRedefineFunction - checks if a function can be redefined. Currently,
2428 /// only extern inline functions can be redefined, and even then only in
2429 /// GNU89 mode.
2430 static bool canRedefineFunction(const FunctionDecl *FD,
2431                                 const LangOptions& LangOpts) {
2432   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2433           !LangOpts.CPlusPlus &&
2434           FD->isInlineSpecified() &&
2435           FD->getStorageClass() == SC_Extern);
2436 }
2437 
2438 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2439   const AttributedType *AT = T->getAs<AttributedType>();
2440   while (AT && !AT->isCallingConv())
2441     AT = AT->getModifiedType()->getAs<AttributedType>();
2442   return AT;
2443 }
2444 
2445 template <typename T>
2446 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2447   const DeclContext *DC = Old->getDeclContext();
2448   if (DC->isRecord())
2449     return false;
2450 
2451   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2452   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2453     return true;
2454   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2455     return true;
2456   return false;
2457 }
2458 
2459 /// MergeFunctionDecl - We just parsed a function 'New' from
2460 /// declarator D which has the same name and scope as a previous
2461 /// declaration 'Old'.  Figure out how to resolve this situation,
2462 /// merging decls or emitting diagnostics as appropriate.
2463 ///
2464 /// In C++, New and Old must be declarations that are not
2465 /// overloaded. Use IsOverload to determine whether New and Old are
2466 /// overloaded, and to select the Old declaration that New should be
2467 /// merged with.
2468 ///
2469 /// Returns true if there was an error, false otherwise.
2470 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2471                              Scope *S, bool MergeTypeWithOld) {
2472   // Verify the old decl was also a function.
2473   FunctionDecl *Old = OldD->getAsFunction();
2474   if (!Old) {
2475     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2476       if (New->getFriendObjectKind()) {
2477         Diag(New->getLocation(), diag::err_using_decl_friend);
2478         Diag(Shadow->getTargetDecl()->getLocation(),
2479              diag::note_using_decl_target);
2480         Diag(Shadow->getUsingDecl()->getLocation(),
2481              diag::note_using_decl) << 0;
2482         return true;
2483       }
2484 
2485       // C++11 [namespace.udecl]p14:
2486       //   If a function declaration in namespace scope or block scope has the
2487       //   same name and the same parameter-type-list as a function introduced
2488       //   by a using-declaration, and the declarations do not declare the same
2489       //   function, the program is ill-formed.
2490 
2491       // Check whether the two declarations might declare the same function.
2492       Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl());
2493       if (Old &&
2494           !Old->getDeclContext()->getRedeclContext()->Equals(
2495               New->getDeclContext()->getRedeclContext()) &&
2496           !(Old->isExternC() && New->isExternC()))
2497         Old = nullptr;
2498 
2499       if (!Old) {
2500         Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2501         Diag(Shadow->getTargetDecl()->getLocation(),
2502              diag::note_using_decl_target);
2503         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2504         return true;
2505       }
2506       OldD = Old;
2507     } else {
2508       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2509         << New->getDeclName();
2510       Diag(OldD->getLocation(), diag::note_previous_definition);
2511       return true;
2512     }
2513   }
2514 
2515   // If the old declaration is invalid, just give up here.
2516   if (Old->isInvalidDecl())
2517     return true;
2518 
2519   diag::kind PrevDiag;
2520   SourceLocation OldLocation;
2521   std::tie(PrevDiag, OldLocation) =
2522       getNoteDiagForInvalidRedeclaration(Old, New);
2523 
2524   // Don't complain about this if we're in GNU89 mode and the old function
2525   // is an extern inline function.
2526   // Don't complain about specializations. They are not supposed to have
2527   // storage classes.
2528   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2529       New->getStorageClass() == SC_Static &&
2530       Old->hasExternalFormalLinkage() &&
2531       !New->getTemplateSpecializationInfo() &&
2532       !canRedefineFunction(Old, getLangOpts())) {
2533     if (getLangOpts().MicrosoftExt) {
2534       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2535       Diag(OldLocation, PrevDiag);
2536     } else {
2537       Diag(New->getLocation(), diag::err_static_non_static) << New;
2538       Diag(OldLocation, PrevDiag);
2539       return true;
2540     }
2541   }
2542 
2543 
2544   // If a function is first declared with a calling convention, but is later
2545   // declared or defined without one, all following decls assume the calling
2546   // convention of the first.
2547   //
2548   // It's OK if a function is first declared without a calling convention,
2549   // but is later declared or defined with the default calling convention.
2550   //
2551   // To test if either decl has an explicit calling convention, we look for
2552   // AttributedType sugar nodes on the type as written.  If they are missing or
2553   // were canonicalized away, we assume the calling convention was implicit.
2554   //
2555   // Note also that we DO NOT return at this point, because we still have
2556   // other tests to run.
2557   QualType OldQType = Context.getCanonicalType(Old->getType());
2558   QualType NewQType = Context.getCanonicalType(New->getType());
2559   const FunctionType *OldType = cast<FunctionType>(OldQType);
2560   const FunctionType *NewType = cast<FunctionType>(NewQType);
2561   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2562   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2563   bool RequiresAdjustment = false;
2564 
2565   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2566     FunctionDecl *First = Old->getFirstDecl();
2567     const FunctionType *FT =
2568         First->getType().getCanonicalType()->castAs<FunctionType>();
2569     FunctionType::ExtInfo FI = FT->getExtInfo();
2570     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2571     if (!NewCCExplicit) {
2572       // Inherit the CC from the previous declaration if it was specified
2573       // there but not here.
2574       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2575       RequiresAdjustment = true;
2576     } else {
2577       // Calling conventions aren't compatible, so complain.
2578       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2579       Diag(New->getLocation(), diag::err_cconv_change)
2580         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2581         << !FirstCCExplicit
2582         << (!FirstCCExplicit ? "" :
2583             FunctionType::getNameForCallConv(FI.getCC()));
2584 
2585       // Put the note on the first decl, since it is the one that matters.
2586       Diag(First->getLocation(), diag::note_previous_declaration);
2587       return true;
2588     }
2589   }
2590 
2591   // FIXME: diagnose the other way around?
2592   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2593     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2594     RequiresAdjustment = true;
2595   }
2596 
2597   // Merge regparm attribute.
2598   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2599       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2600     if (NewTypeInfo.getHasRegParm()) {
2601       Diag(New->getLocation(), diag::err_regparm_mismatch)
2602         << NewType->getRegParmType()
2603         << OldType->getRegParmType();
2604       Diag(OldLocation, diag::note_previous_declaration);
2605       return true;
2606     }
2607 
2608     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2609     RequiresAdjustment = true;
2610   }
2611 
2612   // Merge ns_returns_retained attribute.
2613   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2614     if (NewTypeInfo.getProducesResult()) {
2615       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2616       Diag(OldLocation, diag::note_previous_declaration);
2617       return true;
2618     }
2619 
2620     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2621     RequiresAdjustment = true;
2622   }
2623 
2624   if (RequiresAdjustment) {
2625     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2626     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2627     New->setType(QualType(AdjustedType, 0));
2628     NewQType = Context.getCanonicalType(New->getType());
2629     NewType = cast<FunctionType>(NewQType);
2630   }
2631 
2632   // If this redeclaration makes the function inline, we may need to add it to
2633   // UndefinedButUsed.
2634   if (!Old->isInlined() && New->isInlined() &&
2635       !New->hasAttr<GNUInlineAttr>() &&
2636       (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2637       Old->isUsed(false) &&
2638       !Old->isDefined() && !New->isThisDeclarationADefinition())
2639     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2640                                            SourceLocation()));
2641 
2642   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2643   // about it.
2644   if (New->hasAttr<GNUInlineAttr>() &&
2645       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2646     UndefinedButUsed.erase(Old->getCanonicalDecl());
2647   }
2648 
2649   if (getLangOpts().CPlusPlus) {
2650     // (C++98 13.1p2):
2651     //   Certain function declarations cannot be overloaded:
2652     //     -- Function declarations that differ only in the return type
2653     //        cannot be overloaded.
2654 
2655     // Go back to the type source info to compare the declared return types,
2656     // per C++1y [dcl.type.auto]p13:
2657     //   Redeclarations or specializations of a function or function template
2658     //   with a declared return type that uses a placeholder type shall also
2659     //   use that placeholder, not a deduced type.
2660     QualType OldDeclaredReturnType =
2661         (Old->getTypeSourceInfo()
2662              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2663              : OldType)->getReturnType();
2664     QualType NewDeclaredReturnType =
2665         (New->getTypeSourceInfo()
2666              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2667              : NewType)->getReturnType();
2668     QualType ResQT;
2669     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2670         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2671           New->isLocalExternDecl())) {
2672       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2673           OldDeclaredReturnType->isObjCObjectPointerType())
2674         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2675       if (ResQT.isNull()) {
2676         if (New->isCXXClassMember() && New->isOutOfLine())
2677           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2678               << New << New->getReturnTypeSourceRange();
2679         else
2680           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2681               << New->getReturnTypeSourceRange();
2682         Diag(OldLocation, PrevDiag) << Old << Old->getType()
2683                                     << Old->getReturnTypeSourceRange();
2684         return true;
2685       }
2686       else
2687         NewQType = ResQT;
2688     }
2689 
2690     QualType OldReturnType = OldType->getReturnType();
2691     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2692     if (OldReturnType != NewReturnType) {
2693       // If this function has a deduced return type and has already been
2694       // defined, copy the deduced value from the old declaration.
2695       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2696       if (OldAT && OldAT->isDeduced()) {
2697         New->setType(
2698             SubstAutoType(New->getType(),
2699                           OldAT->isDependentType() ? Context.DependentTy
2700                                                    : OldAT->getDeducedType()));
2701         NewQType = Context.getCanonicalType(
2702             SubstAutoType(NewQType,
2703                           OldAT->isDependentType() ? Context.DependentTy
2704                                                    : OldAT->getDeducedType()));
2705       }
2706     }
2707 
2708     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2709     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2710     if (OldMethod && NewMethod) {
2711       // Preserve triviality.
2712       NewMethod->setTrivial(OldMethod->isTrivial());
2713 
2714       // MSVC allows explicit template specialization at class scope:
2715       // 2 CXXMethodDecls referring to the same function will be injected.
2716       // We don't want a redeclaration error.
2717       bool IsClassScopeExplicitSpecialization =
2718                               OldMethod->isFunctionTemplateSpecialization() &&
2719                               NewMethod->isFunctionTemplateSpecialization();
2720       bool isFriend = NewMethod->getFriendObjectKind();
2721 
2722       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2723           !IsClassScopeExplicitSpecialization) {
2724         //    -- Member function declarations with the same name and the
2725         //       same parameter types cannot be overloaded if any of them
2726         //       is a static member function declaration.
2727         if (OldMethod->isStatic() != NewMethod->isStatic()) {
2728           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2729           Diag(OldLocation, PrevDiag) << Old << Old->getType();
2730           return true;
2731         }
2732 
2733         // C++ [class.mem]p1:
2734         //   [...] A member shall not be declared twice in the
2735         //   member-specification, except that a nested class or member
2736         //   class template can be declared and then later defined.
2737         if (ActiveTemplateInstantiations.empty()) {
2738           unsigned NewDiag;
2739           if (isa<CXXConstructorDecl>(OldMethod))
2740             NewDiag = diag::err_constructor_redeclared;
2741           else if (isa<CXXDestructorDecl>(NewMethod))
2742             NewDiag = diag::err_destructor_redeclared;
2743           else if (isa<CXXConversionDecl>(NewMethod))
2744             NewDiag = diag::err_conv_function_redeclared;
2745           else
2746             NewDiag = diag::err_member_redeclared;
2747 
2748           Diag(New->getLocation(), NewDiag);
2749         } else {
2750           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2751             << New << New->getType();
2752         }
2753         Diag(OldLocation, PrevDiag) << Old << Old->getType();
2754 
2755       // Complain if this is an explicit declaration of a special
2756       // member that was initially declared implicitly.
2757       //
2758       // As an exception, it's okay to befriend such methods in order
2759       // to permit the implicit constructor/destructor/operator calls.
2760       } else if (OldMethod->isImplicit()) {
2761         if (isFriend) {
2762           NewMethod->setImplicit();
2763         } else {
2764           Diag(NewMethod->getLocation(),
2765                diag::err_definition_of_implicitly_declared_member)
2766             << New << getSpecialMember(OldMethod);
2767           return true;
2768         }
2769       } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2770         Diag(NewMethod->getLocation(),
2771              diag::err_definition_of_explicitly_defaulted_member)
2772           << getSpecialMember(OldMethod);
2773         return true;
2774       }
2775     }
2776 
2777     // C++11 [dcl.attr.noreturn]p1:
2778     //   The first declaration of a function shall specify the noreturn
2779     //   attribute if any declaration of that function specifies the noreturn
2780     //   attribute.
2781     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2782     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2783       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
2784       Diag(Old->getFirstDecl()->getLocation(),
2785            diag::note_noreturn_missing_first_decl);
2786     }
2787 
2788     // C++11 [dcl.attr.depend]p2:
2789     //   The first declaration of a function shall specify the
2790     //   carries_dependency attribute for its declarator-id if any declaration
2791     //   of the function specifies the carries_dependency attribute.
2792     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2793     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2794       Diag(CDA->getLocation(),
2795            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
2796       Diag(Old->getFirstDecl()->getLocation(),
2797            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2798     }
2799 
2800     // (C++98 8.3.5p3):
2801     //   All declarations for a function shall agree exactly in both the
2802     //   return type and the parameter-type-list.
2803     // We also want to respect all the extended bits except noreturn.
2804 
2805     // noreturn should now match unless the old type info didn't have it.
2806     QualType OldQTypeForComparison = OldQType;
2807     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2808       assert(OldQType == QualType(OldType, 0));
2809       const FunctionType *OldTypeForComparison
2810         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2811       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2812       assert(OldQTypeForComparison.isCanonical());
2813     }
2814 
2815     if (haveIncompatibleLanguageLinkages(Old, New)) {
2816       // As a special case, retain the language linkage from previous
2817       // declarations of a friend function as an extension.
2818       //
2819       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2820       // and is useful because there's otherwise no way to specify language
2821       // linkage within class scope.
2822       //
2823       // Check cautiously as the friend object kind isn't yet complete.
2824       if (New->getFriendObjectKind() != Decl::FOK_None) {
2825         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2826         Diag(OldLocation, PrevDiag);
2827       } else {
2828         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2829         Diag(OldLocation, PrevDiag);
2830         return true;
2831       }
2832     }
2833 
2834     if (OldQTypeForComparison == NewQType)
2835       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2836 
2837     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2838         New->isLocalExternDecl()) {
2839       // It's OK if we couldn't merge types for a local function declaraton
2840       // if either the old or new type is dependent. We'll merge the types
2841       // when we instantiate the function.
2842       return false;
2843     }
2844 
2845     // Fall through for conflicting redeclarations and redefinitions.
2846   }
2847 
2848   // C: Function types need to be compatible, not identical. This handles
2849   // duplicate function decls like "void f(int); void f(enum X);" properly.
2850   if (!getLangOpts().CPlusPlus &&
2851       Context.typesAreCompatible(OldQType, NewQType)) {
2852     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2853     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
2854     const FunctionProtoType *OldProto = nullptr;
2855     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
2856         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
2857       // The old declaration provided a function prototype, but the
2858       // new declaration does not. Merge in the prototype.
2859       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
2860       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
2861       NewQType =
2862           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
2863                                   OldProto->getExtProtoInfo());
2864       New->setType(NewQType);
2865       New->setHasInheritedPrototype();
2866 
2867       // Synthesize parameters with the same types.
2868       SmallVector<ParmVarDecl*, 16> Params;
2869       for (const auto &ParamType : OldProto->param_types()) {
2870         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
2871                                                  SourceLocation(), nullptr,
2872                                                  ParamType, /*TInfo=*/nullptr,
2873                                                  SC_None, nullptr);
2874         Param->setScopeInfo(0, Params.size());
2875         Param->setImplicit();
2876         Params.push_back(Param);
2877       }
2878 
2879       New->setParams(Params);
2880     }
2881 
2882     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2883   }
2884 
2885   // GNU C permits a K&R definition to follow a prototype declaration
2886   // if the declared types of the parameters in the K&R definition
2887   // match the types in the prototype declaration, even when the
2888   // promoted types of the parameters from the K&R definition differ
2889   // from the types in the prototype. GCC then keeps the types from
2890   // the prototype.
2891   //
2892   // If a variadic prototype is followed by a non-variadic K&R definition,
2893   // the K&R definition becomes variadic.  This is sort of an edge case, but
2894   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2895   // C99 6.9.1p8.
2896   if (!getLangOpts().CPlusPlus &&
2897       Old->hasPrototype() && !New->hasPrototype() &&
2898       New->getType()->getAs<FunctionProtoType>() &&
2899       Old->getNumParams() == New->getNumParams()) {
2900     SmallVector<QualType, 16> ArgTypes;
2901     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
2902     const FunctionProtoType *OldProto
2903       = Old->getType()->getAs<FunctionProtoType>();
2904     const FunctionProtoType *NewProto
2905       = New->getType()->getAs<FunctionProtoType>();
2906 
2907     // Determine whether this is the GNU C extension.
2908     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
2909                                                NewProto->getReturnType());
2910     bool LooseCompatible = !MergedReturn.isNull();
2911     for (unsigned Idx = 0, End = Old->getNumParams();
2912          LooseCompatible && Idx != End; ++Idx) {
2913       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2914       ParmVarDecl *NewParm = New->getParamDecl(Idx);
2915       if (Context.typesAreCompatible(OldParm->getType(),
2916                                      NewProto->getParamType(Idx))) {
2917         ArgTypes.push_back(NewParm->getType());
2918       } else if (Context.typesAreCompatible(OldParm->getType(),
2919                                             NewParm->getType(),
2920                                             /*CompareUnqualified=*/true)) {
2921         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
2922                                            NewProto->getParamType(Idx) };
2923         Warnings.push_back(Warn);
2924         ArgTypes.push_back(NewParm->getType());
2925       } else
2926         LooseCompatible = false;
2927     }
2928 
2929     if (LooseCompatible) {
2930       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2931         Diag(Warnings[Warn].NewParm->getLocation(),
2932              diag::ext_param_promoted_not_compatible_with_prototype)
2933           << Warnings[Warn].PromotedType
2934           << Warnings[Warn].OldParm->getType();
2935         if (Warnings[Warn].OldParm->getLocation().isValid())
2936           Diag(Warnings[Warn].OldParm->getLocation(),
2937                diag::note_previous_declaration);
2938       }
2939 
2940       if (MergeTypeWithOld)
2941         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2942                                              OldProto->getExtProtoInfo()));
2943       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2944     }
2945 
2946     // Fall through to diagnose conflicting types.
2947   }
2948 
2949   // A function that has already been declared has been redeclared or
2950   // defined with a different type; show an appropriate diagnostic.
2951 
2952   // If the previous declaration was an implicitly-generated builtin
2953   // declaration, then at the very least we should use a specialized note.
2954   unsigned BuiltinID;
2955   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2956     // If it's actually a library-defined builtin function like 'malloc'
2957     // or 'printf', just warn about the incompatible redeclaration.
2958     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2959       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2960       Diag(OldLocation, diag::note_previous_builtin_declaration)
2961         << Old << Old->getType();
2962 
2963       // If this is a global redeclaration, just forget hereafter
2964       // about the "builtin-ness" of the function.
2965       //
2966       // Doing this for local extern declarations is problematic.  If
2967       // the builtin declaration remains visible, a second invalid
2968       // local declaration will produce a hard error; if it doesn't
2969       // remain visible, a single bogus local redeclaration (which is
2970       // actually only a warning) could break all the downstream code.
2971       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
2972         New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2973 
2974       return false;
2975     }
2976 
2977     PrevDiag = diag::note_previous_builtin_declaration;
2978   }
2979 
2980   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
2981   Diag(OldLocation, PrevDiag) << Old << Old->getType();
2982   return true;
2983 }
2984 
2985 /// \brief Completes the merge of two function declarations that are
2986 /// known to be compatible.
2987 ///
2988 /// This routine handles the merging of attributes and other
2989 /// properties of function declarations from the old declaration to
2990 /// the new declaration, once we know that New is in fact a
2991 /// redeclaration of Old.
2992 ///
2993 /// \returns false
2994 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2995                                         Scope *S, bool MergeTypeWithOld) {
2996   // Merge the attributes
2997   mergeDeclAttributes(New, Old);
2998 
2999   // Merge "pure" flag.
3000   if (Old->isPure())
3001     New->setPure();
3002 
3003   // Merge "used" flag.
3004   if (Old->getMostRecentDecl()->isUsed(false))
3005     New->setIsUsed();
3006 
3007   // Merge attributes from the parameters.  These can mismatch with K&R
3008   // declarations.
3009   if (New->getNumParams() == Old->getNumParams())
3010     for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
3011       mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
3012                                *this);
3013 
3014   if (getLangOpts().CPlusPlus)
3015     return MergeCXXFunctionDecl(New, Old, S);
3016 
3017   // Merge the function types so the we get the composite types for the return
3018   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3019   // was visible.
3020   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3021   if (!Merged.isNull() && MergeTypeWithOld)
3022     New->setType(Merged);
3023 
3024   return false;
3025 }
3026 
3027 
3028 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3029                                 ObjCMethodDecl *oldMethod) {
3030 
3031   // Merge the attributes, including deprecated/unavailable
3032   AvailabilityMergeKind MergeKind =
3033     isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3034                                                    : AMK_Override;
3035   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3036 
3037   // Merge attributes from the parameters.
3038   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3039                                        oe = oldMethod->param_end();
3040   for (ObjCMethodDecl::param_iterator
3041          ni = newMethod->param_begin(), ne = newMethod->param_end();
3042        ni != ne && oi != oe; ++ni, ++oi)
3043     mergeParamDeclAttributes(*ni, *oi, *this);
3044 
3045   CheckObjCMethodOverride(newMethod, oldMethod);
3046 }
3047 
3048 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3049 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3050 /// emitting diagnostics as appropriate.
3051 ///
3052 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3053 /// to here in AddInitializerToDecl. We can't check them before the initializer
3054 /// is attached.
3055 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3056                              bool MergeTypeWithOld) {
3057   if (New->isInvalidDecl() || Old->isInvalidDecl())
3058     return;
3059 
3060   QualType MergedT;
3061   if (getLangOpts().CPlusPlus) {
3062     if (New->getType()->isUndeducedType()) {
3063       // We don't know what the new type is until the initializer is attached.
3064       return;
3065     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3066       // These could still be something that needs exception specs checked.
3067       return MergeVarDeclExceptionSpecs(New, Old);
3068     }
3069     // C++ [basic.link]p10:
3070     //   [...] the types specified by all declarations referring to a given
3071     //   object or function shall be identical, except that declarations for an
3072     //   array object can specify array types that differ by the presence or
3073     //   absence of a major array bound (8.3.4).
3074     else if (Old->getType()->isIncompleteArrayType() &&
3075              New->getType()->isArrayType()) {
3076       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3077       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3078       if (Context.hasSameType(OldArray->getElementType(),
3079                               NewArray->getElementType()))
3080         MergedT = New->getType();
3081     } else if (Old->getType()->isArrayType() &&
3082                New->getType()->isIncompleteArrayType()) {
3083       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3084       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3085       if (Context.hasSameType(OldArray->getElementType(),
3086                               NewArray->getElementType()))
3087         MergedT = Old->getType();
3088     } else if (New->getType()->isObjCObjectPointerType() &&
3089                Old->getType()->isObjCObjectPointerType()) {
3090       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3091                                               Old->getType());
3092     }
3093   } else {
3094     // C 6.2.7p2:
3095     //   All declarations that refer to the same object or function shall have
3096     //   compatible type.
3097     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3098   }
3099   if (MergedT.isNull()) {
3100     // It's OK if we couldn't merge types if either type is dependent, for a
3101     // block-scope variable. In other cases (static data members of class
3102     // templates, variable templates, ...), we require the types to be
3103     // equivalent.
3104     // FIXME: The C++ standard doesn't say anything about this.
3105     if ((New->getType()->isDependentType() ||
3106          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3107       // If the old type was dependent, we can't merge with it, so the new type
3108       // becomes dependent for now. We'll reproduce the original type when we
3109       // instantiate the TypeSourceInfo for the variable.
3110       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3111         New->setType(Context.DependentTy);
3112       return;
3113     }
3114 
3115     // FIXME: Even if this merging succeeds, some other non-visible declaration
3116     // of this variable might have an incompatible type. For instance:
3117     //
3118     //   extern int arr[];
3119     //   void f() { extern int arr[2]; }
3120     //   void g() { extern int arr[3]; }
3121     //
3122     // Neither C nor C++ requires a diagnostic for this, but we should still try
3123     // to diagnose it.
3124     Diag(New->getLocation(), diag::err_redefinition_different_type)
3125       << New->getDeclName() << New->getType() << Old->getType();
3126     Diag(Old->getLocation(), diag::note_previous_definition);
3127     return New->setInvalidDecl();
3128   }
3129 
3130   // Don't actually update the type on the new declaration if the old
3131   // declaration was an extern declaration in a different scope.
3132   if (MergeTypeWithOld)
3133     New->setType(MergedT);
3134 }
3135 
3136 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3137                                   LookupResult &Previous) {
3138   // C11 6.2.7p4:
3139   //   For an identifier with internal or external linkage declared
3140   //   in a scope in which a prior declaration of that identifier is
3141   //   visible, if the prior declaration specifies internal or
3142   //   external linkage, the type of the identifier at the later
3143   //   declaration becomes the composite type.
3144   //
3145   // If the variable isn't visible, we do not merge with its type.
3146   if (Previous.isShadowed())
3147     return false;
3148 
3149   if (S.getLangOpts().CPlusPlus) {
3150     // C++11 [dcl.array]p3:
3151     //   If there is a preceding declaration of the entity in the same
3152     //   scope in which the bound was specified, an omitted array bound
3153     //   is taken to be the same as in that earlier declaration.
3154     return NewVD->isPreviousDeclInSameBlockScope() ||
3155            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3156             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3157   } else {
3158     // If the old declaration was function-local, don't merge with its
3159     // type unless we're in the same function.
3160     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3161            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3162   }
3163 }
3164 
3165 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3166 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3167 /// situation, merging decls or emitting diagnostics as appropriate.
3168 ///
3169 /// Tentative definition rules (C99 6.9.2p2) are checked by
3170 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3171 /// definitions here, since the initializer hasn't been attached.
3172 ///
3173 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3174   // If the new decl is already invalid, don't do any other checking.
3175   if (New->isInvalidDecl())
3176     return;
3177 
3178   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3179 
3180   // Verify the old decl was also a variable or variable template.
3181   VarDecl *Old = nullptr;
3182   VarTemplateDecl *OldTemplate = nullptr;
3183   if (Previous.isSingleResult()) {
3184     if (NewTemplate) {
3185       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3186       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3187     } else
3188       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3189   }
3190   if (!Old) {
3191     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3192       << New->getDeclName();
3193     Diag(Previous.getRepresentativeDecl()->getLocation(),
3194          diag::note_previous_definition);
3195     return New->setInvalidDecl();
3196   }
3197 
3198   if (!shouldLinkPossiblyHiddenDecl(Old, New))
3199     return;
3200 
3201   // Ensure the template parameters are compatible.
3202   if (NewTemplate &&
3203       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3204                                       OldTemplate->getTemplateParameters(),
3205                                       /*Complain=*/true, TPL_TemplateMatch))
3206     return;
3207 
3208   // C++ [class.mem]p1:
3209   //   A member shall not be declared twice in the member-specification [...]
3210   //
3211   // Here, we need only consider static data members.
3212   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3213     Diag(New->getLocation(), diag::err_duplicate_member)
3214       << New->getIdentifier();
3215     Diag(Old->getLocation(), diag::note_previous_declaration);
3216     New->setInvalidDecl();
3217   }
3218 
3219   mergeDeclAttributes(New, Old);
3220   // Warn if an already-declared variable is made a weak_import in a subsequent
3221   // declaration
3222   if (New->hasAttr<WeakImportAttr>() &&
3223       Old->getStorageClass() == SC_None &&
3224       !Old->hasAttr<WeakImportAttr>()) {
3225     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3226     Diag(Old->getLocation(), diag::note_previous_definition);
3227     // Remove weak_import attribute on new declaration.
3228     New->dropAttr<WeakImportAttr>();
3229   }
3230 
3231   // Merge the types.
3232   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3233 
3234   if (New->isInvalidDecl())
3235     return;
3236 
3237   diag::kind PrevDiag;
3238   SourceLocation OldLocation;
3239   std::tie(PrevDiag, OldLocation) =
3240       getNoteDiagForInvalidRedeclaration(Old, New);
3241 
3242   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3243   if (New->getStorageClass() == SC_Static &&
3244       !New->isStaticDataMember() &&
3245       Old->hasExternalFormalLinkage()) {
3246     if (getLangOpts().MicrosoftExt) {
3247       Diag(New->getLocation(), diag::ext_static_non_static)
3248           << New->getDeclName();
3249       Diag(OldLocation, PrevDiag);
3250     } else {
3251       Diag(New->getLocation(), diag::err_static_non_static)
3252           << New->getDeclName();
3253       Diag(OldLocation, PrevDiag);
3254       return New->setInvalidDecl();
3255     }
3256   }
3257   // C99 6.2.2p4:
3258   //   For an identifier declared with the storage-class specifier
3259   //   extern in a scope in which a prior declaration of that
3260   //   identifier is visible,23) if the prior declaration specifies
3261   //   internal or external linkage, the linkage of the identifier at
3262   //   the later declaration is the same as the linkage specified at
3263   //   the prior declaration. If no prior declaration is visible, or
3264   //   if the prior declaration specifies no linkage, then the
3265   //   identifier has external linkage.
3266   if (New->hasExternalStorage() && Old->hasLinkage())
3267     /* Okay */;
3268   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3269            !New->isStaticDataMember() &&
3270            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3271     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3272     Diag(OldLocation, PrevDiag);
3273     return New->setInvalidDecl();
3274   }
3275 
3276   // Check if extern is followed by non-extern and vice-versa.
3277   if (New->hasExternalStorage() &&
3278       !Old->hasLinkage() && Old->isLocalVarDecl()) {
3279     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3280     Diag(OldLocation, PrevDiag);
3281     return New->setInvalidDecl();
3282   }
3283   if (Old->hasLinkage() && New->isLocalVarDecl() &&
3284       !New->hasExternalStorage()) {
3285     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3286     Diag(OldLocation, PrevDiag);
3287     return New->setInvalidDecl();
3288   }
3289 
3290   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3291 
3292   // FIXME: The test for external storage here seems wrong? We still
3293   // need to check for mismatches.
3294   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3295       // Don't complain about out-of-line definitions of static members.
3296       !(Old->getLexicalDeclContext()->isRecord() &&
3297         !New->getLexicalDeclContext()->isRecord())) {
3298     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3299     Diag(OldLocation, PrevDiag);
3300     return New->setInvalidDecl();
3301   }
3302 
3303   if (New->getTLSKind() != Old->getTLSKind()) {
3304     if (!Old->getTLSKind()) {
3305       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3306       Diag(OldLocation, PrevDiag);
3307     } else if (!New->getTLSKind()) {
3308       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3309       Diag(OldLocation, PrevDiag);
3310     } else {
3311       // Do not allow redeclaration to change the variable between requiring
3312       // static and dynamic initialization.
3313       // FIXME: GCC allows this, but uses the TLS keyword on the first
3314       // declaration to determine the kind. Do we need to be compatible here?
3315       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3316         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3317       Diag(OldLocation, PrevDiag);
3318     }
3319   }
3320 
3321   // C++ doesn't have tentative definitions, so go right ahead and check here.
3322   const VarDecl *Def;
3323   if (getLangOpts().CPlusPlus &&
3324       New->isThisDeclarationADefinition() == VarDecl::Definition &&
3325       (Def = Old->getDefinition())) {
3326     Diag(New->getLocation(), diag::err_redefinition) << New;
3327     Diag(Def->getLocation(), diag::note_previous_definition);
3328     New->setInvalidDecl();
3329     return;
3330   }
3331 
3332   if (haveIncompatibleLanguageLinkages(Old, New)) {
3333     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3334     Diag(OldLocation, PrevDiag);
3335     New->setInvalidDecl();
3336     return;
3337   }
3338 
3339   // Merge "used" flag.
3340   if (Old->getMostRecentDecl()->isUsed(false))
3341     New->setIsUsed();
3342 
3343   // Keep a chain of previous declarations.
3344   New->setPreviousDecl(Old);
3345   if (NewTemplate)
3346     NewTemplate->setPreviousDecl(OldTemplate);
3347 
3348   // Inherit access appropriately.
3349   New->setAccess(Old->getAccess());
3350   if (NewTemplate)
3351     NewTemplate->setAccess(New->getAccess());
3352 }
3353 
3354 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3355 /// no declarator (e.g. "struct foo;") is parsed.
3356 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3357                                        DeclSpec &DS) {
3358   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
3359 }
3360 
3361 static void HandleTagNumbering(Sema &S, const TagDecl *Tag, Scope *TagScope) {
3362   if (!S.Context.getLangOpts().CPlusPlus)
3363     return;
3364 
3365   if (isa<CXXRecordDecl>(Tag->getParent())) {
3366     // If this tag is the direct child of a class, number it if
3367     // it is anonymous.
3368     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3369       return;
3370     MangleNumberingContext &MCtx =
3371         S.Context.getManglingNumberContext(Tag->getParent());
3372     S.Context.setManglingNumber(
3373         Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
3374     return;
3375   }
3376 
3377   // If this tag isn't a direct child of a class, number it if it is local.
3378   Decl *ManglingContextDecl;
3379   if (MangleNumberingContext *MCtx =
3380           S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3381                                           ManglingContextDecl)) {
3382     S.Context.setManglingNumber(
3383         Tag,
3384         MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
3385   }
3386 }
3387 
3388 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3389 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3390 /// parameters to cope with template friend declarations.
3391 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3392                                        DeclSpec &DS,
3393                                        MultiTemplateParamsArg TemplateParams,
3394                                        bool IsExplicitInstantiation) {
3395   Decl *TagD = nullptr;
3396   TagDecl *Tag = nullptr;
3397   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3398       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3399       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3400       DS.getTypeSpecType() == DeclSpec::TST_union ||
3401       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3402     TagD = DS.getRepAsDecl();
3403 
3404     if (!TagD) // We probably had an error
3405       return nullptr;
3406 
3407     // Note that the above type specs guarantee that the
3408     // type rep is a Decl, whereas in many of the others
3409     // it's a Type.
3410     if (isa<TagDecl>(TagD))
3411       Tag = cast<TagDecl>(TagD);
3412     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3413       Tag = CTD->getTemplatedDecl();
3414   }
3415 
3416   if (Tag) {
3417     HandleTagNumbering(*this, Tag, S);
3418     Tag->setFreeStanding();
3419     if (Tag->isInvalidDecl())
3420       return Tag;
3421   }
3422 
3423   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3424     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3425     // or incomplete types shall not be restrict-qualified."
3426     if (TypeQuals & DeclSpec::TQ_restrict)
3427       Diag(DS.getRestrictSpecLoc(),
3428            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3429            << DS.getSourceRange();
3430   }
3431 
3432   if (DS.isConstexprSpecified()) {
3433     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3434     // and definitions of functions and variables.
3435     if (Tag)
3436       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3437         << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3438             DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3439             DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3440             DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
3441     else
3442       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3443     // Don't emit warnings after this error.
3444     return TagD;
3445   }
3446 
3447   DiagnoseFunctionSpecifiers(DS);
3448 
3449   if (DS.isFriendSpecified()) {
3450     // If we're dealing with a decl but not a TagDecl, assume that
3451     // whatever routines created it handled the friendship aspect.
3452     if (TagD && !Tag)
3453       return nullptr;
3454     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3455   }
3456 
3457   CXXScopeSpec &SS = DS.getTypeSpecScope();
3458   bool IsExplicitSpecialization =
3459     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3460   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3461       !IsExplicitInstantiation && !IsExplicitSpecialization) {
3462     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3463     // nested-name-specifier unless it is an explicit instantiation
3464     // or an explicit specialization.
3465     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3466     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3467       << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3468           DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3469           DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3470           DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3471       << SS.getRange();
3472     return nullptr;
3473   }
3474 
3475   // Track whether this decl-specifier declares anything.
3476   bool DeclaresAnything = true;
3477 
3478   // Handle anonymous struct definitions.
3479   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3480     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3481         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3482       if (getLangOpts().CPlusPlus ||
3483           Record->getDeclContext()->isRecord())
3484         return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy());
3485 
3486       DeclaresAnything = false;
3487     }
3488   }
3489 
3490   // C11 6.7.2.1p2:
3491   //   A struct-declaration that does not declare an anonymous structure or
3492   //   anonymous union shall contain a struct-declarator-list.
3493   //
3494   // This rule also existed in C89 and C99; the grammar for struct-declaration
3495   // did not permit a struct-declaration without a struct-declarator-list.
3496   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3497       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3498     // Check for Microsoft C extension: anonymous struct/union member.
3499     // Handle 2 kinds of anonymous struct/union:
3500     //   struct STRUCT;
3501     //   union UNION;
3502     // and
3503     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3504     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
3505     if ((Tag && Tag->getDeclName()) ||
3506         DS.getTypeSpecType() == DeclSpec::TST_typename) {
3507       RecordDecl *Record = nullptr;
3508       if (Tag)
3509         Record = dyn_cast<RecordDecl>(Tag);
3510       else if (const RecordType *RT =
3511                    DS.getRepAsType().get()->getAsStructureType())
3512         Record = RT->getDecl();
3513       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3514         Record = UT->getDecl();
3515 
3516       if (Record && getLangOpts().MicrosoftExt) {
3517         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3518           << Record->isUnion() << DS.getSourceRange();
3519         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3520       }
3521 
3522       DeclaresAnything = false;
3523     }
3524   }
3525 
3526   // Skip all the checks below if we have a type error.
3527   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3528       (TagD && TagD->isInvalidDecl()))
3529     return TagD;
3530 
3531   if (getLangOpts().CPlusPlus &&
3532       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3533     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3534       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3535           !Enum->getIdentifier() && !Enum->isInvalidDecl())
3536         DeclaresAnything = false;
3537 
3538   if (!DS.isMissingDeclaratorOk()) {
3539     // Customize diagnostic for a typedef missing a name.
3540     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3541       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3542         << DS.getSourceRange();
3543     else
3544       DeclaresAnything = false;
3545   }
3546 
3547   if (DS.isModulePrivateSpecified() &&
3548       Tag && Tag->getDeclContext()->isFunctionOrMethod())
3549     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3550       << Tag->getTagKind()
3551       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3552 
3553   ActOnDocumentableDecl(TagD);
3554 
3555   // C 6.7/2:
3556   //   A declaration [...] shall declare at least a declarator [...], a tag,
3557   //   or the members of an enumeration.
3558   // C++ [dcl.dcl]p3:
3559   //   [If there are no declarators], and except for the declaration of an
3560   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
3561   //   names into the program, or shall redeclare a name introduced by a
3562   //   previous declaration.
3563   if (!DeclaresAnything) {
3564     // In C, we allow this as a (popular) extension / bug. Don't bother
3565     // producing further diagnostics for redundant qualifiers after this.
3566     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3567     return TagD;
3568   }
3569 
3570   // C++ [dcl.stc]p1:
3571   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3572   //   init-declarator-list of the declaration shall not be empty.
3573   // C++ [dcl.fct.spec]p1:
3574   //   If a cv-qualifier appears in a decl-specifier-seq, the
3575   //   init-declarator-list of the declaration shall not be empty.
3576   //
3577   // Spurious qualifiers here appear to be valid in C.
3578   unsigned DiagID = diag::warn_standalone_specifier;
3579   if (getLangOpts().CPlusPlus)
3580     DiagID = diag::ext_standalone_specifier;
3581 
3582   // Note that a linkage-specification sets a storage class, but
3583   // 'extern "C" struct foo;' is actually valid and not theoretically
3584   // useless.
3585   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3586     if (SCS == DeclSpec::SCS_mutable)
3587       // Since mutable is not a viable storage class specifier in C, there is
3588       // no reason to treat it as an extension. Instead, diagnose as an error.
3589       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
3590     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3591       Diag(DS.getStorageClassSpecLoc(), DiagID)
3592         << DeclSpec::getSpecifierName(SCS);
3593   }
3594 
3595   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3596     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3597       << DeclSpec::getSpecifierName(TSCS);
3598   if (DS.getTypeQualifiers()) {
3599     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3600       Diag(DS.getConstSpecLoc(), DiagID) << "const";
3601     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3602       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3603     // Restrict is covered above.
3604     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3605       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3606   }
3607 
3608   // Warn about ignored type attributes, for example:
3609   // __attribute__((aligned)) struct A;
3610   // Attributes should be placed after tag to apply to type declaration.
3611   if (!DS.getAttributes().empty()) {
3612     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3613     if (TypeSpecType == DeclSpec::TST_class ||
3614         TypeSpecType == DeclSpec::TST_struct ||
3615         TypeSpecType == DeclSpec::TST_interface ||
3616         TypeSpecType == DeclSpec::TST_union ||
3617         TypeSpecType == DeclSpec::TST_enum) {
3618       AttributeList* attrs = DS.getAttributes().getList();
3619       while (attrs) {
3620         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
3621         << attrs->getName()
3622         << (TypeSpecType == DeclSpec::TST_class ? 0 :
3623             TypeSpecType == DeclSpec::TST_struct ? 1 :
3624             TypeSpecType == DeclSpec::TST_union ? 2 :
3625             TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
3626         attrs = attrs->getNext();
3627       }
3628     }
3629   }
3630 
3631   return TagD;
3632 }
3633 
3634 /// We are trying to inject an anonymous member into the given scope;
3635 /// check if there's an existing declaration that can't be overloaded.
3636 ///
3637 /// \return true if this is a forbidden redeclaration
3638 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3639                                          Scope *S,
3640                                          DeclContext *Owner,
3641                                          DeclarationName Name,
3642                                          SourceLocation NameLoc,
3643                                          unsigned diagnostic) {
3644   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3645                  Sema::ForRedeclaration);
3646   if (!SemaRef.LookupName(R, S)) return false;
3647 
3648   if (R.getAsSingle<TagDecl>())
3649     return false;
3650 
3651   // Pick a representative declaration.
3652   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
3653   assert(PrevDecl && "Expected a non-null Decl");
3654 
3655   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3656     return false;
3657 
3658   SemaRef.Diag(NameLoc, diagnostic) << Name;
3659   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3660 
3661   return true;
3662 }
3663 
3664 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
3665 /// anonymous struct or union AnonRecord into the owning context Owner
3666 /// and scope S. This routine will be invoked just after we realize
3667 /// that an unnamed union or struct is actually an anonymous union or
3668 /// struct, e.g.,
3669 ///
3670 /// @code
3671 /// union {
3672 ///   int i;
3673 ///   float f;
3674 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3675 ///    // f into the surrounding scope.x
3676 /// @endcode
3677 ///
3678 /// This routine is recursive, injecting the names of nested anonymous
3679 /// structs/unions into the owning context and scope as well.
3680 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
3681                                          DeclContext *Owner,
3682                                          RecordDecl *AnonRecord,
3683                                          AccessSpecifier AS,
3684                                          SmallVectorImpl<NamedDecl *> &Chaining,
3685                                          bool MSAnonStruct) {
3686   unsigned diagKind
3687     = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3688                             : diag::err_anonymous_struct_member_redecl;
3689 
3690   bool Invalid = false;
3691 
3692   // Look every FieldDecl and IndirectFieldDecl with a name.
3693   for (auto *D : AnonRecord->decls()) {
3694     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
3695         cast<NamedDecl>(D)->getDeclName()) {
3696       ValueDecl *VD = cast<ValueDecl>(D);
3697       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3698                                        VD->getLocation(), diagKind)) {
3699         // C++ [class.union]p2:
3700         //   The names of the members of an anonymous union shall be
3701         //   distinct from the names of any other entity in the
3702         //   scope in which the anonymous union is declared.
3703         Invalid = true;
3704       } else {
3705         // C++ [class.union]p2:
3706         //   For the purpose of name lookup, after the anonymous union
3707         //   definition, the members of the anonymous union are
3708         //   considered to have been defined in the scope in which the
3709         //   anonymous union is declared.
3710         unsigned OldChainingSize = Chaining.size();
3711         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3712           for (auto *PI : IF->chain())
3713             Chaining.push_back(PI);
3714         else
3715           Chaining.push_back(VD);
3716 
3717         assert(Chaining.size() >= 2);
3718         NamedDecl **NamedChain =
3719           new (SemaRef.Context)NamedDecl*[Chaining.size()];
3720         for (unsigned i = 0; i < Chaining.size(); i++)
3721           NamedChain[i] = Chaining[i];
3722 
3723         IndirectFieldDecl* IndirectField =
3724           IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3725                                     VD->getIdentifier(), VD->getType(),
3726                                     NamedChain, Chaining.size());
3727 
3728         IndirectField->setAccess(AS);
3729         IndirectField->setImplicit();
3730         SemaRef.PushOnScopeChains(IndirectField, S);
3731 
3732         // That includes picking up the appropriate access specifier.
3733         if (AS != AS_none) IndirectField->setAccess(AS);
3734 
3735         Chaining.resize(OldChainingSize);
3736       }
3737     }
3738   }
3739 
3740   return Invalid;
3741 }
3742 
3743 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3744 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
3745 /// illegal input values are mapped to SC_None.
3746 static StorageClass
3747 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3748   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3749   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3750          "Parser allowed 'typedef' as storage class VarDecl.");
3751   switch (StorageClassSpec) {
3752   case DeclSpec::SCS_unspecified:    return SC_None;
3753   case DeclSpec::SCS_extern:
3754     if (DS.isExternInLinkageSpec())
3755       return SC_None;
3756     return SC_Extern;
3757   case DeclSpec::SCS_static:         return SC_Static;
3758   case DeclSpec::SCS_auto:           return SC_Auto;
3759   case DeclSpec::SCS_register:       return SC_Register;
3760   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
3761     // Illegal SCSs map to None: error reporting is up to the caller.
3762   case DeclSpec::SCS_mutable:        // Fall through.
3763   case DeclSpec::SCS_typedef:        return SC_None;
3764   }
3765   llvm_unreachable("unknown storage class specifier");
3766 }
3767 
3768 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
3769   assert(Record->hasInClassInitializer());
3770 
3771   for (const auto *I : Record->decls()) {
3772     const auto *FD = dyn_cast<FieldDecl>(I);
3773     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
3774       FD = IFD->getAnonField();
3775     if (FD && FD->hasInClassInitializer())
3776       return FD->getLocation();
3777   }
3778 
3779   llvm_unreachable("couldn't find in-class initializer");
3780 }
3781 
3782 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3783                                       SourceLocation DefaultInitLoc) {
3784   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3785     return;
3786 
3787   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
3788   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
3789 }
3790 
3791 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3792                                       CXXRecordDecl *AnonUnion) {
3793   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3794     return;
3795 
3796   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
3797 }
3798 
3799 /// BuildAnonymousStructOrUnion - Handle the declaration of an
3800 /// anonymous structure or union. Anonymous unions are a C++ feature
3801 /// (C++ [class.union]) and a C11 feature; anonymous structures
3802 /// are a C11 feature and GNU C++ extension.
3803 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3804                                         AccessSpecifier AS,
3805                                         RecordDecl *Record,
3806                                         const PrintingPolicy &Policy) {
3807   DeclContext *Owner = Record->getDeclContext();
3808 
3809   // Diagnose whether this anonymous struct/union is an extension.
3810   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
3811     Diag(Record->getLocation(), diag::ext_anonymous_union);
3812   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
3813     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
3814   else if (!Record->isUnion() && !getLangOpts().C11)
3815     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
3816 
3817   // C and C++ require different kinds of checks for anonymous
3818   // structs/unions.
3819   bool Invalid = false;
3820   if (getLangOpts().CPlusPlus) {
3821     const char *PrevSpec = nullptr;
3822     unsigned DiagID;
3823     if (Record->isUnion()) {
3824       // C++ [class.union]p6:
3825       //   Anonymous unions declared in a named namespace or in the
3826       //   global namespace shall be declared static.
3827       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3828           (isa<TranslationUnitDecl>(Owner) ||
3829            (isa<NamespaceDecl>(Owner) &&
3830             cast<NamespaceDecl>(Owner)->getDeclName()))) {
3831         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3832           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
3833 
3834         // Recover by adding 'static'.
3835         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3836                                PrevSpec, DiagID, Policy);
3837       }
3838       // C++ [class.union]p6:
3839       //   A storage class is not allowed in a declaration of an
3840       //   anonymous union in a class scope.
3841       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3842                isa<RecordDecl>(Owner)) {
3843         Diag(DS.getStorageClassSpecLoc(),
3844              diag::err_anonymous_union_with_storage_spec)
3845           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3846 
3847         // Recover by removing the storage specifier.
3848         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3849                                SourceLocation(),
3850                                PrevSpec, DiagID, Context.getPrintingPolicy());
3851       }
3852     }
3853 
3854     // Ignore const/volatile/restrict qualifiers.
3855     if (DS.getTypeQualifiers()) {
3856       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3857         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
3858           << Record->isUnion() << "const"
3859           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3860       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3861         Diag(DS.getVolatileSpecLoc(),
3862              diag::ext_anonymous_struct_union_qualified)
3863           << Record->isUnion() << "volatile"
3864           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3865       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
3866         Diag(DS.getRestrictSpecLoc(),
3867              diag::ext_anonymous_struct_union_qualified)
3868           << Record->isUnion() << "restrict"
3869           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
3870       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3871         Diag(DS.getAtomicSpecLoc(),
3872              diag::ext_anonymous_struct_union_qualified)
3873           << Record->isUnion() << "_Atomic"
3874           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
3875 
3876       DS.ClearTypeQualifiers();
3877     }
3878 
3879     // C++ [class.union]p2:
3880     //   The member-specification of an anonymous union shall only
3881     //   define non-static data members. [Note: nested types and
3882     //   functions cannot be declared within an anonymous union. ]
3883     for (auto *Mem : Record->decls()) {
3884       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
3885         // C++ [class.union]p3:
3886         //   An anonymous union shall not have private or protected
3887         //   members (clause 11).
3888         assert(FD->getAccess() != AS_none);
3889         if (FD->getAccess() != AS_public) {
3890           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3891             << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3892           Invalid = true;
3893         }
3894 
3895         // C++ [class.union]p1
3896         //   An object of a class with a non-trivial constructor, a non-trivial
3897         //   copy constructor, a non-trivial destructor, or a non-trivial copy
3898         //   assignment operator cannot be a member of a union, nor can an
3899         //   array of such objects.
3900         if (CheckNontrivialField(FD))
3901           Invalid = true;
3902       } else if (Mem->isImplicit()) {
3903         // Any implicit members are fine.
3904       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
3905         // This is a type that showed up in an
3906         // elaborated-type-specifier inside the anonymous struct or
3907         // union, but which actually declares a type outside of the
3908         // anonymous struct or union. It's okay.
3909       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
3910         if (!MemRecord->isAnonymousStructOrUnion() &&
3911             MemRecord->getDeclName()) {
3912           // Visual C++ allows type definition in anonymous struct or union.
3913           if (getLangOpts().MicrosoftExt)
3914             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3915               << (int)Record->isUnion();
3916           else {
3917             // This is a nested type declaration.
3918             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3919               << (int)Record->isUnion();
3920             Invalid = true;
3921           }
3922         } else {
3923           // This is an anonymous type definition within another anonymous type.
3924           // This is a popular extension, provided by Plan9, MSVC and GCC, but
3925           // not part of standard C++.
3926           Diag(MemRecord->getLocation(),
3927                diag::ext_anonymous_record_with_anonymous_type)
3928             << (int)Record->isUnion();
3929         }
3930       } else if (isa<AccessSpecDecl>(Mem)) {
3931         // Any access specifier is fine.
3932       } else if (isa<StaticAssertDecl>(Mem)) {
3933         // In C++1z, static_assert declarations are also fine.
3934       } else {
3935         // We have something that isn't a non-static data
3936         // member. Complain about it.
3937         unsigned DK = diag::err_anonymous_record_bad_member;
3938         if (isa<TypeDecl>(Mem))
3939           DK = diag::err_anonymous_record_with_type;
3940         else if (isa<FunctionDecl>(Mem))
3941           DK = diag::err_anonymous_record_with_function;
3942         else if (isa<VarDecl>(Mem))
3943           DK = diag::err_anonymous_record_with_static;
3944 
3945         // Visual C++ allows type definition in anonymous struct or union.
3946         if (getLangOpts().MicrosoftExt &&
3947             DK == diag::err_anonymous_record_with_type)
3948           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
3949             << (int)Record->isUnion();
3950         else {
3951           Diag(Mem->getLocation(), DK)
3952               << (int)Record->isUnion();
3953           Invalid = true;
3954         }
3955       }
3956     }
3957 
3958     // C++11 [class.union]p8 (DR1460):
3959     //   At most one variant member of a union may have a
3960     //   brace-or-equal-initializer.
3961     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
3962         Owner->isRecord())
3963       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
3964                                 cast<CXXRecordDecl>(Record));
3965   }
3966 
3967   if (!Record->isUnion() && !Owner->isRecord()) {
3968     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
3969       << (int)getLangOpts().CPlusPlus;
3970     Invalid = true;
3971   }
3972 
3973   // Mock up a declarator.
3974   Declarator Dc(DS, Declarator::MemberContext);
3975   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3976   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
3977 
3978   // Create a declaration for this anonymous struct/union.
3979   NamedDecl *Anon = nullptr;
3980   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
3981     Anon = FieldDecl::Create(Context, OwningClass,
3982                              DS.getLocStart(),
3983                              Record->getLocation(),
3984                              /*IdentifierInfo=*/nullptr,
3985                              Context.getTypeDeclType(Record),
3986                              TInfo,
3987                              /*BitWidth=*/nullptr, /*Mutable=*/false,
3988                              /*InitStyle=*/ICIS_NoInit);
3989     Anon->setAccess(AS);
3990     if (getLangOpts().CPlusPlus)
3991       FieldCollector->Add(cast<FieldDecl>(Anon));
3992   } else {
3993     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
3994     VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
3995     if (SCSpec == DeclSpec::SCS_mutable) {
3996       // mutable can only appear on non-static class members, so it's always
3997       // an error here
3998       Diag(Record->getLocation(), diag::err_mutable_nonmember);
3999       Invalid = true;
4000       SC = SC_None;
4001     }
4002 
4003     Anon = VarDecl::Create(Context, Owner,
4004                            DS.getLocStart(),
4005                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4006                            Context.getTypeDeclType(Record),
4007                            TInfo, SC);
4008 
4009     // Default-initialize the implicit variable. This initialization will be
4010     // trivial in almost all cases, except if a union member has an in-class
4011     // initializer:
4012     //   union { int n = 0; };
4013     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4014   }
4015   Anon->setImplicit();
4016 
4017   // Mark this as an anonymous struct/union type.
4018   Record->setAnonymousStructOrUnion(true);
4019 
4020   // Add the anonymous struct/union object to the current
4021   // context. We'll be referencing this object when we refer to one of
4022   // its members.
4023   Owner->addDecl(Anon);
4024 
4025   // Inject the members of the anonymous struct/union into the owning
4026   // context and into the identifier resolver chain for name lookup
4027   // purposes.
4028   SmallVector<NamedDecl*, 2> Chain;
4029   Chain.push_back(Anon);
4030 
4031   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
4032                                           Chain, false))
4033     Invalid = true;
4034 
4035   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4036     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4037       Decl *ManglingContextDecl;
4038       if (MangleNumberingContext *MCtx =
4039               getCurrentMangleNumberContext(NewVD->getDeclContext(),
4040                                             ManglingContextDecl)) {
4041         Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
4042         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4043       }
4044     }
4045   }
4046 
4047   if (Invalid)
4048     Anon->setInvalidDecl();
4049 
4050   return Anon;
4051 }
4052 
4053 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4054 /// Microsoft C anonymous structure.
4055 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4056 /// Example:
4057 ///
4058 /// struct A { int a; };
4059 /// struct B { struct A; int b; };
4060 ///
4061 /// void foo() {
4062 ///   B var;
4063 ///   var.a = 3;
4064 /// }
4065 ///
4066 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4067                                            RecordDecl *Record) {
4068   assert(Record && "expected a record!");
4069 
4070   // Mock up a declarator.
4071   Declarator Dc(DS, Declarator::TypeNameContext);
4072   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4073   assert(TInfo && "couldn't build declarator info for anonymous struct");
4074 
4075   auto *ParentDecl = cast<RecordDecl>(CurContext);
4076   QualType RecTy = Context.getTypeDeclType(Record);
4077 
4078   // Create a declaration for this anonymous struct.
4079   NamedDecl *Anon = FieldDecl::Create(Context,
4080                              ParentDecl,
4081                              DS.getLocStart(),
4082                              DS.getLocStart(),
4083                              /*IdentifierInfo=*/nullptr,
4084                              RecTy,
4085                              TInfo,
4086                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4087                              /*InitStyle=*/ICIS_NoInit);
4088   Anon->setImplicit();
4089 
4090   // Add the anonymous struct object to the current context.
4091   CurContext->addDecl(Anon);
4092 
4093   // Inject the members of the anonymous struct into the current
4094   // context and into the identifier resolver chain for name lookup
4095   // purposes.
4096   SmallVector<NamedDecl*, 2> Chain;
4097   Chain.push_back(Anon);
4098 
4099   RecordDecl *RecordDef = Record->getDefinition();
4100   if (RequireCompleteType(Anon->getLocation(), RecTy,
4101                           diag::err_field_incomplete) ||
4102       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4103                                           AS_none, Chain, true)) {
4104     Anon->setInvalidDecl();
4105     ParentDecl->setInvalidDecl();
4106   }
4107 
4108   return Anon;
4109 }
4110 
4111 /// GetNameForDeclarator - Determine the full declaration name for the
4112 /// given Declarator.
4113 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4114   return GetNameFromUnqualifiedId(D.getName());
4115 }
4116 
4117 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4118 DeclarationNameInfo
4119 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4120   DeclarationNameInfo NameInfo;
4121   NameInfo.setLoc(Name.StartLocation);
4122 
4123   switch (Name.getKind()) {
4124 
4125   case UnqualifiedId::IK_ImplicitSelfParam:
4126   case UnqualifiedId::IK_Identifier:
4127     NameInfo.setName(Name.Identifier);
4128     NameInfo.setLoc(Name.StartLocation);
4129     return NameInfo;
4130 
4131   case UnqualifiedId::IK_OperatorFunctionId:
4132     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4133                                            Name.OperatorFunctionId.Operator));
4134     NameInfo.setLoc(Name.StartLocation);
4135     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4136       = Name.OperatorFunctionId.SymbolLocations[0];
4137     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4138       = Name.EndLocation.getRawEncoding();
4139     return NameInfo;
4140 
4141   case UnqualifiedId::IK_LiteralOperatorId:
4142     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4143                                                            Name.Identifier));
4144     NameInfo.setLoc(Name.StartLocation);
4145     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4146     return NameInfo;
4147 
4148   case UnqualifiedId::IK_ConversionFunctionId: {
4149     TypeSourceInfo *TInfo;
4150     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4151     if (Ty.isNull())
4152       return DeclarationNameInfo();
4153     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4154                                                Context.getCanonicalType(Ty)));
4155     NameInfo.setLoc(Name.StartLocation);
4156     NameInfo.setNamedTypeInfo(TInfo);
4157     return NameInfo;
4158   }
4159 
4160   case UnqualifiedId::IK_ConstructorName: {
4161     TypeSourceInfo *TInfo;
4162     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4163     if (Ty.isNull())
4164       return DeclarationNameInfo();
4165     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4166                                               Context.getCanonicalType(Ty)));
4167     NameInfo.setLoc(Name.StartLocation);
4168     NameInfo.setNamedTypeInfo(TInfo);
4169     return NameInfo;
4170   }
4171 
4172   case UnqualifiedId::IK_ConstructorTemplateId: {
4173     // In well-formed code, we can only have a constructor
4174     // template-id that refers to the current context, so go there
4175     // to find the actual type being constructed.
4176     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4177     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4178       return DeclarationNameInfo();
4179 
4180     // Determine the type of the class being constructed.
4181     QualType CurClassType = Context.getTypeDeclType(CurClass);
4182 
4183     // FIXME: Check two things: that the template-id names the same type as
4184     // CurClassType, and that the template-id does not occur when the name
4185     // was qualified.
4186 
4187     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4188                                     Context.getCanonicalType(CurClassType)));
4189     NameInfo.setLoc(Name.StartLocation);
4190     // FIXME: should we retrieve TypeSourceInfo?
4191     NameInfo.setNamedTypeInfo(nullptr);
4192     return NameInfo;
4193   }
4194 
4195   case UnqualifiedId::IK_DestructorName: {
4196     TypeSourceInfo *TInfo;
4197     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4198     if (Ty.isNull())
4199       return DeclarationNameInfo();
4200     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4201                                               Context.getCanonicalType(Ty)));
4202     NameInfo.setLoc(Name.StartLocation);
4203     NameInfo.setNamedTypeInfo(TInfo);
4204     return NameInfo;
4205   }
4206 
4207   case UnqualifiedId::IK_TemplateId: {
4208     TemplateName TName = Name.TemplateId->Template.get();
4209     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4210     return Context.getNameForTemplate(TName, TNameLoc);
4211   }
4212 
4213   } // switch (Name.getKind())
4214 
4215   llvm_unreachable("Unknown name kind");
4216 }
4217 
4218 static QualType getCoreType(QualType Ty) {
4219   do {
4220     if (Ty->isPointerType() || Ty->isReferenceType())
4221       Ty = Ty->getPointeeType();
4222     else if (Ty->isArrayType())
4223       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4224     else
4225       return Ty.withoutLocalFastQualifiers();
4226   } while (true);
4227 }
4228 
4229 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4230 /// and Definition have "nearly" matching parameters. This heuristic is
4231 /// used to improve diagnostics in the case where an out-of-line function
4232 /// definition doesn't match any declaration within the class or namespace.
4233 /// Also sets Params to the list of indices to the parameters that differ
4234 /// between the declaration and the definition. If hasSimilarParameters
4235 /// returns true and Params is empty, then all of the parameters match.
4236 static bool hasSimilarParameters(ASTContext &Context,
4237                                      FunctionDecl *Declaration,
4238                                      FunctionDecl *Definition,
4239                                      SmallVectorImpl<unsigned> &Params) {
4240   Params.clear();
4241   if (Declaration->param_size() != Definition->param_size())
4242     return false;
4243   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4244     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4245     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4246 
4247     // The parameter types are identical
4248     if (Context.hasSameType(DefParamTy, DeclParamTy))
4249       continue;
4250 
4251     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4252     QualType DefParamBaseTy = getCoreType(DefParamTy);
4253     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4254     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4255 
4256     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4257         (DeclTyName && DeclTyName == DefTyName))
4258       Params.push_back(Idx);
4259     else  // The two parameters aren't even close
4260       return false;
4261   }
4262 
4263   return true;
4264 }
4265 
4266 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4267 /// declarator needs to be rebuilt in the current instantiation.
4268 /// Any bits of declarator which appear before the name are valid for
4269 /// consideration here.  That's specifically the type in the decl spec
4270 /// and the base type in any member-pointer chunks.
4271 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4272                                                     DeclarationName Name) {
4273   // The types we specifically need to rebuild are:
4274   //   - typenames, typeofs, and decltypes
4275   //   - types which will become injected class names
4276   // Of course, we also need to rebuild any type referencing such a
4277   // type.  It's safest to just say "dependent", but we call out a
4278   // few cases here.
4279 
4280   DeclSpec &DS = D.getMutableDeclSpec();
4281   switch (DS.getTypeSpecType()) {
4282   case DeclSpec::TST_typename:
4283   case DeclSpec::TST_typeofType:
4284   case DeclSpec::TST_underlyingType:
4285   case DeclSpec::TST_atomic: {
4286     // Grab the type from the parser.
4287     TypeSourceInfo *TSI = nullptr;
4288     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4289     if (T.isNull() || !T->isDependentType()) break;
4290 
4291     // Make sure there's a type source info.  This isn't really much
4292     // of a waste; most dependent types should have type source info
4293     // attached already.
4294     if (!TSI)
4295       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4296 
4297     // Rebuild the type in the current instantiation.
4298     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4299     if (!TSI) return true;
4300 
4301     // Store the new type back in the decl spec.
4302     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4303     DS.UpdateTypeRep(LocType);
4304     break;
4305   }
4306 
4307   case DeclSpec::TST_decltype:
4308   case DeclSpec::TST_typeofExpr: {
4309     Expr *E = DS.getRepAsExpr();
4310     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4311     if (Result.isInvalid()) return true;
4312     DS.UpdateExprRep(Result.get());
4313     break;
4314   }
4315 
4316   default:
4317     // Nothing to do for these decl specs.
4318     break;
4319   }
4320 
4321   // It doesn't matter what order we do this in.
4322   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4323     DeclaratorChunk &Chunk = D.getTypeObject(I);
4324 
4325     // The only type information in the declarator which can come
4326     // before the declaration name is the base type of a member
4327     // pointer.
4328     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4329       continue;
4330 
4331     // Rebuild the scope specifier in-place.
4332     CXXScopeSpec &SS = Chunk.Mem.Scope();
4333     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4334       return true;
4335   }
4336 
4337   return false;
4338 }
4339 
4340 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4341   D.setFunctionDefinitionKind(FDK_Declaration);
4342   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4343 
4344   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4345       Dcl && Dcl->getDeclContext()->isFileContext())
4346     Dcl->setTopLevelDeclInObjCContainer();
4347 
4348   return Dcl;
4349 }
4350 
4351 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4352 ///   If T is the name of a class, then each of the following shall have a
4353 ///   name different from T:
4354 ///     - every static data member of class T;
4355 ///     - every member function of class T
4356 ///     - every member of class T that is itself a type;
4357 /// \returns true if the declaration name violates these rules.
4358 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4359                                    DeclarationNameInfo NameInfo) {
4360   DeclarationName Name = NameInfo.getName();
4361 
4362   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4363     if (Record->getIdentifier() && Record->getDeclName() == Name) {
4364       Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4365       return true;
4366     }
4367 
4368   return false;
4369 }
4370 
4371 /// \brief Diagnose a declaration whose declarator-id has the given
4372 /// nested-name-specifier.
4373 ///
4374 /// \param SS The nested-name-specifier of the declarator-id.
4375 ///
4376 /// \param DC The declaration context to which the nested-name-specifier
4377 /// resolves.
4378 ///
4379 /// \param Name The name of the entity being declared.
4380 ///
4381 /// \param Loc The location of the name of the entity being declared.
4382 ///
4383 /// \returns true if we cannot safely recover from this error, false otherwise.
4384 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4385                                         DeclarationName Name,
4386                                         SourceLocation Loc) {
4387   DeclContext *Cur = CurContext;
4388   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4389     Cur = Cur->getParent();
4390 
4391   // If the user provided a superfluous scope specifier that refers back to the
4392   // class in which the entity is already declared, diagnose and ignore it.
4393   //
4394   // class X {
4395   //   void X::f();
4396   // };
4397   //
4398   // Note, it was once ill-formed to give redundant qualification in all
4399   // contexts, but that rule was removed by DR482.
4400   if (Cur->Equals(DC)) {
4401     if (Cur->isRecord()) {
4402       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4403                                       : diag::err_member_extra_qualification)
4404         << Name << FixItHint::CreateRemoval(SS.getRange());
4405       SS.clear();
4406     } else {
4407       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4408     }
4409     return false;
4410   }
4411 
4412   // Check whether the qualifying scope encloses the scope of the original
4413   // declaration.
4414   if (!Cur->Encloses(DC)) {
4415     if (Cur->isRecord())
4416       Diag(Loc, diag::err_member_qualification)
4417         << Name << SS.getRange();
4418     else if (isa<TranslationUnitDecl>(DC))
4419       Diag(Loc, diag::err_invalid_declarator_global_scope)
4420         << Name << SS.getRange();
4421     else if (isa<FunctionDecl>(Cur))
4422       Diag(Loc, diag::err_invalid_declarator_in_function)
4423         << Name << SS.getRange();
4424     else if (isa<BlockDecl>(Cur))
4425       Diag(Loc, diag::err_invalid_declarator_in_block)
4426         << Name << SS.getRange();
4427     else
4428       Diag(Loc, diag::err_invalid_declarator_scope)
4429       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4430 
4431     return true;
4432   }
4433 
4434   if (Cur->isRecord()) {
4435     // Cannot qualify members within a class.
4436     Diag(Loc, diag::err_member_qualification)
4437       << Name << SS.getRange();
4438     SS.clear();
4439 
4440     // C++ constructors and destructors with incorrect scopes can break
4441     // our AST invariants by having the wrong underlying types. If
4442     // that's the case, then drop this declaration entirely.
4443     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4444          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4445         !Context.hasSameType(Name.getCXXNameType(),
4446                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4447       return true;
4448 
4449     return false;
4450   }
4451 
4452   // C++11 [dcl.meaning]p1:
4453   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4454   //   not begin with a decltype-specifer"
4455   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4456   while (SpecLoc.getPrefix())
4457     SpecLoc = SpecLoc.getPrefix();
4458   if (dyn_cast_or_null<DecltypeType>(
4459         SpecLoc.getNestedNameSpecifier()->getAsType()))
4460     Diag(Loc, diag::err_decltype_in_declarator)
4461       << SpecLoc.getTypeLoc().getSourceRange();
4462 
4463   return false;
4464 }
4465 
4466 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4467                                   MultiTemplateParamsArg TemplateParamLists) {
4468   // TODO: consider using NameInfo for diagnostic.
4469   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4470   DeclarationName Name = NameInfo.getName();
4471 
4472   // All of these full declarators require an identifier.  If it doesn't have
4473   // one, the ParsedFreeStandingDeclSpec action should be used.
4474   if (!Name) {
4475     if (!D.isInvalidType())  // Reject this if we think it is valid.
4476       Diag(D.getDeclSpec().getLocStart(),
4477            diag::err_declarator_need_ident)
4478         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4479     return nullptr;
4480   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4481     return nullptr;
4482 
4483   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4484   // we find one that is.
4485   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4486          (S->getFlags() & Scope::TemplateParamScope) != 0)
4487     S = S->getParent();
4488 
4489   DeclContext *DC = CurContext;
4490   if (D.getCXXScopeSpec().isInvalid())
4491     D.setInvalidType();
4492   else if (D.getCXXScopeSpec().isSet()) {
4493     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4494                                         UPPC_DeclarationQualifier))
4495       return nullptr;
4496 
4497     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4498     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4499     if (!DC || isa<EnumDecl>(DC)) {
4500       // If we could not compute the declaration context, it's because the
4501       // declaration context is dependent but does not refer to a class,
4502       // class template, or class template partial specialization. Complain
4503       // and return early, to avoid the coming semantic disaster.
4504       Diag(D.getIdentifierLoc(),
4505            diag::err_template_qualified_declarator_no_match)
4506         << D.getCXXScopeSpec().getScopeRep()
4507         << D.getCXXScopeSpec().getRange();
4508       return nullptr;
4509     }
4510     bool IsDependentContext = DC->isDependentContext();
4511 
4512     if (!IsDependentContext &&
4513         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4514       return nullptr;
4515 
4516     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4517       Diag(D.getIdentifierLoc(),
4518            diag::err_member_def_undefined_record)
4519         << Name << DC << D.getCXXScopeSpec().getRange();
4520       D.setInvalidType();
4521     } else if (!D.getDeclSpec().isFriendSpecified()) {
4522       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4523                                       Name, D.getIdentifierLoc())) {
4524         if (DC->isRecord())
4525           return nullptr;
4526 
4527         D.setInvalidType();
4528       }
4529     }
4530 
4531     // Check whether we need to rebuild the type of the given
4532     // declaration in the current instantiation.
4533     if (EnteringContext && IsDependentContext &&
4534         TemplateParamLists.size() != 0) {
4535       ContextRAII SavedContext(*this, DC);
4536       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4537         D.setInvalidType();
4538     }
4539   }
4540 
4541   if (DiagnoseClassNameShadow(DC, NameInfo))
4542     // If this is a typedef, we'll end up spewing multiple diagnostics.
4543     // Just return early; it's safer.
4544     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4545       return nullptr;
4546 
4547   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4548   QualType R = TInfo->getType();
4549 
4550   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4551                                       UPPC_DeclarationType))
4552     D.setInvalidType();
4553 
4554   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4555                         ForRedeclaration);
4556 
4557   // See if this is a redefinition of a variable in the same scope.
4558   if (!D.getCXXScopeSpec().isSet()) {
4559     bool IsLinkageLookup = false;
4560     bool CreateBuiltins = false;
4561 
4562     // If the declaration we're planning to build will be a function
4563     // or object with linkage, then look for another declaration with
4564     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4565     //
4566     // If the declaration we're planning to build will be declared with
4567     // external linkage in the translation unit, create any builtin with
4568     // the same name.
4569     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4570       /* Do nothing*/;
4571     else if (CurContext->isFunctionOrMethod() &&
4572              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4573               R->isFunctionType())) {
4574       IsLinkageLookup = true;
4575       CreateBuiltins =
4576           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4577     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4578                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4579       CreateBuiltins = true;
4580 
4581     if (IsLinkageLookup)
4582       Previous.clear(LookupRedeclarationWithLinkage);
4583 
4584     LookupName(Previous, S, CreateBuiltins);
4585   } else { // Something like "int foo::x;"
4586     LookupQualifiedName(Previous, DC);
4587 
4588     // C++ [dcl.meaning]p1:
4589     //   When the declarator-id is qualified, the declaration shall refer to a
4590     //  previously declared member of the class or namespace to which the
4591     //  qualifier refers (or, in the case of a namespace, of an element of the
4592     //  inline namespace set of that namespace (7.3.1)) or to a specialization
4593     //  thereof; [...]
4594     //
4595     // Note that we already checked the context above, and that we do not have
4596     // enough information to make sure that Previous contains the declaration
4597     // we want to match. For example, given:
4598     //
4599     //   class X {
4600     //     void f();
4601     //     void f(float);
4602     //   };
4603     //
4604     //   void X::f(int) { } // ill-formed
4605     //
4606     // In this case, Previous will point to the overload set
4607     // containing the two f's declared in X, but neither of them
4608     // matches.
4609 
4610     // C++ [dcl.meaning]p1:
4611     //   [...] the member shall not merely have been introduced by a
4612     //   using-declaration in the scope of the class or namespace nominated by
4613     //   the nested-name-specifier of the declarator-id.
4614     RemoveUsingDecls(Previous);
4615   }
4616 
4617   if (Previous.isSingleResult() &&
4618       Previous.getFoundDecl()->isTemplateParameter()) {
4619     // Maybe we will complain about the shadowed template parameter.
4620     if (!D.isInvalidType())
4621       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4622                                       Previous.getFoundDecl());
4623 
4624     // Just pretend that we didn't see the previous declaration.
4625     Previous.clear();
4626   }
4627 
4628   // In C++, the previous declaration we find might be a tag type
4629   // (class or enum). In this case, the new declaration will hide the
4630   // tag type. Note that this does does not apply if we're declaring a
4631   // typedef (C++ [dcl.typedef]p4).
4632   if (Previous.isSingleTagDecl() &&
4633       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
4634     Previous.clear();
4635 
4636   // Check that there are no default arguments other than in the parameters
4637   // of a function declaration (C++ only).
4638   if (getLangOpts().CPlusPlus)
4639     CheckExtraCXXDefaultArguments(D);
4640 
4641   NamedDecl *New;
4642 
4643   bool AddToScope = true;
4644   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4645     if (TemplateParamLists.size()) {
4646       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
4647       return nullptr;
4648     }
4649 
4650     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
4651   } else if (R->isFunctionType()) {
4652     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
4653                                   TemplateParamLists,
4654                                   AddToScope);
4655   } else {
4656     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4657                                   AddToScope);
4658   }
4659 
4660   if (!New)
4661     return nullptr;
4662 
4663   // If this has an identifier and is not an invalid redeclaration or
4664   // function template specialization, add it to the scope stack.
4665   if (New->getDeclName() && AddToScope &&
4666        !(D.isRedeclaration() && New->isInvalidDecl())) {
4667     // Only make a locally-scoped extern declaration visible if it is the first
4668     // declaration of this entity. Qualified lookup for such an entity should
4669     // only find this declaration if there is no visible declaration of it.
4670     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4671     PushOnScopeChains(New, S, AddToContext);
4672     if (!AddToContext)
4673       CurContext->addHiddenDecl(New);
4674   }
4675 
4676   return New;
4677 }
4678 
4679 /// Helper method to turn variable array types into constant array
4680 /// types in certain situations which would otherwise be errors (for
4681 /// GCC compatibility).
4682 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4683                                                     ASTContext &Context,
4684                                                     bool &SizeIsNegative,
4685                                                     llvm::APSInt &Oversized) {
4686   // This method tries to turn a variable array into a constant
4687   // array even when the size isn't an ICE.  This is necessary
4688   // for compatibility with code that depends on gcc's buggy
4689   // constant expression folding, like struct {char x[(int)(char*)2];}
4690   SizeIsNegative = false;
4691   Oversized = 0;
4692 
4693   if (T->isDependentType())
4694     return QualType();
4695 
4696   QualifierCollector Qs;
4697   const Type *Ty = Qs.strip(T);
4698 
4699   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
4700     QualType Pointee = PTy->getPointeeType();
4701     QualType FixedType =
4702         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4703                                             Oversized);
4704     if (FixedType.isNull()) return FixedType;
4705     FixedType = Context.getPointerType(FixedType);
4706     return Qs.apply(Context, FixedType);
4707   }
4708   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4709     QualType Inner = PTy->getInnerType();
4710     QualType FixedType =
4711         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4712                                             Oversized);
4713     if (FixedType.isNull()) return FixedType;
4714     FixedType = Context.getParenType(FixedType);
4715     return Qs.apply(Context, FixedType);
4716   }
4717 
4718   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
4719   if (!VLATy)
4720     return QualType();
4721   // FIXME: We should probably handle this case
4722   if (VLATy->getElementType()->isVariablyModifiedType())
4723     return QualType();
4724 
4725   llvm::APSInt Res;
4726   if (!VLATy->getSizeExpr() ||
4727       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
4728     return QualType();
4729 
4730   // Check whether the array size is negative.
4731   if (Res.isSigned() && Res.isNegative()) {
4732     SizeIsNegative = true;
4733     return QualType();
4734   }
4735 
4736   // Check whether the array is too large to be addressed.
4737   unsigned ActiveSizeBits
4738     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4739                                               Res);
4740   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4741     Oversized = Res;
4742     return QualType();
4743   }
4744 
4745   return Context.getConstantArrayType(VLATy->getElementType(),
4746                                       Res, ArrayType::Normal, 0);
4747 }
4748 
4749 static void
4750 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
4751   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4752     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4753     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4754                                       DstPTL.getPointeeLoc());
4755     DstPTL.setStarLoc(SrcPTL.getStarLoc());
4756     return;
4757   }
4758   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4759     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4760     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4761                                       DstPTL.getInnerLoc());
4762     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4763     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
4764     return;
4765   }
4766   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4767   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4768   TypeLoc SrcElemTL = SrcATL.getElementLoc();
4769   TypeLoc DstElemTL = DstATL.getElementLoc();
4770   DstElemTL.initializeFullCopy(SrcElemTL);
4771   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4772   DstATL.setSizeExpr(SrcATL.getSizeExpr());
4773   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
4774 }
4775 
4776 /// Helper method to turn variable array types into constant array
4777 /// types in certain situations which would otherwise be errors (for
4778 /// GCC compatibility).
4779 static TypeSourceInfo*
4780 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4781                                               ASTContext &Context,
4782                                               bool &SizeIsNegative,
4783                                               llvm::APSInt &Oversized) {
4784   QualType FixedTy
4785     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4786                                           SizeIsNegative, Oversized);
4787   if (FixedTy.isNull())
4788     return nullptr;
4789   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4790   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4791                                     FixedTInfo->getTypeLoc());
4792   return FixedTInfo;
4793 }
4794 
4795 /// \brief Register the given locally-scoped extern "C" declaration so
4796 /// that it can be found later for redeclarations. We include any extern "C"
4797 /// declaration that is not visible in the translation unit here, not just
4798 /// function-scope declarations.
4799 void
4800 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
4801   if (!getLangOpts().CPlusPlus &&
4802       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4803     // Don't need to track declarations in the TU in C.
4804     return;
4805 
4806   // Note that we have a locally-scoped external with this name.
4807   // FIXME: There can be multiple such declarations if they are functions marked
4808   // __attribute__((overloadable)) declared in function scope in C.
4809   LocallyScopedExternCDecls[ND->getDeclName()] = ND;
4810 }
4811 
4812 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
4813   if (ExternalSource) {
4814     // Load locally-scoped external decls from the external source.
4815     // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
4816     SmallVector<NamedDecl *, 4> Decls;
4817     ExternalSource->ReadLocallyScopedExternCDecls(Decls);
4818     for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4819       llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4820         = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4821       if (Pos == LocallyScopedExternCDecls.end())
4822         LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
4823     }
4824   }
4825 
4826   NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
4827   return D ? D->getMostRecentDecl() : nullptr;
4828 }
4829 
4830 /// \brief Diagnose function specifiers on a declaration of an identifier that
4831 /// does not identify a function.
4832 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
4833   // FIXME: We should probably indicate the identifier in question to avoid
4834   // confusion for constructs like "inline int a(), b;"
4835   if (DS.isInlineSpecified())
4836     Diag(DS.getInlineSpecLoc(),
4837          diag::err_inline_non_function);
4838 
4839   if (DS.isVirtualSpecified())
4840     Diag(DS.getVirtualSpecLoc(),
4841          diag::err_virtual_non_function);
4842 
4843   if (DS.isExplicitSpecified())
4844     Diag(DS.getExplicitSpecLoc(),
4845          diag::err_explicit_non_function);
4846 
4847   if (DS.isNoreturnSpecified())
4848     Diag(DS.getNoreturnSpecLoc(),
4849          diag::err_noreturn_non_function);
4850 }
4851 
4852 NamedDecl*
4853 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
4854                              TypeSourceInfo *TInfo, LookupResult &Previous) {
4855   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4856   if (D.getCXXScopeSpec().isSet()) {
4857     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4858       << D.getCXXScopeSpec().getRange();
4859     D.setInvalidType();
4860     // Pretend we didn't see the scope specifier.
4861     DC = CurContext;
4862     Previous.clear();
4863   }
4864 
4865   DiagnoseFunctionSpecifiers(D.getDeclSpec());
4866 
4867   if (D.getDeclSpec().isConstexprSpecified())
4868     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4869       << 1;
4870 
4871   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4872     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4873       << D.getName().getSourceRange();
4874     return nullptr;
4875   }
4876 
4877   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
4878   if (!NewTD) return nullptr;
4879 
4880   // Handle attributes prior to checking for duplicates in MergeVarDecl
4881   ProcessDeclAttributes(S, NewTD, D);
4882 
4883   CheckTypedefForVariablyModifiedType(S, NewTD);
4884 
4885   bool Redeclaration = D.isRedeclaration();
4886   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4887   D.setRedeclaration(Redeclaration);
4888   return ND;
4889 }
4890 
4891 void
4892 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
4893   // C99 6.7.7p2: If a typedef name specifies a variably modified type
4894   // then it shall have block scope.
4895   // Note that variably modified types must be fixed before merging the decl so
4896   // that redeclarations will match.
4897   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4898   QualType T = TInfo->getType();
4899   if (T->isVariablyModifiedType()) {
4900     getCurFunction()->setHasBranchProtectedScope();
4901 
4902     if (S->getFnParent() == nullptr) {
4903       bool SizeIsNegative;
4904       llvm::APSInt Oversized;
4905       TypeSourceInfo *FixedTInfo =
4906         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4907                                                       SizeIsNegative,
4908                                                       Oversized);
4909       if (FixedTInfo) {
4910         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
4911         NewTD->setTypeSourceInfo(FixedTInfo);
4912       } else {
4913         if (SizeIsNegative)
4914           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
4915         else if (T->isVariableArrayType())
4916           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
4917         else if (Oversized.getBoolValue())
4918           Diag(NewTD->getLocation(), diag::err_array_too_large)
4919             << Oversized.toString(10);
4920         else
4921           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
4922         NewTD->setInvalidDecl();
4923       }
4924     }
4925   }
4926 }
4927 
4928 
4929 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4930 /// declares a typedef-name, either using the 'typedef' type specifier or via
4931 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4932 NamedDecl*
4933 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4934                            LookupResult &Previous, bool &Redeclaration) {
4935   // Merge the decl with the existing one if appropriate. If the decl is
4936   // in an outer scope, it isn't the same thing.
4937   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
4938                        /*AllowInlineNamespace*/false);
4939   filterNonConflictingPreviousTypedefDecls(Context, NewTD, Previous);
4940   if (!Previous.empty()) {
4941     Redeclaration = true;
4942     MergeTypedefNameDecl(NewTD, Previous);
4943   }
4944 
4945   // If this is the C FILE type, notify the AST context.
4946   if (IdentifierInfo *II = NewTD->getIdentifier())
4947     if (!NewTD->isInvalidDecl() &&
4948         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
4949       if (II->isStr("FILE"))
4950         Context.setFILEDecl(NewTD);
4951       else if (II->isStr("jmp_buf"))
4952         Context.setjmp_bufDecl(NewTD);
4953       else if (II->isStr("sigjmp_buf"))
4954         Context.setsigjmp_bufDecl(NewTD);
4955       else if (II->isStr("ucontext_t"))
4956         Context.setucontext_tDecl(NewTD);
4957     }
4958 
4959   return NewTD;
4960 }
4961 
4962 /// \brief Determines whether the given declaration is an out-of-scope
4963 /// previous declaration.
4964 ///
4965 /// This routine should be invoked when name lookup has found a
4966 /// previous declaration (PrevDecl) that is not in the scope where a
4967 /// new declaration by the same name is being introduced. If the new
4968 /// declaration occurs in a local scope, previous declarations with
4969 /// linkage may still be considered previous declarations (C99
4970 /// 6.2.2p4-5, C++ [basic.link]p6).
4971 ///
4972 /// \param PrevDecl the previous declaration found by name
4973 /// lookup
4974 ///
4975 /// \param DC the context in which the new declaration is being
4976 /// declared.
4977 ///
4978 /// \returns true if PrevDecl is an out-of-scope previous declaration
4979 /// for a new delcaration with the same name.
4980 static bool
4981 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4982                                 ASTContext &Context) {
4983   if (!PrevDecl)
4984     return false;
4985 
4986   if (!PrevDecl->hasLinkage())
4987     return false;
4988 
4989   if (Context.getLangOpts().CPlusPlus) {
4990     // C++ [basic.link]p6:
4991     //   If there is a visible declaration of an entity with linkage
4992     //   having the same name and type, ignoring entities declared
4993     //   outside the innermost enclosing namespace scope, the block
4994     //   scope declaration declares that same entity and receives the
4995     //   linkage of the previous declaration.
4996     DeclContext *OuterContext = DC->getRedeclContext();
4997     if (!OuterContext->isFunctionOrMethod())
4998       // This rule only applies to block-scope declarations.
4999       return false;
5000 
5001     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5002     if (PrevOuterContext->isRecord())
5003       // We found a member function: ignore it.
5004       return false;
5005 
5006     // Find the innermost enclosing namespace for the new and
5007     // previous declarations.
5008     OuterContext = OuterContext->getEnclosingNamespaceContext();
5009     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5010 
5011     // The previous declaration is in a different namespace, so it
5012     // isn't the same function.
5013     if (!OuterContext->Equals(PrevOuterContext))
5014       return false;
5015   }
5016 
5017   return true;
5018 }
5019 
5020 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5021   CXXScopeSpec &SS = D.getCXXScopeSpec();
5022   if (!SS.isSet()) return;
5023   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5024 }
5025 
5026 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5027   QualType type = decl->getType();
5028   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5029   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5030     // Various kinds of declaration aren't allowed to be __autoreleasing.
5031     unsigned kind = -1U;
5032     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5033       if (var->hasAttr<BlocksAttr>())
5034         kind = 0; // __block
5035       else if (!var->hasLocalStorage())
5036         kind = 1; // global
5037     } else if (isa<ObjCIvarDecl>(decl)) {
5038       kind = 3; // ivar
5039     } else if (isa<FieldDecl>(decl)) {
5040       kind = 2; // field
5041     }
5042 
5043     if (kind != -1U) {
5044       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5045         << kind;
5046     }
5047   } else if (lifetime == Qualifiers::OCL_None) {
5048     // Try to infer lifetime.
5049     if (!type->isObjCLifetimeType())
5050       return false;
5051 
5052     lifetime = type->getObjCARCImplicitLifetime();
5053     type = Context.getLifetimeQualifiedType(type, lifetime);
5054     decl->setType(type);
5055   }
5056 
5057   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5058     // Thread-local variables cannot have lifetime.
5059     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5060         var->getTLSKind()) {
5061       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5062         << var->getType();
5063       return true;
5064     }
5065   }
5066 
5067   return false;
5068 }
5069 
5070 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5071   // Ensure that an auto decl is deduced otherwise the checks below might cache
5072   // the wrong linkage.
5073   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5074 
5075   // 'weak' only applies to declarations with external linkage.
5076   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5077     if (!ND.isExternallyVisible()) {
5078       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5079       ND.dropAttr<WeakAttr>();
5080     }
5081   }
5082   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5083     if (ND.isExternallyVisible()) {
5084       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5085       ND.dropAttr<WeakRefAttr>();
5086     }
5087   }
5088 
5089   // 'selectany' only applies to externally visible varable declarations.
5090   // It does not apply to functions.
5091   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5092     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5093       S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
5094       ND.dropAttr<SelectAnyAttr>();
5095     }
5096   }
5097 
5098   // dll attributes require external linkage.
5099   if (const DLLImportAttr *Attr = ND.getAttr<DLLImportAttr>()) {
5100     if (!ND.isExternallyVisible()) {
5101       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5102         << &ND << Attr;
5103       ND.setInvalidDecl();
5104     }
5105   }
5106   if (const DLLExportAttr *Attr = ND.getAttr<DLLExportAttr>()) {
5107     if (!ND.isExternallyVisible()) {
5108       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5109         << &ND << Attr;
5110       ND.setInvalidDecl();
5111     }
5112   }
5113 }
5114 
5115 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5116                                            NamedDecl *NewDecl,
5117                                            bool IsSpecialization) {
5118   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
5119     OldDecl = OldTD->getTemplatedDecl();
5120   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5121     NewDecl = NewTD->getTemplatedDecl();
5122 
5123   if (!OldDecl || !NewDecl)
5124     return;
5125 
5126   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5127   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5128   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5129   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5130 
5131   // dllimport and dllexport are inheritable attributes so we have to exclude
5132   // inherited attribute instances.
5133   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5134                     (NewExportAttr && !NewExportAttr->isInherited());
5135 
5136   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5137   // the only exception being explicit specializations.
5138   // Implicitly generated declarations are also excluded for now because there
5139   // is no other way to switch these to use dllimport or dllexport.
5140   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5141 
5142   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5143     // If the declaration hasn't been used yet, allow with a warning for
5144     // free functions and global variables.
5145     bool JustWarn = false;
5146     if (!OldDecl->isUsed() && OldDecl->getDeclContext()->isFileContext()) {
5147       auto *VD = dyn_cast<VarDecl>(OldDecl);
5148       if (VD && !VD->getDescribedVarTemplate())
5149         JustWarn = true;
5150       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5151       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5152         JustWarn = true;
5153     }
5154 
5155     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5156                                : diag::err_attribute_dll_redeclaration;
5157     S.Diag(NewDecl->getLocation(), DiagID)
5158         << NewDecl
5159         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5160     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5161     if (!JustWarn) {
5162       NewDecl->setInvalidDecl();
5163       return;
5164     }
5165   }
5166 
5167   // A redeclaration is not allowed to drop a dllimport attribute, the only
5168   // exceptions being inline function definitions, local extern declarations,
5169   // and qualified friend declarations.
5170   // NB: MSVC converts such a declaration to dllexport.
5171   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5172   if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
5173     // Ignore static data because out-of-line definitions are diagnosed
5174     // separately.
5175     IsStaticDataMember = VD->isStaticDataMember();
5176   else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5177     IsInline = FD->isInlined();
5178     IsQualifiedFriend = FD->getQualifier() &&
5179                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5180   }
5181 
5182   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5183       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5184     S.Diag(NewDecl->getLocation(),
5185            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5186       << NewDecl << OldImportAttr;
5187     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5188     S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5189     OldDecl->dropAttr<DLLImportAttr>();
5190     NewDecl->dropAttr<DLLImportAttr>();
5191   }
5192 }
5193 
5194 /// Given that we are within the definition of the given function,
5195 /// will that definition behave like C99's 'inline', where the
5196 /// definition is discarded except for optimization purposes?
5197 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5198   // Try to avoid calling GetGVALinkageForFunction.
5199 
5200   // All cases of this require the 'inline' keyword.
5201   if (!FD->isInlined()) return false;
5202 
5203   // This is only possible in C++ with the gnu_inline attribute.
5204   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5205     return false;
5206 
5207   // Okay, go ahead and call the relatively-more-expensive function.
5208 
5209 #ifndef NDEBUG
5210   // AST quite reasonably asserts that it's working on a function
5211   // definition.  We don't really have a way to tell it that we're
5212   // currently defining the function, so just lie to it in +Asserts
5213   // builds.  This is an awful hack.
5214   FD->setLazyBody(1);
5215 #endif
5216 
5217   bool isC99Inline =
5218       S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5219 
5220 #ifndef NDEBUG
5221   FD->setLazyBody(0);
5222 #endif
5223 
5224   return isC99Inline;
5225 }
5226 
5227 /// Determine whether a variable is extern "C" prior to attaching
5228 /// an initializer. We can't just call isExternC() here, because that
5229 /// will also compute and cache whether the declaration is externally
5230 /// visible, which might change when we attach the initializer.
5231 ///
5232 /// This can only be used if the declaration is known to not be a
5233 /// redeclaration of an internal linkage declaration.
5234 ///
5235 /// For instance:
5236 ///
5237 ///   auto x = []{};
5238 ///
5239 /// Attaching the initializer here makes this declaration not externally
5240 /// visible, because its type has internal linkage.
5241 ///
5242 /// FIXME: This is a hack.
5243 template<typename T>
5244 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5245   if (S.getLangOpts().CPlusPlus) {
5246     // In C++, the overloadable attribute negates the effects of extern "C".
5247     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5248       return false;
5249   }
5250   return D->isExternC();
5251 }
5252 
5253 static bool shouldConsiderLinkage(const VarDecl *VD) {
5254   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5255   if (DC->isFunctionOrMethod())
5256     return VD->hasExternalStorage();
5257   if (DC->isFileContext())
5258     return true;
5259   if (DC->isRecord())
5260     return false;
5261   llvm_unreachable("Unexpected context");
5262 }
5263 
5264 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5265   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5266   if (DC->isFileContext() || DC->isFunctionOrMethod())
5267     return true;
5268   if (DC->isRecord())
5269     return false;
5270   llvm_unreachable("Unexpected context");
5271 }
5272 
5273 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5274                           AttributeList::Kind Kind) {
5275   for (const AttributeList *L = AttrList; L; L = L->getNext())
5276     if (L->getKind() == Kind)
5277       return true;
5278   return false;
5279 }
5280 
5281 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5282                           AttributeList::Kind Kind) {
5283   // Check decl attributes on the DeclSpec.
5284   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5285     return true;
5286 
5287   // Walk the declarator structure, checking decl attributes that were in a type
5288   // position to the decl itself.
5289   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5290     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5291       return true;
5292   }
5293 
5294   // Finally, check attributes on the decl itself.
5295   return hasParsedAttr(S, PD.getAttributes(), Kind);
5296 }
5297 
5298 /// Adjust the \c DeclContext for a function or variable that might be a
5299 /// function-local external declaration.
5300 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5301   if (!DC->isFunctionOrMethod())
5302     return false;
5303 
5304   // If this is a local extern function or variable declared within a function
5305   // template, don't add it into the enclosing namespace scope until it is
5306   // instantiated; it might have a dependent type right now.
5307   if (DC->isDependentContext())
5308     return true;
5309 
5310   // C++11 [basic.link]p7:
5311   //   When a block scope declaration of an entity with linkage is not found to
5312   //   refer to some other declaration, then that entity is a member of the
5313   //   innermost enclosing namespace.
5314   //
5315   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5316   // semantically-enclosing namespace, not a lexically-enclosing one.
5317   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5318     DC = DC->getParent();
5319   return true;
5320 }
5321 
5322 NamedDecl *
5323 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5324                               TypeSourceInfo *TInfo, LookupResult &Previous,
5325                               MultiTemplateParamsArg TemplateParamLists,
5326                               bool &AddToScope) {
5327   QualType R = TInfo->getType();
5328   DeclarationName Name = GetNameForDeclarator(D).getName();
5329 
5330   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5331   VarDecl::StorageClass SC =
5332     StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5333 
5334   // dllimport globals without explicit storage class are treated as extern. We
5335   // have to change the storage class this early to get the right DeclContext.
5336   if (SC == SC_None && !DC->isRecord() &&
5337       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5338       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5339     SC = SC_Extern;
5340 
5341   DeclContext *OriginalDC = DC;
5342   bool IsLocalExternDecl = SC == SC_Extern &&
5343                            adjustContextForLocalExternDecl(DC);
5344 
5345   if (getLangOpts().OpenCL) {
5346     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5347     QualType NR = R;
5348     while (NR->isPointerType()) {
5349       if (NR->isFunctionPointerType()) {
5350         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5351         D.setInvalidType();
5352         break;
5353       }
5354       NR = NR->getPointeeType();
5355     }
5356 
5357     if (!getOpenCLOptions().cl_khr_fp16) {
5358       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5359       // half array type (unless the cl_khr_fp16 extension is enabled).
5360       if (Context.getBaseElementType(R)->isHalfType()) {
5361         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5362         D.setInvalidType();
5363       }
5364     }
5365   }
5366 
5367   if (SCSpec == DeclSpec::SCS_mutable) {
5368     // mutable can only appear on non-static class members, so it's always
5369     // an error here
5370     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5371     D.setInvalidType();
5372     SC = SC_None;
5373   }
5374 
5375   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5376       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5377                               D.getDeclSpec().getStorageClassSpecLoc())) {
5378     // In C++11, the 'register' storage class specifier is deprecated.
5379     // Suppress the warning in system macros, it's used in macros in some
5380     // popular C system headers, such as in glibc's htonl() macro.
5381     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5382          diag::warn_deprecated_register)
5383       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5384   }
5385 
5386   IdentifierInfo *II = Name.getAsIdentifierInfo();
5387   if (!II) {
5388     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5389       << Name;
5390     return nullptr;
5391   }
5392 
5393   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5394 
5395   if (!DC->isRecord() && S->getFnParent() == nullptr) {
5396     // C99 6.9p2: The storage-class specifiers auto and register shall not
5397     // appear in the declaration specifiers in an external declaration.
5398     // Global Register+Asm is a GNU extension we support.
5399     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5400       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5401       D.setInvalidType();
5402     }
5403   }
5404 
5405   if (getLangOpts().OpenCL) {
5406     // Set up the special work-group-local storage class for variables in the
5407     // OpenCL __local address space.
5408     if (R.getAddressSpace() == LangAS::opencl_local) {
5409       SC = SC_OpenCLWorkGroupLocal;
5410     }
5411 
5412     // OpenCL v1.2 s6.9.b p4:
5413     // The sampler type cannot be used with the __local and __global address
5414     // space qualifiers.
5415     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5416       R.getAddressSpace() == LangAS::opencl_global)) {
5417       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5418     }
5419 
5420     // OpenCL 1.2 spec, p6.9 r:
5421     // The event type cannot be used to declare a program scope variable.
5422     // The event type cannot be used with the __local, __constant and __global
5423     // address space qualifiers.
5424     if (R->isEventT()) {
5425       if (S->getParent() == nullptr) {
5426         Diag(D.getLocStart(), diag::err_event_t_global_var);
5427         D.setInvalidType();
5428       }
5429 
5430       if (R.getAddressSpace()) {
5431         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5432         D.setInvalidType();
5433       }
5434     }
5435   }
5436 
5437   bool IsExplicitSpecialization = false;
5438   bool IsVariableTemplateSpecialization = false;
5439   bool IsPartialSpecialization = false;
5440   bool IsVariableTemplate = false;
5441   VarDecl *NewVD = nullptr;
5442   VarTemplateDecl *NewTemplate = nullptr;
5443   TemplateParameterList *TemplateParams = nullptr;
5444   if (!getLangOpts().CPlusPlus) {
5445     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5446                             D.getIdentifierLoc(), II,
5447                             R, TInfo, SC);
5448 
5449     if (D.isInvalidType())
5450       NewVD->setInvalidDecl();
5451   } else {
5452     bool Invalid = false;
5453 
5454     if (DC->isRecord() && !CurContext->isRecord()) {
5455       // This is an out-of-line definition of a static data member.
5456       switch (SC) {
5457       case SC_None:
5458         break;
5459       case SC_Static:
5460         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5461              diag::err_static_out_of_line)
5462           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5463         break;
5464       case SC_Auto:
5465       case SC_Register:
5466       case SC_Extern:
5467         // [dcl.stc] p2: The auto or register specifiers shall be applied only
5468         // to names of variables declared in a block or to function parameters.
5469         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5470         // of class members
5471 
5472         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5473              diag::err_storage_class_for_static_member)
5474           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5475         break;
5476       case SC_PrivateExtern:
5477         llvm_unreachable("C storage class in c++!");
5478       case SC_OpenCLWorkGroupLocal:
5479         llvm_unreachable("OpenCL storage class in c++!");
5480       }
5481     }
5482 
5483     if (SC == SC_Static && CurContext->isRecord()) {
5484       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5485         if (RD->isLocalClass())
5486           Diag(D.getIdentifierLoc(),
5487                diag::err_static_data_member_not_allowed_in_local_class)
5488             << Name << RD->getDeclName();
5489 
5490         // C++98 [class.union]p1: If a union contains a static data member,
5491         // the program is ill-formed. C++11 drops this restriction.
5492         if (RD->isUnion())
5493           Diag(D.getIdentifierLoc(),
5494                getLangOpts().CPlusPlus11
5495                  ? diag::warn_cxx98_compat_static_data_member_in_union
5496                  : diag::ext_static_data_member_in_union) << Name;
5497         // We conservatively disallow static data members in anonymous structs.
5498         else if (!RD->getDeclName())
5499           Diag(D.getIdentifierLoc(),
5500                diag::err_static_data_member_not_allowed_in_anon_struct)
5501             << Name << RD->isUnion();
5502       }
5503     }
5504 
5505     // Match up the template parameter lists with the scope specifier, then
5506     // determine whether we have a template or a template specialization.
5507     TemplateParams = MatchTemplateParametersToScopeSpecifier(
5508         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5509         D.getCXXScopeSpec(),
5510         D.getName().getKind() == UnqualifiedId::IK_TemplateId
5511             ? D.getName().TemplateId
5512             : nullptr,
5513         TemplateParamLists,
5514         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5515 
5516     if (TemplateParams) {
5517       if (!TemplateParams->size() &&
5518           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5519         // There is an extraneous 'template<>' for this variable. Complain
5520         // about it, but allow the declaration of the variable.
5521         Diag(TemplateParams->getTemplateLoc(),
5522              diag::err_template_variable_noparams)
5523           << II
5524           << SourceRange(TemplateParams->getTemplateLoc(),
5525                          TemplateParams->getRAngleLoc());
5526         TemplateParams = nullptr;
5527       } else {
5528         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5529           // This is an explicit specialization or a partial specialization.
5530           // FIXME: Check that we can declare a specialization here.
5531           IsVariableTemplateSpecialization = true;
5532           IsPartialSpecialization = TemplateParams->size() > 0;
5533         } else { // if (TemplateParams->size() > 0)
5534           // This is a template declaration.
5535           IsVariableTemplate = true;
5536 
5537           // Check that we can declare a template here.
5538           if (CheckTemplateDeclScope(S, TemplateParams))
5539             return nullptr;
5540 
5541           // Only C++1y supports variable templates (N3651).
5542           Diag(D.getIdentifierLoc(),
5543                getLangOpts().CPlusPlus14
5544                    ? diag::warn_cxx11_compat_variable_template
5545                    : diag::ext_variable_template);
5546         }
5547       }
5548     } else {
5549       assert(D.getName().getKind() != UnqualifiedId::IK_TemplateId &&
5550              "should have a 'template<>' for this decl");
5551     }
5552 
5553     if (IsVariableTemplateSpecialization) {
5554       SourceLocation TemplateKWLoc =
5555           TemplateParamLists.size() > 0
5556               ? TemplateParamLists[0]->getTemplateLoc()
5557               : SourceLocation();
5558       DeclResult Res = ActOnVarTemplateSpecialization(
5559           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5560           IsPartialSpecialization);
5561       if (Res.isInvalid())
5562         return nullptr;
5563       NewVD = cast<VarDecl>(Res.get());
5564       AddToScope = false;
5565     } else
5566       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5567                               D.getIdentifierLoc(), II, R, TInfo, SC);
5568 
5569     // If this is supposed to be a variable template, create it as such.
5570     if (IsVariableTemplate) {
5571       NewTemplate =
5572           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5573                                   TemplateParams, NewVD);
5574       NewVD->setDescribedVarTemplate(NewTemplate);
5575     }
5576 
5577     // If this decl has an auto type in need of deduction, make a note of the
5578     // Decl so we can diagnose uses of it in its own initializer.
5579     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5580       ParsingInitForAutoVars.insert(NewVD);
5581 
5582     if (D.isInvalidType() || Invalid) {
5583       NewVD->setInvalidDecl();
5584       if (NewTemplate)
5585         NewTemplate->setInvalidDecl();
5586     }
5587 
5588     SetNestedNameSpecifier(NewVD, D);
5589 
5590     // If we have any template parameter lists that don't directly belong to
5591     // the variable (matching the scope specifier), store them.
5592     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5593     if (TemplateParamLists.size() > VDTemplateParamLists)
5594       NewVD->setTemplateParameterListsInfo(
5595           Context, TemplateParamLists.size() - VDTemplateParamLists,
5596           TemplateParamLists.data());
5597 
5598     if (D.getDeclSpec().isConstexprSpecified())
5599       NewVD->setConstexpr(true);
5600   }
5601 
5602   // Set the lexical context. If the declarator has a C++ scope specifier, the
5603   // lexical context will be different from the semantic context.
5604   NewVD->setLexicalDeclContext(CurContext);
5605   if (NewTemplate)
5606     NewTemplate->setLexicalDeclContext(CurContext);
5607 
5608   if (IsLocalExternDecl)
5609     NewVD->setLocalExternDecl();
5610 
5611   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
5612     if (NewVD->hasLocalStorage()) {
5613       // C++11 [dcl.stc]p4:
5614       //   When thread_local is applied to a variable of block scope the
5615       //   storage-class-specifier static is implied if it does not appear
5616       //   explicitly.
5617       // Core issue: 'static' is not implied if the variable is declared
5618       //   'extern'.
5619       if (SCSpec == DeclSpec::SCS_unspecified &&
5620           TSCS == DeclSpec::TSCS_thread_local &&
5621           DC->isFunctionOrMethod())
5622         NewVD->setTSCSpec(TSCS);
5623       else
5624         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5625              diag::err_thread_non_global)
5626           << DeclSpec::getSpecifierName(TSCS);
5627     } else if (!Context.getTargetInfo().isTLSSupported())
5628       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5629            diag::err_thread_unsupported);
5630     else
5631       NewVD->setTSCSpec(TSCS);
5632   }
5633 
5634   // C99 6.7.4p3
5635   //   An inline definition of a function with external linkage shall
5636   //   not contain a definition of a modifiable object with static or
5637   //   thread storage duration...
5638   // We only apply this when the function is required to be defined
5639   // elsewhere, i.e. when the function is not 'extern inline'.  Note
5640   // that a local variable with thread storage duration still has to
5641   // be marked 'static'.  Also note that it's possible to get these
5642   // semantics in C++ using __attribute__((gnu_inline)).
5643   if (SC == SC_Static && S->getFnParent() != nullptr &&
5644       !NewVD->getType().isConstQualified()) {
5645     FunctionDecl *CurFD = getCurFunctionDecl();
5646     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5647       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5648            diag::warn_static_local_in_extern_inline);
5649       MaybeSuggestAddingStaticToDecl(CurFD);
5650     }
5651   }
5652 
5653   if (D.getDeclSpec().isModulePrivateSpecified()) {
5654     if (IsVariableTemplateSpecialization)
5655       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5656           << (IsPartialSpecialization ? 1 : 0)
5657           << FixItHint::CreateRemoval(
5658                  D.getDeclSpec().getModulePrivateSpecLoc());
5659     else if (IsExplicitSpecialization)
5660       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5661         << 2
5662         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5663     else if (NewVD->hasLocalStorage())
5664       Diag(NewVD->getLocation(), diag::err_module_private_local)
5665         << 0 << NewVD->getDeclName()
5666         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5667         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5668     else {
5669       NewVD->setModulePrivate();
5670       if (NewTemplate)
5671         NewTemplate->setModulePrivate();
5672     }
5673   }
5674 
5675   // Handle attributes prior to checking for duplicates in MergeVarDecl
5676   ProcessDeclAttributes(S, NewVD, D);
5677 
5678   if (getLangOpts().CUDA) {
5679     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5680     // storage [duration]."
5681     if (SC == SC_None && S->getFnParent() != nullptr &&
5682         (NewVD->hasAttr<CUDASharedAttr>() ||
5683          NewVD->hasAttr<CUDAConstantAttr>())) {
5684       NewVD->setStorageClass(SC_Static);
5685     }
5686   }
5687 
5688   // Ensure that dllimport globals without explicit storage class are treated as
5689   // extern. The storage class is set above using parsed attributes. Now we can
5690   // check the VarDecl itself.
5691   assert(!NewVD->hasAttr<DLLImportAttr>() ||
5692          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
5693          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
5694 
5695   // In auto-retain/release, infer strong retension for variables of
5696   // retainable type.
5697   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
5698     NewVD->setInvalidDecl();
5699 
5700   // Handle GNU asm-label extension (encoded as an attribute).
5701   if (Expr *E = (Expr*)D.getAsmLabel()) {
5702     // The parser guarantees this is a string.
5703     StringLiteral *SE = cast<StringLiteral>(E);
5704     StringRef Label = SE->getString();
5705     if (S->getFnParent() != nullptr) {
5706       switch (SC) {
5707       case SC_None:
5708       case SC_Auto:
5709         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5710         break;
5711       case SC_Register:
5712         // Local Named register
5713         if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
5714           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5715         break;
5716       case SC_Static:
5717       case SC_Extern:
5718       case SC_PrivateExtern:
5719       case SC_OpenCLWorkGroupLocal:
5720         break;
5721       }
5722     } else if (SC == SC_Register) {
5723       // Global Named register
5724       if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
5725         Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5726       if (!R->isIntegralType(Context) && !R->isPointerType()) {
5727         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
5728         NewVD->setInvalidDecl(true);
5729       }
5730     }
5731 
5732     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
5733                                                 Context, Label, 0));
5734   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5735     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5736       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5737     if (I != ExtnameUndeclaredIdentifiers.end()) {
5738       NewVD->addAttr(I->second);
5739       ExtnameUndeclaredIdentifiers.erase(I);
5740     }
5741   }
5742 
5743   // Diagnose shadowed variables before filtering for scope.
5744   if (D.getCXXScopeSpec().isEmpty())
5745     CheckShadow(S, NewVD, Previous);
5746 
5747   // Don't consider existing declarations that are in a different
5748   // scope and are out-of-semantic-context declarations (if the new
5749   // declaration has linkage).
5750   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
5751                        D.getCXXScopeSpec().isNotEmpty() ||
5752                        IsExplicitSpecialization ||
5753                        IsVariableTemplateSpecialization);
5754 
5755   // Check whether the previous declaration is in the same block scope. This
5756   // affects whether we merge types with it, per C++11 [dcl.array]p3.
5757   if (getLangOpts().CPlusPlus &&
5758       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5759     NewVD->setPreviousDeclInSameBlockScope(
5760         Previous.isSingleResult() && !Previous.isShadowed() &&
5761         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
5762 
5763   if (!getLangOpts().CPlusPlus) {
5764     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5765   } else {
5766     // If this is an explicit specialization of a static data member, check it.
5767     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
5768         CheckMemberSpecialization(NewVD, Previous))
5769       NewVD->setInvalidDecl();
5770 
5771     // Merge the decl with the existing one if appropriate.
5772     if (!Previous.empty()) {
5773       if (Previous.isSingleResult() &&
5774           isa<FieldDecl>(Previous.getFoundDecl()) &&
5775           D.getCXXScopeSpec().isSet()) {
5776         // The user tried to define a non-static data member
5777         // out-of-line (C++ [dcl.meaning]p1).
5778         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5779           << D.getCXXScopeSpec().getRange();
5780         Previous.clear();
5781         NewVD->setInvalidDecl();
5782       }
5783     } else if (D.getCXXScopeSpec().isSet()) {
5784       // No previous declaration in the qualifying scope.
5785       Diag(D.getIdentifierLoc(), diag::err_no_member)
5786         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
5787         << D.getCXXScopeSpec().getRange();
5788       NewVD->setInvalidDecl();
5789     }
5790 
5791     if (!IsVariableTemplateSpecialization)
5792       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5793 
5794     if (NewTemplate) {
5795       VarTemplateDecl *PrevVarTemplate =
5796           NewVD->getPreviousDecl()
5797               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
5798               : nullptr;
5799 
5800       // Check the template parameter list of this declaration, possibly
5801       // merging in the template parameter list from the previous variable
5802       // template declaration.
5803       if (CheckTemplateParameterList(
5804               TemplateParams,
5805               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5806                               : nullptr,
5807               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5808                DC->isDependentContext())
5809                   ? TPC_ClassTemplateMember
5810                   : TPC_VarTemplate))
5811         NewVD->setInvalidDecl();
5812 
5813       // If we are providing an explicit specialization of a static variable
5814       // template, make a note of that.
5815       if (PrevVarTemplate &&
5816           PrevVarTemplate->getInstantiatedFromMemberTemplate())
5817         PrevVarTemplate->setMemberSpecialization();
5818     }
5819   }
5820 
5821   ProcessPragmaWeak(S, NewVD);
5822 
5823   // If this is the first declaration of an extern C variable, update
5824   // the map of such variables.
5825   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
5826       isIncompleteDeclExternC(*this, NewVD))
5827     RegisterLocallyScopedExternCDecl(NewVD, S);
5828 
5829   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5830     Decl *ManglingContextDecl;
5831     if (MangleNumberingContext *MCtx =
5832             getCurrentMangleNumberContext(NewVD->getDeclContext(),
5833                                           ManglingContextDecl)) {
5834       Context.setManglingNumber(
5835           NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
5836       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5837     }
5838   }
5839 
5840   if (D.isRedeclaration() && !Previous.empty()) {
5841     checkDLLAttributeRedeclaration(
5842         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
5843         IsExplicitSpecialization);
5844   }
5845 
5846   if (NewTemplate) {
5847     if (NewVD->isInvalidDecl())
5848       NewTemplate->setInvalidDecl();
5849     ActOnDocumentableDecl(NewTemplate);
5850     return NewTemplate;
5851   }
5852 
5853   return NewVD;
5854 }
5855 
5856 /// \brief Diagnose variable or built-in function shadowing.  Implements
5857 /// -Wshadow.
5858 ///
5859 /// This method is called whenever a VarDecl is added to a "useful"
5860 /// scope.
5861 ///
5862 /// \param S the scope in which the shadowing name is being declared
5863 /// \param R the lookup of the name
5864 ///
5865 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
5866   // Return if warning is ignored.
5867   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
5868     return;
5869 
5870   // Don't diagnose declarations at file scope.
5871   if (D->hasGlobalStorage())
5872     return;
5873 
5874   DeclContext *NewDC = D->getDeclContext();
5875 
5876   // Only diagnose if we're shadowing an unambiguous field or variable.
5877   if (R.getResultKind() != LookupResult::Found)
5878     return;
5879 
5880   NamedDecl* ShadowedDecl = R.getFoundDecl();
5881   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5882     return;
5883 
5884   // Fields are not shadowed by variables in C++ static methods.
5885   if (isa<FieldDecl>(ShadowedDecl))
5886     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5887       if (MD->isStatic())
5888         return;
5889 
5890   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5891     if (shadowedVar->isExternC()) {
5892       // For shadowing external vars, make sure that we point to the global
5893       // declaration, not a locally scoped extern declaration.
5894       for (auto I : shadowedVar->redecls())
5895         if (I->isFileVarDecl()) {
5896           ShadowedDecl = I;
5897           break;
5898         }
5899     }
5900 
5901   DeclContext *OldDC = ShadowedDecl->getDeclContext();
5902 
5903   // Only warn about certain kinds of shadowing for class members.
5904   if (NewDC && NewDC->isRecord()) {
5905     // In particular, don't warn about shadowing non-class members.
5906     if (!OldDC->isRecord())
5907       return;
5908 
5909     // TODO: should we warn about static data members shadowing
5910     // static data members from base classes?
5911 
5912     // TODO: don't diagnose for inaccessible shadowed members.
5913     // This is hard to do perfectly because we might friend the
5914     // shadowing context, but that's just a false negative.
5915   }
5916 
5917   // Determine what kind of declaration we're shadowing.
5918   unsigned Kind;
5919   if (isa<RecordDecl>(OldDC)) {
5920     if (isa<FieldDecl>(ShadowedDecl))
5921       Kind = 3; // field
5922     else
5923       Kind = 2; // static data member
5924   } else if (OldDC->isFileContext())
5925     Kind = 1; // global
5926   else
5927     Kind = 0; // local
5928 
5929   DeclarationName Name = R.getLookupName();
5930 
5931   // Emit warning and note.
5932   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
5933     return;
5934   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
5935   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5936 }
5937 
5938 /// \brief Check -Wshadow without the advantage of a previous lookup.
5939 void Sema::CheckShadow(Scope *S, VarDecl *D) {
5940   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
5941     return;
5942 
5943   LookupResult R(*this, D->getDeclName(), D->getLocation(),
5944                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5945   LookupName(R, S);
5946   CheckShadow(S, D, R);
5947 }
5948 
5949 /// Check for conflict between this global or extern "C" declaration and
5950 /// previous global or extern "C" declarations. This is only used in C++.
5951 template<typename T>
5952 static bool checkGlobalOrExternCConflict(
5953     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5954   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5955   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
5956 
5957   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5958     // The common case: this global doesn't conflict with any extern "C"
5959     // declaration.
5960     return false;
5961   }
5962 
5963   if (Prev) {
5964     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5965       // Both the old and new declarations have C language linkage. This is a
5966       // redeclaration.
5967       Previous.clear();
5968       Previous.addDecl(Prev);
5969       return true;
5970     }
5971 
5972     // This is a global, non-extern "C" declaration, and there is a previous
5973     // non-global extern "C" declaration. Diagnose if this is a variable
5974     // declaration.
5975     if (!isa<VarDecl>(ND))
5976       return false;
5977   } else {
5978     // The declaration is extern "C". Check for any declaration in the
5979     // translation unit which might conflict.
5980     if (IsGlobal) {
5981       // We have already performed the lookup into the translation unit.
5982       IsGlobal = false;
5983       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5984            I != E; ++I) {
5985         if (isa<VarDecl>(*I)) {
5986           Prev = *I;
5987           break;
5988         }
5989       }
5990     } else {
5991       DeclContext::lookup_result R =
5992           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5993       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5994            I != E; ++I) {
5995         if (isa<VarDecl>(*I)) {
5996           Prev = *I;
5997           break;
5998         }
5999         // FIXME: If we have any other entity with this name in global scope,
6000         // the declaration is ill-formed, but that is a defect: it breaks the
6001         // 'stat' hack, for instance. Only variables can have mangled name
6002         // clashes with extern "C" declarations, so only they deserve a
6003         // diagnostic.
6004       }
6005     }
6006 
6007     if (!Prev)
6008       return false;
6009   }
6010 
6011   // Use the first declaration's location to ensure we point at something which
6012   // is lexically inside an extern "C" linkage-spec.
6013   assert(Prev && "should have found a previous declaration to diagnose");
6014   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6015     Prev = FD->getFirstDecl();
6016   else
6017     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6018 
6019   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6020     << IsGlobal << ND;
6021   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6022     << IsGlobal;
6023   return false;
6024 }
6025 
6026 /// Apply special rules for handling extern "C" declarations. Returns \c true
6027 /// if we have found that this is a redeclaration of some prior entity.
6028 ///
6029 /// Per C++ [dcl.link]p6:
6030 ///   Two declarations [for a function or variable] with C language linkage
6031 ///   with the same name that appear in different scopes refer to the same
6032 ///   [entity]. An entity with C language linkage shall not be declared with
6033 ///   the same name as an entity in global scope.
6034 template<typename T>
6035 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6036                                                   LookupResult &Previous) {
6037   if (!S.getLangOpts().CPlusPlus) {
6038     // In C, when declaring a global variable, look for a corresponding 'extern'
6039     // variable declared in function scope. We don't need this in C++, because
6040     // we find local extern decls in the surrounding file-scope DeclContext.
6041     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6042       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6043         Previous.clear();
6044         Previous.addDecl(Prev);
6045         return true;
6046       }
6047     }
6048     return false;
6049   }
6050 
6051   // A declaration in the translation unit can conflict with an extern "C"
6052   // declaration.
6053   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6054     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6055 
6056   // An extern "C" declaration can conflict with a declaration in the
6057   // translation unit or can be a redeclaration of an extern "C" declaration
6058   // in another scope.
6059   if (isIncompleteDeclExternC(S,ND))
6060     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6061 
6062   // Neither global nor extern "C": nothing to do.
6063   return false;
6064 }
6065 
6066 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6067   // If the decl is already known invalid, don't check it.
6068   if (NewVD->isInvalidDecl())
6069     return;
6070 
6071   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6072   QualType T = TInfo->getType();
6073 
6074   // Defer checking an 'auto' type until its initializer is attached.
6075   if (T->isUndeducedType())
6076     return;
6077 
6078   if (NewVD->hasAttrs())
6079     CheckAlignasUnderalignment(NewVD);
6080 
6081   if (T->isObjCObjectType()) {
6082     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6083       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6084     T = Context.getObjCObjectPointerType(T);
6085     NewVD->setType(T);
6086   }
6087 
6088   // Emit an error if an address space was applied to decl with local storage.
6089   // This includes arrays of objects with address space qualifiers, but not
6090   // automatic variables that point to other address spaces.
6091   // ISO/IEC TR 18037 S5.1.2
6092   if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6093     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6094     NewVD->setInvalidDecl();
6095     return;
6096   }
6097 
6098   // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6099   // __constant address space.
6100   if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
6101       && T.getAddressSpace() != LangAS::opencl_constant
6102       && !T->isSamplerT()){
6103     Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
6104     NewVD->setInvalidDecl();
6105     return;
6106   }
6107 
6108   // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
6109   // scope.
6110   if ((getLangOpts().OpenCLVersion >= 120)
6111       && NewVD->isStaticLocal()) {
6112     Diag(NewVD->getLocation(), diag::err_static_function_scope);
6113     NewVD->setInvalidDecl();
6114     return;
6115   }
6116 
6117   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6118       && !NewVD->hasAttr<BlocksAttr>()) {
6119     if (getLangOpts().getGC() != LangOptions::NonGC)
6120       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6121     else {
6122       assert(!getLangOpts().ObjCAutoRefCount);
6123       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6124     }
6125   }
6126 
6127   bool isVM = T->isVariablyModifiedType();
6128   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6129       NewVD->hasAttr<BlocksAttr>())
6130     getCurFunction()->setHasBranchProtectedScope();
6131 
6132   if ((isVM && NewVD->hasLinkage()) ||
6133       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6134     bool SizeIsNegative;
6135     llvm::APSInt Oversized;
6136     TypeSourceInfo *FixedTInfo =
6137       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6138                                                     SizeIsNegative, Oversized);
6139     if (!FixedTInfo && T->isVariableArrayType()) {
6140       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6141       // FIXME: This won't give the correct result for
6142       // int a[10][n];
6143       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6144 
6145       if (NewVD->isFileVarDecl())
6146         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6147         << SizeRange;
6148       else if (NewVD->isStaticLocal())
6149         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6150         << SizeRange;
6151       else
6152         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6153         << SizeRange;
6154       NewVD->setInvalidDecl();
6155       return;
6156     }
6157 
6158     if (!FixedTInfo) {
6159       if (NewVD->isFileVarDecl())
6160         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6161       else
6162         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6163       NewVD->setInvalidDecl();
6164       return;
6165     }
6166 
6167     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6168     NewVD->setType(FixedTInfo->getType());
6169     NewVD->setTypeSourceInfo(FixedTInfo);
6170   }
6171 
6172   if (T->isVoidType()) {
6173     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6174     //                    of objects and functions.
6175     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6176       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6177         << T;
6178       NewVD->setInvalidDecl();
6179       return;
6180     }
6181   }
6182 
6183   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6184     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6185     NewVD->setInvalidDecl();
6186     return;
6187   }
6188 
6189   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6190     Diag(NewVD->getLocation(), diag::err_block_on_vm);
6191     NewVD->setInvalidDecl();
6192     return;
6193   }
6194 
6195   if (NewVD->isConstexpr() && !T->isDependentType() &&
6196       RequireLiteralType(NewVD->getLocation(), T,
6197                          diag::err_constexpr_var_non_literal)) {
6198     NewVD->setInvalidDecl();
6199     return;
6200   }
6201 }
6202 
6203 /// \brief Perform semantic checking on a newly-created variable
6204 /// declaration.
6205 ///
6206 /// This routine performs all of the type-checking required for a
6207 /// variable declaration once it has been built. It is used both to
6208 /// check variables after they have been parsed and their declarators
6209 /// have been translated into a declaration, and to check variables
6210 /// that have been instantiated from a template.
6211 ///
6212 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6213 ///
6214 /// Returns true if the variable declaration is a redeclaration.
6215 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6216   CheckVariableDeclarationType(NewVD);
6217 
6218   // If the decl is already known invalid, don't check it.
6219   if (NewVD->isInvalidDecl())
6220     return false;
6221 
6222   // If we did not find anything by this name, look for a non-visible
6223   // extern "C" declaration with the same name.
6224   if (Previous.empty() &&
6225       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6226     Previous.setShadowed();
6227 
6228   // Filter out any non-conflicting previous declarations.
6229   filterNonConflictingPreviousDecls(Context, NewVD, Previous);
6230 
6231   if (!Previous.empty()) {
6232     MergeVarDecl(NewVD, Previous);
6233     return true;
6234   }
6235   return false;
6236 }
6237 
6238 /// \brief Data used with FindOverriddenMethod
6239 struct FindOverriddenMethodData {
6240   Sema *S;
6241   CXXMethodDecl *Method;
6242 };
6243 
6244 /// \brief Member lookup function that determines whether a given C++
6245 /// method overrides a method in a base class, to be used with
6246 /// CXXRecordDecl::lookupInBases().
6247 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
6248                                  CXXBasePath &Path,
6249                                  void *UserData) {
6250   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6251 
6252   FindOverriddenMethodData *Data
6253     = reinterpret_cast<FindOverriddenMethodData*>(UserData);
6254 
6255   DeclarationName Name = Data->Method->getDeclName();
6256 
6257   // FIXME: Do we care about other names here too?
6258   if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6259     // We really want to find the base class destructor here.
6260     QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
6261     CanQualType CT = Data->S->Context.getCanonicalType(T);
6262 
6263     Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
6264   }
6265 
6266   for (Path.Decls = BaseRecord->lookup(Name);
6267        !Path.Decls.empty();
6268        Path.Decls = Path.Decls.slice(1)) {
6269     NamedDecl *D = Path.Decls.front();
6270     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6271       if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
6272         return true;
6273     }
6274   }
6275 
6276   return false;
6277 }
6278 
6279 namespace {
6280   enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6281 }
6282 /// \brief Report an error regarding overriding, along with any relevant
6283 /// overriden methods.
6284 ///
6285 /// \param DiagID the primary error to report.
6286 /// \param MD the overriding method.
6287 /// \param OEK which overrides to include as notes.
6288 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6289                             OverrideErrorKind OEK = OEK_All) {
6290   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6291   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6292                                       E = MD->end_overridden_methods();
6293        I != E; ++I) {
6294     // This check (& the OEK parameter) could be replaced by a predicate, but
6295     // without lambdas that would be overkill. This is still nicer than writing
6296     // out the diag loop 3 times.
6297     if ((OEK == OEK_All) ||
6298         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6299         (OEK == OEK_Deleted && (*I)->isDeleted()))
6300       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6301   }
6302 }
6303 
6304 /// AddOverriddenMethods - See if a method overrides any in the base classes,
6305 /// and if so, check that it's a valid override and remember it.
6306 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
6307   // Look for virtual methods in base classes that this method might override.
6308   CXXBasePaths Paths;
6309   FindOverriddenMethodData Data;
6310   Data.Method = MD;
6311   Data.S = this;
6312   bool hasDeletedOverridenMethods = false;
6313   bool hasNonDeletedOverridenMethods = false;
6314   bool AddedAny = false;
6315   if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
6316     for (auto *I : Paths.found_decls()) {
6317       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
6318         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
6319         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
6320             !CheckOverridingFunctionAttributes(MD, OldMD) &&
6321             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
6322             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
6323           hasDeletedOverridenMethods |= OldMD->isDeleted();
6324           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
6325           AddedAny = true;
6326         }
6327       }
6328     }
6329   }
6330 
6331   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6332     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6333   }
6334   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6335     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6336   }
6337 
6338   return AddedAny;
6339 }
6340 
6341 namespace {
6342   // Struct for holding all of the extra arguments needed by
6343   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6344   struct ActOnFDArgs {
6345     Scope *S;
6346     Declarator &D;
6347     MultiTemplateParamsArg TemplateParamLists;
6348     bool AddToScope;
6349   };
6350 }
6351 
6352 namespace {
6353 
6354 // Callback to only accept typo corrections that have a non-zero edit distance.
6355 // Also only accept corrections that have the same parent decl.
6356 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6357  public:
6358   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6359                             CXXRecordDecl *Parent)
6360       : Context(Context), OriginalFD(TypoFD),
6361         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
6362 
6363   bool ValidateCandidate(const TypoCorrection &candidate) override {
6364     if (candidate.getEditDistance() == 0)
6365       return false;
6366 
6367     SmallVector<unsigned, 1> MismatchedParams;
6368     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6369                                           CDeclEnd = candidate.end();
6370          CDecl != CDeclEnd; ++CDecl) {
6371       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6372 
6373       if (FD && !FD->hasBody() &&
6374           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6375         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6376           CXXRecordDecl *Parent = MD->getParent();
6377           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6378             return true;
6379         } else if (!ExpectedParent) {
6380           return true;
6381         }
6382       }
6383     }
6384 
6385     return false;
6386   }
6387 
6388  private:
6389   ASTContext &Context;
6390   FunctionDecl *OriginalFD;
6391   CXXRecordDecl *ExpectedParent;
6392 };
6393 
6394 }
6395 
6396 /// \brief Generate diagnostics for an invalid function redeclaration.
6397 ///
6398 /// This routine handles generating the diagnostic messages for an invalid
6399 /// function redeclaration, including finding possible similar declarations
6400 /// or performing typo correction if there are no previous declarations with
6401 /// the same name.
6402 ///
6403 /// Returns a NamedDecl iff typo correction was performed and substituting in
6404 /// the new declaration name does not cause new errors.
6405 static NamedDecl *DiagnoseInvalidRedeclaration(
6406     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
6407     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
6408   DeclarationName Name = NewFD->getDeclName();
6409   DeclContext *NewDC = NewFD->getDeclContext();
6410   SmallVector<unsigned, 1> MismatchedParams;
6411   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
6412   TypoCorrection Correction;
6413   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
6414   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6415                                    : diag::err_member_decl_does_not_match;
6416   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6417                     IsLocalFriend ? Sema::LookupLocalFriendName
6418                                   : Sema::LookupOrdinaryName,
6419                     Sema::ForRedeclaration);
6420 
6421   NewFD->setInvalidDecl();
6422   if (IsLocalFriend)
6423     SemaRef.LookupName(Prev, S);
6424   else
6425     SemaRef.LookupQualifiedName(Prev, NewDC);
6426   assert(!Prev.isAmbiguous() &&
6427          "Cannot have an ambiguity in previous-declaration lookup");
6428   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6429   DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
6430                                       MD ? MD->getParent() : nullptr);
6431   if (!Prev.empty()) {
6432     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6433          Func != FuncEnd; ++Func) {
6434       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
6435       if (FD &&
6436           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6437         // Add 1 to the index so that 0 can mean the mismatch didn't
6438         // involve a parameter
6439         unsigned ParamNum =
6440             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6441         NearMatches.push_back(std::make_pair(FD, ParamNum));
6442       }
6443     }
6444   // If the qualified name lookup yielded nothing, try typo correction
6445   } else if ((Correction = SemaRef.CorrectTypo(
6446                  Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6447                  &ExtraArgs.D.getCXXScopeSpec(), Validator,
6448                  Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
6449     // Set up everything for the call to ActOnFunctionDeclarator
6450     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6451                               ExtraArgs.D.getIdentifierLoc());
6452     Previous.clear();
6453     Previous.setLookupName(Correction.getCorrection());
6454     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6455                                     CDeclEnd = Correction.end();
6456          CDecl != CDeclEnd; ++CDecl) {
6457       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6458       if (FD && !FD->hasBody() &&
6459           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6460         Previous.addDecl(FD);
6461       }
6462     }
6463     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
6464 
6465     NamedDecl *Result;
6466     // Retry building the function declaration with the new previous
6467     // declarations, and with errors suppressed.
6468     {
6469       // Trap errors.
6470       Sema::SFINAETrap Trap(SemaRef);
6471 
6472       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6473       // pieces need to verify the typo-corrected C++ declaration and hopefully
6474       // eliminate the need for the parameter pack ExtraArgs.
6475       Result = SemaRef.ActOnFunctionDeclarator(
6476           ExtraArgs.S, ExtraArgs.D,
6477           Correction.getCorrectionDecl()->getDeclContext(),
6478           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6479           ExtraArgs.AddToScope);
6480 
6481       if (Trap.hasErrorOccurred())
6482         Result = nullptr;
6483     }
6484 
6485     if (Result) {
6486       // Determine which correction we picked.
6487       Decl *Canonical = Result->getCanonicalDecl();
6488       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6489            I != E; ++I)
6490         if ((*I)->getCanonicalDecl() == Canonical)
6491           Correction.setCorrectionDecl(*I);
6492 
6493       SemaRef.diagnoseTypo(
6494           Correction,
6495           SemaRef.PDiag(IsLocalFriend
6496                           ? diag::err_no_matching_local_friend_suggest
6497                           : diag::err_member_decl_does_not_match_suggest)
6498             << Name << NewDC << IsDefinition);
6499       return Result;
6500     }
6501 
6502     // Pretend the typo correction never occurred
6503     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6504                               ExtraArgs.D.getIdentifierLoc());
6505     ExtraArgs.D.setRedeclaration(wasRedeclaration);
6506     Previous.clear();
6507     Previous.setLookupName(Name);
6508   }
6509 
6510   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6511       << Name << NewDC << IsDefinition << NewFD->getLocation();
6512 
6513   bool NewFDisConst = false;
6514   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
6515     NewFDisConst = NewMD->isConst();
6516 
6517   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
6518        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6519        NearMatch != NearMatchEnd; ++NearMatch) {
6520     FunctionDecl *FD = NearMatch->first;
6521     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6522     bool FDisConst = MD && MD->isConst();
6523     bool IsMember = MD || !IsLocalFriend;
6524 
6525     // FIXME: These notes are poorly worded for the local friend case.
6526     if (unsigned Idx = NearMatch->second) {
6527       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
6528       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6529       if (Loc.isInvalid()) Loc = FD->getLocation();
6530       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6531                                  : diag::note_local_decl_close_param_match)
6532         << Idx << FDParam->getType()
6533         << NewFD->getParamDecl(Idx - 1)->getType();
6534     } else if (FDisConst != NewFDisConst) {
6535       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
6536           << NewFDisConst << FD->getSourceRange().getEnd();
6537     } else
6538       SemaRef.Diag(FD->getLocation(),
6539                    IsMember ? diag::note_member_def_close_match
6540                             : diag::note_local_decl_close_match);
6541   }
6542   return nullptr;
6543 }
6544 
6545 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6546                                                           Declarator &D) {
6547   switch (D.getDeclSpec().getStorageClassSpec()) {
6548   default: llvm_unreachable("Unknown storage class!");
6549   case DeclSpec::SCS_auto:
6550   case DeclSpec::SCS_register:
6551   case DeclSpec::SCS_mutable:
6552     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6553                  diag::err_typecheck_sclass_func);
6554     D.setInvalidType();
6555     break;
6556   case DeclSpec::SCS_unspecified: break;
6557   case DeclSpec::SCS_extern:
6558     if (D.getDeclSpec().isExternInLinkageSpec())
6559       return SC_None;
6560     return SC_Extern;
6561   case DeclSpec::SCS_static: {
6562     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6563       // C99 6.7.1p5:
6564       //   The declaration of an identifier for a function that has
6565       //   block scope shall have no explicit storage-class specifier
6566       //   other than extern
6567       // See also (C++ [dcl.stc]p4).
6568       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6569                    diag::err_static_block_func);
6570       break;
6571     } else
6572       return SC_Static;
6573   }
6574   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6575   }
6576 
6577   // No explicit storage class has already been returned
6578   return SC_None;
6579 }
6580 
6581 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6582                                            DeclContext *DC, QualType &R,
6583                                            TypeSourceInfo *TInfo,
6584                                            FunctionDecl::StorageClass SC,
6585                                            bool &IsVirtualOkay) {
6586   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6587   DeclarationName Name = NameInfo.getName();
6588 
6589   FunctionDecl *NewFD = nullptr;
6590   bool isInline = D.getDeclSpec().isInlineSpecified();
6591 
6592   if (!SemaRef.getLangOpts().CPlusPlus) {
6593     // Determine whether the function was written with a
6594     // prototype. This true when:
6595     //   - there is a prototype in the declarator, or
6596     //   - the type R of the function is some kind of typedef or other reference
6597     //     to a type name (which eventually refers to a function type).
6598     bool HasPrototype =
6599       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6600       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6601 
6602     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
6603                                  D.getLocStart(), NameInfo, R,
6604                                  TInfo, SC, isInline,
6605                                  HasPrototype, false);
6606     if (D.isInvalidType())
6607       NewFD->setInvalidDecl();
6608 
6609     // Set the lexical context.
6610     NewFD->setLexicalDeclContext(SemaRef.CurContext);
6611 
6612     return NewFD;
6613   }
6614 
6615   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6616   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6617 
6618   // Check that the return type is not an abstract class type.
6619   // For record types, this is done by the AbstractClassUsageDiagnoser once
6620   // the class has been completely parsed.
6621   if (!DC->isRecord() &&
6622       SemaRef.RequireNonAbstractType(
6623           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
6624           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
6625     D.setInvalidType();
6626 
6627   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6628     // This is a C++ constructor declaration.
6629     assert(DC->isRecord() &&
6630            "Constructors can only be declared in a member context");
6631 
6632     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6633     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6634                                       D.getLocStart(), NameInfo,
6635                                       R, TInfo, isExplicit, isInline,
6636                                       /*isImplicitlyDeclared=*/false,
6637                                       isConstexpr);
6638 
6639   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6640     // This is a C++ destructor declaration.
6641     if (DC->isRecord()) {
6642       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6643       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6644       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6645                                         SemaRef.Context, Record,
6646                                         D.getLocStart(),
6647                                         NameInfo, R, TInfo, isInline,
6648                                         /*isImplicitlyDeclared=*/false);
6649 
6650       // If the class is complete, then we now create the implicit exception
6651       // specification. If the class is incomplete or dependent, we can't do
6652       // it yet.
6653       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
6654           Record->getDefinition() && !Record->isBeingDefined() &&
6655           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6656         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6657       }
6658 
6659       IsVirtualOkay = true;
6660       return NewDD;
6661 
6662     } else {
6663       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6664       D.setInvalidType();
6665 
6666       // Create a FunctionDecl to satisfy the function definition parsing
6667       // code path.
6668       return FunctionDecl::Create(SemaRef.Context, DC,
6669                                   D.getLocStart(),
6670                                   D.getIdentifierLoc(), Name, R, TInfo,
6671                                   SC, isInline,
6672                                   /*hasPrototype=*/true, isConstexpr);
6673     }
6674 
6675   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6676     if (!DC->isRecord()) {
6677       SemaRef.Diag(D.getIdentifierLoc(),
6678            diag::err_conv_function_not_member);
6679       return nullptr;
6680     }
6681 
6682     SemaRef.CheckConversionDeclarator(D, R, SC);
6683     IsVirtualOkay = true;
6684     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6685                                      D.getLocStart(), NameInfo,
6686                                      R, TInfo, isInline, isExplicit,
6687                                      isConstexpr, SourceLocation());
6688 
6689   } else if (DC->isRecord()) {
6690     // If the name of the function is the same as the name of the record,
6691     // then this must be an invalid constructor that has a return type.
6692     // (The parser checks for a return type and makes the declarator a
6693     // constructor if it has no return type).
6694     if (Name.getAsIdentifierInfo() &&
6695         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6696       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6697         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6698         << SourceRange(D.getIdentifierLoc());
6699       return nullptr;
6700     }
6701 
6702     // This is a C++ method declaration.
6703     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6704                                                cast<CXXRecordDecl>(DC),
6705                                                D.getLocStart(), NameInfo, R,
6706                                                TInfo, SC, isInline,
6707                                                isConstexpr, SourceLocation());
6708     IsVirtualOkay = !Ret->isStatic();
6709     return Ret;
6710   } else {
6711     // Determine whether the function was written with a
6712     // prototype. This true when:
6713     //   - we're in C++ (where every function has a prototype),
6714     return FunctionDecl::Create(SemaRef.Context, DC,
6715                                 D.getLocStart(),
6716                                 NameInfo, R, TInfo, SC, isInline,
6717                                 true/*HasPrototype*/, isConstexpr);
6718   }
6719 }
6720 
6721 enum OpenCLParamType {
6722   ValidKernelParam,
6723   PtrPtrKernelParam,
6724   PtrKernelParam,
6725   PrivatePtrKernelParam,
6726   InvalidKernelParam,
6727   RecordKernelParam
6728 };
6729 
6730 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6731   if (PT->isPointerType()) {
6732     QualType PointeeType = PT->getPointeeType();
6733     if (PointeeType->isPointerType())
6734       return PtrPtrKernelParam;
6735     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
6736                                               : PtrKernelParam;
6737   }
6738 
6739   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6740   // be used as builtin types.
6741 
6742   if (PT->isImageType())
6743     return PtrKernelParam;
6744 
6745   if (PT->isBooleanType())
6746     return InvalidKernelParam;
6747 
6748   if (PT->isEventT())
6749     return InvalidKernelParam;
6750 
6751   if (PT->isHalfType())
6752     return InvalidKernelParam;
6753 
6754   if (PT->isRecordType())
6755     return RecordKernelParam;
6756 
6757   return ValidKernelParam;
6758 }
6759 
6760 static void checkIsValidOpenCLKernelParameter(
6761   Sema &S,
6762   Declarator &D,
6763   ParmVarDecl *Param,
6764   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
6765   QualType PT = Param->getType();
6766 
6767   // Cache the valid types we encounter to avoid rechecking structs that are
6768   // used again
6769   if (ValidTypes.count(PT.getTypePtr()))
6770     return;
6771 
6772   switch (getOpenCLKernelParameterType(PT)) {
6773   case PtrPtrKernelParam:
6774     // OpenCL v1.2 s6.9.a:
6775     // A kernel function argument cannot be declared as a
6776     // pointer to a pointer type.
6777     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6778     D.setInvalidType();
6779     return;
6780 
6781   case PrivatePtrKernelParam:
6782     // OpenCL v1.2 s6.9.a:
6783     // A kernel function argument cannot be declared as a
6784     // pointer to the private address space.
6785     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
6786     D.setInvalidType();
6787     return;
6788 
6789     // OpenCL v1.2 s6.9.k:
6790     // Arguments to kernel functions in a program cannot be declared with the
6791     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6792     // uintptr_t or a struct and/or union that contain fields declared to be
6793     // one of these built-in scalar types.
6794 
6795   case InvalidKernelParam:
6796     // OpenCL v1.2 s6.8 n:
6797     // A kernel function argument cannot be declared
6798     // of event_t type.
6799     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6800     D.setInvalidType();
6801     return;
6802 
6803   case PtrKernelParam:
6804   case ValidKernelParam:
6805     ValidTypes.insert(PT.getTypePtr());
6806     return;
6807 
6808   case RecordKernelParam:
6809     break;
6810   }
6811 
6812   // Track nested structs we will inspect
6813   SmallVector<const Decl *, 4> VisitStack;
6814 
6815   // Track where we are in the nested structs. Items will migrate from
6816   // VisitStack to HistoryStack as we do the DFS for bad field.
6817   SmallVector<const FieldDecl *, 4> HistoryStack;
6818   HistoryStack.push_back(nullptr);
6819 
6820   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6821   VisitStack.push_back(PD);
6822 
6823   assert(VisitStack.back() && "First decl null?");
6824 
6825   do {
6826     const Decl *Next = VisitStack.pop_back_val();
6827     if (!Next) {
6828       assert(!HistoryStack.empty());
6829       // Found a marker, we have gone up a level
6830       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6831         ValidTypes.insert(Hist->getType().getTypePtr());
6832 
6833       continue;
6834     }
6835 
6836     // Adds everything except the original parameter declaration (which is not a
6837     // field itself) to the history stack.
6838     const RecordDecl *RD;
6839     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6840       HistoryStack.push_back(Field);
6841       RD = Field->getType()->castAs<RecordType>()->getDecl();
6842     } else {
6843       RD = cast<RecordDecl>(Next);
6844     }
6845 
6846     // Add a null marker so we know when we've gone back up a level
6847     VisitStack.push_back(nullptr);
6848 
6849     for (const auto *FD : RD->fields()) {
6850       QualType QT = FD->getType();
6851 
6852       if (ValidTypes.count(QT.getTypePtr()))
6853         continue;
6854 
6855       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6856       if (ParamType == ValidKernelParam)
6857         continue;
6858 
6859       if (ParamType == RecordKernelParam) {
6860         VisitStack.push_back(FD);
6861         continue;
6862       }
6863 
6864       // OpenCL v1.2 s6.9.p:
6865       // Arguments to kernel functions that are declared to be a struct or union
6866       // do not allow OpenCL objects to be passed as elements of the struct or
6867       // union.
6868       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
6869           ParamType == PrivatePtrKernelParam) {
6870         S.Diag(Param->getLocation(),
6871                diag::err_record_with_pointers_kernel_param)
6872           << PT->isUnionType()
6873           << PT;
6874       } else {
6875         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6876       }
6877 
6878       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6879         << PD->getDeclName();
6880 
6881       // We have an error, now let's go back up through history and show where
6882       // the offending field came from
6883       for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6884              E = HistoryStack.end(); I != E; ++I) {
6885         const FieldDecl *OuterField = *I;
6886         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6887           << OuterField->getType();
6888       }
6889 
6890       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6891         << QT->isPointerType()
6892         << QT;
6893       D.setInvalidType();
6894       return;
6895     }
6896   } while (!VisitStack.empty());
6897 }
6898 
6899 NamedDecl*
6900 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
6901                               TypeSourceInfo *TInfo, LookupResult &Previous,
6902                               MultiTemplateParamsArg TemplateParamLists,
6903                               bool &AddToScope) {
6904   QualType R = TInfo->getType();
6905 
6906   assert(R.getTypePtr()->isFunctionType());
6907 
6908   // TODO: consider using NameInfo for diagnostic.
6909   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6910   DeclarationName Name = NameInfo.getName();
6911   FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
6912 
6913   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6914     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6915          diag::err_invalid_thread)
6916       << DeclSpec::getSpecifierName(TSCS);
6917 
6918   if (D.isFirstDeclarationOfMember())
6919     adjustMemberFunctionCC(R, D.isStaticMember());
6920 
6921   bool isFriend = false;
6922   FunctionTemplateDecl *FunctionTemplate = nullptr;
6923   bool isExplicitSpecialization = false;
6924   bool isFunctionTemplateSpecialization = false;
6925 
6926   bool isDependentClassScopeExplicitSpecialization = false;
6927   bool HasExplicitTemplateArgs = false;
6928   TemplateArgumentListInfo TemplateArgs;
6929 
6930   bool isVirtualOkay = false;
6931 
6932   DeclContext *OriginalDC = DC;
6933   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6934 
6935   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6936                                               isVirtualOkay);
6937   if (!NewFD) return nullptr;
6938 
6939   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6940     NewFD->setTopLevelDeclInObjCContainer();
6941 
6942   // Set the lexical context. If this is a function-scope declaration, or has a
6943   // C++ scope specifier, or is the object of a friend declaration, the lexical
6944   // context will be different from the semantic context.
6945   NewFD->setLexicalDeclContext(CurContext);
6946 
6947   if (IsLocalExternDecl)
6948     NewFD->setLocalExternDecl();
6949 
6950   if (getLangOpts().CPlusPlus) {
6951     bool isInline = D.getDeclSpec().isInlineSpecified();
6952     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6953     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6954     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6955     isFriend = D.getDeclSpec().isFriendSpecified();
6956     if (isFriend && !isInline && D.isFunctionDefinition()) {
6957       // C++ [class.friend]p5
6958       //   A function can be defined in a friend declaration of a
6959       //   class . . . . Such a function is implicitly inline.
6960       NewFD->setImplicitlyInline();
6961     }
6962 
6963     // If this is a method defined in an __interface, and is not a constructor
6964     // or an overloaded operator, then set the pure flag (isVirtual will already
6965     // return true).
6966     if (const CXXRecordDecl *Parent =
6967           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6968       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
6969         NewFD->setPure(true);
6970     }
6971 
6972     SetNestedNameSpecifier(NewFD, D);
6973     isExplicitSpecialization = false;
6974     isFunctionTemplateSpecialization = false;
6975     if (D.isInvalidType())
6976       NewFD->setInvalidDecl();
6977 
6978     // Match up the template parameter lists with the scope specifier, then
6979     // determine whether we have a template or a template specialization.
6980     bool Invalid = false;
6981     if (TemplateParameterList *TemplateParams =
6982             MatchTemplateParametersToScopeSpecifier(
6983                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6984                 D.getCXXScopeSpec(),
6985                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
6986                     ? D.getName().TemplateId
6987                     : nullptr,
6988                 TemplateParamLists, isFriend, isExplicitSpecialization,
6989                 Invalid)) {
6990       if (TemplateParams->size() > 0) {
6991         // This is a function template
6992 
6993         // Check that we can declare a template here.
6994         if (CheckTemplateDeclScope(S, TemplateParams))
6995           return nullptr;
6996 
6997         // A destructor cannot be a template.
6998         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6999           Diag(NewFD->getLocation(), diag::err_destructor_template);
7000           return nullptr;
7001         }
7002 
7003         // If we're adding a template to a dependent context, we may need to
7004         // rebuilding some of the types used within the template parameter list,
7005         // now that we know what the current instantiation is.
7006         if (DC->isDependentContext()) {
7007           ContextRAII SavedContext(*this, DC);
7008           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7009             Invalid = true;
7010         }
7011 
7012 
7013         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7014                                                         NewFD->getLocation(),
7015                                                         Name, TemplateParams,
7016                                                         NewFD);
7017         FunctionTemplate->setLexicalDeclContext(CurContext);
7018         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7019 
7020         // For source fidelity, store the other template param lists.
7021         if (TemplateParamLists.size() > 1) {
7022           NewFD->setTemplateParameterListsInfo(Context,
7023                                                TemplateParamLists.size() - 1,
7024                                                TemplateParamLists.data());
7025         }
7026       } else {
7027         // This is a function template specialization.
7028         isFunctionTemplateSpecialization = true;
7029         // For source fidelity, store all the template param lists.
7030         if (TemplateParamLists.size() > 0)
7031           NewFD->setTemplateParameterListsInfo(Context,
7032                                                TemplateParamLists.size(),
7033                                                TemplateParamLists.data());
7034 
7035         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7036         if (isFriend) {
7037           // We want to remove the "template<>", found here.
7038           SourceRange RemoveRange = TemplateParams->getSourceRange();
7039 
7040           // If we remove the template<> and the name is not a
7041           // template-id, we're actually silently creating a problem:
7042           // the friend declaration will refer to an untemplated decl,
7043           // and clearly the user wants a template specialization.  So
7044           // we need to insert '<>' after the name.
7045           SourceLocation InsertLoc;
7046           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7047             InsertLoc = D.getName().getSourceRange().getEnd();
7048             InsertLoc = getLocForEndOfToken(InsertLoc);
7049           }
7050 
7051           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7052             << Name << RemoveRange
7053             << FixItHint::CreateRemoval(RemoveRange)
7054             << FixItHint::CreateInsertion(InsertLoc, "<>");
7055         }
7056       }
7057     }
7058     else {
7059       // All template param lists were matched against the scope specifier:
7060       // this is NOT (an explicit specialization of) a template.
7061       if (TemplateParamLists.size() > 0)
7062         // For source fidelity, store all the template param lists.
7063         NewFD->setTemplateParameterListsInfo(Context,
7064                                              TemplateParamLists.size(),
7065                                              TemplateParamLists.data());
7066     }
7067 
7068     if (Invalid) {
7069       NewFD->setInvalidDecl();
7070       if (FunctionTemplate)
7071         FunctionTemplate->setInvalidDecl();
7072     }
7073 
7074     // C++ [dcl.fct.spec]p5:
7075     //   The virtual specifier shall only be used in declarations of
7076     //   nonstatic class member functions that appear within a
7077     //   member-specification of a class declaration; see 10.3.
7078     //
7079     if (isVirtual && !NewFD->isInvalidDecl()) {
7080       if (!isVirtualOkay) {
7081         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7082              diag::err_virtual_non_function);
7083       } else if (!CurContext->isRecord()) {
7084         // 'virtual' was specified outside of the class.
7085         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7086              diag::err_virtual_out_of_class)
7087           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7088       } else if (NewFD->getDescribedFunctionTemplate()) {
7089         // C++ [temp.mem]p3:
7090         //  A member function template shall not be virtual.
7091         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7092              diag::err_virtual_member_function_template)
7093           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7094       } else {
7095         // Okay: Add virtual to the method.
7096         NewFD->setVirtualAsWritten(true);
7097       }
7098 
7099       if (getLangOpts().CPlusPlus14 &&
7100           NewFD->getReturnType()->isUndeducedType())
7101         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7102     }
7103 
7104     if (getLangOpts().CPlusPlus14 &&
7105         (NewFD->isDependentContext() ||
7106          (isFriend && CurContext->isDependentContext())) &&
7107         NewFD->getReturnType()->isUndeducedType()) {
7108       // If the function template is referenced directly (for instance, as a
7109       // member of the current instantiation), pretend it has a dependent type.
7110       // This is not really justified by the standard, but is the only sane
7111       // thing to do.
7112       // FIXME: For a friend function, we have not marked the function as being
7113       // a friend yet, so 'isDependentContext' on the FD doesn't work.
7114       const FunctionProtoType *FPT =
7115           NewFD->getType()->castAs<FunctionProtoType>();
7116       QualType Result =
7117           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7118       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7119                                              FPT->getExtProtoInfo()));
7120     }
7121 
7122     // C++ [dcl.fct.spec]p3:
7123     //  The inline specifier shall not appear on a block scope function
7124     //  declaration.
7125     if (isInline && !NewFD->isInvalidDecl()) {
7126       if (CurContext->isFunctionOrMethod()) {
7127         // 'inline' is not allowed on block scope function declaration.
7128         Diag(D.getDeclSpec().getInlineSpecLoc(),
7129              diag::err_inline_declaration_block_scope) << Name
7130           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7131       }
7132     }
7133 
7134     // C++ [dcl.fct.spec]p6:
7135     //  The explicit specifier shall be used only in the declaration of a
7136     //  constructor or conversion function within its class definition;
7137     //  see 12.3.1 and 12.3.2.
7138     if (isExplicit && !NewFD->isInvalidDecl()) {
7139       if (!CurContext->isRecord()) {
7140         // 'explicit' was specified outside of the class.
7141         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7142              diag::err_explicit_out_of_class)
7143           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7144       } else if (!isa<CXXConstructorDecl>(NewFD) &&
7145                  !isa<CXXConversionDecl>(NewFD)) {
7146         // 'explicit' was specified on a function that wasn't a constructor
7147         // or conversion function.
7148         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7149              diag::err_explicit_non_ctor_or_conv_function)
7150           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7151       }
7152     }
7153 
7154     if (isConstexpr) {
7155       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7156       // are implicitly inline.
7157       NewFD->setImplicitlyInline();
7158 
7159       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7160       // be either constructors or to return a literal type. Therefore,
7161       // destructors cannot be declared constexpr.
7162       if (isa<CXXDestructorDecl>(NewFD))
7163         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7164     }
7165 
7166     // If __module_private__ was specified, mark the function accordingly.
7167     if (D.getDeclSpec().isModulePrivateSpecified()) {
7168       if (isFunctionTemplateSpecialization) {
7169         SourceLocation ModulePrivateLoc
7170           = D.getDeclSpec().getModulePrivateSpecLoc();
7171         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
7172           << 0
7173           << FixItHint::CreateRemoval(ModulePrivateLoc);
7174       } else {
7175         NewFD->setModulePrivate();
7176         if (FunctionTemplate)
7177           FunctionTemplate->setModulePrivate();
7178       }
7179     }
7180 
7181     if (isFriend) {
7182       if (FunctionTemplate) {
7183         FunctionTemplate->setObjectOfFriendDecl();
7184         FunctionTemplate->setAccess(AS_public);
7185       }
7186       NewFD->setObjectOfFriendDecl();
7187       NewFD->setAccess(AS_public);
7188     }
7189 
7190     // If a function is defined as defaulted or deleted, mark it as such now.
7191     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
7192     // definition kind to FDK_Definition.
7193     switch (D.getFunctionDefinitionKind()) {
7194       case FDK_Declaration:
7195       case FDK_Definition:
7196         break;
7197 
7198       case FDK_Defaulted:
7199         NewFD->setDefaulted();
7200         break;
7201 
7202       case FDK_Deleted:
7203         NewFD->setDeletedAsWritten();
7204         break;
7205     }
7206 
7207     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
7208         D.isFunctionDefinition()) {
7209       // C++ [class.mfct]p2:
7210       //   A member function may be defined (8.4) in its class definition, in
7211       //   which case it is an inline member function (7.1.2)
7212       NewFD->setImplicitlyInline();
7213     }
7214 
7215     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
7216         !CurContext->isRecord()) {
7217       // C++ [class.static]p1:
7218       //   A data or function member of a class may be declared static
7219       //   in a class definition, in which case it is a static member of
7220       //   the class.
7221 
7222       // Complain about the 'static' specifier if it's on an out-of-line
7223       // member function definition.
7224       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7225            diag::err_static_out_of_line)
7226         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7227     }
7228 
7229     // C++11 [except.spec]p15:
7230     //   A deallocation function with no exception-specification is treated
7231     //   as if it were specified with noexcept(true).
7232     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
7233     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
7234          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
7235         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
7236       NewFD->setType(Context.getFunctionType(
7237           FPT->getReturnType(), FPT->getParamTypes(),
7238           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
7239   }
7240 
7241   // Filter out previous declarations that don't match the scope.
7242   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
7243                        D.getCXXScopeSpec().isNotEmpty() ||
7244                        isExplicitSpecialization ||
7245                        isFunctionTemplateSpecialization);
7246 
7247   // Handle GNU asm-label extension (encoded as an attribute).
7248   if (Expr *E = (Expr*) D.getAsmLabel()) {
7249     // The parser guarantees this is a string.
7250     StringLiteral *SE = cast<StringLiteral>(E);
7251     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
7252                                                 SE->getString(), 0));
7253   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7254     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7255       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
7256     if (I != ExtnameUndeclaredIdentifiers.end()) {
7257       NewFD->addAttr(I->second);
7258       ExtnameUndeclaredIdentifiers.erase(I);
7259     }
7260   }
7261 
7262   // Copy the parameter declarations from the declarator D to the function
7263   // declaration NewFD, if they are available.  First scavenge them into Params.
7264   SmallVector<ParmVarDecl*, 16> Params;
7265   if (D.isFunctionDeclarator()) {
7266     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7267 
7268     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
7269     // function that takes no arguments, not a function that takes a
7270     // single void argument.
7271     // We let through "const void" here because Sema::GetTypeForDeclarator
7272     // already checks for that case.
7273     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
7274       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
7275         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
7276         assert(Param->getDeclContext() != NewFD && "Was set before ?");
7277         Param->setDeclContext(NewFD);
7278         Params.push_back(Param);
7279 
7280         if (Param->isInvalidDecl())
7281           NewFD->setInvalidDecl();
7282       }
7283     }
7284 
7285   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
7286     // When we're declaring a function with a typedef, typeof, etc as in the
7287     // following example, we'll need to synthesize (unnamed)
7288     // parameters for use in the declaration.
7289     //
7290     // @code
7291     // typedef void fn(int);
7292     // fn f;
7293     // @endcode
7294 
7295     // Synthesize a parameter for each argument type.
7296     for (const auto &AI : FT->param_types()) {
7297       ParmVarDecl *Param =
7298           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
7299       Param->setScopeInfo(0, Params.size());
7300       Params.push_back(Param);
7301     }
7302   } else {
7303     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
7304            "Should not need args for typedef of non-prototype fn");
7305   }
7306 
7307   // Finally, we know we have the right number of parameters, install them.
7308   NewFD->setParams(Params);
7309 
7310   // Find all anonymous symbols defined during the declaration of this function
7311   // and add to NewFD. This lets us track decls such 'enum Y' in:
7312   //
7313   //   void f(enum Y {AA} x) {}
7314   //
7315   // which would otherwise incorrectly end up in the translation unit scope.
7316   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
7317   DeclsInPrototypeScope.clear();
7318 
7319   if (D.getDeclSpec().isNoreturnSpecified())
7320     NewFD->addAttr(
7321         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
7322                                        Context, 0));
7323 
7324   // Functions returning a variably modified type violate C99 6.7.5.2p2
7325   // because all functions have linkage.
7326   if (!NewFD->isInvalidDecl() &&
7327       NewFD->getReturnType()->isVariablyModifiedType()) {
7328     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
7329     NewFD->setInvalidDecl();
7330   }
7331 
7332   if (D.isFunctionDefinition() && CodeSegStack.CurrentValue &&
7333       !NewFD->hasAttr<SectionAttr>()) {
7334     NewFD->addAttr(
7335         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
7336                                     CodeSegStack.CurrentValue->getString(),
7337                                     CodeSegStack.CurrentPragmaLocation));
7338     if (UnifySection(CodeSegStack.CurrentValue->getString(),
7339                      PSF_Implicit | PSF_Execute | PSF_Read, NewFD))
7340       NewFD->dropAttr<SectionAttr>();
7341   }
7342 
7343   // Handle attributes.
7344   ProcessDeclAttributes(S, NewFD, D);
7345 
7346   QualType RetType = NewFD->getReturnType();
7347   const CXXRecordDecl *Ret = RetType->isRecordType() ?
7348       RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
7349   if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
7350       Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
7351     const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7352     // Attach WarnUnusedResult to functions returning types with that attribute.
7353     // Don't apply the attribute to that type's own non-static member functions
7354     // (to avoid warning on things like assignment operators)
7355     if (!MD || MD->getParent() != Ret)
7356       NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context));
7357   }
7358 
7359   if (getLangOpts().OpenCL) {
7360     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
7361     // type declaration will generate a compilation error.
7362     unsigned AddressSpace = RetType.getAddressSpace();
7363     if (AddressSpace == LangAS::opencl_local ||
7364         AddressSpace == LangAS::opencl_global ||
7365         AddressSpace == LangAS::opencl_constant) {
7366       Diag(NewFD->getLocation(),
7367            diag::err_opencl_return_value_with_address_space);
7368       NewFD->setInvalidDecl();
7369     }
7370   }
7371 
7372   if (!getLangOpts().CPlusPlus) {
7373     // Perform semantic checking on the function declaration.
7374     bool isExplicitSpecialization=false;
7375     if (!NewFD->isInvalidDecl() && NewFD->isMain())
7376       CheckMain(NewFD, D.getDeclSpec());
7377 
7378     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7379       CheckMSVCRTEntryPoint(NewFD);
7380 
7381     if (!NewFD->isInvalidDecl())
7382       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7383                                                   isExplicitSpecialization));
7384     else if (!Previous.empty())
7385       // Make graceful recovery from an invalid redeclaration.
7386       D.setRedeclaration(true);
7387     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7388             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7389            "previous declaration set still overloaded");
7390   } else {
7391     // C++11 [replacement.functions]p3:
7392     //  The program's definitions shall not be specified as inline.
7393     //
7394     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7395     //
7396     // Suppress the diagnostic if the function is __attribute__((used)), since
7397     // that forces an external definition to be emitted.
7398     if (D.getDeclSpec().isInlineSpecified() &&
7399         NewFD->isReplaceableGlobalAllocationFunction() &&
7400         !NewFD->hasAttr<UsedAttr>())
7401       Diag(D.getDeclSpec().getInlineSpecLoc(),
7402            diag::ext_operator_new_delete_declared_inline)
7403         << NewFD->getDeclName();
7404 
7405     // If the declarator is a template-id, translate the parser's template
7406     // argument list into our AST format.
7407     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7408       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7409       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7410       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
7411       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7412                                          TemplateId->NumArgs);
7413       translateTemplateArguments(TemplateArgsPtr,
7414                                  TemplateArgs);
7415 
7416       HasExplicitTemplateArgs = true;
7417 
7418       if (NewFD->isInvalidDecl()) {
7419         HasExplicitTemplateArgs = false;
7420       } else if (FunctionTemplate) {
7421         // Function template with explicit template arguments.
7422         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7423           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7424 
7425         HasExplicitTemplateArgs = false;
7426       } else {
7427         assert((isFunctionTemplateSpecialization ||
7428                 D.getDeclSpec().isFriendSpecified()) &&
7429                "should have a 'template<>' for this decl");
7430         // "friend void foo<>(int);" is an implicit specialization decl.
7431         isFunctionTemplateSpecialization = true;
7432       }
7433     } else if (isFriend && isFunctionTemplateSpecialization) {
7434       // This combination is only possible in a recovery case;  the user
7435       // wrote something like:
7436       //   template <> friend void foo(int);
7437       // which we're recovering from as if the user had written:
7438       //   friend void foo<>(int);
7439       // Go ahead and fake up a template id.
7440       HasExplicitTemplateArgs = true;
7441       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7442       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
7443     }
7444 
7445     // If it's a friend (and only if it's a friend), it's possible
7446     // that either the specialized function type or the specialized
7447     // template is dependent, and therefore matching will fail.  In
7448     // this case, don't check the specialization yet.
7449     bool InstantiationDependent = false;
7450     if (isFunctionTemplateSpecialization && isFriend &&
7451         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7452          TemplateSpecializationType::anyDependentTemplateArguments(
7453             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7454             InstantiationDependent))) {
7455       assert(HasExplicitTemplateArgs &&
7456              "friend function specialization without template args");
7457       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7458                                                        Previous))
7459         NewFD->setInvalidDecl();
7460     } else if (isFunctionTemplateSpecialization) {
7461       if (CurContext->isDependentContext() && CurContext->isRecord()
7462           && !isFriend) {
7463         isDependentClassScopeExplicitSpecialization = true;
7464         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
7465           diag::ext_function_specialization_in_class :
7466           diag::err_function_specialization_in_class)
7467           << NewFD->getDeclName();
7468       } else if (CheckFunctionTemplateSpecialization(NewFD,
7469                                   (HasExplicitTemplateArgs ? &TemplateArgs
7470                                                            : nullptr),
7471                                                      Previous))
7472         NewFD->setInvalidDecl();
7473 
7474       // C++ [dcl.stc]p1:
7475       //   A storage-class-specifier shall not be specified in an explicit
7476       //   specialization (14.7.3)
7477       FunctionTemplateSpecializationInfo *Info =
7478           NewFD->getTemplateSpecializationInfo();
7479       if (Info && SC != SC_None) {
7480         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
7481           Diag(NewFD->getLocation(),
7482                diag::err_explicit_specialization_inconsistent_storage_class)
7483             << SC
7484             << FixItHint::CreateRemoval(
7485                                       D.getDeclSpec().getStorageClassSpecLoc());
7486 
7487         else
7488           Diag(NewFD->getLocation(),
7489                diag::ext_explicit_specialization_storage_class)
7490             << FixItHint::CreateRemoval(
7491                                       D.getDeclSpec().getStorageClassSpecLoc());
7492       }
7493 
7494     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7495       if (CheckMemberSpecialization(NewFD, Previous))
7496           NewFD->setInvalidDecl();
7497     }
7498 
7499     // Perform semantic checking on the function declaration.
7500     if (!isDependentClassScopeExplicitSpecialization) {
7501       if (!NewFD->isInvalidDecl() && NewFD->isMain())
7502         CheckMain(NewFD, D.getDeclSpec());
7503 
7504       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7505         CheckMSVCRTEntryPoint(NewFD);
7506 
7507       if (!NewFD->isInvalidDecl())
7508         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7509                                                     isExplicitSpecialization));
7510     }
7511 
7512     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7513             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7514            "previous declaration set still overloaded");
7515 
7516     NamedDecl *PrincipalDecl = (FunctionTemplate
7517                                 ? cast<NamedDecl>(FunctionTemplate)
7518                                 : NewFD);
7519 
7520     if (isFriend && D.isRedeclaration()) {
7521       AccessSpecifier Access = AS_public;
7522       if (!NewFD->isInvalidDecl())
7523         Access = NewFD->getPreviousDecl()->getAccess();
7524 
7525       NewFD->setAccess(Access);
7526       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
7527     }
7528 
7529     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7530         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7531       PrincipalDecl->setNonMemberOperator();
7532 
7533     // If we have a function template, check the template parameter
7534     // list. This will check and merge default template arguments.
7535     if (FunctionTemplate) {
7536       FunctionTemplateDecl *PrevTemplate =
7537                                      FunctionTemplate->getPreviousDecl();
7538       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
7539                        PrevTemplate ? PrevTemplate->getTemplateParameters()
7540                                     : nullptr,
7541                             D.getDeclSpec().isFriendSpecified()
7542                               ? (D.isFunctionDefinition()
7543                                    ? TPC_FriendFunctionTemplateDefinition
7544                                    : TPC_FriendFunctionTemplate)
7545                               : (D.getCXXScopeSpec().isSet() &&
7546                                  DC && DC->isRecord() &&
7547                                  DC->isDependentContext())
7548                                   ? TPC_ClassTemplateMember
7549                                   : TPC_FunctionTemplate);
7550     }
7551 
7552     if (NewFD->isInvalidDecl()) {
7553       // Ignore all the rest of this.
7554     } else if (!D.isRedeclaration()) {
7555       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
7556                                        AddToScope };
7557       // Fake up an access specifier if it's supposed to be a class member.
7558       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7559         NewFD->setAccess(AS_public);
7560 
7561       // Qualified decls generally require a previous declaration.
7562       if (D.getCXXScopeSpec().isSet()) {
7563         // ...with the major exception of templated-scope or
7564         // dependent-scope friend declarations.
7565 
7566         // TODO: we currently also suppress this check in dependent
7567         // contexts because (1) the parameter depth will be off when
7568         // matching friend templates and (2) we might actually be
7569         // selecting a friend based on a dependent factor.  But there
7570         // are situations where these conditions don't apply and we
7571         // can actually do this check immediately.
7572         if (isFriend &&
7573             (TemplateParamLists.size() ||
7574              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7575              CurContext->isDependentContext())) {
7576           // ignore these
7577         } else {
7578           // The user tried to provide an out-of-line definition for a
7579           // function that is a member of a class or namespace, but there
7580           // was no such member function declared (C++ [class.mfct]p2,
7581           // C++ [namespace.memdef]p2). For example:
7582           //
7583           // class X {
7584           //   void f() const;
7585           // };
7586           //
7587           // void X::f() { } // ill-formed
7588           //
7589           // Complain about this problem, and attempt to suggest close
7590           // matches (e.g., those that differ only in cv-qualifiers and
7591           // whether the parameter types are references).
7592 
7593           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7594                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
7595             AddToScope = ExtraArgs.AddToScope;
7596             return Result;
7597           }
7598         }
7599 
7600         // Unqualified local friend declarations are required to resolve
7601         // to something.
7602       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
7603         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7604                 *this, Previous, NewFD, ExtraArgs, true, S)) {
7605           AddToScope = ExtraArgs.AddToScope;
7606           return Result;
7607         }
7608       }
7609 
7610     } else if (!D.isFunctionDefinition() &&
7611                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
7612                !isFriend && !isFunctionTemplateSpecialization &&
7613                !isExplicitSpecialization) {
7614       // An out-of-line member function declaration must also be a
7615       // definition (C++ [class.mfct]p2).
7616       // Note that this is not the case for explicit specializations of
7617       // function templates or member functions of class templates, per
7618       // C++ [temp.expl.spec]p2. We also allow these declarations as an
7619       // extension for compatibility with old SWIG code which likes to
7620       // generate them.
7621       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7622         << D.getCXXScopeSpec().getRange();
7623     }
7624   }
7625 
7626   ProcessPragmaWeak(S, NewFD);
7627   checkAttributesAfterMerging(*this, *NewFD);
7628 
7629   AddKnownFunctionAttributes(NewFD);
7630 
7631   if (NewFD->hasAttr<OverloadableAttr>() &&
7632       !NewFD->getType()->getAs<FunctionProtoType>()) {
7633     Diag(NewFD->getLocation(),
7634          diag::err_attribute_overloadable_no_prototype)
7635       << NewFD;
7636 
7637     // Turn this into a variadic function with no parameters.
7638     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
7639     FunctionProtoType::ExtProtoInfo EPI(
7640         Context.getDefaultCallingConvention(true, false));
7641     EPI.Variadic = true;
7642     EPI.ExtInfo = FT->getExtInfo();
7643 
7644     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
7645     NewFD->setType(R);
7646   }
7647 
7648   // If there's a #pragma GCC visibility in scope, and this isn't a class
7649   // member, set the visibility of this function.
7650   if (!DC->isRecord() && NewFD->isExternallyVisible())
7651     AddPushedVisibilityAttribute(NewFD);
7652 
7653   // If there's a #pragma clang arc_cf_code_audited in scope, consider
7654   // marking the function.
7655   AddCFAuditedAttribute(NewFD);
7656 
7657   // If this is a function definition, check if we have to apply optnone due to
7658   // a pragma.
7659   if(D.isFunctionDefinition())
7660     AddRangeBasedOptnone(NewFD);
7661 
7662   // If this is the first declaration of an extern C variable, update
7663   // the map of such variables.
7664   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
7665       isIncompleteDeclExternC(*this, NewFD))
7666     RegisterLocallyScopedExternCDecl(NewFD, S);
7667 
7668   // Set this FunctionDecl's range up to the right paren.
7669   NewFD->setRangeEnd(D.getSourceRange().getEnd());
7670 
7671   if (D.isRedeclaration() && !Previous.empty()) {
7672     checkDLLAttributeRedeclaration(
7673         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
7674         isExplicitSpecialization || isFunctionTemplateSpecialization);
7675   }
7676 
7677   if (getLangOpts().CPlusPlus) {
7678     if (FunctionTemplate) {
7679       if (NewFD->isInvalidDecl())
7680         FunctionTemplate->setInvalidDecl();
7681       return FunctionTemplate;
7682     }
7683   }
7684 
7685   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
7686     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7687     if ((getLangOpts().OpenCLVersion >= 120)
7688         && (SC == SC_Static)) {
7689       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7690       D.setInvalidType();
7691     }
7692 
7693     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7694     if (!NewFD->getReturnType()->isVoidType()) {
7695       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
7696       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
7697           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
7698                                 : FixItHint());
7699       D.setInvalidType();
7700     }
7701 
7702     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
7703     for (auto Param : NewFD->params())
7704       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
7705   }
7706 
7707   MarkUnusedFileScopedDecl(NewFD);
7708 
7709   if (getLangOpts().CUDA)
7710     if (IdentifierInfo *II = NewFD->getIdentifier())
7711       if (!NewFD->isInvalidDecl() &&
7712           NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7713         if (II->isStr("cudaConfigureCall")) {
7714           if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
7715             Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7716 
7717           Context.setcudaConfigureCallDecl(NewFD);
7718         }
7719       }
7720 
7721   // Here we have an function template explicit specialization at class scope.
7722   // The actually specialization will be postponed to template instatiation
7723   // time via the ClassScopeFunctionSpecializationDecl node.
7724   if (isDependentClassScopeExplicitSpecialization) {
7725     ClassScopeFunctionSpecializationDecl *NewSpec =
7726                          ClassScopeFunctionSpecializationDecl::Create(
7727                                 Context, CurContext, SourceLocation(),
7728                                 cast<CXXMethodDecl>(NewFD),
7729                                 HasExplicitTemplateArgs, TemplateArgs);
7730     CurContext->addDecl(NewSpec);
7731     AddToScope = false;
7732   }
7733 
7734   return NewFD;
7735 }
7736 
7737 /// \brief Perform semantic checking of a new function declaration.
7738 ///
7739 /// Performs semantic analysis of the new function declaration
7740 /// NewFD. This routine performs all semantic checking that does not
7741 /// require the actual declarator involved in the declaration, and is
7742 /// used both for the declaration of functions as they are parsed
7743 /// (called via ActOnDeclarator) and for the declaration of functions
7744 /// that have been instantiated via C++ template instantiation (called
7745 /// via InstantiateDecl).
7746 ///
7747 /// \param IsExplicitSpecialization whether this new function declaration is
7748 /// an explicit specialization of the previous declaration.
7749 ///
7750 /// This sets NewFD->isInvalidDecl() to true if there was an error.
7751 ///
7752 /// \returns true if the function declaration is a redeclaration.
7753 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
7754                                     LookupResult &Previous,
7755                                     bool IsExplicitSpecialization) {
7756   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
7757          "Variably modified return types are not handled here");
7758 
7759   // Determine whether the type of this function should be merged with
7760   // a previous visible declaration. This never happens for functions in C++,
7761   // and always happens in C if the previous declaration was visible.
7762   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7763                                !Previous.isShadowed();
7764 
7765   // Filter out any non-conflicting previous declarations.
7766   filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7767 
7768   bool Redeclaration = false;
7769   NamedDecl *OldDecl = nullptr;
7770 
7771   // Merge or overload the declaration with an existing declaration of
7772   // the same name, if appropriate.
7773   if (!Previous.empty()) {
7774     // Determine whether NewFD is an overload of PrevDecl or
7775     // a declaration that requires merging. If it's an overload,
7776     // there's no more work to do here; we'll just add the new
7777     // function to the scope.
7778     if (!AllowOverloadingOfFunction(Previous, Context)) {
7779       NamedDecl *Candidate = Previous.getFoundDecl();
7780       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7781         Redeclaration = true;
7782         OldDecl = Candidate;
7783       }
7784     } else {
7785       switch (CheckOverload(S, NewFD, Previous, OldDecl,
7786                             /*NewIsUsingDecl*/ false)) {
7787       case Ovl_Match:
7788         Redeclaration = true;
7789         break;
7790 
7791       case Ovl_NonFunction:
7792         Redeclaration = true;
7793         break;
7794 
7795       case Ovl_Overload:
7796         Redeclaration = false;
7797         break;
7798       }
7799 
7800       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7801         // If a function name is overloadable in C, then every function
7802         // with that name must be marked "overloadable".
7803         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7804           << Redeclaration << NewFD;
7805         NamedDecl *OverloadedDecl = nullptr;
7806         if (Redeclaration)
7807           OverloadedDecl = OldDecl;
7808         else if (!Previous.empty())
7809           OverloadedDecl = Previous.getRepresentativeDecl();
7810         if (OverloadedDecl)
7811           Diag(OverloadedDecl->getLocation(),
7812                diag::note_attribute_overloadable_prev_overload);
7813         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
7814       }
7815     }
7816   }
7817 
7818   // Check for a previous extern "C" declaration with this name.
7819   if (!Redeclaration &&
7820       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7821     filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7822     if (!Previous.empty()) {
7823       // This is an extern "C" declaration with the same name as a previous
7824       // declaration, and thus redeclares that entity...
7825       Redeclaration = true;
7826       OldDecl = Previous.getFoundDecl();
7827       MergeTypeWithPrevious = false;
7828 
7829       // ... except in the presence of __attribute__((overloadable)).
7830       if (OldDecl->hasAttr<OverloadableAttr>()) {
7831         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7832           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7833             << Redeclaration << NewFD;
7834           Diag(Previous.getFoundDecl()->getLocation(),
7835                diag::note_attribute_overloadable_prev_overload);
7836           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
7837         }
7838         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7839           Redeclaration = false;
7840           OldDecl = nullptr;
7841         }
7842       }
7843     }
7844   }
7845 
7846   // C++11 [dcl.constexpr]p8:
7847   //   A constexpr specifier for a non-static member function that is not
7848   //   a constructor declares that member function to be const.
7849   //
7850   // This needs to be delayed until we know whether this is an out-of-line
7851   // definition of a static member function.
7852   //
7853   // This rule is not present in C++1y, so we produce a backwards
7854   // compatibility warning whenever it happens in C++11.
7855   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7856   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
7857       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
7858       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7859     CXXMethodDecl *OldMD = nullptr;
7860     if (OldDecl)
7861       OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction());
7862     if (!OldMD || !OldMD->isStatic()) {
7863       const FunctionProtoType *FPT =
7864         MD->getType()->castAs<FunctionProtoType>();
7865       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7866       EPI.TypeQuals |= Qualifiers::Const;
7867       MD->setType(Context.getFunctionType(FPT->getReturnType(),
7868                                           FPT->getParamTypes(), EPI));
7869 
7870       // Warn that we did this, if we're not performing template instantiation.
7871       // In that case, we'll have warned already when the template was defined.
7872       if (ActiveTemplateInstantiations.empty()) {
7873         SourceLocation AddConstLoc;
7874         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7875                 .IgnoreParens().getAs<FunctionTypeLoc>())
7876           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
7877 
7878         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
7879           << FixItHint::CreateInsertion(AddConstLoc, " const");
7880       }
7881     }
7882   }
7883 
7884   if (Redeclaration) {
7885     // NewFD and OldDecl represent declarations that need to be
7886     // merged.
7887     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
7888       NewFD->setInvalidDecl();
7889       return Redeclaration;
7890     }
7891 
7892     Previous.clear();
7893     Previous.addDecl(OldDecl);
7894 
7895     if (FunctionTemplateDecl *OldTemplateDecl
7896                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7897       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7898       FunctionTemplateDecl *NewTemplateDecl
7899         = NewFD->getDescribedFunctionTemplate();
7900       assert(NewTemplateDecl && "Template/non-template mismatch");
7901       if (CXXMethodDecl *Method
7902             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7903         Method->setAccess(OldTemplateDecl->getAccess());
7904         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
7905       }
7906 
7907       // If this is an explicit specialization of a member that is a function
7908       // template, mark it as a member specialization.
7909       if (IsExplicitSpecialization &&
7910           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7911         NewTemplateDecl->setMemberSpecialization();
7912         assert(OldTemplateDecl->isMemberSpecialization());
7913       }
7914 
7915     } else {
7916       // This needs to happen first so that 'inline' propagates.
7917       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
7918 
7919       if (isa<CXXMethodDecl>(NewFD)) {
7920         // A valid redeclaration of a C++ method must be out-of-line,
7921         // but (unfortunately) it's not necessarily a definition
7922         // because of templates, which means that the previous
7923         // declaration is not necessarily from the class definition.
7924 
7925         // For just setting the access, that doesn't matter.
7926         CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7927         NewFD->setAccess(oldMethod->getAccess());
7928 
7929         // Update the key-function state if necessary for this ABI.
7930         if (NewFD->isInlined() &&
7931             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7932           // setNonKeyFunction needs to work with the original
7933           // declaration from the class definition, and isVirtual() is
7934           // just faster in that case, so map back to that now.
7935           oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
7936           if (oldMethod->isVirtual()) {
7937             Context.setNonKeyFunction(oldMethod);
7938           }
7939         }
7940       }
7941     }
7942   }
7943 
7944   // Semantic checking for this function declaration (in isolation).
7945 
7946   // Diagnose the use of callee-cleanup calls on unprototyped functions.
7947   QualType NewQType = Context.getCanonicalType(NewFD->getType());
7948   const FunctionType *NewType = cast<FunctionType>(NewQType);
7949   if (isa<FunctionNoProtoType>(NewType)) {
7950     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
7951     if (isCalleeCleanup(NewTypeInfo.getCC())) {
7952       // Windows system headers sometimes accidentally use stdcall without
7953       // (void) parameters, so use a default-error warning in this case :-/
7954       int DiagID = NewTypeInfo.getCC() == CC_X86StdCall
7955           ? diag::warn_cconv_knr : diag::err_cconv_knr;
7956       Diag(NewFD->getLocation(), DiagID)
7957           << FunctionType::getNameForCallConv(NewTypeInfo.getCC());
7958     }
7959   }
7960 
7961   if (getLangOpts().CPlusPlus) {
7962     // C++-specific checks.
7963     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7964       CheckConstructor(Constructor);
7965     } else if (CXXDestructorDecl *Destructor =
7966                 dyn_cast<CXXDestructorDecl>(NewFD)) {
7967       CXXRecordDecl *Record = Destructor->getParent();
7968       QualType ClassType = Context.getTypeDeclType(Record);
7969 
7970       // FIXME: Shouldn't we be able to perform this check even when the class
7971       // type is dependent? Both gcc and edg can handle that.
7972       if (!ClassType->isDependentType()) {
7973         DeclarationName Name
7974           = Context.DeclarationNames.getCXXDestructorName(
7975                                         Context.getCanonicalType(ClassType));
7976         if (NewFD->getDeclName() != Name) {
7977           Diag(NewFD->getLocation(), diag::err_destructor_name);
7978           NewFD->setInvalidDecl();
7979           return Redeclaration;
7980         }
7981       }
7982     } else if (CXXConversionDecl *Conversion
7983                = dyn_cast<CXXConversionDecl>(NewFD)) {
7984       ActOnConversionDeclarator(Conversion);
7985     }
7986 
7987     // Find any virtual functions that this function overrides.
7988     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7989       if (!Method->isFunctionTemplateSpecialization() &&
7990           !Method->getDescribedFunctionTemplate() &&
7991           Method->isCanonicalDecl()) {
7992         if (AddOverriddenMethods(Method->getParent(), Method)) {
7993           // If the function was marked as "static", we have a problem.
7994           if (NewFD->getStorageClass() == SC_Static) {
7995             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
7996           }
7997         }
7998       }
7999 
8000       if (Method->isStatic())
8001         checkThisInStaticMemberFunctionType(Method);
8002     }
8003 
8004     // Extra checking for C++ overloaded operators (C++ [over.oper]).
8005     if (NewFD->isOverloadedOperator() &&
8006         CheckOverloadedOperatorDeclaration(NewFD)) {
8007       NewFD->setInvalidDecl();
8008       return Redeclaration;
8009     }
8010 
8011     // Extra checking for C++0x literal operators (C++0x [over.literal]).
8012     if (NewFD->getLiteralIdentifier() &&
8013         CheckLiteralOperatorDeclaration(NewFD)) {
8014       NewFD->setInvalidDecl();
8015       return Redeclaration;
8016     }
8017 
8018     // In C++, check default arguments now that we have merged decls. Unless
8019     // the lexical context is the class, because in this case this is done
8020     // during delayed parsing anyway.
8021     if (!CurContext->isRecord())
8022       CheckCXXDefaultArguments(NewFD);
8023 
8024     // If this function declares a builtin function, check the type of this
8025     // declaration against the expected type for the builtin.
8026     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8027       ASTContext::GetBuiltinTypeError Error;
8028       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8029       QualType T = Context.GetBuiltinType(BuiltinID, Error);
8030       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8031         // The type of this function differs from the type of the builtin,
8032         // so forget about the builtin entirely.
8033         Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
8034       }
8035     }
8036 
8037     // If this function is declared as being extern "C", then check to see if
8038     // the function returns a UDT (class, struct, or union type) that is not C
8039     // compatible, and if it does, warn the user.
8040     // But, issue any diagnostic on the first declaration only.
8041     if (NewFD->isExternC() && Previous.empty()) {
8042       QualType R = NewFD->getReturnType();
8043       if (R->isIncompleteType() && !R->isVoidType())
8044         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8045             << NewFD << R;
8046       else if (!R.isPODType(Context) && !R->isVoidType() &&
8047                !R->isObjCObjectPointerType())
8048         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8049     }
8050   }
8051   return Redeclaration;
8052 }
8053 
8054 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8055   // C++11 [basic.start.main]p3:
8056   //   A program that [...] declares main to be inline, static or
8057   //   constexpr is ill-formed.
8058   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
8059   //   appear in a declaration of main.
8060   // static main is not an error under C99, but we should warn about it.
8061   // We accept _Noreturn main as an extension.
8062   if (FD->getStorageClass() == SC_Static)
8063     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8064          ? diag::err_static_main : diag::warn_static_main)
8065       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8066   if (FD->isInlineSpecified())
8067     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8068       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8069   if (DS.isNoreturnSpecified()) {
8070     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8071     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8072     Diag(NoreturnLoc, diag::ext_noreturn_main);
8073     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8074       << FixItHint::CreateRemoval(NoreturnRange);
8075   }
8076   if (FD->isConstexpr()) {
8077     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8078       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8079     FD->setConstexpr(false);
8080   }
8081 
8082   if (getLangOpts().OpenCL) {
8083     Diag(FD->getLocation(), diag::err_opencl_no_main)
8084         << FD->hasAttr<OpenCLKernelAttr>();
8085     FD->setInvalidDecl();
8086     return;
8087   }
8088 
8089   QualType T = FD->getType();
8090   assert(T->isFunctionType() && "function decl is not of function type");
8091   const FunctionType* FT = T->castAs<FunctionType>();
8092 
8093   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8094     // In C with GNU extensions we allow main() to have non-integer return
8095     // type, but we should warn about the extension, and we disable the
8096     // implicit-return-zero rule.
8097 
8098     // GCC in C mode accepts qualified 'int'.
8099     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8100       FD->setHasImplicitReturnZero(true);
8101     else {
8102       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8103       SourceRange RTRange = FD->getReturnTypeSourceRange();
8104       if (RTRange.isValid())
8105         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8106             << FixItHint::CreateReplacement(RTRange, "int");
8107     }
8108   } else {
8109     // In C and C++, main magically returns 0 if you fall off the end;
8110     // set the flag which tells us that.
8111     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8112 
8113     // All the standards say that main() should return 'int'.
8114     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8115       FD->setHasImplicitReturnZero(true);
8116     else {
8117       // Otherwise, this is just a flat-out error.
8118       SourceRange RTRange = FD->getReturnTypeSourceRange();
8119       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8120           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8121                                 : FixItHint());
8122       FD->setInvalidDecl(true);
8123     }
8124   }
8125 
8126   // Treat protoless main() as nullary.
8127   if (isa<FunctionNoProtoType>(FT)) return;
8128 
8129   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8130   unsigned nparams = FTP->getNumParams();
8131   assert(FD->getNumParams() == nparams);
8132 
8133   bool HasExtraParameters = (nparams > 3);
8134 
8135   // Darwin passes an undocumented fourth argument of type char**.  If
8136   // other platforms start sprouting these, the logic below will start
8137   // getting shifty.
8138   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8139     HasExtraParameters = false;
8140 
8141   if (HasExtraParameters) {
8142     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8143     FD->setInvalidDecl(true);
8144     nparams = 3;
8145   }
8146 
8147   // FIXME: a lot of the following diagnostics would be improved
8148   // if we had some location information about types.
8149 
8150   QualType CharPP =
8151     Context.getPointerType(Context.getPointerType(Context.CharTy));
8152   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
8153 
8154   for (unsigned i = 0; i < nparams; ++i) {
8155     QualType AT = FTP->getParamType(i);
8156 
8157     bool mismatch = true;
8158 
8159     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
8160       mismatch = false;
8161     else if (Expected[i] == CharPP) {
8162       // As an extension, the following forms are okay:
8163       //   char const **
8164       //   char const * const *
8165       //   char * const *
8166 
8167       QualifierCollector qs;
8168       const PointerType* PT;
8169       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
8170           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
8171           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
8172                               Context.CharTy)) {
8173         qs.removeConst();
8174         mismatch = !qs.empty();
8175       }
8176     }
8177 
8178     if (mismatch) {
8179       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
8180       // TODO: suggest replacing given type with expected type
8181       FD->setInvalidDecl(true);
8182     }
8183   }
8184 
8185   if (nparams == 1 && !FD->isInvalidDecl()) {
8186     Diag(FD->getLocation(), diag::warn_main_one_arg);
8187   }
8188 
8189   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8190     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8191     FD->setInvalidDecl();
8192   }
8193 }
8194 
8195 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
8196   QualType T = FD->getType();
8197   assert(T->isFunctionType() && "function decl is not of function type");
8198   const FunctionType *FT = T->castAs<FunctionType>();
8199 
8200   // Set an implicit return of 'zero' if the function can return some integral,
8201   // enumeration, pointer or nullptr type.
8202   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
8203       FT->getReturnType()->isAnyPointerType() ||
8204       FT->getReturnType()->isNullPtrType())
8205     // DllMain is exempt because a return value of zero means it failed.
8206     if (FD->getName() != "DllMain")
8207       FD->setHasImplicitReturnZero(true);
8208 
8209   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8210     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8211     FD->setInvalidDecl();
8212   }
8213 }
8214 
8215 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
8216   // FIXME: Need strict checking.  In C89, we need to check for
8217   // any assignment, increment, decrement, function-calls, or
8218   // commas outside of a sizeof.  In C99, it's the same list,
8219   // except that the aforementioned are allowed in unevaluated
8220   // expressions.  Everything else falls under the
8221   // "may accept other forms of constant expressions" exception.
8222   // (We never end up here for C++, so the constant expression
8223   // rules there don't matter.)
8224   const Expr *Culprit;
8225   if (Init->isConstantInitializer(Context, false, &Culprit))
8226     return false;
8227   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
8228     << Culprit->getSourceRange();
8229   return true;
8230 }
8231 
8232 namespace {
8233   // Visits an initialization expression to see if OrigDecl is evaluated in
8234   // its own initialization and throws a warning if it does.
8235   class SelfReferenceChecker
8236       : public EvaluatedExprVisitor<SelfReferenceChecker> {
8237     Sema &S;
8238     Decl *OrigDecl;
8239     bool isRecordType;
8240     bool isPODType;
8241     bool isReferenceType;
8242 
8243   public:
8244     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
8245 
8246     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
8247                                                     S(S), OrigDecl(OrigDecl) {
8248       isPODType = false;
8249       isRecordType = false;
8250       isReferenceType = false;
8251       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
8252         isPODType = VD->getType().isPODType(S.Context);
8253         isRecordType = VD->getType()->isRecordType();
8254         isReferenceType = VD->getType()->isReferenceType();
8255       }
8256     }
8257 
8258     // For most expressions, the cast is directly above the DeclRefExpr.
8259     // For conditional operators, the cast can be outside the conditional
8260     // operator if both expressions are DeclRefExpr's.
8261     void HandleValue(Expr *E) {
8262       E = E->IgnoreParens();
8263       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
8264         HandleDeclRefExpr(DRE);
8265         return;
8266       }
8267 
8268       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8269         HandleValue(CO->getTrueExpr());
8270         HandleValue(CO->getFalseExpr());
8271         return;
8272       }
8273 
8274       if (BinaryConditionalOperator *BCO =
8275               dyn_cast<BinaryConditionalOperator>(E)) {
8276         Visit(BCO->getCond());
8277         HandleValue(BCO->getFalseExpr());
8278         return;
8279       }
8280 
8281       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
8282         HandleValue(OVE->getSourceExpr());
8283         return;
8284       }
8285 
8286       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8287         if (BO->getOpcode() == BO_Comma)
8288           HandleValue(BO->getRHS());
8289         return;
8290       }
8291 
8292       if (isa<MemberExpr>(E)) {
8293         Expr *Base = E->IgnoreParenImpCasts();
8294         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8295           // Check for static member variables and don't warn on them.
8296           if (!isa<FieldDecl>(ME->getMemberDecl()))
8297             return;
8298           Base = ME->getBase()->IgnoreParenImpCasts();
8299         }
8300         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
8301           HandleDeclRefExpr(DRE);
8302         return;
8303       }
8304 
8305       Visit(E);
8306     }
8307 
8308     // Reference types not handled in HandleValue are handled here since all
8309     // uses of references are bad, not just r-value uses.
8310     void VisitDeclRefExpr(DeclRefExpr *E) {
8311       if (isReferenceType)
8312         HandleDeclRefExpr(E);
8313     }
8314 
8315     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
8316       if (E->getCastKind() == CK_LValueToRValue ||
8317           (isRecordType && E->getCastKind() == CK_NoOp)) {
8318         HandleValue(E->getSubExpr());
8319         return;
8320       }
8321 
8322       Inherited::VisitImplicitCastExpr(E);
8323     }
8324 
8325     void VisitMemberExpr(MemberExpr *E) {
8326       // Don't warn on arrays since they can be treated as pointers.
8327       if (E->getType()->canDecayToPointerType()) return;
8328 
8329       // Warn when a non-static method call is followed by non-static member
8330       // field accesses, which is followed by a DeclRefExpr.
8331       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
8332       bool Warn = (MD && !MD->isStatic());
8333       Expr *Base = E->getBase()->IgnoreParenImpCasts();
8334       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8335         if (!isa<FieldDecl>(ME->getMemberDecl()))
8336           Warn = false;
8337         Base = ME->getBase()->IgnoreParenImpCasts();
8338       }
8339 
8340       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
8341         if (Warn)
8342           HandleDeclRefExpr(DRE);
8343         return;
8344       }
8345 
8346       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
8347       // Visit that expression.
8348       Visit(Base);
8349     }
8350 
8351     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8352       if (E->getNumArgs() > 0)
8353         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
8354           HandleDeclRefExpr(DRE);
8355 
8356       Inherited::VisitCXXOperatorCallExpr(E);
8357     }
8358 
8359     void VisitUnaryOperator(UnaryOperator *E) {
8360       // For POD record types, addresses of its own members are well-defined.
8361       if (E->getOpcode() == UO_AddrOf && isRecordType &&
8362           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
8363         if (!isPODType)
8364           HandleValue(E->getSubExpr());
8365         return;
8366       }
8367       Inherited::VisitUnaryOperator(E);
8368     }
8369 
8370     void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
8371 
8372     void VisitCXXConstructExpr(CXXConstructExpr *E) {
8373       if (E->getConstructor()->isCopyConstructor()) {
8374         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0))) {
8375           HandleDeclRefExpr(DRE);
8376         }
8377       }
8378       Inherited::VisitCXXConstructExpr(E);
8379     }
8380 
8381     void VisitCallExpr(CallExpr *E) {
8382       // Treat std::move as a use.
8383       if (E->getNumArgs() == 1) {
8384         if (FunctionDecl *FD = E->getDirectCallee()) {
8385           if (FD->getIdentifier() && FD->getIdentifier()->isStr("move")) {
8386             HandleValue(E->getArg(0));
8387             return;
8388           }
8389         }
8390       }
8391 
8392       Inherited::VisitCallExpr(E);
8393     }
8394 
8395     // A custom visitor for BinaryConditionalOperator is needed because the
8396     // regular visitor would check the condition and true expression separately
8397     // but both point to the same place giving duplicate diagnostics.
8398     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
8399       Visit(E->getCond());
8400       Visit(E->getFalseExpr());
8401     }
8402 
8403     void HandleDeclRefExpr(DeclRefExpr *DRE) {
8404       Decl* ReferenceDecl = DRE->getDecl();
8405       if (OrigDecl != ReferenceDecl) return;
8406       unsigned diag;
8407       if (isReferenceType) {
8408         diag = diag::warn_uninit_self_reference_in_reference_init;
8409       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
8410         diag = diag::warn_static_self_reference_in_init;
8411       } else {
8412         diag = diag::warn_uninit_self_reference_in_init;
8413       }
8414 
8415       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
8416                             S.PDiag(diag)
8417                               << DRE->getNameInfo().getName()
8418                               << OrigDecl->getLocation()
8419                               << DRE->getSourceRange());
8420     }
8421   };
8422 
8423   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
8424   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
8425                                  bool DirectInit) {
8426     // Parameters arguments are occassionially constructed with itself,
8427     // for instance, in recursive functions.  Skip them.
8428     if (isa<ParmVarDecl>(OrigDecl))
8429       return;
8430 
8431     E = E->IgnoreParens();
8432 
8433     // Skip checking T a = a where T is not a record or reference type.
8434     // Doing so is a way to silence uninitialized warnings.
8435     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
8436       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
8437         if (ICE->getCastKind() == CK_LValueToRValue)
8438           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8439             if (DRE->getDecl() == OrigDecl)
8440               return;
8441 
8442     SelfReferenceChecker(S, OrigDecl).Visit(E);
8443   }
8444 }
8445 
8446 /// AddInitializerToDecl - Adds the initializer Init to the
8447 /// declaration dcl. If DirectInit is true, this is C++ direct
8448 /// initialization rather than copy initialization.
8449 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8450                                 bool DirectInit, bool TypeMayContainAuto) {
8451   // If there is no declaration, there was an error parsing it.  Just ignore
8452   // the initializer.
8453   if (!RealDecl || RealDecl->isInvalidDecl())
8454     return;
8455 
8456   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8457     // With declarators parsed the way they are, the parser cannot
8458     // distinguish between a normal initializer and a pure-specifier.
8459     // Thus this grotesque test.
8460     IntegerLiteral *IL;
8461     if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
8462         Context.getCanonicalType(IL->getType()) == Context.IntTy)
8463       CheckPureMethod(Method, Init->getSourceRange());
8464     else {
8465       Diag(Method->getLocation(), diag::err_member_function_initialization)
8466         << Method->getDeclName() << Init->getSourceRange();
8467       Method->setInvalidDecl();
8468     }
8469     return;
8470   }
8471 
8472   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8473   if (!VDecl) {
8474     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8475     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8476     RealDecl->setInvalidDecl();
8477     return;
8478   }
8479   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8480 
8481   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8482   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
8483     Expr *DeduceInit = Init;
8484     // Initializer could be a C++ direct-initializer. Deduction only works if it
8485     // contains exactly one expression.
8486     if (CXXDirectInit) {
8487       if (CXXDirectInit->getNumExprs() == 0) {
8488         // It isn't possible to write this directly, but it is possible to
8489         // end up in this situation with "auto x(some_pack...);"
8490         Diag(CXXDirectInit->getLocStart(),
8491              VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8492                                     : diag::err_auto_var_init_no_expression)
8493           << VDecl->getDeclName() << VDecl->getType()
8494           << VDecl->getSourceRange();
8495         RealDecl->setInvalidDecl();
8496         return;
8497       } else if (CXXDirectInit->getNumExprs() > 1) {
8498         Diag(CXXDirectInit->getExpr(1)->getLocStart(),
8499              VDecl->isInitCapture()
8500                  ? diag::err_init_capture_multiple_expressions
8501                  : diag::err_auto_var_init_multiple_expressions)
8502           << VDecl->getDeclName() << VDecl->getType()
8503           << VDecl->getSourceRange();
8504         RealDecl->setInvalidDecl();
8505         return;
8506       } else {
8507         DeduceInit = CXXDirectInit->getExpr(0);
8508         if (isa<InitListExpr>(DeduceInit))
8509           Diag(CXXDirectInit->getLocStart(),
8510                diag::err_auto_var_init_paren_braces)
8511             << VDecl->getDeclName() << VDecl->getType()
8512             << VDecl->getSourceRange();
8513       }
8514     }
8515 
8516     // Expressions default to 'id' when we're in a debugger.
8517     bool DefaultedToAuto = false;
8518     if (getLangOpts().DebuggerCastResultToId &&
8519         Init->getType() == Context.UnknownAnyTy) {
8520       ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8521       if (Result.isInvalid()) {
8522         VDecl->setInvalidDecl();
8523         return;
8524       }
8525       Init = Result.get();
8526       DefaultedToAuto = true;
8527     }
8528 
8529     QualType DeducedType;
8530     if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
8531             DAR_Failed)
8532       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
8533     if (DeducedType.isNull()) {
8534       RealDecl->setInvalidDecl();
8535       return;
8536     }
8537     VDecl->setType(DeducedType);
8538     assert(VDecl->isLinkageValid());
8539 
8540     // In ARC, infer lifetime.
8541     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8542       VDecl->setInvalidDecl();
8543 
8544     // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8545     // 'id' instead of a specific object type prevents most of our usual checks.
8546     // We only want to warn outside of template instantiations, though:
8547     // inside a template, the 'id' could have come from a parameter.
8548     if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
8549         DeducedType->isObjCIdType()) {
8550       SourceLocation Loc =
8551           VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
8552       Diag(Loc, diag::warn_auto_var_is_id)
8553         << VDecl->getDeclName() << DeduceInit->getSourceRange();
8554     }
8555 
8556     // If this is a redeclaration, check that the type we just deduced matches
8557     // the previously declared type.
8558     if (VarDecl *Old = VDecl->getPreviousDecl()) {
8559       // We never need to merge the type, because we cannot form an incomplete
8560       // array of auto, nor deduce such a type.
8561       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8562     }
8563 
8564     // Check the deduced type is valid for a variable declaration.
8565     CheckVariableDeclarationType(VDecl);
8566     if (VDecl->isInvalidDecl())
8567       return;
8568   }
8569 
8570   // dllimport cannot be used on variable definitions.
8571   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
8572     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
8573     VDecl->setInvalidDecl();
8574     return;
8575   }
8576 
8577   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8578     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8579     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8580     VDecl->setInvalidDecl();
8581     return;
8582   }
8583 
8584   if (!VDecl->getType()->isDependentType()) {
8585     // A definition must end up with a complete type, which means it must be
8586     // complete with the restriction that an array type might be completed by
8587     // the initializer; note that later code assumes this restriction.
8588     QualType BaseDeclType = VDecl->getType();
8589     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8590       BaseDeclType = Array->getElementType();
8591     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8592                             diag::err_typecheck_decl_incomplete_type)) {
8593       RealDecl->setInvalidDecl();
8594       return;
8595     }
8596 
8597     // The variable can not have an abstract class type.
8598     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8599                                diag::err_abstract_type_in_decl,
8600                                AbstractVariableType))
8601       VDecl->setInvalidDecl();
8602   }
8603 
8604   const VarDecl *Def;
8605   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
8606     Diag(VDecl->getLocation(), diag::err_redefinition)
8607       << VDecl->getDeclName();
8608     Diag(Def->getLocation(), diag::note_previous_definition);
8609     VDecl->setInvalidDecl();
8610     return;
8611   }
8612 
8613   const VarDecl *PrevInit = nullptr;
8614   if (getLangOpts().CPlusPlus) {
8615     // C++ [class.static.data]p4
8616     //   If a static data member is of const integral or const
8617     //   enumeration type, its declaration in the class definition can
8618     //   specify a constant-initializer which shall be an integral
8619     //   constant expression (5.19). In that case, the member can appear
8620     //   in integral constant expressions. The member shall still be
8621     //   defined in a namespace scope if it is used in the program and the
8622     //   namespace scope definition shall not contain an initializer.
8623     //
8624     // We already performed a redefinition check above, but for static
8625     // data members we also need to check whether there was an in-class
8626     // declaration with an initializer.
8627     if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
8628       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
8629           << VDecl->getDeclName();
8630       Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0;
8631       return;
8632     }
8633 
8634     if (VDecl->hasLocalStorage())
8635       getCurFunction()->setHasBranchProtectedScope();
8636 
8637     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8638       VDecl->setInvalidDecl();
8639       return;
8640     }
8641   }
8642 
8643   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8644   // a kernel function cannot be initialized."
8645   if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8646     Diag(VDecl->getLocation(), diag::err_local_cant_init);
8647     VDecl->setInvalidDecl();
8648     return;
8649   }
8650 
8651   // Get the decls type and save a reference for later, since
8652   // CheckInitializerTypes may change it.
8653   QualType DclT = VDecl->getType(), SavT = DclT;
8654 
8655   // Expressions default to 'id' when we're in a debugger
8656   // and we are assigning it to a variable of Objective-C pointer type.
8657   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8658       Init->getType() == Context.UnknownAnyTy) {
8659     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8660     if (Result.isInvalid()) {
8661       VDecl->setInvalidDecl();
8662       return;
8663     }
8664     Init = Result.get();
8665   }
8666 
8667   // Perform the initialization.
8668   if (!VDecl->isInvalidDecl()) {
8669     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8670     InitializationKind Kind
8671       = DirectInit ?
8672           CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8673                                                            Init->getLocStart(),
8674                                                            Init->getLocEnd())
8675                         : InitializationKind::CreateDirectList(
8676                                                           VDecl->getLocation())
8677                    : InitializationKind::CreateCopy(VDecl->getLocation(),
8678                                                     Init->getLocStart());
8679 
8680     MultiExprArg Args = Init;
8681     if (CXXDirectInit)
8682       Args = MultiExprArg(CXXDirectInit->getExprs(),
8683                           CXXDirectInit->getNumExprs());
8684 
8685     InitializationSequence InitSeq(*this, Entity, Kind, Args);
8686     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
8687     if (Result.isInvalid()) {
8688       VDecl->setInvalidDecl();
8689       return;
8690     }
8691 
8692     Init = Result.getAs<Expr>();
8693   }
8694 
8695   // Check for self-references within variable initializers.
8696   // Variables declared within a function/method body (except for references)
8697   // are handled by a dataflow analysis.
8698   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8699       VDecl->getType()->isReferenceType()) {
8700     CheckSelfReference(*this, RealDecl, Init, DirectInit);
8701   }
8702 
8703   // If the type changed, it means we had an incomplete type that was
8704   // completed by the initializer. For example:
8705   //   int ary[] = { 1, 3, 5 };
8706   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
8707   if (!VDecl->isInvalidDecl() && (DclT != SavT))
8708     VDecl->setType(DclT);
8709 
8710   if (!VDecl->isInvalidDecl()) {
8711     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8712 
8713     if (VDecl->hasAttr<BlocksAttr>())
8714       checkRetainCycles(VDecl, Init);
8715 
8716     // It is safe to assign a weak reference into a strong variable.
8717     // Although this code can still have problems:
8718     //   id x = self.weakProp;
8719     //   id y = self.weakProp;
8720     // we do not warn to warn spuriously when 'x' and 'y' are on separate
8721     // paths through the function. This should be revisited if
8722     // -Wrepeated-use-of-weak is made flow-sensitive.
8723     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
8724         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
8725                          Init->getLocStart()))
8726         getCurFunction()->markSafeWeakUse(Init);
8727   }
8728 
8729   // The initialization is usually a full-expression.
8730   //
8731   // FIXME: If this is a braced initialization of an aggregate, it is not
8732   // an expression, and each individual field initializer is a separate
8733   // full-expression. For instance, in:
8734   //
8735   //   struct Temp { ~Temp(); };
8736   //   struct S { S(Temp); };
8737   //   struct T { S a, b; } t = { Temp(), Temp() }
8738   //
8739   // we should destroy the first Temp before constructing the second.
8740   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8741                                           false,
8742                                           VDecl->isConstexpr());
8743   if (Result.isInvalid()) {
8744     VDecl->setInvalidDecl();
8745     return;
8746   }
8747   Init = Result.get();
8748 
8749   // Attach the initializer to the decl.
8750   VDecl->setInit(Init);
8751 
8752   if (VDecl->isLocalVarDecl()) {
8753     // C99 6.7.8p4: All the expressions in an initializer for an object that has
8754     // static storage duration shall be constant expressions or string literals.
8755     // C++ does not have this restriction.
8756     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8757       const Expr *Culprit;
8758       if (VDecl->getStorageClass() == SC_Static)
8759         CheckForConstantInitializer(Init, DclT);
8760       // C89 is stricter than C99 for non-static aggregate types.
8761       // C89 6.5.7p3: All the expressions [...] in an initializer list
8762       // for an object that has aggregate or union type shall be
8763       // constant expressions.
8764       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
8765                isa<InitListExpr>(Init) &&
8766                !Init->isConstantInitializer(Context, false, &Culprit))
8767         Diag(Culprit->getExprLoc(),
8768              diag::ext_aggregate_init_not_constant)
8769           << Culprit->getSourceRange();
8770     }
8771   } else if (VDecl->isStaticDataMember() &&
8772              VDecl->getLexicalDeclContext()->isRecord()) {
8773     // This is an in-class initialization for a static data member, e.g.,
8774     //
8775     // struct S {
8776     //   static const int value = 17;
8777     // };
8778 
8779     // C++ [class.mem]p4:
8780     //   A member-declarator can contain a constant-initializer only
8781     //   if it declares a static member (9.4) of const integral or
8782     //   const enumeration type, see 9.4.2.
8783     //
8784     // C++11 [class.static.data]p3:
8785     //   If a non-volatile const static data member is of integral or
8786     //   enumeration type, its declaration in the class definition can
8787     //   specify a brace-or-equal-initializer in which every initalizer-clause
8788     //   that is an assignment-expression is a constant expression. A static
8789     //   data member of literal type can be declared in the class definition
8790     //   with the constexpr specifier; if so, its declaration shall specify a
8791     //   brace-or-equal-initializer in which every initializer-clause that is
8792     //   an assignment-expression is a constant expression.
8793 
8794     // Do nothing on dependent types.
8795     if (DclT->isDependentType()) {
8796 
8797     // Allow any 'static constexpr' members, whether or not they are of literal
8798     // type. We separately check that every constexpr variable is of literal
8799     // type.
8800     } else if (VDecl->isConstexpr()) {
8801 
8802     // Require constness.
8803     } else if (!DclT.isConstQualified()) {
8804       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8805         << Init->getSourceRange();
8806       VDecl->setInvalidDecl();
8807 
8808     // We allow integer constant expressions in all cases.
8809     } else if (DclT->isIntegralOrEnumerationType()) {
8810       // Check whether the expression is a constant expression.
8811       SourceLocation Loc;
8812       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
8813         // In C++11, a non-constexpr const static data member with an
8814         // in-class initializer cannot be volatile.
8815         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8816       else if (Init->isValueDependent())
8817         ; // Nothing to check.
8818       else if (Init->isIntegerConstantExpr(Context, &Loc))
8819         ; // Ok, it's an ICE!
8820       else if (Init->isEvaluatable(Context)) {
8821         // If we can constant fold the initializer through heroics, accept it,
8822         // but report this as a use of an extension for -pedantic.
8823         Diag(Loc, diag::ext_in_class_initializer_non_constant)
8824           << Init->getSourceRange();
8825       } else {
8826         // Otherwise, this is some crazy unknown case.  Report the issue at the
8827         // location provided by the isIntegerConstantExpr failed check.
8828         Diag(Loc, diag::err_in_class_initializer_non_constant)
8829           << Init->getSourceRange();
8830         VDecl->setInvalidDecl();
8831       }
8832 
8833     // We allow foldable floating-point constants as an extension.
8834     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
8835       // In C++98, this is a GNU extension. In C++11, it is not, but we support
8836       // it anyway and provide a fixit to add the 'constexpr'.
8837       if (getLangOpts().CPlusPlus11) {
8838         Diag(VDecl->getLocation(),
8839              diag::ext_in_class_initializer_float_type_cxx11)
8840             << DclT << Init->getSourceRange();
8841         Diag(VDecl->getLocStart(),
8842              diag::note_in_class_initializer_float_type_cxx11)
8843             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8844       } else {
8845         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8846           << DclT << Init->getSourceRange();
8847 
8848         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8849           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8850             << Init->getSourceRange();
8851           VDecl->setInvalidDecl();
8852         }
8853       }
8854 
8855     // Suggest adding 'constexpr' in C++11 for literal types.
8856     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
8857       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
8858         << DclT << Init->getSourceRange()
8859         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8860       VDecl->setConstexpr(true);
8861 
8862     } else {
8863       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
8864         << DclT << Init->getSourceRange();
8865       VDecl->setInvalidDecl();
8866     }
8867   } else if (VDecl->isFileVarDecl()) {
8868     if (VDecl->getStorageClass() == SC_Extern &&
8869         (!getLangOpts().CPlusPlus ||
8870          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
8871            VDecl->isExternC())) &&
8872         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
8873       Diag(VDecl->getLocation(), diag::warn_extern_init);
8874 
8875     // C99 6.7.8p4. All file scoped initializers need to be constant.
8876     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
8877       CheckForConstantInitializer(Init, DclT);
8878   }
8879 
8880   // We will represent direct-initialization similarly to copy-initialization:
8881   //    int x(1);  -as-> int x = 1;
8882   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8883   //
8884   // Clients that want to distinguish between the two forms, can check for
8885   // direct initializer using VarDecl::getInitStyle().
8886   // A major benefit is that clients that don't particularly care about which
8887   // exactly form was it (like the CodeGen) can handle both cases without
8888   // special case code.
8889 
8890   // C++ 8.5p11:
8891   // The form of initialization (using parentheses or '=') is generally
8892   // insignificant, but does matter when the entity being initialized has a
8893   // class type.
8894   if (CXXDirectInit) {
8895     assert(DirectInit && "Call-style initializer must be direct init.");
8896     VDecl->setInitStyle(VarDecl::CallInit);
8897   } else if (DirectInit) {
8898     // This must be list-initialization. No other way is direct-initialization.
8899     VDecl->setInitStyle(VarDecl::ListInit);
8900   }
8901 
8902   CheckCompleteVariableDeclaration(VDecl);
8903 }
8904 
8905 /// ActOnInitializerError - Given that there was an error parsing an
8906 /// initializer for the given declaration, try to return to some form
8907 /// of sanity.
8908 void Sema::ActOnInitializerError(Decl *D) {
8909   // Our main concern here is re-establishing invariants like "a
8910   // variable's type is either dependent or complete".
8911   if (!D || D->isInvalidDecl()) return;
8912 
8913   VarDecl *VD = dyn_cast<VarDecl>(D);
8914   if (!VD) return;
8915 
8916   // Auto types are meaningless if we can't make sense of the initializer.
8917   if (ParsingInitForAutoVars.count(D)) {
8918     D->setInvalidDecl();
8919     return;
8920   }
8921 
8922   QualType Ty = VD->getType();
8923   if (Ty->isDependentType()) return;
8924 
8925   // Require a complete type.
8926   if (RequireCompleteType(VD->getLocation(),
8927                           Context.getBaseElementType(Ty),
8928                           diag::err_typecheck_decl_incomplete_type)) {
8929     VD->setInvalidDecl();
8930     return;
8931   }
8932 
8933   // Require a non-abstract type.
8934   if (RequireNonAbstractType(VD->getLocation(), Ty,
8935                              diag::err_abstract_type_in_decl,
8936                              AbstractVariableType)) {
8937     VD->setInvalidDecl();
8938     return;
8939   }
8940 
8941   // Don't bother complaining about constructors or destructors,
8942   // though.
8943 }
8944 
8945 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
8946                                   bool TypeMayContainAuto) {
8947   // If there is no declaration, there was an error parsing it. Just ignore it.
8948   if (!RealDecl)
8949     return;
8950 
8951   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8952     QualType Type = Var->getType();
8953 
8954     // C++11 [dcl.spec.auto]p3
8955     if (TypeMayContainAuto && Type->getContainedAutoType()) {
8956       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8957         << Var->getDeclName() << Type;
8958       Var->setInvalidDecl();
8959       return;
8960     }
8961 
8962     // C++11 [class.static.data]p3: A static data member can be declared with
8963     // the constexpr specifier; if so, its declaration shall specify
8964     // a brace-or-equal-initializer.
8965     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8966     // the definition of a variable [...] or the declaration of a static data
8967     // member.
8968     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8969       if (Var->isStaticDataMember())
8970         Diag(Var->getLocation(),
8971              diag::err_constexpr_static_mem_var_requires_init)
8972           << Var->getDeclName();
8973       else
8974         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
8975       Var->setInvalidDecl();
8976       return;
8977     }
8978 
8979     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
8980     // be initialized.
8981     if (!Var->isInvalidDecl() &&
8982         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
8983         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
8984       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
8985       Var->setInvalidDecl();
8986       return;
8987     }
8988 
8989     switch (Var->isThisDeclarationADefinition()) {
8990     case VarDecl::Definition:
8991       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8992         break;
8993 
8994       // We have an out-of-line definition of a static data member
8995       // that has an in-class initializer, so we type-check this like
8996       // a declaration.
8997       //
8998       // Fall through
8999 
9000     case VarDecl::DeclarationOnly:
9001       // It's only a declaration.
9002 
9003       // Block scope. C99 6.7p7: If an identifier for an object is
9004       // declared with no linkage (C99 6.2.2p6), the type for the
9005       // object shall be complete.
9006       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
9007           !Var->hasLinkage() && !Var->isInvalidDecl() &&
9008           RequireCompleteType(Var->getLocation(), Type,
9009                               diag::err_typecheck_decl_incomplete_type))
9010         Var->setInvalidDecl();
9011 
9012       // Make sure that the type is not abstract.
9013       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9014           RequireNonAbstractType(Var->getLocation(), Type,
9015                                  diag::err_abstract_type_in_decl,
9016                                  AbstractVariableType))
9017         Var->setInvalidDecl();
9018       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9019           Var->getStorageClass() == SC_PrivateExtern) {
9020         Diag(Var->getLocation(), diag::warn_private_extern);
9021         Diag(Var->getLocation(), diag::note_private_extern);
9022       }
9023 
9024       return;
9025 
9026     case VarDecl::TentativeDefinition:
9027       // File scope. C99 6.9.2p2: A declaration of an identifier for an
9028       // object that has file scope without an initializer, and without a
9029       // storage-class specifier or with the storage-class specifier "static",
9030       // constitutes a tentative definition. Note: A tentative definition with
9031       // external linkage is valid (C99 6.2.2p5).
9032       if (!Var->isInvalidDecl()) {
9033         if (const IncompleteArrayType *ArrayT
9034                                     = Context.getAsIncompleteArrayType(Type)) {
9035           if (RequireCompleteType(Var->getLocation(),
9036                                   ArrayT->getElementType(),
9037                                   diag::err_illegal_decl_array_incomplete_type))
9038             Var->setInvalidDecl();
9039         } else if (Var->getStorageClass() == SC_Static) {
9040           // C99 6.9.2p3: If the declaration of an identifier for an object is
9041           // a tentative definition and has internal linkage (C99 6.2.2p3), the
9042           // declared type shall not be an incomplete type.
9043           // NOTE: code such as the following
9044           //     static struct s;
9045           //     struct s { int a; };
9046           // is accepted by gcc. Hence here we issue a warning instead of
9047           // an error and we do not invalidate the static declaration.
9048           // NOTE: to avoid multiple warnings, only check the first declaration.
9049           if (Var->isFirstDecl())
9050             RequireCompleteType(Var->getLocation(), Type,
9051                                 diag::ext_typecheck_decl_incomplete_type);
9052         }
9053       }
9054 
9055       // Record the tentative definition; we're done.
9056       if (!Var->isInvalidDecl())
9057         TentativeDefinitions.push_back(Var);
9058       return;
9059     }
9060 
9061     // Provide a specific diagnostic for uninitialized variable
9062     // definitions with incomplete array type.
9063     if (Type->isIncompleteArrayType()) {
9064       Diag(Var->getLocation(),
9065            diag::err_typecheck_incomplete_array_needs_initializer);
9066       Var->setInvalidDecl();
9067       return;
9068     }
9069 
9070     // Provide a specific diagnostic for uninitialized variable
9071     // definitions with reference type.
9072     if (Type->isReferenceType()) {
9073       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
9074         << Var->getDeclName()
9075         << SourceRange(Var->getLocation(), Var->getLocation());
9076       Var->setInvalidDecl();
9077       return;
9078     }
9079 
9080     // Do not attempt to type-check the default initializer for a
9081     // variable with dependent type.
9082     if (Type->isDependentType())
9083       return;
9084 
9085     if (Var->isInvalidDecl())
9086       return;
9087 
9088     if (!Var->hasAttr<AliasAttr>()) {
9089       if (RequireCompleteType(Var->getLocation(),
9090                               Context.getBaseElementType(Type),
9091                               diag::err_typecheck_decl_incomplete_type)) {
9092         Var->setInvalidDecl();
9093         return;
9094       }
9095     }
9096 
9097     // The variable can not have an abstract class type.
9098     if (RequireNonAbstractType(Var->getLocation(), Type,
9099                                diag::err_abstract_type_in_decl,
9100                                AbstractVariableType)) {
9101       Var->setInvalidDecl();
9102       return;
9103     }
9104 
9105     // Check for jumps past the implicit initializer.  C++0x
9106     // clarifies that this applies to a "variable with automatic
9107     // storage duration", not a "local variable".
9108     // C++11 [stmt.dcl]p3
9109     //   A program that jumps from a point where a variable with automatic
9110     //   storage duration is not in scope to a point where it is in scope is
9111     //   ill-formed unless the variable has scalar type, class type with a
9112     //   trivial default constructor and a trivial destructor, a cv-qualified
9113     //   version of one of these types, or an array of one of the preceding
9114     //   types and is declared without an initializer.
9115     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
9116       if (const RecordType *Record
9117             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
9118         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
9119         // Mark the function for further checking even if the looser rules of
9120         // C++11 do not require such checks, so that we can diagnose
9121         // incompatibilities with C++98.
9122         if (!CXXRecord->isPOD())
9123           getCurFunction()->setHasBranchProtectedScope();
9124       }
9125     }
9126 
9127     // C++03 [dcl.init]p9:
9128     //   If no initializer is specified for an object, and the
9129     //   object is of (possibly cv-qualified) non-POD class type (or
9130     //   array thereof), the object shall be default-initialized; if
9131     //   the object is of const-qualified type, the underlying class
9132     //   type shall have a user-declared default
9133     //   constructor. Otherwise, if no initializer is specified for
9134     //   a non- static object, the object and its subobjects, if
9135     //   any, have an indeterminate initial value); if the object
9136     //   or any of its subobjects are of const-qualified type, the
9137     //   program is ill-formed.
9138     // C++0x [dcl.init]p11:
9139     //   If no initializer is specified for an object, the object is
9140     //   default-initialized; [...].
9141     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
9142     InitializationKind Kind
9143       = InitializationKind::CreateDefault(Var->getLocation());
9144 
9145     InitializationSequence InitSeq(*this, Entity, Kind, None);
9146     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
9147     if (Init.isInvalid())
9148       Var->setInvalidDecl();
9149     else if (Init.get()) {
9150       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
9151       // This is important for template substitution.
9152       Var->setInitStyle(VarDecl::CallInit);
9153     }
9154 
9155     CheckCompleteVariableDeclaration(Var);
9156   }
9157 }
9158 
9159 void Sema::ActOnCXXForRangeDecl(Decl *D) {
9160   VarDecl *VD = dyn_cast<VarDecl>(D);
9161   if (!VD) {
9162     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
9163     D->setInvalidDecl();
9164     return;
9165   }
9166 
9167   VD->setCXXForRangeDecl(true);
9168 
9169   // for-range-declaration cannot be given a storage class specifier.
9170   int Error = -1;
9171   switch (VD->getStorageClass()) {
9172   case SC_None:
9173     break;
9174   case SC_Extern:
9175     Error = 0;
9176     break;
9177   case SC_Static:
9178     Error = 1;
9179     break;
9180   case SC_PrivateExtern:
9181     Error = 2;
9182     break;
9183   case SC_Auto:
9184     Error = 3;
9185     break;
9186   case SC_Register:
9187     Error = 4;
9188     break;
9189   case SC_OpenCLWorkGroupLocal:
9190     llvm_unreachable("Unexpected storage class");
9191   }
9192   if (VD->isConstexpr())
9193     Error = 5;
9194   if (Error != -1) {
9195     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
9196       << VD->getDeclName() << Error;
9197     D->setInvalidDecl();
9198   }
9199 }
9200 
9201 StmtResult
9202 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
9203                                  IdentifierInfo *Ident,
9204                                  ParsedAttributes &Attrs,
9205                                  SourceLocation AttrEnd) {
9206   // C++1y [stmt.iter]p1:
9207   //   A range-based for statement of the form
9208   //      for ( for-range-identifier : for-range-initializer ) statement
9209   //   is equivalent to
9210   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
9211   DeclSpec DS(Attrs.getPool().getFactory());
9212 
9213   const char *PrevSpec;
9214   unsigned DiagID;
9215   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
9216                      getPrintingPolicy());
9217 
9218   Declarator D(DS, Declarator::ForContext);
9219   D.SetIdentifier(Ident, IdentLoc);
9220   D.takeAttributes(Attrs, AttrEnd);
9221 
9222   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
9223   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
9224                 EmptyAttrs, IdentLoc);
9225   Decl *Var = ActOnDeclarator(S, D);
9226   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
9227   FinalizeDeclaration(Var);
9228   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
9229                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
9230 }
9231 
9232 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
9233   if (var->isInvalidDecl()) return;
9234 
9235   // In ARC, don't allow jumps past the implicit initialization of a
9236   // local retaining variable.
9237   if (getLangOpts().ObjCAutoRefCount &&
9238       var->hasLocalStorage()) {
9239     switch (var->getType().getObjCLifetime()) {
9240     case Qualifiers::OCL_None:
9241     case Qualifiers::OCL_ExplicitNone:
9242     case Qualifiers::OCL_Autoreleasing:
9243       break;
9244 
9245     case Qualifiers::OCL_Weak:
9246     case Qualifiers::OCL_Strong:
9247       getCurFunction()->setHasBranchProtectedScope();
9248       break;
9249     }
9250   }
9251 
9252   // Warn about externally-visible variables being defined without a
9253   // prior declaration.  We only want to do this for global
9254   // declarations, but we also specifically need to avoid doing it for
9255   // class members because the linkage of an anonymous class can
9256   // change if it's later given a typedef name.
9257   if (var->isThisDeclarationADefinition() &&
9258       var->getDeclContext()->getRedeclContext()->isFileContext() &&
9259       var->isExternallyVisible() && var->hasLinkage() &&
9260       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
9261                                   var->getLocation())) {
9262     // Find a previous declaration that's not a definition.
9263     VarDecl *prev = var->getPreviousDecl();
9264     while (prev && prev->isThisDeclarationADefinition())
9265       prev = prev->getPreviousDecl();
9266 
9267     if (!prev)
9268       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
9269   }
9270 
9271   if (var->getTLSKind() == VarDecl::TLS_Static) {
9272     const Expr *Culprit;
9273     if (var->getType().isDestructedType()) {
9274       // GNU C++98 edits for __thread, [basic.start.term]p3:
9275       //   The type of an object with thread storage duration shall not
9276       //   have a non-trivial destructor.
9277       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
9278       if (getLangOpts().CPlusPlus11)
9279         Diag(var->getLocation(), diag::note_use_thread_local);
9280     } else if (getLangOpts().CPlusPlus && var->hasInit() &&
9281                !var->getInit()->isConstantInitializer(
9282                    Context, var->getType()->isReferenceType(), &Culprit)) {
9283       // GNU C++98 edits for __thread, [basic.start.init]p4:
9284       //   An object of thread storage duration shall not require dynamic
9285       //   initialization.
9286       // FIXME: Need strict checking here.
9287       Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
9288         << Culprit->getSourceRange();
9289       if (getLangOpts().CPlusPlus11)
9290         Diag(var->getLocation(), diag::note_use_thread_local);
9291     }
9292 
9293   }
9294 
9295   if (var->isThisDeclarationADefinition() &&
9296       ActiveTemplateInstantiations.empty()) {
9297     PragmaStack<StringLiteral *> *Stack = nullptr;
9298     int SectionFlags = PSF_Implicit | PSF_Read;
9299     if (var->getType().isConstQualified())
9300       Stack = &ConstSegStack;
9301     else if (!var->getInit()) {
9302       Stack = &BSSSegStack;
9303       SectionFlags |= PSF_Write;
9304     } else {
9305       Stack = &DataSegStack;
9306       SectionFlags |= PSF_Write;
9307     }
9308     if (!var->hasAttr<SectionAttr>() && Stack->CurrentValue)
9309       var->addAttr(
9310           SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
9311                                       Stack->CurrentValue->getString(),
9312                                       Stack->CurrentPragmaLocation));
9313     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
9314       if (UnifySection(SA->getName(), SectionFlags, var))
9315         var->dropAttr<SectionAttr>();
9316 
9317     // Apply the init_seg attribute if this has an initializer.  If the
9318     // initializer turns out to not be dynamic, we'll end up ignoring this
9319     // attribute.
9320     if (CurInitSeg && var->getInit())
9321       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
9322                                                CurInitSegLoc));
9323   }
9324 
9325   // All the following checks are C++ only.
9326   if (!getLangOpts().CPlusPlus) return;
9327 
9328   QualType type = var->getType();
9329   if (type->isDependentType()) return;
9330 
9331   // __block variables might require us to capture a copy-initializer.
9332   if (var->hasAttr<BlocksAttr>()) {
9333     // It's currently invalid to ever have a __block variable with an
9334     // array type; should we diagnose that here?
9335 
9336     // Regardless, we don't want to ignore array nesting when
9337     // constructing this copy.
9338     if (type->isStructureOrClassType()) {
9339       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
9340       SourceLocation poi = var->getLocation();
9341       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
9342       ExprResult result
9343         = PerformMoveOrCopyInitialization(
9344             InitializedEntity::InitializeBlock(poi, type, false),
9345             var, var->getType(), varRef, /*AllowNRVO=*/true);
9346       if (!result.isInvalid()) {
9347         result = MaybeCreateExprWithCleanups(result);
9348         Expr *init = result.getAs<Expr>();
9349         Context.setBlockVarCopyInits(var, init);
9350       }
9351     }
9352   }
9353 
9354   Expr *Init = var->getInit();
9355   bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
9356   QualType baseType = Context.getBaseElementType(type);
9357 
9358   if (!var->getDeclContext()->isDependentContext() &&
9359       Init && !Init->isValueDependent()) {
9360     if (IsGlobal && !var->isConstexpr() &&
9361         !getDiagnostics().isIgnored(diag::warn_global_constructor,
9362                                     var->getLocation())) {
9363       // Warn about globals which don't have a constant initializer.  Don't
9364       // warn about globals with a non-trivial destructor because we already
9365       // warned about them.
9366       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
9367       if (!(RD && !RD->hasTrivialDestructor()) &&
9368           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
9369         Diag(var->getLocation(), diag::warn_global_constructor)
9370           << Init->getSourceRange();
9371     }
9372 
9373     if (var->isConstexpr()) {
9374       SmallVector<PartialDiagnosticAt, 8> Notes;
9375       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
9376         SourceLocation DiagLoc = var->getLocation();
9377         // If the note doesn't add any useful information other than a source
9378         // location, fold it into the primary diagnostic.
9379         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9380               diag::note_invalid_subexpr_in_const_expr) {
9381           DiagLoc = Notes[0].first;
9382           Notes.clear();
9383         }
9384         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
9385           << var << Init->getSourceRange();
9386         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9387           Diag(Notes[I].first, Notes[I].second);
9388       }
9389     } else if (var->isUsableInConstantExpressions(Context)) {
9390       // Check whether the initializer of a const variable of integral or
9391       // enumeration type is an ICE now, since we can't tell whether it was
9392       // initialized by a constant expression if we check later.
9393       var->checkInitIsICE();
9394     }
9395   }
9396 
9397   // Require the destructor.
9398   if (const RecordType *recordType = baseType->getAs<RecordType>())
9399     FinalizeVarWithDestructor(var, recordType);
9400 }
9401 
9402 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
9403 /// any semantic actions necessary after any initializer has been attached.
9404 void
9405 Sema::FinalizeDeclaration(Decl *ThisDecl) {
9406   // Note that we are no longer parsing the initializer for this declaration.
9407   ParsingInitForAutoVars.erase(ThisDecl);
9408 
9409   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
9410   if (!VD)
9411     return;
9412 
9413   checkAttributesAfterMerging(*this, *VD);
9414 
9415   // Static locals inherit dll attributes from their function.
9416   if (VD->isStaticLocal()) {
9417     if (FunctionDecl *FD =
9418             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
9419       if (Attr *A = getDLLAttr(FD)) {
9420         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
9421         NewAttr->setInherited(true);
9422         VD->addAttr(NewAttr);
9423       }
9424     }
9425   }
9426 
9427   // Imported static data members cannot be defined out-of-line.
9428   if (const DLLImportAttr *IA = VD->getAttr<DLLImportAttr>()) {
9429     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
9430         VD->isThisDeclarationADefinition()) {
9431       // We allow definitions of dllimport class template static data members
9432       // with a warning.
9433       CXXRecordDecl *Context =
9434         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
9435       bool IsClassTemplateMember =
9436           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
9437           Context->getDescribedClassTemplate();
9438 
9439       Diag(VD->getLocation(),
9440            IsClassTemplateMember
9441                ? diag::warn_attribute_dllimport_static_field_definition
9442                : diag::err_attribute_dllimport_static_field_definition);
9443       Diag(IA->getLocation(), diag::note_attribute);
9444       if (!IsClassTemplateMember)
9445         VD->setInvalidDecl();
9446     }
9447   }
9448 
9449   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
9450     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
9451       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
9452       VD->dropAttr<UsedAttr>();
9453     }
9454   }
9455 
9456   if (!VD->isInvalidDecl() &&
9457       VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
9458     if (const VarDecl *Def = VD->getDefinition()) {
9459       if (Def->hasAttr<AliasAttr>()) {
9460         Diag(VD->getLocation(), diag::err_tentative_after_alias)
9461             << VD->getDeclName();
9462         Diag(Def->getLocation(), diag::note_previous_definition);
9463         VD->setInvalidDecl();
9464       }
9465     }
9466   }
9467 
9468   const DeclContext *DC = VD->getDeclContext();
9469   // If there's a #pragma GCC visibility in scope, and this isn't a class
9470   // member, set the visibility of this variable.
9471   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
9472     AddPushedVisibilityAttribute(VD);
9473 
9474   // FIXME: Warn on unused templates.
9475   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
9476       !isa<VarTemplatePartialSpecializationDecl>(VD))
9477     MarkUnusedFileScopedDecl(VD);
9478 
9479   // Now we have parsed the initializer and can update the table of magic
9480   // tag values.
9481   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
9482       !VD->getType()->isIntegralOrEnumerationType())
9483     return;
9484 
9485   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
9486     const Expr *MagicValueExpr = VD->getInit();
9487     if (!MagicValueExpr) {
9488       continue;
9489     }
9490     llvm::APSInt MagicValueInt;
9491     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
9492       Diag(I->getRange().getBegin(),
9493            diag::err_type_tag_for_datatype_not_ice)
9494         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9495       continue;
9496     }
9497     if (MagicValueInt.getActiveBits() > 64) {
9498       Diag(I->getRange().getBegin(),
9499            diag::err_type_tag_for_datatype_too_large)
9500         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9501       continue;
9502     }
9503     uint64_t MagicValue = MagicValueInt.getZExtValue();
9504     RegisterTypeTagForDatatype(I->getArgumentKind(),
9505                                MagicValue,
9506                                I->getMatchingCType(),
9507                                I->getLayoutCompatible(),
9508                                I->getMustBeNull());
9509   }
9510 }
9511 
9512 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
9513                                                    ArrayRef<Decl *> Group) {
9514   SmallVector<Decl*, 8> Decls;
9515 
9516   if (DS.isTypeSpecOwned())
9517     Decls.push_back(DS.getRepAsDecl());
9518 
9519   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
9520   for (unsigned i = 0, e = Group.size(); i != e; ++i)
9521     if (Decl *D = Group[i]) {
9522       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
9523         if (!FirstDeclaratorInGroup)
9524           FirstDeclaratorInGroup = DD;
9525       Decls.push_back(D);
9526     }
9527 
9528   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
9529     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
9530       HandleTagNumbering(*this, Tag, S);
9531       if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
9532         Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
9533     }
9534   }
9535 
9536   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
9537 }
9538 
9539 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
9540 /// group, performing any necessary semantic checking.
9541 Sema::DeclGroupPtrTy
9542 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
9543                            bool TypeMayContainAuto) {
9544   // C++0x [dcl.spec.auto]p7:
9545   //   If the type deduced for the template parameter U is not the same in each
9546   //   deduction, the program is ill-formed.
9547   // FIXME: When initializer-list support is added, a distinction is needed
9548   // between the deduced type U and the deduced type which 'auto' stands for.
9549   //   auto a = 0, b = { 1, 2, 3 };
9550   // is legal because the deduced type U is 'int' in both cases.
9551   if (TypeMayContainAuto && Group.size() > 1) {
9552     QualType Deduced;
9553     CanQualType DeducedCanon;
9554     VarDecl *DeducedDecl = nullptr;
9555     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
9556       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
9557         AutoType *AT = D->getType()->getContainedAutoType();
9558         // Don't reissue diagnostics when instantiating a template.
9559         if (AT && D->isInvalidDecl())
9560           break;
9561         QualType U = AT ? AT->getDeducedType() : QualType();
9562         if (!U.isNull()) {
9563           CanQualType UCanon = Context.getCanonicalType(U);
9564           if (Deduced.isNull()) {
9565             Deduced = U;
9566             DeducedCanon = UCanon;
9567             DeducedDecl = D;
9568           } else if (DeducedCanon != UCanon) {
9569             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9570                  diag::err_auto_different_deductions)
9571               << (AT->isDecltypeAuto() ? 1 : 0)
9572               << Deduced << DeducedDecl->getDeclName()
9573               << U << D->getDeclName()
9574               << DeducedDecl->getInit()->getSourceRange()
9575               << D->getInit()->getSourceRange();
9576             D->setInvalidDecl();
9577             break;
9578           }
9579         }
9580       }
9581     }
9582   }
9583 
9584   ActOnDocumentableDecls(Group);
9585 
9586   return DeclGroupPtrTy::make(
9587       DeclGroupRef::Create(Context, Group.data(), Group.size()));
9588 }
9589 
9590 void Sema::ActOnDocumentableDecl(Decl *D) {
9591   ActOnDocumentableDecls(D);
9592 }
9593 
9594 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
9595   // Don't parse the comment if Doxygen diagnostics are ignored.
9596   if (Group.empty() || !Group[0])
9597    return;
9598 
9599   if (Diags.isIgnored(diag::warn_doc_param_not_found, Group[0]->getLocation()))
9600     return;
9601 
9602   if (Group.size() >= 2) {
9603     // This is a decl group.  Normally it will contain only declarations
9604     // produced from declarator list.  But in case we have any definitions or
9605     // additional declaration references:
9606     //   'typedef struct S {} S;'
9607     //   'typedef struct S *S;'
9608     //   'struct S *pS;'
9609     // FinalizeDeclaratorGroup adds these as separate declarations.
9610     Decl *MaybeTagDecl = Group[0];
9611     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
9612       Group = Group.slice(1);
9613     }
9614   }
9615 
9616   // See if there are any new comments that are not attached to a decl.
9617   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9618   if (!Comments.empty() &&
9619       !Comments.back()->isAttached()) {
9620     // There is at least one comment that not attached to a decl.
9621     // Maybe it should be attached to one of these decls?
9622     //
9623     // Note that this way we pick up not only comments that precede the
9624     // declaration, but also comments that *follow* the declaration -- thanks to
9625     // the lookahead in the lexer: we've consumed the semicolon and looked
9626     // ahead through comments.
9627     for (unsigned i = 0, e = Group.size(); i != e; ++i)
9628       Context.getCommentForDecl(Group[i], &PP);
9629   }
9630 }
9631 
9632 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9633 /// to introduce parameters into function prototype scope.
9634 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
9635   const DeclSpec &DS = D.getDeclSpec();
9636 
9637   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
9638 
9639   // C++03 [dcl.stc]p2 also permits 'auto'.
9640   VarDecl::StorageClass StorageClass = SC_None;
9641   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
9642     StorageClass = SC_Register;
9643   } else if (getLangOpts().CPlusPlus &&
9644              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9645     StorageClass = SC_Auto;
9646   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
9647     Diag(DS.getStorageClassSpecLoc(),
9648          diag::err_invalid_storage_class_in_func_decl);
9649     D.getMutableDeclSpec().ClearStorageClassSpecs();
9650   }
9651 
9652   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9653     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9654       << DeclSpec::getSpecifierName(TSCS);
9655   if (DS.isConstexprSpecified())
9656     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
9657       << 0;
9658 
9659   DiagnoseFunctionSpecifiers(DS);
9660 
9661   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9662   QualType parmDeclType = TInfo->getType();
9663 
9664   if (getLangOpts().CPlusPlus) {
9665     // Check that there are no default arguments inside the type of this
9666     // parameter.
9667     CheckExtraCXXDefaultArguments(D);
9668 
9669     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9670     if (D.getCXXScopeSpec().isSet()) {
9671       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9672         << D.getCXXScopeSpec().getRange();
9673       D.getCXXScopeSpec().clear();
9674     }
9675   }
9676 
9677   // Ensure we have a valid name
9678   IdentifierInfo *II = nullptr;
9679   if (D.hasName()) {
9680     II = D.getIdentifier();
9681     if (!II) {
9682       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
9683         << GetNameForDeclarator(D).getName();
9684       D.setInvalidType(true);
9685     }
9686   }
9687 
9688   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
9689   if (II) {
9690     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9691                    ForRedeclaration);
9692     LookupName(R, S);
9693     if (R.isSingleResult()) {
9694       NamedDecl *PrevDecl = R.getFoundDecl();
9695       if (PrevDecl->isTemplateParameter()) {
9696         // Maybe we will complain about the shadowed template parameter.
9697         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9698         // Just pretend that we didn't see the previous declaration.
9699         PrevDecl = nullptr;
9700       } else if (S->isDeclScope(PrevDecl)) {
9701         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
9702         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9703 
9704         // Recover by removing the name
9705         II = nullptr;
9706         D.SetIdentifier(nullptr, D.getIdentifierLoc());
9707         D.setInvalidType(true);
9708       }
9709     }
9710   }
9711 
9712   // Temporarily put parameter variables in the translation unit, not
9713   // the enclosing context.  This prevents them from accidentally
9714   // looking like class members in C++.
9715   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
9716                                     D.getLocStart(),
9717                                     D.getIdentifierLoc(), II,
9718                                     parmDeclType, TInfo,
9719                                     StorageClass);
9720 
9721   if (D.isInvalidType())
9722     New->setInvalidDecl();
9723 
9724   assert(S->isFunctionPrototypeScope());
9725   assert(S->getFunctionPrototypeDepth() >= 1);
9726   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9727                     S->getNextFunctionPrototypeIndex());
9728 
9729   // Add the parameter declaration into this scope.
9730   S->AddDecl(New);
9731   if (II)
9732     IdResolver.AddDecl(New);
9733 
9734   ProcessDeclAttributes(S, New, D);
9735 
9736   if (D.getDeclSpec().isModulePrivateSpecified())
9737     Diag(New->getLocation(), diag::err_module_private_local)
9738       << 1 << New->getDeclName()
9739       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9740       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9741 
9742   if (New->hasAttr<BlocksAttr>()) {
9743     Diag(New->getLocation(), diag::err_block_on_nonlocal);
9744   }
9745   return New;
9746 }
9747 
9748 /// \brief Synthesizes a variable for a parameter arising from a
9749 /// typedef.
9750 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9751                                               SourceLocation Loc,
9752                                               QualType T) {
9753   /* FIXME: setting StartLoc == Loc.
9754      Would it be worth to modify callers so as to provide proper source
9755      location for the unnamed parameters, embedding the parameter's type? */
9756   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
9757                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
9758                                            SC_None, nullptr);
9759   Param->setImplicit();
9760   return Param;
9761 }
9762 
9763 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9764                                     ParmVarDecl * const *ParamEnd) {
9765   // Don't diagnose unused-parameter errors in template instantiations; we
9766   // will already have done so in the template itself.
9767   if (!ActiveTemplateInstantiations.empty())
9768     return;
9769 
9770   for (; Param != ParamEnd; ++Param) {
9771     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
9772         !(*Param)->hasAttr<UnusedAttr>()) {
9773       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9774         << (*Param)->getDeclName();
9775     }
9776   }
9777 }
9778 
9779 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9780                                                   ParmVarDecl * const *ParamEnd,
9781                                                   QualType ReturnTy,
9782                                                   NamedDecl *D) {
9783   if (LangOpts.NumLargeByValueCopy == 0) // No check.
9784     return;
9785 
9786   // Warn if the return value is pass-by-value and larger than the specified
9787   // threshold.
9788   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
9789     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
9790     if (Size > LangOpts.NumLargeByValueCopy)
9791       Diag(D->getLocation(), diag::warn_return_value_size)
9792           << D->getDeclName() << Size;
9793   }
9794 
9795   // Warn if any parameter is pass-by-value and larger than the specified
9796   // threshold.
9797   for (; Param != ParamEnd; ++Param) {
9798     QualType T = (*Param)->getType();
9799     if (T->isDependentType() || !T.isPODType(Context))
9800       continue;
9801     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
9802     if (Size > LangOpts.NumLargeByValueCopy)
9803       Diag((*Param)->getLocation(), diag::warn_parameter_size)
9804           << (*Param)->getDeclName() << Size;
9805   }
9806 }
9807 
9808 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9809                                   SourceLocation NameLoc, IdentifierInfo *Name,
9810                                   QualType T, TypeSourceInfo *TSInfo,
9811                                   VarDecl::StorageClass StorageClass) {
9812   // In ARC, infer a lifetime qualifier for appropriate parameter types.
9813   if (getLangOpts().ObjCAutoRefCount &&
9814       T.getObjCLifetime() == Qualifiers::OCL_None &&
9815       T->isObjCLifetimeType()) {
9816 
9817     Qualifiers::ObjCLifetime lifetime;
9818 
9819     // Special cases for arrays:
9820     //   - if it's const, use __unsafe_unretained
9821     //   - otherwise, it's an error
9822     if (T->isArrayType()) {
9823       if (!T.isConstQualified()) {
9824         DelayedDiagnostics.add(
9825             sema::DelayedDiagnostic::makeForbiddenType(
9826             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
9827       }
9828       lifetime = Qualifiers::OCL_ExplicitNone;
9829     } else {
9830       lifetime = T->getObjCARCImplicitLifetime();
9831     }
9832     T = Context.getLifetimeQualifiedType(T, lifetime);
9833   }
9834 
9835   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
9836                                          Context.getAdjustedParameterType(T),
9837                                          TSInfo,
9838                                          StorageClass, nullptr);
9839 
9840   // Parameters can not be abstract class types.
9841   // For record types, this is done by the AbstractClassUsageDiagnoser once
9842   // the class has been completely parsed.
9843   if (!CurContext->isRecord() &&
9844       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9845                              AbstractParamType))
9846     New->setInvalidDecl();
9847 
9848   // Parameter declarators cannot be interface types. All ObjC objects are
9849   // passed by reference.
9850   if (T->isObjCObjectType()) {
9851     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
9852     Diag(NameLoc,
9853          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
9854       << FixItHint::CreateInsertion(TypeEndLoc, "*");
9855     T = Context.getObjCObjectPointerType(T);
9856     New->setType(T);
9857   }
9858 
9859   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9860   // duration shall not be qualified by an address-space qualifier."
9861   // Since all parameters have automatic store duration, they can not have
9862   // an address space.
9863   if (T.getAddressSpace() != 0) {
9864     // OpenCL allows function arguments declared to be an array of a type
9865     // to be qualified with an address space.
9866     if (!(getLangOpts().OpenCL && T->isArrayType())) {
9867       Diag(NameLoc, diag::err_arg_with_address_space);
9868       New->setInvalidDecl();
9869     }
9870   }
9871 
9872   return New;
9873 }
9874 
9875 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9876                                            SourceLocation LocAfterDecls) {
9877   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
9878 
9879   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9880   // for a K&R function.
9881   if (!FTI.hasPrototype) {
9882     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
9883       --i;
9884       if (FTI.Params[i].Param == nullptr) {
9885         SmallString<256> Code;
9886         llvm::raw_svector_ostream(Code)
9887             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
9888         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
9889             << FTI.Params[i].Ident
9890             << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
9891 
9892         // Implicitly declare the argument as type 'int' for lack of a better
9893         // type.
9894         AttributeFactory attrs;
9895         DeclSpec DS(attrs);
9896         const char* PrevSpec; // unused
9897         unsigned DiagID; // unused
9898         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
9899                            DiagID, Context.getPrintingPolicy());
9900         // Use the identifier location for the type source range.
9901         DS.SetRangeStart(FTI.Params[i].IdentLoc);
9902         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
9903         Declarator ParamD(DS, Declarator::KNRTypeListContext);
9904         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
9905         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
9906       }
9907     }
9908   }
9909 }
9910 
9911 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
9912   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
9913   assert(D.isFunctionDeclarator() && "Not a function declarator!");
9914   Scope *ParentScope = FnBodyScope->getParent();
9915 
9916   D.setFunctionDefinitionKind(FDK_Definition);
9917   Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
9918   return ActOnStartOfFunctionDef(FnBodyScope, DP);
9919 }
9920 
9921 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) {
9922   Consumer.HandleInlineMethodDefinition(D);
9923 }
9924 
9925 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9926                              const FunctionDecl*& PossibleZeroParamPrototype) {
9927   // Don't warn about invalid declarations.
9928   if (FD->isInvalidDecl())
9929     return false;
9930 
9931   // Or declarations that aren't global.
9932   if (!FD->isGlobal())
9933     return false;
9934 
9935   // Don't warn about C++ member functions.
9936   if (isa<CXXMethodDecl>(FD))
9937     return false;
9938 
9939   // Don't warn about 'main'.
9940   if (FD->isMain())
9941     return false;
9942 
9943   // Don't warn about inline functions.
9944   if (FD->isInlined())
9945     return false;
9946 
9947   // Don't warn about function templates.
9948   if (FD->getDescribedFunctionTemplate())
9949     return false;
9950 
9951   // Don't warn about function template specializations.
9952   if (FD->isFunctionTemplateSpecialization())
9953     return false;
9954 
9955   // Don't warn for OpenCL kernels.
9956   if (FD->hasAttr<OpenCLKernelAttr>())
9957     return false;
9958 
9959   bool MissingPrototype = true;
9960   for (const FunctionDecl *Prev = FD->getPreviousDecl();
9961        Prev; Prev = Prev->getPreviousDecl()) {
9962     // Ignore any declarations that occur in function or method
9963     // scope, because they aren't visible from the header.
9964     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
9965       continue;
9966 
9967     MissingPrototype = !Prev->getType()->isFunctionProtoType();
9968     if (FD->getNumParams() == 0)
9969       PossibleZeroParamPrototype = Prev;
9970     break;
9971   }
9972 
9973   return MissingPrototype;
9974 }
9975 
9976 void
9977 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
9978                                    const FunctionDecl *EffectiveDefinition) {
9979   // Don't complain if we're in GNU89 mode and the previous definition
9980   // was an extern inline function.
9981   const FunctionDecl *Definition = EffectiveDefinition;
9982   if (!Definition)
9983     if (!FD->isDefined(Definition))
9984       return;
9985 
9986   if (canRedefineFunction(Definition, getLangOpts()))
9987     return;
9988 
9989   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9990       Definition->getStorageClass() == SC_Extern)
9991     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
9992         << FD->getDeclName() << getLangOpts().CPlusPlus;
9993   else
9994     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9995 
9996   Diag(Definition->getLocation(), diag::note_previous_definition);
9997   FD->setInvalidDecl();
9998 }
9999 
10000 
10001 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
10002                                    Sema &S) {
10003   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
10004 
10005   LambdaScopeInfo *LSI = S.PushLambdaScope();
10006   LSI->CallOperator = CallOperator;
10007   LSI->Lambda = LambdaClass;
10008   LSI->ReturnType = CallOperator->getReturnType();
10009   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
10010 
10011   if (LCD == LCD_None)
10012     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
10013   else if (LCD == LCD_ByCopy)
10014     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
10015   else if (LCD == LCD_ByRef)
10016     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
10017   DeclarationNameInfo DNI = CallOperator->getNameInfo();
10018 
10019   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
10020   LSI->Mutable = !CallOperator->isConst();
10021 
10022   // Add the captures to the LSI so they can be noted as already
10023   // captured within tryCaptureVar.
10024   auto I = LambdaClass->field_begin();
10025   for (const auto &C : LambdaClass->captures()) {
10026     if (C.capturesVariable()) {
10027       VarDecl *VD = C.getCapturedVar();
10028       if (VD->isInitCapture())
10029         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
10030       QualType CaptureType = VD->getType();
10031       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
10032       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
10033           /*RefersToEnclosingLocal*/true, C.getLocation(),
10034           /*EllipsisLoc*/C.isPackExpansion()
10035                          ? C.getEllipsisLoc() : SourceLocation(),
10036           CaptureType, /*Expr*/ nullptr);
10037 
10038     } else if (C.capturesThis()) {
10039       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
10040                               S.getCurrentThisType(), /*Expr*/ nullptr);
10041     } else {
10042       LSI->addVLATypeCapture(C.getLocation(), I->getType());
10043     }
10044     ++I;
10045   }
10046 }
10047 
10048 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
10049   // Clear the last template instantiation error context.
10050   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
10051 
10052   if (!D)
10053     return D;
10054   FunctionDecl *FD = nullptr;
10055 
10056   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
10057     FD = FunTmpl->getTemplatedDecl();
10058   else
10059     FD = cast<FunctionDecl>(D);
10060   // If we are instantiating a generic lambda call operator, push
10061   // a LambdaScopeInfo onto the function stack.  But use the information
10062   // that's already been calculated (ActOnLambdaExpr) to prime the current
10063   // LambdaScopeInfo.
10064   // When the template operator is being specialized, the LambdaScopeInfo,
10065   // has to be properly restored so that tryCaptureVariable doesn't try
10066   // and capture any new variables. In addition when calculating potential
10067   // captures during transformation of nested lambdas, it is necessary to
10068   // have the LSI properly restored.
10069   if (isGenericLambdaCallOperatorSpecialization(FD)) {
10070     assert(ActiveTemplateInstantiations.size() &&
10071       "There should be an active template instantiation on the stack "
10072       "when instantiating a generic lambda!");
10073     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
10074   }
10075   else
10076     // Enter a new function scope
10077     PushFunctionScope();
10078 
10079   // See if this is a redefinition.
10080   if (!FD->isLateTemplateParsed())
10081     CheckForFunctionRedefinition(FD);
10082 
10083   // Builtin functions cannot be defined.
10084   if (unsigned BuiltinID = FD->getBuiltinID()) {
10085     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
10086         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
10087       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
10088       FD->setInvalidDecl();
10089     }
10090   }
10091 
10092   // The return type of a function definition must be complete
10093   // (C99 6.9.1p3, C++ [dcl.fct]p6).
10094   QualType ResultType = FD->getReturnType();
10095   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
10096       !FD->isInvalidDecl() &&
10097       RequireCompleteType(FD->getLocation(), ResultType,
10098                           diag::err_func_def_incomplete_result))
10099     FD->setInvalidDecl();
10100 
10101   // GNU warning -Wmissing-prototypes:
10102   //   Warn if a global function is defined without a previous
10103   //   prototype declaration. This warning is issued even if the
10104   //   definition itself provides a prototype. The aim is to detect
10105   //   global functions that fail to be declared in header files.
10106   const FunctionDecl *PossibleZeroParamPrototype = nullptr;
10107   if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
10108     Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
10109 
10110     if (PossibleZeroParamPrototype) {
10111       // We found a declaration that is not a prototype,
10112       // but that could be a zero-parameter prototype
10113       if (TypeSourceInfo *TI =
10114               PossibleZeroParamPrototype->getTypeSourceInfo()) {
10115         TypeLoc TL = TI->getTypeLoc();
10116         if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
10117           Diag(PossibleZeroParamPrototype->getLocation(),
10118                diag::note_declaration_not_a_prototype)
10119             << PossibleZeroParamPrototype
10120             << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
10121       }
10122     }
10123   }
10124 
10125   if (FnBodyScope)
10126     PushDeclContext(FnBodyScope, FD);
10127 
10128   // Check the validity of our function parameters
10129   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
10130                            /*CheckParameterNames=*/true);
10131 
10132   // Introduce our parameters into the function scope
10133   for (auto Param : FD->params()) {
10134     Param->setOwningFunction(FD);
10135 
10136     // If this has an identifier, add it to the scope stack.
10137     if (Param->getIdentifier() && FnBodyScope) {
10138       CheckShadow(FnBodyScope, Param);
10139 
10140       PushOnScopeChains(Param, FnBodyScope);
10141     }
10142   }
10143 
10144   // If we had any tags defined in the function prototype,
10145   // introduce them into the function scope.
10146   if (FnBodyScope) {
10147     for (ArrayRef<NamedDecl *>::iterator
10148              I = FD->getDeclsInPrototypeScope().begin(),
10149              E = FD->getDeclsInPrototypeScope().end();
10150          I != E; ++I) {
10151       NamedDecl *D = *I;
10152 
10153       // Some of these decls (like enums) may have been pinned to the translation unit
10154       // for lack of a real context earlier. If so, remove from the translation unit
10155       // and reattach to the current context.
10156       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
10157         // Is the decl actually in the context?
10158         for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
10159           if (DI == D) {
10160             Context.getTranslationUnitDecl()->removeDecl(D);
10161             break;
10162           }
10163         }
10164         // Either way, reassign the lexical decl context to our FunctionDecl.
10165         D->setLexicalDeclContext(CurContext);
10166       }
10167 
10168       // If the decl has a non-null name, make accessible in the current scope.
10169       if (!D->getName().empty())
10170         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
10171 
10172       // Similarly, dive into enums and fish their constants out, making them
10173       // accessible in this scope.
10174       if (auto *ED = dyn_cast<EnumDecl>(D)) {
10175         for (auto *EI : ED->enumerators())
10176           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
10177       }
10178     }
10179   }
10180 
10181   // Ensure that the function's exception specification is instantiated.
10182   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
10183     ResolveExceptionSpec(D->getLocation(), FPT);
10184 
10185   // dllimport cannot be applied to non-inline function definitions.
10186   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
10187       !FD->isTemplateInstantiation()) {
10188     assert(!FD->hasAttr<DLLExportAttr>());
10189     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
10190     FD->setInvalidDecl();
10191     return D;
10192   }
10193   // We want to attach documentation to original Decl (which might be
10194   // a function template).
10195   ActOnDocumentableDecl(D);
10196   if (getCurLexicalContext()->isObjCContainer() &&
10197       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
10198       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
10199     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
10200 
10201   return D;
10202 }
10203 
10204 /// \brief Given the set of return statements within a function body,
10205 /// compute the variables that are subject to the named return value
10206 /// optimization.
10207 ///
10208 /// Each of the variables that is subject to the named return value
10209 /// optimization will be marked as NRVO variables in the AST, and any
10210 /// return statement that has a marked NRVO variable as its NRVO candidate can
10211 /// use the named return value optimization.
10212 ///
10213 /// This function applies a very simplistic algorithm for NRVO: if every return
10214 /// statement in the scope of a variable has the same NRVO candidate, that
10215 /// candidate is an NRVO variable.
10216 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
10217   ReturnStmt **Returns = Scope->Returns.data();
10218 
10219   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
10220     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
10221       if (!NRVOCandidate->isNRVOVariable())
10222         Returns[I]->setNRVOCandidate(nullptr);
10223     }
10224   }
10225 }
10226 
10227 bool Sema::canDelayFunctionBody(const Declarator &D) {
10228   // We can't delay parsing the body of a constexpr function template (yet).
10229   if (D.getDeclSpec().isConstexprSpecified())
10230     return false;
10231 
10232   // We can't delay parsing the body of a function template with a deduced
10233   // return type (yet).
10234   if (D.getDeclSpec().containsPlaceholderType()) {
10235     // If the placeholder introduces a non-deduced trailing return type,
10236     // we can still delay parsing it.
10237     if (D.getNumTypeObjects()) {
10238       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
10239       if (Outer.Kind == DeclaratorChunk::Function &&
10240           Outer.Fun.hasTrailingReturnType()) {
10241         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
10242         return Ty.isNull() || !Ty->isUndeducedType();
10243       }
10244     }
10245     return false;
10246   }
10247 
10248   return true;
10249 }
10250 
10251 bool Sema::canSkipFunctionBody(Decl *D) {
10252   // We cannot skip the body of a function (or function template) which is
10253   // constexpr, since we may need to evaluate its body in order to parse the
10254   // rest of the file.
10255   // We cannot skip the body of a function with an undeduced return type,
10256   // because any callers of that function need to know the type.
10257   if (const FunctionDecl *FD = D->getAsFunction())
10258     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
10259       return false;
10260   return Consumer.shouldSkipFunctionBody(D);
10261 }
10262 
10263 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
10264   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
10265     FD->setHasSkippedBody();
10266   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
10267     MD->setHasSkippedBody();
10268   return ActOnFinishFunctionBody(Decl, nullptr);
10269 }
10270 
10271 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
10272   return ActOnFinishFunctionBody(D, BodyArg, false);
10273 }
10274 
10275 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
10276                                     bool IsInstantiation) {
10277   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
10278 
10279   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10280   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
10281 
10282   if (FD) {
10283     FD->setBody(Body);
10284 
10285     if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body &&
10286         !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
10287       // If the function has a deduced result type but contains no 'return'
10288       // statements, the result type as written must be exactly 'auto', and
10289       // the deduced result type is 'void'.
10290       if (!FD->getReturnType()->getAs<AutoType>()) {
10291         Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
10292             << FD->getReturnType();
10293         FD->setInvalidDecl();
10294       } else {
10295         // Substitute 'void' for the 'auto' in the type.
10296         TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
10297             IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc();
10298         Context.adjustDeducedFunctionResultType(
10299             FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
10300       }
10301     }
10302 
10303     // The only way to be included in UndefinedButUsed is if there is an
10304     // ODR use before the definition. Avoid the expensive map lookup if this
10305     // is the first declaration.
10306     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
10307       if (!FD->isExternallyVisible())
10308         UndefinedButUsed.erase(FD);
10309       else if (FD->isInlined() &&
10310                (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
10311                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
10312         UndefinedButUsed.erase(FD);
10313     }
10314 
10315     // If the function implicitly returns zero (like 'main') or is naked,
10316     // don't complain about missing return statements.
10317     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
10318       WP.disableCheckFallThrough();
10319 
10320     // MSVC permits the use of pure specifier (=0) on function definition,
10321     // defined at class scope, warn about this non-standard construct.
10322     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
10323       Diag(FD->getLocation(), diag::ext_pure_function_definition);
10324 
10325     if (!FD->isInvalidDecl()) {
10326       // Don't diagnose unused parameters of defaulted or deleted functions.
10327       if (Body)
10328         DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
10329       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
10330                                              FD->getReturnType(), FD);
10331 
10332       // If this is a constructor, we need a vtable.
10333       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
10334         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
10335 
10336       // Try to apply the named return value optimization. We have to check
10337       // if we can do this here because lambdas keep return statements around
10338       // to deduce an implicit return type.
10339       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
10340           !FD->isDependentContext())
10341         computeNRVO(Body, getCurFunction());
10342     }
10343 
10344     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
10345            "Function parsing confused");
10346   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
10347     assert(MD == getCurMethodDecl() && "Method parsing confused");
10348     MD->setBody(Body);
10349     if (!MD->isInvalidDecl()) {
10350       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
10351       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
10352                                              MD->getReturnType(), MD);
10353 
10354       if (Body)
10355         computeNRVO(Body, getCurFunction());
10356     }
10357     if (getCurFunction()->ObjCShouldCallSuper) {
10358       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
10359         << MD->getSelector().getAsString();
10360       getCurFunction()->ObjCShouldCallSuper = false;
10361     }
10362     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
10363       const ObjCMethodDecl *InitMethod = nullptr;
10364       bool isDesignated =
10365           MD->isDesignatedInitializerForTheInterface(&InitMethod);
10366       assert(isDesignated && InitMethod);
10367       (void)isDesignated;
10368 
10369       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
10370         auto IFace = MD->getClassInterface();
10371         if (!IFace)
10372           return false;
10373         auto SuperD = IFace->getSuperClass();
10374         if (!SuperD)
10375           return false;
10376         return SuperD->getIdentifier() ==
10377             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
10378       };
10379       // Don't issue this warning for unavailable inits or direct subclasses
10380       // of NSObject.
10381       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
10382         Diag(MD->getLocation(),
10383              diag::warn_objc_designated_init_missing_super_call);
10384         Diag(InitMethod->getLocation(),
10385              diag::note_objc_designated_init_marked_here);
10386       }
10387       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
10388     }
10389     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
10390       // Don't issue this warning for unavaialable inits.
10391       if (!MD->isUnavailable())
10392         Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call);
10393       getCurFunction()->ObjCWarnForNoInitDelegation = false;
10394     }
10395   } else {
10396     return nullptr;
10397   }
10398 
10399   assert(!getCurFunction()->ObjCShouldCallSuper &&
10400          "This should only be set for ObjC methods, which should have been "
10401          "handled in the block above.");
10402 
10403   // Verify and clean out per-function state.
10404   if (Body) {
10405     // C++ constructors that have function-try-blocks can't have return
10406     // statements in the handlers of that block. (C++ [except.handle]p14)
10407     // Verify this.
10408     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
10409       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
10410 
10411     // Verify that gotos and switch cases don't jump into scopes illegally.
10412     if (getCurFunction()->NeedsScopeChecking() &&
10413         !PP.isCodeCompletionEnabled())
10414       DiagnoseInvalidJumps(Body);
10415 
10416     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
10417       if (!Destructor->getParent()->isDependentType())
10418         CheckDestructor(Destructor);
10419 
10420       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10421                                              Destructor->getParent());
10422     }
10423 
10424     // If any errors have occurred, clear out any temporaries that may have
10425     // been leftover. This ensures that these temporaries won't be picked up for
10426     // deletion in some later function.
10427     if (getDiagnostics().hasErrorOccurred() ||
10428         getDiagnostics().getSuppressAllDiagnostics()) {
10429       DiscardCleanupsInEvaluationContext();
10430     }
10431     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
10432         !isa<FunctionTemplateDecl>(dcl)) {
10433       // Since the body is valid, issue any analysis-based warnings that are
10434       // enabled.
10435       ActivePolicy = &WP;
10436     }
10437 
10438     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
10439         (!CheckConstexprFunctionDecl(FD) ||
10440          !CheckConstexprFunctionBody(FD, Body)))
10441       FD->setInvalidDecl();
10442 
10443     if (FD && FD->hasAttr<NakedAttr>()) {
10444       for (const Stmt *S : Body->children()) {
10445         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
10446           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
10447           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
10448           FD->setInvalidDecl();
10449           break;
10450         }
10451       }
10452     }
10453 
10454     assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
10455     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
10456     assert(MaybeODRUseExprs.empty() &&
10457            "Leftover expressions for odr-use checking");
10458   }
10459 
10460   if (!IsInstantiation)
10461     PopDeclContext();
10462 
10463   PopFunctionScopeInfo(ActivePolicy, dcl);
10464   // If any errors have occurred, clear out any temporaries that may have
10465   // been leftover. This ensures that these temporaries won't be picked up for
10466   // deletion in some later function.
10467   if (getDiagnostics().hasErrorOccurred()) {
10468     DiscardCleanupsInEvaluationContext();
10469   }
10470 
10471   return dcl;
10472 }
10473 
10474 
10475 /// When we finish delayed parsing of an attribute, we must attach it to the
10476 /// relevant Decl.
10477 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
10478                                        ParsedAttributes &Attrs) {
10479   // Always attach attributes to the underlying decl.
10480   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
10481     D = TD->getTemplatedDecl();
10482   ProcessDeclAttributeList(S, D, Attrs.getList());
10483 
10484   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
10485     if (Method->isStatic())
10486       checkThisInStaticMemberFunctionAttributes(Method);
10487 }
10488 
10489 
10490 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
10491 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
10492 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
10493                                           IdentifierInfo &II, Scope *S) {
10494   // Before we produce a declaration for an implicitly defined
10495   // function, see whether there was a locally-scoped declaration of
10496   // this name as a function or variable. If so, use that
10497   // (non-visible) declaration, and complain about it.
10498   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
10499     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
10500     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
10501     return ExternCPrev;
10502   }
10503 
10504   // Extension in C99.  Legal in C90, but warn about it.
10505   unsigned diag_id;
10506   if (II.getName().startswith("__builtin_"))
10507     diag_id = diag::warn_builtin_unknown;
10508   else if (getLangOpts().C99)
10509     diag_id = diag::ext_implicit_function_decl;
10510   else
10511     diag_id = diag::warn_implicit_function_decl;
10512   Diag(Loc, diag_id) << &II;
10513 
10514   // Because typo correction is expensive, only do it if the implicit
10515   // function declaration is going to be treated as an error.
10516   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
10517     TypoCorrection Corrected;
10518     DeclFilterCCC<FunctionDecl> Validator;
10519     if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
10520                                       LookupOrdinaryName, S, nullptr, Validator,
10521                                       CTK_NonError)))
10522       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
10523                    /*ErrorRecovery*/false);
10524   }
10525 
10526   // Set a Declarator for the implicit definition: int foo();
10527   const char *Dummy;
10528   AttributeFactory attrFactory;
10529   DeclSpec DS(attrFactory);
10530   unsigned DiagID;
10531   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
10532                                   Context.getPrintingPolicy());
10533   (void)Error; // Silence warning.
10534   assert(!Error && "Error setting up implicit decl!");
10535   SourceLocation NoLoc;
10536   Declarator D(DS, Declarator::BlockContext);
10537   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
10538                                              /*IsAmbiguous=*/false,
10539                                              /*LParenLoc=*/NoLoc,
10540                                              /*Params=*/nullptr,
10541                                              /*NumParams=*/0,
10542                                              /*EllipsisLoc=*/NoLoc,
10543                                              /*RParenLoc=*/NoLoc,
10544                                              /*TypeQuals=*/0,
10545                                              /*RefQualifierIsLvalueRef=*/true,
10546                                              /*RefQualifierLoc=*/NoLoc,
10547                                              /*ConstQualifierLoc=*/NoLoc,
10548                                              /*VolatileQualifierLoc=*/NoLoc,
10549                                              /*MutableLoc=*/NoLoc,
10550                                              EST_None,
10551                                              /*ESpecLoc=*/NoLoc,
10552                                              /*Exceptions=*/nullptr,
10553                                              /*ExceptionRanges=*/nullptr,
10554                                              /*NumExceptions=*/0,
10555                                              /*NoexceptExpr=*/nullptr,
10556                                              Loc, Loc, D),
10557                 DS.getAttributes(),
10558                 SourceLocation());
10559   D.SetIdentifier(&II, Loc);
10560 
10561   // Insert this function into translation-unit scope.
10562 
10563   DeclContext *PrevDC = CurContext;
10564   CurContext = Context.getTranslationUnitDecl();
10565 
10566   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
10567   FD->setImplicit();
10568 
10569   CurContext = PrevDC;
10570 
10571   AddKnownFunctionAttributes(FD);
10572 
10573   return FD;
10574 }
10575 
10576 /// \brief Adds any function attributes that we know a priori based on
10577 /// the declaration of this function.
10578 ///
10579 /// These attributes can apply both to implicitly-declared builtins
10580 /// (like __builtin___printf_chk) or to library-declared functions
10581 /// like NSLog or printf.
10582 ///
10583 /// We need to check for duplicate attributes both here and where user-written
10584 /// attributes are applied to declarations.
10585 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
10586   if (FD->isInvalidDecl())
10587     return;
10588 
10589   // If this is a built-in function, map its builtin attributes to
10590   // actual attributes.
10591   if (unsigned BuiltinID = FD->getBuiltinID()) {
10592     // Handle printf-formatting attributes.
10593     unsigned FormatIdx;
10594     bool HasVAListArg;
10595     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
10596       if (!FD->hasAttr<FormatAttr>()) {
10597         const char *fmt = "printf";
10598         unsigned int NumParams = FD->getNumParams();
10599         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10600             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10601           fmt = "NSString";
10602         FD->addAttr(FormatAttr::CreateImplicit(Context,
10603                                                &Context.Idents.get(fmt),
10604                                                FormatIdx+1,
10605                                                HasVAListArg ? 0 : FormatIdx+2,
10606                                                FD->getLocation()));
10607       }
10608     }
10609     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10610                                              HasVAListArg)) {
10611      if (!FD->hasAttr<FormatAttr>())
10612        FD->addAttr(FormatAttr::CreateImplicit(Context,
10613                                               &Context.Idents.get("scanf"),
10614                                               FormatIdx+1,
10615                                               HasVAListArg ? 0 : FormatIdx+2,
10616                                               FD->getLocation()));
10617     }
10618 
10619     // Mark const if we don't care about errno and that is the only
10620     // thing preventing the function from being const. This allows
10621     // IRgen to use LLVM intrinsics for such functions.
10622     if (!getLangOpts().MathErrno &&
10623         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
10624       if (!FD->hasAttr<ConstAttr>())
10625         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
10626     }
10627 
10628     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
10629         !FD->hasAttr<ReturnsTwiceAttr>())
10630       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
10631                                          FD->getLocation()));
10632     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
10633       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
10634     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
10635       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
10636   }
10637 
10638   IdentifierInfo *Name = FD->getIdentifier();
10639   if (!Name)
10640     return;
10641   if ((!getLangOpts().CPlusPlus &&
10642        FD->getDeclContext()->isTranslationUnit()) ||
10643       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
10644        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
10645        LinkageSpecDecl::lang_c)) {
10646     // Okay: this could be a libc/libm/Objective-C function we know
10647     // about.
10648   } else
10649     return;
10650 
10651   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
10652     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
10653     // target-specific builtins, perhaps?
10654     if (!FD->hasAttr<FormatAttr>())
10655       FD->addAttr(FormatAttr::CreateImplicit(Context,
10656                                              &Context.Idents.get("printf"), 2,
10657                                              Name->isStr("vasprintf") ? 0 : 3,
10658                                              FD->getLocation()));
10659   }
10660 
10661   if (Name->isStr("__CFStringMakeConstantString")) {
10662     // We already have a __builtin___CFStringMakeConstantString,
10663     // but builds that use -fno-constant-cfstrings don't go through that.
10664     if (!FD->hasAttr<FormatArgAttr>())
10665       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
10666                                                 FD->getLocation()));
10667   }
10668 }
10669 
10670 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
10671                                     TypeSourceInfo *TInfo) {
10672   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
10673   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
10674 
10675   if (!TInfo) {
10676     assert(D.isInvalidType() && "no declarator info for valid type");
10677     TInfo = Context.getTrivialTypeSourceInfo(T);
10678   }
10679 
10680   // Scope manipulation handled by caller.
10681   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
10682                                            D.getLocStart(),
10683                                            D.getIdentifierLoc(),
10684                                            D.getIdentifier(),
10685                                            TInfo);
10686 
10687   // Bail out immediately if we have an invalid declaration.
10688   if (D.isInvalidType()) {
10689     NewTD->setInvalidDecl();
10690     return NewTD;
10691   }
10692 
10693   if (D.getDeclSpec().isModulePrivateSpecified()) {
10694     if (CurContext->isFunctionOrMethod())
10695       Diag(NewTD->getLocation(), diag::err_module_private_local)
10696         << 2 << NewTD->getDeclName()
10697         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10698         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10699     else
10700       NewTD->setModulePrivate();
10701   }
10702 
10703   // C++ [dcl.typedef]p8:
10704   //   If the typedef declaration defines an unnamed class (or
10705   //   enum), the first typedef-name declared by the declaration
10706   //   to be that class type (or enum type) is used to denote the
10707   //   class type (or enum type) for linkage purposes only.
10708   // We need to check whether the type was declared in the declaration.
10709   switch (D.getDeclSpec().getTypeSpecType()) {
10710   case TST_enum:
10711   case TST_struct:
10712   case TST_interface:
10713   case TST_union:
10714   case TST_class: {
10715     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10716 
10717     // Do nothing if the tag is not anonymous or already has an
10718     // associated typedef (from an earlier typedef in this decl group).
10719     if (tagFromDeclSpec->getIdentifier()) break;
10720     if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
10721 
10722     // A well-formed anonymous tag must always be a TUK_Definition.
10723     assert(tagFromDeclSpec->isThisDeclarationADefinition());
10724 
10725     // The type must match the tag exactly;  no qualifiers allowed.
10726     if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10727       break;
10728 
10729     // If we've already computed linkage for the anonymous tag, then
10730     // adding a typedef name for the anonymous decl can change that
10731     // linkage, which might be a serious problem.  Diagnose this as
10732     // unsupported and ignore the typedef name.  TODO: we should
10733     // pursue this as a language defect and establish a formal rule
10734     // for how to handle it.
10735     if (tagFromDeclSpec->hasLinkageBeenComputed()) {
10736       Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage);
10737 
10738       SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
10739       tagLoc = getLocForEndOfToken(tagLoc);
10740 
10741       llvm::SmallString<40> textToInsert;
10742       textToInsert += ' ';
10743       textToInsert += D.getIdentifier()->getName();
10744       Diag(tagLoc, diag::note_typedef_changes_linkage)
10745         << FixItHint::CreateInsertion(tagLoc, textToInsert);
10746       break;
10747     }
10748 
10749     // Otherwise, set this is the anon-decl typedef for the tag.
10750     tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
10751     break;
10752   }
10753 
10754   default:
10755     break;
10756   }
10757 
10758   return NewTD;
10759 }
10760 
10761 
10762 /// \brief Check that this is a valid underlying type for an enum declaration.
10763 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10764   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10765   QualType T = TI->getType();
10766 
10767   if (T->isDependentType())
10768     return false;
10769 
10770   if (const BuiltinType *BT = T->getAs<BuiltinType>())
10771     if (BT->isInteger())
10772       return false;
10773 
10774   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10775   return true;
10776 }
10777 
10778 /// Check whether this is a valid redeclaration of a previous enumeration.
10779 /// \return true if the redeclaration was invalid.
10780 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10781                                   QualType EnumUnderlyingTy,
10782                                   const EnumDecl *Prev) {
10783   bool IsFixed = !EnumUnderlyingTy.isNull();
10784 
10785   if (IsScoped != Prev->isScoped()) {
10786     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10787       << Prev->isScoped();
10788     Diag(Prev->getLocation(), diag::note_previous_declaration);
10789     return true;
10790   }
10791 
10792   if (IsFixed && Prev->isFixed()) {
10793     if (!EnumUnderlyingTy->isDependentType() &&
10794         !Prev->getIntegerType()->isDependentType() &&
10795         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
10796                                         Prev->getIntegerType())) {
10797       // TODO: Highlight the underlying type of the redeclaration.
10798       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10799         << EnumUnderlyingTy << Prev->getIntegerType();
10800       Diag(Prev->getLocation(), diag::note_previous_declaration)
10801           << Prev->getIntegerTypeRange();
10802       return true;
10803     }
10804   } else if (IsFixed != Prev->isFixed()) {
10805     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10806       << Prev->isFixed();
10807     Diag(Prev->getLocation(), diag::note_previous_declaration);
10808     return true;
10809   }
10810 
10811   return false;
10812 }
10813 
10814 /// \brief Get diagnostic %select index for tag kind for
10815 /// redeclaration diagnostic message.
10816 /// WARNING: Indexes apply to particular diagnostics only!
10817 ///
10818 /// \returns diagnostic %select index.
10819 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
10820   switch (Tag) {
10821   case TTK_Struct: return 0;
10822   case TTK_Interface: return 1;
10823   case TTK_Class:  return 2;
10824   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
10825   }
10826 }
10827 
10828 /// \brief Determine if tag kind is a class-key compatible with
10829 /// class for redeclaration (class, struct, or __interface).
10830 ///
10831 /// \returns true iff the tag kind is compatible.
10832 static bool isClassCompatTagKind(TagTypeKind Tag)
10833 {
10834   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10835 }
10836 
10837 /// \brief Determine whether a tag with a given kind is acceptable
10838 /// as a redeclaration of the given tag declaration.
10839 ///
10840 /// \returns true if the new tag kind is acceptable, false otherwise.
10841 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
10842                                         TagTypeKind NewTag, bool isDefinition,
10843                                         SourceLocation NewTagLoc,
10844                                         const IdentifierInfo &Name) {
10845   // C++ [dcl.type.elab]p3:
10846   //   The class-key or enum keyword present in the
10847   //   elaborated-type-specifier shall agree in kind with the
10848   //   declaration to which the name in the elaborated-type-specifier
10849   //   refers. This rule also applies to the form of
10850   //   elaborated-type-specifier that declares a class-name or
10851   //   friend class since it can be construed as referring to the
10852   //   definition of the class. Thus, in any
10853   //   elaborated-type-specifier, the enum keyword shall be used to
10854   //   refer to an enumeration (7.2), the union class-key shall be
10855   //   used to refer to a union (clause 9), and either the class or
10856   //   struct class-key shall be used to refer to a class (clause 9)
10857   //   declared using the class or struct class-key.
10858   TagTypeKind OldTag = Previous->getTagKind();
10859   if (!isDefinition || !isClassCompatTagKind(NewTag))
10860     if (OldTag == NewTag)
10861       return true;
10862 
10863   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
10864     // Warn about the struct/class tag mismatch.
10865     bool isTemplate = false;
10866     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10867       isTemplate = Record->getDescribedClassTemplate();
10868 
10869     if (!ActiveTemplateInstantiations.empty()) {
10870       // In a template instantiation, do not offer fix-its for tag mismatches
10871       // since they usually mess up the template instead of fixing the problem.
10872       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
10873         << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10874         << getRedeclDiagFromTagKind(OldTag);
10875       return true;
10876     }
10877 
10878     if (isDefinition) {
10879       // On definitions, check previous tags and issue a fix-it for each
10880       // one that doesn't match the current tag.
10881       if (Previous->getDefinition()) {
10882         // Don't suggest fix-its for redefinitions.
10883         return true;
10884       }
10885 
10886       bool previousMismatch = false;
10887       for (auto I : Previous->redecls()) {
10888         if (I->getTagKind() != NewTag) {
10889           if (!previousMismatch) {
10890             previousMismatch = true;
10891             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
10892               << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10893               << getRedeclDiagFromTagKind(I->getTagKind());
10894           }
10895           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
10896             << getRedeclDiagFromTagKind(NewTag)
10897             << FixItHint::CreateReplacement(I->getInnerLocStart(),
10898                  TypeWithKeyword::getTagTypeKindName(NewTag));
10899         }
10900       }
10901       return true;
10902     }
10903 
10904     // Check for a previous definition.  If current tag and definition
10905     // are same type, do nothing.  If no definition, but disagree with
10906     // with previous tag type, give a warning, but no fix-it.
10907     const TagDecl *Redecl = Previous->getDefinition() ?
10908                             Previous->getDefinition() : Previous;
10909     if (Redecl->getTagKind() == NewTag) {
10910       return true;
10911     }
10912 
10913     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
10914       << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10915       << getRedeclDiagFromTagKind(OldTag);
10916     Diag(Redecl->getLocation(), diag::note_previous_use);
10917 
10918     // If there is a previous definition, suggest a fix-it.
10919     if (Previous->getDefinition()) {
10920         Diag(NewTagLoc, diag::note_struct_class_suggestion)
10921           << getRedeclDiagFromTagKind(Redecl->getTagKind())
10922           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
10923                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
10924     }
10925 
10926     return true;
10927   }
10928   return false;
10929 }
10930 
10931 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
10932 /// from an outer enclosing namespace or file scope inside a friend declaration.
10933 /// This should provide the commented out code in the following snippet:
10934 ///   namespace N {
10935 ///     struct X;
10936 ///     namespace M {
10937 ///       struct Y { friend struct /*N::*/ X; };
10938 ///     }
10939 ///   }
10940 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
10941                                          SourceLocation NameLoc) {
10942   // While the decl is in a namespace, do repeated lookup of that name and see
10943   // if we get the same namespace back.  If we do not, continue until
10944   // translation unit scope, at which point we have a fully qualified NNS.
10945   SmallVector<IdentifierInfo *, 4> Namespaces;
10946   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
10947   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
10948     // This tag should be declared in a namespace, which can only be enclosed by
10949     // other namespaces.  Bail if there's an anonymous namespace in the chain.
10950     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
10951     if (!Namespace || Namespace->isAnonymousNamespace())
10952       return FixItHint();
10953     IdentifierInfo *II = Namespace->getIdentifier();
10954     Namespaces.push_back(II);
10955     NamedDecl *Lookup = SemaRef.LookupSingleName(
10956         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
10957     if (Lookup == Namespace)
10958       break;
10959   }
10960 
10961   // Once we have all the namespaces, reverse them to go outermost first, and
10962   // build an NNS.
10963   SmallString<64> Insertion;
10964   llvm::raw_svector_ostream OS(Insertion);
10965   if (DC->isTranslationUnit())
10966     OS << "::";
10967   std::reverse(Namespaces.begin(), Namespaces.end());
10968   for (auto *II : Namespaces)
10969     OS << II->getName() << "::";
10970   OS.flush();
10971   return FixItHint::CreateInsertion(NameLoc, Insertion);
10972 }
10973 
10974 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
10975 /// former case, Name will be non-null.  In the later case, Name will be null.
10976 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
10977 /// reference/declaration/definition of a tag.
10978 ///
10979 /// IsTypeSpecifier is true if this is a type-specifier (or
10980 /// trailing-type-specifier) other than one in an alias-declaration.
10981 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
10982                      SourceLocation KWLoc, CXXScopeSpec &SS,
10983                      IdentifierInfo *Name, SourceLocation NameLoc,
10984                      AttributeList *Attr, AccessSpecifier AS,
10985                      SourceLocation ModulePrivateLoc,
10986                      MultiTemplateParamsArg TemplateParameterLists,
10987                      bool &OwnedDecl, bool &IsDependent,
10988                      SourceLocation ScopedEnumKWLoc,
10989                      bool ScopedEnumUsesClassTag,
10990                      TypeResult UnderlyingType,
10991                      bool IsTypeSpecifier) {
10992   // If this is not a definition, it must have a name.
10993   IdentifierInfo *OrigName = Name;
10994   assert((Name != nullptr || TUK == TUK_Definition) &&
10995          "Nameless record must be a definition!");
10996   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
10997 
10998   OwnedDecl = false;
10999   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11000   bool ScopedEnum = ScopedEnumKWLoc.isValid();
11001 
11002   // FIXME: Check explicit specializations more carefully.
11003   bool isExplicitSpecialization = false;
11004   bool Invalid = false;
11005 
11006   // We only need to do this matching if we have template parameters
11007   // or a scope specifier, which also conveniently avoids this work
11008   // for non-C++ cases.
11009   if (TemplateParameterLists.size() > 0 ||
11010       (SS.isNotEmpty() && TUK != TUK_Reference)) {
11011     if (TemplateParameterList *TemplateParams =
11012             MatchTemplateParametersToScopeSpecifier(
11013                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
11014                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
11015       if (Kind == TTK_Enum) {
11016         Diag(KWLoc, diag::err_enum_template);
11017         return nullptr;
11018       }
11019 
11020       if (TemplateParams->size() > 0) {
11021         // This is a declaration or definition of a class template (which may
11022         // be a member of another template).
11023 
11024         if (Invalid)
11025           return nullptr;
11026 
11027         OwnedDecl = false;
11028         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
11029                                                SS, Name, NameLoc, Attr,
11030                                                TemplateParams, AS,
11031                                                ModulePrivateLoc,
11032                                                /*FriendLoc*/SourceLocation(),
11033                                                TemplateParameterLists.size()-1,
11034                                                TemplateParameterLists.data());
11035         return Result.get();
11036       } else {
11037         // The "template<>" header is extraneous.
11038         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11039           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11040         isExplicitSpecialization = true;
11041       }
11042     }
11043   }
11044 
11045   // Figure out the underlying type if this a enum declaration. We need to do
11046   // this early, because it's needed to detect if this is an incompatible
11047   // redeclaration.
11048   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
11049 
11050   if (Kind == TTK_Enum) {
11051     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
11052       // No underlying type explicitly specified, or we failed to parse the
11053       // type, default to int.
11054       EnumUnderlying = Context.IntTy.getTypePtr();
11055     else if (UnderlyingType.get()) {
11056       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
11057       // integral type; any cv-qualification is ignored.
11058       TypeSourceInfo *TI = nullptr;
11059       GetTypeFromParser(UnderlyingType.get(), &TI);
11060       EnumUnderlying = TI;
11061 
11062       if (CheckEnumUnderlyingType(TI))
11063         // Recover by falling back to int.
11064         EnumUnderlying = Context.IntTy.getTypePtr();
11065 
11066       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
11067                                           UPPC_FixedUnderlyingType))
11068         EnumUnderlying = Context.IntTy.getTypePtr();
11069 
11070     } else if (getLangOpts().MSVCCompat)
11071       // Microsoft enums are always of int type.
11072       EnumUnderlying = Context.IntTy.getTypePtr();
11073   }
11074 
11075   DeclContext *SearchDC = CurContext;
11076   DeclContext *DC = CurContext;
11077   bool isStdBadAlloc = false;
11078 
11079   RedeclarationKind Redecl = ForRedeclaration;
11080   if (TUK == TUK_Friend || TUK == TUK_Reference)
11081     Redecl = NotForRedeclaration;
11082 
11083   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
11084   if (Name && SS.isNotEmpty()) {
11085     // We have a nested-name tag ('struct foo::bar').
11086 
11087     // Check for invalid 'foo::'.
11088     if (SS.isInvalid()) {
11089       Name = nullptr;
11090       goto CreateNewDecl;
11091     }
11092 
11093     // If this is a friend or a reference to a class in a dependent
11094     // context, don't try to make a decl for it.
11095     if (TUK == TUK_Friend || TUK == TUK_Reference) {
11096       DC = computeDeclContext(SS, false);
11097       if (!DC) {
11098         IsDependent = true;
11099         return nullptr;
11100       }
11101     } else {
11102       DC = computeDeclContext(SS, true);
11103       if (!DC) {
11104         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
11105           << SS.getRange();
11106         return nullptr;
11107       }
11108     }
11109 
11110     if (RequireCompleteDeclContext(SS, DC))
11111       return nullptr;
11112 
11113     SearchDC = DC;
11114     // Look-up name inside 'foo::'.
11115     LookupQualifiedName(Previous, DC);
11116 
11117     if (Previous.isAmbiguous())
11118       return nullptr;
11119 
11120     if (Previous.empty()) {
11121       // Name lookup did not find anything. However, if the
11122       // nested-name-specifier refers to the current instantiation,
11123       // and that current instantiation has any dependent base
11124       // classes, we might find something at instantiation time: treat
11125       // this as a dependent elaborated-type-specifier.
11126       // But this only makes any sense for reference-like lookups.
11127       if (Previous.wasNotFoundInCurrentInstantiation() &&
11128           (TUK == TUK_Reference || TUK == TUK_Friend)) {
11129         IsDependent = true;
11130         return nullptr;
11131       }
11132 
11133       // A tag 'foo::bar' must already exist.
11134       Diag(NameLoc, diag::err_not_tag_in_scope)
11135         << Kind << Name << DC << SS.getRange();
11136       Name = nullptr;
11137       Invalid = true;
11138       goto CreateNewDecl;
11139     }
11140   } else if (Name) {
11141     // If this is a named struct, check to see if there was a previous forward
11142     // declaration or definition.
11143     // FIXME: We're looking into outer scopes here, even when we
11144     // shouldn't be. Doing so can result in ambiguities that we
11145     // shouldn't be diagnosing.
11146     LookupName(Previous, S);
11147 
11148     // When declaring or defining a tag, ignore ambiguities introduced
11149     // by types using'ed into this scope.
11150     if (Previous.isAmbiguous() &&
11151         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
11152       LookupResult::Filter F = Previous.makeFilter();
11153       while (F.hasNext()) {
11154         NamedDecl *ND = F.next();
11155         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
11156           F.erase();
11157       }
11158       F.done();
11159     }
11160 
11161     // C++11 [namespace.memdef]p3:
11162     //   If the name in a friend declaration is neither qualified nor
11163     //   a template-id and the declaration is a function or an
11164     //   elaborated-type-specifier, the lookup to determine whether
11165     //   the entity has been previously declared shall not consider
11166     //   any scopes outside the innermost enclosing namespace.
11167     //
11168     // MSVC doesn't implement the above rule for types, so a friend tag
11169     // declaration may be a redeclaration of a type declared in an enclosing
11170     // scope.  They do implement this rule for friend functions.
11171     //
11172     // Does it matter that this should be by scope instead of by
11173     // semantic context?
11174     if (!Previous.empty() && TUK == TUK_Friend) {
11175       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
11176       LookupResult::Filter F = Previous.makeFilter();
11177       bool FriendSawTagOutsideEnclosingNamespace = false;
11178       while (F.hasNext()) {
11179         NamedDecl *ND = F.next();
11180         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11181         if (DC->isFileContext() &&
11182             !EnclosingNS->Encloses(ND->getDeclContext())) {
11183           if (getLangOpts().MSVCCompat)
11184             FriendSawTagOutsideEnclosingNamespace = true;
11185           else
11186             F.erase();
11187         }
11188       }
11189       F.done();
11190 
11191       // Diagnose this MSVC extension in the easy case where lookup would have
11192       // unambiguously found something outside the enclosing namespace.
11193       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
11194         NamedDecl *ND = Previous.getFoundDecl();
11195         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
11196             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
11197       }
11198     }
11199 
11200     // Note:  there used to be some attempt at recovery here.
11201     if (Previous.isAmbiguous())
11202       return nullptr;
11203 
11204     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
11205       // FIXME: This makes sure that we ignore the contexts associated
11206       // with C structs, unions, and enums when looking for a matching
11207       // tag declaration or definition. See the similar lookup tweak
11208       // in Sema::LookupName; is there a better way to deal with this?
11209       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
11210         SearchDC = SearchDC->getParent();
11211     }
11212   }
11213 
11214   if (Previous.isSingleResult() &&
11215       Previous.getFoundDecl()->isTemplateParameter()) {
11216     // Maybe we will complain about the shadowed template parameter.
11217     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
11218     // Just pretend that we didn't see the previous declaration.
11219     Previous.clear();
11220   }
11221 
11222   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
11223       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
11224     // This is a declaration of or a reference to "std::bad_alloc".
11225     isStdBadAlloc = true;
11226 
11227     if (Previous.empty() && StdBadAlloc) {
11228       // std::bad_alloc has been implicitly declared (but made invisible to
11229       // name lookup). Fill in this implicit declaration as the previous
11230       // declaration, so that the declarations get chained appropriately.
11231       Previous.addDecl(getStdBadAlloc());
11232     }
11233   }
11234 
11235   // If we didn't find a previous declaration, and this is a reference
11236   // (or friend reference), move to the correct scope.  In C++, we
11237   // also need to do a redeclaration lookup there, just in case
11238   // there's a shadow friend decl.
11239   if (Name && Previous.empty() &&
11240       (TUK == TUK_Reference || TUK == TUK_Friend)) {
11241     if (Invalid) goto CreateNewDecl;
11242     assert(SS.isEmpty());
11243 
11244     if (TUK == TUK_Reference) {
11245       // C++ [basic.scope.pdecl]p5:
11246       //   -- for an elaborated-type-specifier of the form
11247       //
11248       //          class-key identifier
11249       //
11250       //      if the elaborated-type-specifier is used in the
11251       //      decl-specifier-seq or parameter-declaration-clause of a
11252       //      function defined in namespace scope, the identifier is
11253       //      declared as a class-name in the namespace that contains
11254       //      the declaration; otherwise, except as a friend
11255       //      declaration, the identifier is declared in the smallest
11256       //      non-class, non-function-prototype scope that contains the
11257       //      declaration.
11258       //
11259       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
11260       // C structs and unions.
11261       //
11262       // It is an error in C++ to declare (rather than define) an enum
11263       // type, including via an elaborated type specifier.  We'll
11264       // diagnose that later; for now, declare the enum in the same
11265       // scope as we would have picked for any other tag type.
11266       //
11267       // GNU C also supports this behavior as part of its incomplete
11268       // enum types extension, while GNU C++ does not.
11269       //
11270       // Find the context where we'll be declaring the tag.
11271       // FIXME: We would like to maintain the current DeclContext as the
11272       // lexical context,
11273       while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
11274         SearchDC = SearchDC->getParent();
11275 
11276       // Find the scope where we'll be declaring the tag.
11277       while (S->isClassScope() ||
11278              (getLangOpts().CPlusPlus &&
11279               S->isFunctionPrototypeScope()) ||
11280              ((S->getFlags() & Scope::DeclScope) == 0) ||
11281              (S->getEntity() && S->getEntity()->isTransparentContext()))
11282         S = S->getParent();
11283     } else {
11284       assert(TUK == TUK_Friend);
11285       // C++ [namespace.memdef]p3:
11286       //   If a friend declaration in a non-local class first declares a
11287       //   class or function, the friend class or function is a member of
11288       //   the innermost enclosing namespace.
11289       SearchDC = SearchDC->getEnclosingNamespaceContext();
11290     }
11291 
11292     // In C++, we need to do a redeclaration lookup to properly
11293     // diagnose some problems.
11294     if (getLangOpts().CPlusPlus) {
11295       Previous.setRedeclarationKind(ForRedeclaration);
11296       LookupQualifiedName(Previous, SearchDC);
11297     }
11298   }
11299 
11300   if (!Previous.empty()) {
11301     NamedDecl *PrevDecl = Previous.getFoundDecl();
11302     NamedDecl *DirectPrevDecl =
11303         getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl;
11304 
11305     // It's okay to have a tag decl in the same scope as a typedef
11306     // which hides a tag decl in the same scope.  Finding this
11307     // insanity with a redeclaration lookup can only actually happen
11308     // in C++.
11309     //
11310     // This is also okay for elaborated-type-specifiers, which is
11311     // technically forbidden by the current standard but which is
11312     // okay according to the likely resolution of an open issue;
11313     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
11314     if (getLangOpts().CPlusPlus) {
11315       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
11316         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
11317           TagDecl *Tag = TT->getDecl();
11318           if (Tag->getDeclName() == Name &&
11319               Tag->getDeclContext()->getRedeclContext()
11320                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
11321             PrevDecl = Tag;
11322             Previous.clear();
11323             Previous.addDecl(Tag);
11324             Previous.resolveKind();
11325           }
11326         }
11327       }
11328     }
11329 
11330     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
11331       // If this is a use of a previous tag, or if the tag is already declared
11332       // in the same scope (so that the definition/declaration completes or
11333       // rementions the tag), reuse the decl.
11334       if (TUK == TUK_Reference || TUK == TUK_Friend ||
11335           isDeclInScope(DirectPrevDecl, SearchDC, S,
11336                         SS.isNotEmpty() || isExplicitSpecialization)) {
11337         // Make sure that this wasn't declared as an enum and now used as a
11338         // struct or something similar.
11339         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
11340                                           TUK == TUK_Definition, KWLoc,
11341                                           *Name)) {
11342           bool SafeToContinue
11343             = (PrevTagDecl->getTagKind() != TTK_Enum &&
11344                Kind != TTK_Enum);
11345           if (SafeToContinue)
11346             Diag(KWLoc, diag::err_use_with_wrong_tag)
11347               << Name
11348               << FixItHint::CreateReplacement(SourceRange(KWLoc),
11349                                               PrevTagDecl->getKindName());
11350           else
11351             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
11352           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
11353 
11354           if (SafeToContinue)
11355             Kind = PrevTagDecl->getTagKind();
11356           else {
11357             // Recover by making this an anonymous redefinition.
11358             Name = nullptr;
11359             Previous.clear();
11360             Invalid = true;
11361           }
11362         }
11363 
11364         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
11365           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
11366 
11367           // If this is an elaborated-type-specifier for a scoped enumeration,
11368           // the 'class' keyword is not necessary and not permitted.
11369           if (TUK == TUK_Reference || TUK == TUK_Friend) {
11370             if (ScopedEnum)
11371               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
11372                 << PrevEnum->isScoped()
11373                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
11374             return PrevTagDecl;
11375           }
11376 
11377           QualType EnumUnderlyingTy;
11378           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
11379             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
11380           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
11381             EnumUnderlyingTy = QualType(T, 0);
11382 
11383           // All conflicts with previous declarations are recovered by
11384           // returning the previous declaration, unless this is a definition,
11385           // in which case we want the caller to bail out.
11386           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
11387                                      ScopedEnum, EnumUnderlyingTy, PrevEnum))
11388             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
11389         }
11390 
11391         // C++11 [class.mem]p1:
11392         //   A member shall not be declared twice in the member-specification,
11393         //   except that a nested class or member class template can be declared
11394         //   and then later defined.
11395         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
11396             S->isDeclScope(PrevDecl)) {
11397           Diag(NameLoc, diag::ext_member_redeclared);
11398           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
11399         }
11400 
11401         if (!Invalid) {
11402           // If this is a use, just return the declaration we found, unless
11403           // we have attributes.
11404 
11405           // FIXME: In the future, return a variant or some other clue
11406           // for the consumer of this Decl to know it doesn't own it.
11407           // For our current ASTs this shouldn't be a problem, but will
11408           // need to be changed with DeclGroups.
11409           if (!Attr &&
11410               ((TUK == TUK_Reference &&
11411                 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt))
11412                || TUK == TUK_Friend))
11413             return PrevTagDecl;
11414 
11415           // Diagnose attempts to redefine a tag.
11416           if (TUK == TUK_Definition) {
11417             if (TagDecl *Def = PrevTagDecl->getDefinition()) {
11418               // If we're defining a specialization and the previous definition
11419               // is from an implicit instantiation, don't emit an error
11420               // here; we'll catch this in the general case below.
11421               bool IsExplicitSpecializationAfterInstantiation = false;
11422               if (isExplicitSpecialization) {
11423                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
11424                   IsExplicitSpecializationAfterInstantiation =
11425                     RD->getTemplateSpecializationKind() !=
11426                     TSK_ExplicitSpecialization;
11427                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
11428                   IsExplicitSpecializationAfterInstantiation =
11429                     ED->getTemplateSpecializationKind() !=
11430                     TSK_ExplicitSpecialization;
11431               }
11432 
11433               if (!IsExplicitSpecializationAfterInstantiation) {
11434                 // A redeclaration in function prototype scope in C isn't
11435                 // visible elsewhere, so merely issue a warning.
11436                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
11437                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
11438                 else
11439                   Diag(NameLoc, diag::err_redefinition) << Name;
11440                 Diag(Def->getLocation(), diag::note_previous_definition);
11441                 // If this is a redefinition, recover by making this
11442                 // struct be anonymous, which will make any later
11443                 // references get the previous definition.
11444                 Name = nullptr;
11445                 Previous.clear();
11446                 Invalid = true;
11447               }
11448             } else {
11449               // If the type is currently being defined, complain
11450               // about a nested redefinition.
11451               const TagType *Tag
11452                 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
11453               if (Tag->isBeingDefined()) {
11454                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
11455                 Diag(PrevTagDecl->getLocation(),
11456                      diag::note_previous_definition);
11457                 Name = nullptr;
11458                 Previous.clear();
11459                 Invalid = true;
11460               }
11461             }
11462 
11463             // Okay, this is definition of a previously declared or referenced
11464             // tag. We're going to create a new Decl for it.
11465           }
11466 
11467           // Okay, we're going to make a redeclaration.  If this is some kind
11468           // of reference, make sure we build the redeclaration in the same DC
11469           // as the original, and ignore the current access specifier.
11470           if (TUK == TUK_Friend || TUK == TUK_Reference) {
11471             SearchDC = PrevTagDecl->getDeclContext();
11472             AS = AS_none;
11473           }
11474         }
11475         // If we get here we have (another) forward declaration or we
11476         // have a definition.  Just create a new decl.
11477 
11478       } else {
11479         // If we get here, this is a definition of a new tag type in a nested
11480         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
11481         // new decl/type.  We set PrevDecl to NULL so that the entities
11482         // have distinct types.
11483         Previous.clear();
11484       }
11485       // If we get here, we're going to create a new Decl. If PrevDecl
11486       // is non-NULL, it's a definition of the tag declared by
11487       // PrevDecl. If it's NULL, we have a new definition.
11488 
11489 
11490     // Otherwise, PrevDecl is not a tag, but was found with tag
11491     // lookup.  This is only actually possible in C++, where a few
11492     // things like templates still live in the tag namespace.
11493     } else {
11494       // Use a better diagnostic if an elaborated-type-specifier
11495       // found the wrong kind of type on the first
11496       // (non-redeclaration) lookup.
11497       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
11498           !Previous.isForRedeclaration()) {
11499         unsigned Kind = 0;
11500         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
11501         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11502         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
11503         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
11504         Diag(PrevDecl->getLocation(), diag::note_declared_at);
11505         Invalid = true;
11506 
11507       // Otherwise, only diagnose if the declaration is in scope.
11508       } else if (!isDeclInScope(PrevDecl, SearchDC, S,
11509                                 SS.isNotEmpty() || isExplicitSpecialization)) {
11510         // do nothing
11511 
11512       // Diagnose implicit declarations introduced by elaborated types.
11513       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
11514         unsigned Kind = 0;
11515         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
11516         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11517         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
11518         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
11519         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11520         Invalid = true;
11521 
11522       // Otherwise it's a declaration.  Call out a particularly common
11523       // case here.
11524       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
11525         unsigned Kind = 0;
11526         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
11527         Diag(NameLoc, diag::err_tag_definition_of_typedef)
11528           << Name << Kind << TND->getUnderlyingType();
11529         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11530         Invalid = true;
11531 
11532       // Otherwise, diagnose.
11533       } else {
11534         // The tag name clashes with something else in the target scope,
11535         // issue an error and recover by making this tag be anonymous.
11536         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
11537         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11538         Name = nullptr;
11539         Invalid = true;
11540       }
11541 
11542       // The existing declaration isn't relevant to us; we're in a
11543       // new scope, so clear out the previous declaration.
11544       Previous.clear();
11545     }
11546   }
11547 
11548 CreateNewDecl:
11549 
11550   TagDecl *PrevDecl = nullptr;
11551   if (Previous.isSingleResult())
11552     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
11553 
11554   // If there is an identifier, use the location of the identifier as the
11555   // location of the decl, otherwise use the location of the struct/union
11556   // keyword.
11557   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
11558 
11559   // Otherwise, create a new declaration. If there is a previous
11560   // declaration of the same entity, the two will be linked via
11561   // PrevDecl.
11562   TagDecl *New;
11563 
11564   bool IsForwardReference = false;
11565   if (Kind == TTK_Enum) {
11566     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11567     // enum X { A, B, C } D;    D should chain to X.
11568     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
11569                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
11570                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
11571     // If this is an undefined enum, warn.
11572     if (TUK != TUK_Definition && !Invalid) {
11573       TagDecl *Def;
11574       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
11575           cast<EnumDecl>(New)->isFixed()) {
11576         // C++0x: 7.2p2: opaque-enum-declaration.
11577         // Conflicts are diagnosed above. Do nothing.
11578       }
11579       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
11580         Diag(Loc, diag::ext_forward_ref_enum_def)
11581           << New;
11582         Diag(Def->getLocation(), diag::note_previous_definition);
11583       } else {
11584         unsigned DiagID = diag::ext_forward_ref_enum;
11585         if (getLangOpts().MSVCCompat)
11586           DiagID = diag::ext_ms_forward_ref_enum;
11587         else if (getLangOpts().CPlusPlus)
11588           DiagID = diag::err_forward_ref_enum;
11589         Diag(Loc, DiagID);
11590 
11591         // If this is a forward-declared reference to an enumeration, make a
11592         // note of it; we won't actually be introducing the declaration into
11593         // the declaration context.
11594         if (TUK == TUK_Reference)
11595           IsForwardReference = true;
11596       }
11597     }
11598 
11599     if (EnumUnderlying) {
11600       EnumDecl *ED = cast<EnumDecl>(New);
11601       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
11602         ED->setIntegerTypeSourceInfo(TI);
11603       else
11604         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
11605       ED->setPromotionType(ED->getIntegerType());
11606     }
11607 
11608   } else {
11609     // struct/union/class
11610 
11611     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11612     // struct X { int A; } D;    D should chain to X.
11613     if (getLangOpts().CPlusPlus) {
11614       // FIXME: Look for a way to use RecordDecl for simple structs.
11615       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
11616                                   cast_or_null<CXXRecordDecl>(PrevDecl));
11617 
11618       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
11619         StdBadAlloc = cast<CXXRecordDecl>(New);
11620     } else
11621       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
11622                                cast_or_null<RecordDecl>(PrevDecl));
11623   }
11624 
11625   // C++11 [dcl.type]p3:
11626   //   A type-specifier-seq shall not define a class or enumeration [...].
11627   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
11628     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
11629       << Context.getTagDeclType(New);
11630     Invalid = true;
11631   }
11632 
11633   // Maybe add qualifier info.
11634   if (SS.isNotEmpty()) {
11635     if (SS.isSet()) {
11636       // If this is either a declaration or a definition, check the
11637       // nested-name-specifier against the current context. We don't do this
11638       // for explicit specializations, because they have similar checking
11639       // (with more specific diagnostics) in the call to
11640       // CheckMemberSpecialization, below.
11641       if (!isExplicitSpecialization &&
11642           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
11643           diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
11644         Invalid = true;
11645 
11646       New->setQualifierInfo(SS.getWithLocInContext(Context));
11647       if (TemplateParameterLists.size() > 0) {
11648         New->setTemplateParameterListsInfo(Context,
11649                                            TemplateParameterLists.size(),
11650                                            TemplateParameterLists.data());
11651       }
11652     }
11653     else
11654       Invalid = true;
11655   }
11656 
11657   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
11658     // Add alignment attributes if necessary; these attributes are checked when
11659     // the ASTContext lays out the structure.
11660     //
11661     // It is important for implementing the correct semantics that this
11662     // happen here (in act on tag decl). The #pragma pack stack is
11663     // maintained as a result of parser callbacks which can occur at
11664     // many points during the parsing of a struct declaration (because
11665     // the #pragma tokens are effectively skipped over during the
11666     // parsing of the struct).
11667     if (TUK == TUK_Definition) {
11668       AddAlignmentAttributesForRecord(RD);
11669       AddMsStructLayoutForRecord(RD);
11670     }
11671   }
11672 
11673   if (ModulePrivateLoc.isValid()) {
11674     if (isExplicitSpecialization)
11675       Diag(New->getLocation(), diag::err_module_private_specialization)
11676         << 2
11677         << FixItHint::CreateRemoval(ModulePrivateLoc);
11678     // __module_private__ does not apply to local classes. However, we only
11679     // diagnose this as an error when the declaration specifiers are
11680     // freestanding. Here, we just ignore the __module_private__.
11681     else if (!SearchDC->isFunctionOrMethod())
11682       New->setModulePrivate();
11683   }
11684 
11685   // If this is a specialization of a member class (of a class template),
11686   // check the specialization.
11687   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
11688     Invalid = true;
11689 
11690   // If we're declaring or defining a tag in function prototype scope in C,
11691   // note that this type can only be used within the function and add it to
11692   // the list of decls to inject into the function definition scope.
11693   if ((Name || Kind == TTK_Enum) &&
11694       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
11695     if (getLangOpts().CPlusPlus) {
11696       // C++ [dcl.fct]p6:
11697       //   Types shall not be defined in return or parameter types.
11698       if (TUK == TUK_Definition && !IsTypeSpecifier) {
11699         Diag(Loc, diag::err_type_defined_in_param_type)
11700             << Name;
11701         Invalid = true;
11702       }
11703     } else {
11704       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
11705     }
11706     DeclsInPrototypeScope.push_back(New);
11707   }
11708 
11709   if (Invalid)
11710     New->setInvalidDecl();
11711 
11712   if (Attr)
11713     ProcessDeclAttributeList(S, New, Attr);
11714 
11715   // Set the lexical context. If the tag has a C++ scope specifier, the
11716   // lexical context will be different from the semantic context.
11717   New->setLexicalDeclContext(CurContext);
11718 
11719   // Mark this as a friend decl if applicable.
11720   // In Microsoft mode, a friend declaration also acts as a forward
11721   // declaration so we always pass true to setObjectOfFriendDecl to make
11722   // the tag name visible.
11723   if (TUK == TUK_Friend)
11724     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
11725 
11726   // Set the access specifier.
11727   if (!Invalid && SearchDC->isRecord())
11728     SetMemberAccessSpecifier(New, PrevDecl, AS);
11729 
11730   if (TUK == TUK_Definition)
11731     New->startDefinition();
11732 
11733   // If this has an identifier, add it to the scope stack.
11734   if (TUK == TUK_Friend) {
11735     // We might be replacing an existing declaration in the lookup tables;
11736     // if so, borrow its access specifier.
11737     if (PrevDecl)
11738       New->setAccess(PrevDecl->getAccess());
11739 
11740     DeclContext *DC = New->getDeclContext()->getRedeclContext();
11741     DC->makeDeclVisibleInContext(New);
11742     if (Name) // can be null along some error paths
11743       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11744         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
11745   } else if (Name) {
11746     S = getNonFieldDeclScope(S);
11747     PushOnScopeChains(New, S, !IsForwardReference);
11748     if (IsForwardReference)
11749       SearchDC->makeDeclVisibleInContext(New);
11750 
11751   } else {
11752     CurContext->addDecl(New);
11753   }
11754 
11755   // If this is the C FILE type, notify the AST context.
11756   if (IdentifierInfo *II = New->getIdentifier())
11757     if (!New->isInvalidDecl() &&
11758         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
11759         II->isStr("FILE"))
11760       Context.setFILEDecl(New);
11761 
11762   if (PrevDecl)
11763     mergeDeclAttributes(New, PrevDecl);
11764 
11765   // If there's a #pragma GCC visibility in scope, set the visibility of this
11766   // record.
11767   AddPushedVisibilityAttribute(New);
11768 
11769   OwnedDecl = true;
11770   // In C++, don't return an invalid declaration. We can't recover well from
11771   // the cases where we make the type anonymous.
11772   return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
11773 }
11774 
11775 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
11776   AdjustDeclIfTemplate(TagD);
11777   TagDecl *Tag = cast<TagDecl>(TagD);
11778 
11779   // Enter the tag context.
11780   PushDeclContext(S, Tag);
11781 
11782   ActOnDocumentableDecl(TagD);
11783 
11784   // If there's a #pragma GCC visibility in scope, set the visibility of this
11785   // record.
11786   AddPushedVisibilityAttribute(Tag);
11787 }
11788 
11789 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
11790   assert(isa<ObjCContainerDecl>(IDecl) &&
11791          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11792   DeclContext *OCD = cast<DeclContext>(IDecl);
11793   assert(getContainingDC(OCD) == CurContext &&
11794       "The next DeclContext should be lexically contained in the current one.");
11795   CurContext = OCD;
11796   return IDecl;
11797 }
11798 
11799 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
11800                                            SourceLocation FinalLoc,
11801                                            bool IsFinalSpelledSealed,
11802                                            SourceLocation LBraceLoc) {
11803   AdjustDeclIfTemplate(TagD);
11804   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
11805 
11806   FieldCollector->StartClass();
11807 
11808   if (!Record->getIdentifier())
11809     return;
11810 
11811   if (FinalLoc.isValid())
11812     Record->addAttr(new (Context)
11813                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11814 
11815   // C++ [class]p2:
11816   //   [...] The class-name is also inserted into the scope of the
11817   //   class itself; this is known as the injected-class-name. For
11818   //   purposes of access checking, the injected-class-name is treated
11819   //   as if it were a public member name.
11820   CXXRecordDecl *InjectedClassName
11821     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11822                             Record->getLocStart(), Record->getLocation(),
11823                             Record->getIdentifier(),
11824                             /*PrevDecl=*/nullptr,
11825                             /*DelayTypeCreation=*/true);
11826   Context.getTypeDeclType(InjectedClassName, Record);
11827   InjectedClassName->setImplicit();
11828   InjectedClassName->setAccess(AS_public);
11829   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11830       InjectedClassName->setDescribedClassTemplate(Template);
11831   PushOnScopeChains(InjectedClassName, S);
11832   assert(InjectedClassName->isInjectedClassName() &&
11833          "Broken injected-class-name");
11834 }
11835 
11836 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
11837                                     SourceLocation RBraceLoc) {
11838   AdjustDeclIfTemplate(TagD);
11839   TagDecl *Tag = cast<TagDecl>(TagD);
11840   Tag->setRBraceLoc(RBraceLoc);
11841 
11842   // Make sure we "complete" the definition even it is invalid.
11843   if (Tag->isBeingDefined()) {
11844     assert(Tag->isInvalidDecl() && "We should already have completed it");
11845     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11846       RD->completeDefinition();
11847   }
11848 
11849   if (isa<CXXRecordDecl>(Tag))
11850     FieldCollector->FinishClass();
11851 
11852   // Exit this scope of this tag's definition.
11853   PopDeclContext();
11854 
11855   if (getCurLexicalContext()->isObjCContainer() &&
11856       Tag->getDeclContext()->isFileContext())
11857     Tag->setTopLevelDeclInObjCContainer();
11858 
11859   // Notify the consumer that we've defined a tag.
11860   if (!Tag->isInvalidDecl())
11861     Consumer.HandleTagDeclDefinition(Tag);
11862 }
11863 
11864 void Sema::ActOnObjCContainerFinishDefinition() {
11865   // Exit this scope of this interface definition.
11866   PopDeclContext();
11867 }
11868 
11869 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
11870   assert(DC == CurContext && "Mismatch of container contexts");
11871   OriginalLexicalContext = DC;
11872   ActOnObjCContainerFinishDefinition();
11873 }
11874 
11875 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11876   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
11877   OriginalLexicalContext = nullptr;
11878 }
11879 
11880 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
11881   AdjustDeclIfTemplate(TagD);
11882   TagDecl *Tag = cast<TagDecl>(TagD);
11883   Tag->setInvalidDecl();
11884 
11885   // Make sure we "complete" the definition even it is invalid.
11886   if (Tag->isBeingDefined()) {
11887     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11888       RD->completeDefinition();
11889   }
11890 
11891   // We're undoing ActOnTagStartDefinition here, not
11892   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11893   // the FieldCollector.
11894 
11895   PopDeclContext();
11896 }
11897 
11898 // Note that FieldName may be null for anonymous bitfields.
11899 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11900                                 IdentifierInfo *FieldName,
11901                                 QualType FieldTy, bool IsMsStruct,
11902                                 Expr *BitWidth, bool *ZeroWidth) {
11903   // Default to true; that shouldn't confuse checks for emptiness
11904   if (ZeroWidth)
11905     *ZeroWidth = true;
11906 
11907   // C99 6.7.2.1p4 - verify the field type.
11908   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
11909   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
11910     // Handle incomplete types with specific error.
11911     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
11912       return ExprError();
11913     if (FieldName)
11914       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11915         << FieldName << FieldTy << BitWidth->getSourceRange();
11916     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11917       << FieldTy << BitWidth->getSourceRange();
11918   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11919                                              UPPC_BitFieldWidth))
11920     return ExprError();
11921 
11922   // If the bit-width is type- or value-dependent, don't try to check
11923   // it now.
11924   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
11925     return BitWidth;
11926 
11927   llvm::APSInt Value;
11928   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11929   if (ICE.isInvalid())
11930     return ICE;
11931   BitWidth = ICE.get();
11932 
11933   if (Value != 0 && ZeroWidth)
11934     *ZeroWidth = false;
11935 
11936   // Zero-width bitfield is ok for anonymous field.
11937   if (Value == 0 && FieldName)
11938     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
11939 
11940   if (Value.isSigned() && Value.isNegative()) {
11941     if (FieldName)
11942       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
11943                << FieldName << Value.toString(10);
11944     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11945       << Value.toString(10);
11946   }
11947 
11948   if (!FieldTy->isDependentType()) {
11949     uint64_t TypeSize = Context.getTypeSize(FieldTy);
11950     if (Value.getZExtValue() > TypeSize) {
11951       if (!getLangOpts().CPlusPlus || IsMsStruct ||
11952           Context.getTargetInfo().getCXXABI().isMicrosoft()) {
11953         if (FieldName)
11954           return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11955             << FieldName << (unsigned)Value.getZExtValue()
11956             << (unsigned)TypeSize;
11957 
11958         return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11959           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11960       }
11961 
11962       if (FieldName)
11963         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11964           << FieldName << (unsigned)Value.getZExtValue()
11965           << (unsigned)TypeSize;
11966       else
11967         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11968           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11969     }
11970   }
11971 
11972   return BitWidth;
11973 }
11974 
11975 /// ActOnField - Each field of a C struct/union is passed into this in order
11976 /// to create a FieldDecl object for it.
11977 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
11978                        Declarator &D, Expr *BitfieldWidth) {
11979   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
11980                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
11981                                /*InitStyle=*/ICIS_NoInit, AS_public);
11982   return Res;
11983 }
11984 
11985 /// HandleField - Analyze a field of a C struct or a C++ data member.
11986 ///
11987 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11988                              SourceLocation DeclStart,
11989                              Declarator &D, Expr *BitWidth,
11990                              InClassInitStyle InitStyle,
11991                              AccessSpecifier AS) {
11992   IdentifierInfo *II = D.getIdentifier();
11993   SourceLocation Loc = DeclStart;
11994   if (II) Loc = D.getIdentifierLoc();
11995 
11996   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11997   QualType T = TInfo->getType();
11998   if (getLangOpts().CPlusPlus) {
11999     CheckExtraCXXDefaultArguments(D);
12000 
12001     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12002                                         UPPC_DataMemberType)) {
12003       D.setInvalidType();
12004       T = Context.IntTy;
12005       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12006     }
12007   }
12008 
12009   // TR 18037 does not allow fields to be declared with address spaces.
12010   if (T.getQualifiers().hasAddressSpace()) {
12011     Diag(Loc, diag::err_field_with_address_space);
12012     D.setInvalidType();
12013   }
12014 
12015   // OpenCL 1.2 spec, s6.9 r:
12016   // The event type cannot be used to declare a structure or union field.
12017   if (LangOpts.OpenCL && T->isEventT()) {
12018     Diag(Loc, diag::err_event_t_struct_field);
12019     D.setInvalidType();
12020   }
12021 
12022   DiagnoseFunctionSpecifiers(D.getDeclSpec());
12023 
12024   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12025     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12026          diag::err_invalid_thread)
12027       << DeclSpec::getSpecifierName(TSCS);
12028 
12029   // Check to see if this name was declared as a member previously
12030   NamedDecl *PrevDecl = nullptr;
12031   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12032   LookupName(Previous, S);
12033   switch (Previous.getResultKind()) {
12034     case LookupResult::Found:
12035     case LookupResult::FoundUnresolvedValue:
12036       PrevDecl = Previous.getAsSingle<NamedDecl>();
12037       break;
12038 
12039     case LookupResult::FoundOverloaded:
12040       PrevDecl = Previous.getRepresentativeDecl();
12041       break;
12042 
12043     case LookupResult::NotFound:
12044     case LookupResult::NotFoundInCurrentInstantiation:
12045     case LookupResult::Ambiguous:
12046       break;
12047   }
12048   Previous.suppressDiagnostics();
12049 
12050   if (PrevDecl && PrevDecl->isTemplateParameter()) {
12051     // Maybe we will complain about the shadowed template parameter.
12052     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12053     // Just pretend that we didn't see the previous declaration.
12054     PrevDecl = nullptr;
12055   }
12056 
12057   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12058     PrevDecl = nullptr;
12059 
12060   bool Mutable
12061     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
12062   SourceLocation TSSL = D.getLocStart();
12063   FieldDecl *NewFD
12064     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
12065                      TSSL, AS, PrevDecl, &D);
12066 
12067   if (NewFD->isInvalidDecl())
12068     Record->setInvalidDecl();
12069 
12070   if (D.getDeclSpec().isModulePrivateSpecified())
12071     NewFD->setModulePrivate();
12072 
12073   if (NewFD->isInvalidDecl() && PrevDecl) {
12074     // Don't introduce NewFD into scope; there's already something
12075     // with the same name in the same scope.
12076   } else if (II) {
12077     PushOnScopeChains(NewFD, S);
12078   } else
12079     Record->addDecl(NewFD);
12080 
12081   return NewFD;
12082 }
12083 
12084 /// \brief Build a new FieldDecl and check its well-formedness.
12085 ///
12086 /// This routine builds a new FieldDecl given the fields name, type,
12087 /// record, etc. \p PrevDecl should refer to any previous declaration
12088 /// with the same name and in the same scope as the field to be
12089 /// created.
12090 ///
12091 /// \returns a new FieldDecl.
12092 ///
12093 /// \todo The Declarator argument is a hack. It will be removed once
12094 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
12095                                 TypeSourceInfo *TInfo,
12096                                 RecordDecl *Record, SourceLocation Loc,
12097                                 bool Mutable, Expr *BitWidth,
12098                                 InClassInitStyle InitStyle,
12099                                 SourceLocation TSSL,
12100                                 AccessSpecifier AS, NamedDecl *PrevDecl,
12101                                 Declarator *D) {
12102   IdentifierInfo *II = Name.getAsIdentifierInfo();
12103   bool InvalidDecl = false;
12104   if (D) InvalidDecl = D->isInvalidType();
12105 
12106   // If we receive a broken type, recover by assuming 'int' and
12107   // marking this declaration as invalid.
12108   if (T.isNull()) {
12109     InvalidDecl = true;
12110     T = Context.IntTy;
12111   }
12112 
12113   QualType EltTy = Context.getBaseElementType(T);
12114   if (!EltTy->isDependentType()) {
12115     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
12116       // Fields of incomplete type force their record to be invalid.
12117       Record->setInvalidDecl();
12118       InvalidDecl = true;
12119     } else {
12120       NamedDecl *Def;
12121       EltTy->isIncompleteType(&Def);
12122       if (Def && Def->isInvalidDecl()) {
12123         Record->setInvalidDecl();
12124         InvalidDecl = true;
12125       }
12126     }
12127   }
12128 
12129   // OpenCL v1.2 s6.9.c: bitfields are not supported.
12130   if (BitWidth && getLangOpts().OpenCL) {
12131     Diag(Loc, diag::err_opencl_bitfields);
12132     InvalidDecl = true;
12133   }
12134 
12135   // C99 6.7.2.1p8: A member of a structure or union may have any type other
12136   // than a variably modified type.
12137   if (!InvalidDecl && T->isVariablyModifiedType()) {
12138     bool SizeIsNegative;
12139     llvm::APSInt Oversized;
12140 
12141     TypeSourceInfo *FixedTInfo =
12142       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
12143                                                     SizeIsNegative,
12144                                                     Oversized);
12145     if (FixedTInfo) {
12146       Diag(Loc, diag::warn_illegal_constant_array_size);
12147       TInfo = FixedTInfo;
12148       T = FixedTInfo->getType();
12149     } else {
12150       if (SizeIsNegative)
12151         Diag(Loc, diag::err_typecheck_negative_array_size);
12152       else if (Oversized.getBoolValue())
12153         Diag(Loc, diag::err_array_too_large)
12154           << Oversized.toString(10);
12155       else
12156         Diag(Loc, diag::err_typecheck_field_variable_size);
12157       InvalidDecl = true;
12158     }
12159   }
12160 
12161   // Fields can not have abstract class types
12162   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
12163                                              diag::err_abstract_type_in_decl,
12164                                              AbstractFieldType))
12165     InvalidDecl = true;
12166 
12167   bool ZeroWidth = false;
12168   // If this is declared as a bit-field, check the bit-field.
12169   if (!InvalidDecl && BitWidth) {
12170     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
12171                               &ZeroWidth).get();
12172     if (!BitWidth) {
12173       InvalidDecl = true;
12174       BitWidth = nullptr;
12175       ZeroWidth = false;
12176     }
12177   }
12178 
12179   // Check that 'mutable' is consistent with the type of the declaration.
12180   if (!InvalidDecl && Mutable) {
12181     unsigned DiagID = 0;
12182     if (T->isReferenceType())
12183       DiagID = diag::err_mutable_reference;
12184     else if (T.isConstQualified())
12185       DiagID = diag::err_mutable_const;
12186 
12187     if (DiagID) {
12188       SourceLocation ErrLoc = Loc;
12189       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
12190         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
12191       Diag(ErrLoc, DiagID);
12192       Mutable = false;
12193       InvalidDecl = true;
12194     }
12195   }
12196 
12197   // C++11 [class.union]p8 (DR1460):
12198   //   At most one variant member of a union may have a
12199   //   brace-or-equal-initializer.
12200   if (InitStyle != ICIS_NoInit)
12201     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
12202 
12203   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
12204                                        BitWidth, Mutable, InitStyle);
12205   if (InvalidDecl)
12206     NewFD->setInvalidDecl();
12207 
12208   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
12209     Diag(Loc, diag::err_duplicate_member) << II;
12210     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12211     NewFD->setInvalidDecl();
12212   }
12213 
12214   if (!InvalidDecl && getLangOpts().CPlusPlus) {
12215     if (Record->isUnion()) {
12216       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
12217         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
12218         if (RDecl->getDefinition()) {
12219           // C++ [class.union]p1: An object of a class with a non-trivial
12220           // constructor, a non-trivial copy constructor, a non-trivial
12221           // destructor, or a non-trivial copy assignment operator
12222           // cannot be a member of a union, nor can an array of such
12223           // objects.
12224           if (CheckNontrivialField(NewFD))
12225             NewFD->setInvalidDecl();
12226         }
12227       }
12228 
12229       // C++ [class.union]p1: If a union contains a member of reference type,
12230       // the program is ill-formed, except when compiling with MSVC extensions
12231       // enabled.
12232       if (EltTy->isReferenceType()) {
12233         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
12234                                     diag::ext_union_member_of_reference_type :
12235                                     diag::err_union_member_of_reference_type)
12236           << NewFD->getDeclName() << EltTy;
12237         if (!getLangOpts().MicrosoftExt)
12238           NewFD->setInvalidDecl();
12239       }
12240     }
12241   }
12242 
12243   // FIXME: We need to pass in the attributes given an AST
12244   // representation, not a parser representation.
12245   if (D) {
12246     // FIXME: The current scope is almost... but not entirely... correct here.
12247     ProcessDeclAttributes(getCurScope(), NewFD, *D);
12248 
12249     if (NewFD->hasAttrs())
12250       CheckAlignasUnderalignment(NewFD);
12251   }
12252 
12253   // In auto-retain/release, infer strong retension for fields of
12254   // retainable type.
12255   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
12256     NewFD->setInvalidDecl();
12257 
12258   if (T.isObjCGCWeak())
12259     Diag(Loc, diag::warn_attribute_weak_on_field);
12260 
12261   NewFD->setAccess(AS);
12262   return NewFD;
12263 }
12264 
12265 bool Sema::CheckNontrivialField(FieldDecl *FD) {
12266   assert(FD);
12267   assert(getLangOpts().CPlusPlus && "valid check only for C++");
12268 
12269   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
12270     return false;
12271 
12272   QualType EltTy = Context.getBaseElementType(FD->getType());
12273   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
12274     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
12275     if (RDecl->getDefinition()) {
12276       // We check for copy constructors before constructors
12277       // because otherwise we'll never get complaints about
12278       // copy constructors.
12279 
12280       CXXSpecialMember member = CXXInvalid;
12281       // We're required to check for any non-trivial constructors. Since the
12282       // implicit default constructor is suppressed if there are any
12283       // user-declared constructors, we just need to check that there is a
12284       // trivial default constructor and a trivial copy constructor. (We don't
12285       // worry about move constructors here, since this is a C++98 check.)
12286       if (RDecl->hasNonTrivialCopyConstructor())
12287         member = CXXCopyConstructor;
12288       else if (!RDecl->hasTrivialDefaultConstructor())
12289         member = CXXDefaultConstructor;
12290       else if (RDecl->hasNonTrivialCopyAssignment())
12291         member = CXXCopyAssignment;
12292       else if (RDecl->hasNonTrivialDestructor())
12293         member = CXXDestructor;
12294 
12295       if (member != CXXInvalid) {
12296         if (!getLangOpts().CPlusPlus11 &&
12297             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
12298           // Objective-C++ ARC: it is an error to have a non-trivial field of
12299           // a union. However, system headers in Objective-C programs
12300           // occasionally have Objective-C lifetime objects within unions,
12301           // and rather than cause the program to fail, we make those
12302           // members unavailable.
12303           SourceLocation Loc = FD->getLocation();
12304           if (getSourceManager().isInSystemHeader(Loc)) {
12305             if (!FD->hasAttr<UnavailableAttr>())
12306               FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12307                                   "this system field has retaining ownership",
12308                                   Loc));
12309             return false;
12310           }
12311         }
12312 
12313         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
12314                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
12315                diag::err_illegal_union_or_anon_struct_member)
12316           << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
12317         DiagnoseNontrivial(RDecl, member);
12318         return !getLangOpts().CPlusPlus11;
12319       }
12320     }
12321   }
12322 
12323   return false;
12324 }
12325 
12326 /// TranslateIvarVisibility - Translate visibility from a token ID to an
12327 ///  AST enum value.
12328 static ObjCIvarDecl::AccessControl
12329 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
12330   switch (ivarVisibility) {
12331   default: llvm_unreachable("Unknown visitibility kind");
12332   case tok::objc_private: return ObjCIvarDecl::Private;
12333   case tok::objc_public: return ObjCIvarDecl::Public;
12334   case tok::objc_protected: return ObjCIvarDecl::Protected;
12335   case tok::objc_package: return ObjCIvarDecl::Package;
12336   }
12337 }
12338 
12339 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
12340 /// in order to create an IvarDecl object for it.
12341 Decl *Sema::ActOnIvar(Scope *S,
12342                                 SourceLocation DeclStart,
12343                                 Declarator &D, Expr *BitfieldWidth,
12344                                 tok::ObjCKeywordKind Visibility) {
12345 
12346   IdentifierInfo *II = D.getIdentifier();
12347   Expr *BitWidth = (Expr*)BitfieldWidth;
12348   SourceLocation Loc = DeclStart;
12349   if (II) Loc = D.getIdentifierLoc();
12350 
12351   // FIXME: Unnamed fields can be handled in various different ways, for
12352   // example, unnamed unions inject all members into the struct namespace!
12353 
12354   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12355   QualType T = TInfo->getType();
12356 
12357   if (BitWidth) {
12358     // 6.7.2.1p3, 6.7.2.1p4
12359     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
12360     if (!BitWidth)
12361       D.setInvalidType();
12362   } else {
12363     // Not a bitfield.
12364 
12365     // validate II.
12366 
12367   }
12368   if (T->isReferenceType()) {
12369     Diag(Loc, diag::err_ivar_reference_type);
12370     D.setInvalidType();
12371   }
12372   // C99 6.7.2.1p8: A member of a structure or union may have any type other
12373   // than a variably modified type.
12374   else if (T->isVariablyModifiedType()) {
12375     Diag(Loc, diag::err_typecheck_ivar_variable_size);
12376     D.setInvalidType();
12377   }
12378 
12379   // Get the visibility (access control) for this ivar.
12380   ObjCIvarDecl::AccessControl ac =
12381     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
12382                                         : ObjCIvarDecl::None;
12383   // Must set ivar's DeclContext to its enclosing interface.
12384   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
12385   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
12386     return nullptr;
12387   ObjCContainerDecl *EnclosingContext;
12388   if (ObjCImplementationDecl *IMPDecl =
12389       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
12390     if (LangOpts.ObjCRuntime.isFragile()) {
12391     // Case of ivar declared in an implementation. Context is that of its class.
12392       EnclosingContext = IMPDecl->getClassInterface();
12393       assert(EnclosingContext && "Implementation has no class interface!");
12394     }
12395     else
12396       EnclosingContext = EnclosingDecl;
12397   } else {
12398     if (ObjCCategoryDecl *CDecl =
12399         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
12400       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
12401         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
12402         return nullptr;
12403       }
12404     }
12405     EnclosingContext = EnclosingDecl;
12406   }
12407 
12408   // Construct the decl.
12409   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
12410                                              DeclStart, Loc, II, T,
12411                                              TInfo, ac, (Expr *)BitfieldWidth);
12412 
12413   if (II) {
12414     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
12415                                            ForRedeclaration);
12416     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
12417         && !isa<TagDecl>(PrevDecl)) {
12418       Diag(Loc, diag::err_duplicate_member) << II;
12419       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12420       NewID->setInvalidDecl();
12421     }
12422   }
12423 
12424   // Process attributes attached to the ivar.
12425   ProcessDeclAttributes(S, NewID, D);
12426 
12427   if (D.isInvalidType())
12428     NewID->setInvalidDecl();
12429 
12430   // In ARC, infer 'retaining' for ivars of retainable type.
12431   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
12432     NewID->setInvalidDecl();
12433 
12434   if (D.getDeclSpec().isModulePrivateSpecified())
12435     NewID->setModulePrivate();
12436 
12437   if (II) {
12438     // FIXME: When interfaces are DeclContexts, we'll need to add
12439     // these to the interface.
12440     S->AddDecl(NewID);
12441     IdResolver.AddDecl(NewID);
12442   }
12443 
12444   if (LangOpts.ObjCRuntime.isNonFragile() &&
12445       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
12446     Diag(Loc, diag::warn_ivars_in_interface);
12447 
12448   return NewID;
12449 }
12450 
12451 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
12452 /// class and class extensions. For every class \@interface and class
12453 /// extension \@interface, if the last ivar is a bitfield of any type,
12454 /// then add an implicit `char :0` ivar to the end of that interface.
12455 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
12456                              SmallVectorImpl<Decl *> &AllIvarDecls) {
12457   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
12458     return;
12459 
12460   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
12461   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
12462 
12463   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
12464     return;
12465   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
12466   if (!ID) {
12467     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
12468       if (!CD->IsClassExtension())
12469         return;
12470     }
12471     // No need to add this to end of @implementation.
12472     else
12473       return;
12474   }
12475   // All conditions are met. Add a new bitfield to the tail end of ivars.
12476   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
12477   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
12478 
12479   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
12480                               DeclLoc, DeclLoc, nullptr,
12481                               Context.CharTy,
12482                               Context.getTrivialTypeSourceInfo(Context.CharTy,
12483                                                                DeclLoc),
12484                               ObjCIvarDecl::Private, BW,
12485                               true);
12486   AllIvarDecls.push_back(Ivar);
12487 }
12488 
12489 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
12490                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
12491                        SourceLocation RBrac, AttributeList *Attr) {
12492   assert(EnclosingDecl && "missing record or interface decl");
12493 
12494   // If this is an Objective-C @implementation or category and we have
12495   // new fields here we should reset the layout of the interface since
12496   // it will now change.
12497   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
12498     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
12499     switch (DC->getKind()) {
12500     default: break;
12501     case Decl::ObjCCategory:
12502       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
12503       break;
12504     case Decl::ObjCImplementation:
12505       Context.
12506         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
12507       break;
12508     }
12509   }
12510 
12511   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
12512 
12513   // Start counting up the number of named members; make sure to include
12514   // members of anonymous structs and unions in the total.
12515   unsigned NumNamedMembers = 0;
12516   if (Record) {
12517     for (const auto *I : Record->decls()) {
12518       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
12519         if (IFD->getDeclName())
12520           ++NumNamedMembers;
12521     }
12522   }
12523 
12524   // Verify that all the fields are okay.
12525   SmallVector<FieldDecl*, 32> RecFields;
12526 
12527   bool ARCErrReported = false;
12528   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
12529        i != end; ++i) {
12530     FieldDecl *FD = cast<FieldDecl>(*i);
12531 
12532     // Get the type for the field.
12533     const Type *FDTy = FD->getType().getTypePtr();
12534 
12535     if (!FD->isAnonymousStructOrUnion()) {
12536       // Remember all fields written by the user.
12537       RecFields.push_back(FD);
12538     }
12539 
12540     // If the field is already invalid for some reason, don't emit more
12541     // diagnostics about it.
12542     if (FD->isInvalidDecl()) {
12543       EnclosingDecl->setInvalidDecl();
12544       continue;
12545     }
12546 
12547     // C99 6.7.2.1p2:
12548     //   A structure or union shall not contain a member with
12549     //   incomplete or function type (hence, a structure shall not
12550     //   contain an instance of itself, but may contain a pointer to
12551     //   an instance of itself), except that the last member of a
12552     //   structure with more than one named member may have incomplete
12553     //   array type; such a structure (and any union containing,
12554     //   possibly recursively, a member that is such a structure)
12555     //   shall not be a member of a structure or an element of an
12556     //   array.
12557     if (FDTy->isFunctionType()) {
12558       // Field declared as a function.
12559       Diag(FD->getLocation(), diag::err_field_declared_as_function)
12560         << FD->getDeclName();
12561       FD->setInvalidDecl();
12562       EnclosingDecl->setInvalidDecl();
12563       continue;
12564     } else if (FDTy->isIncompleteArrayType() && Record &&
12565                ((i + 1 == Fields.end() && !Record->isUnion()) ||
12566                 ((getLangOpts().MicrosoftExt ||
12567                   getLangOpts().CPlusPlus) &&
12568                  (i + 1 == Fields.end() || Record->isUnion())))) {
12569       // Flexible array member.
12570       // Microsoft and g++ is more permissive regarding flexible array.
12571       // It will accept flexible array in union and also
12572       // as the sole element of a struct/class.
12573       unsigned DiagID = 0;
12574       if (Record->isUnion())
12575         DiagID = getLangOpts().MicrosoftExt
12576                      ? diag::ext_flexible_array_union_ms
12577                      : getLangOpts().CPlusPlus
12578                            ? diag::ext_flexible_array_union_gnu
12579                            : diag::err_flexible_array_union;
12580       else if (Fields.size() == 1)
12581         DiagID = getLangOpts().MicrosoftExt
12582                      ? diag::ext_flexible_array_empty_aggregate_ms
12583                      : getLangOpts().CPlusPlus
12584                            ? diag::ext_flexible_array_empty_aggregate_gnu
12585                            : NumNamedMembers < 1
12586                                  ? diag::err_flexible_array_empty_aggregate
12587                                  : 0;
12588 
12589       if (DiagID)
12590         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
12591                                         << Record->getTagKind();
12592       // While the layout of types that contain virtual bases is not specified
12593       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
12594       // virtual bases after the derived members.  This would make a flexible
12595       // array member declared at the end of an object not adjacent to the end
12596       // of the type.
12597       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
12598         if (RD->getNumVBases() != 0)
12599           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
12600             << FD->getDeclName() << Record->getTagKind();
12601       if (!getLangOpts().C99)
12602         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
12603           << FD->getDeclName() << Record->getTagKind();
12604 
12605       // If the element type has a non-trivial destructor, we would not
12606       // implicitly destroy the elements, so disallow it for now.
12607       //
12608       // FIXME: GCC allows this. We should probably either implicitly delete
12609       // the destructor of the containing class, or just allow this.
12610       QualType BaseElem = Context.getBaseElementType(FD->getType());
12611       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
12612         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
12613           << FD->getDeclName() << FD->getType();
12614         FD->setInvalidDecl();
12615         EnclosingDecl->setInvalidDecl();
12616         continue;
12617       }
12618       // Okay, we have a legal flexible array member at the end of the struct.
12619       if (Record)
12620         Record->setHasFlexibleArrayMember(true);
12621     } else if (!FDTy->isDependentType() &&
12622                RequireCompleteType(FD->getLocation(), FD->getType(),
12623                                    diag::err_field_incomplete)) {
12624       // Incomplete type
12625       FD->setInvalidDecl();
12626       EnclosingDecl->setInvalidDecl();
12627       continue;
12628     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
12629       if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
12630         // If this is a member of a union, then entire union becomes "flexible".
12631         if (Record && Record->isUnion()) {
12632           Record->setHasFlexibleArrayMember(true);
12633         } else {
12634           // If this is a struct/class and this is not the last element, reject
12635           // it.  Note that GCC supports variable sized arrays in the middle of
12636           // structures.
12637           if (i + 1 != Fields.end())
12638             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
12639               << FD->getDeclName() << FD->getType();
12640           else {
12641             // We support flexible arrays at the end of structs in
12642             // other structs as an extension.
12643             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
12644               << FD->getDeclName();
12645             if (Record)
12646               Record->setHasFlexibleArrayMember(true);
12647           }
12648         }
12649       }
12650       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
12651           RequireNonAbstractType(FD->getLocation(), FD->getType(),
12652                                  diag::err_abstract_type_in_decl,
12653                                  AbstractIvarType)) {
12654         // Ivars can not have abstract class types
12655         FD->setInvalidDecl();
12656       }
12657       if (Record && FDTTy->getDecl()->hasObjectMember())
12658         Record->setHasObjectMember(true);
12659       if (Record && FDTTy->getDecl()->hasVolatileMember())
12660         Record->setHasVolatileMember(true);
12661     } else if (FDTy->isObjCObjectType()) {
12662       /// A field cannot be an Objective-c object
12663       Diag(FD->getLocation(), diag::err_statically_allocated_object)
12664         << FixItHint::CreateInsertion(FD->getLocation(), "*");
12665       QualType T = Context.getObjCObjectPointerType(FD->getType());
12666       FD->setType(T);
12667     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
12668                (!getLangOpts().CPlusPlus || Record->isUnion())) {
12669       // It's an error in ARC if a field has lifetime.
12670       // We don't want to report this in a system header, though,
12671       // so we just make the field unavailable.
12672       // FIXME: that's really not sufficient; we need to make the type
12673       // itself invalid to, say, initialize or copy.
12674       QualType T = FD->getType();
12675       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
12676       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
12677         SourceLocation loc = FD->getLocation();
12678         if (getSourceManager().isInSystemHeader(loc)) {
12679           if (!FD->hasAttr<UnavailableAttr>()) {
12680             FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12681                               "this system field has retaining ownership",
12682                               loc));
12683           }
12684         } else {
12685           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
12686             << T->isBlockPointerType() << Record->getTagKind();
12687         }
12688         ARCErrReported = true;
12689       }
12690     } else if (getLangOpts().ObjC1 &&
12691                getLangOpts().getGC() != LangOptions::NonGC &&
12692                Record && !Record->hasObjectMember()) {
12693       if (FD->getType()->isObjCObjectPointerType() ||
12694           FD->getType().isObjCGCStrong())
12695         Record->setHasObjectMember(true);
12696       else if (Context.getAsArrayType(FD->getType())) {
12697         QualType BaseType = Context.getBaseElementType(FD->getType());
12698         if (BaseType->isRecordType() &&
12699             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
12700           Record->setHasObjectMember(true);
12701         else if (BaseType->isObjCObjectPointerType() ||
12702                  BaseType.isObjCGCStrong())
12703                Record->setHasObjectMember(true);
12704       }
12705     }
12706     if (Record && FD->getType().isVolatileQualified())
12707       Record->setHasVolatileMember(true);
12708     // Keep track of the number of named members.
12709     if (FD->getIdentifier())
12710       ++NumNamedMembers;
12711   }
12712 
12713   // Okay, we successfully defined 'Record'.
12714   if (Record) {
12715     bool Completed = false;
12716     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12717       if (!CXXRecord->isInvalidDecl()) {
12718         // Set access bits correctly on the directly-declared conversions.
12719         for (CXXRecordDecl::conversion_iterator
12720                I = CXXRecord->conversion_begin(),
12721                E = CXXRecord->conversion_end(); I != E; ++I)
12722           I.setAccess((*I)->getAccess());
12723 
12724         if (!CXXRecord->isDependentType()) {
12725           if (CXXRecord->hasUserDeclaredDestructor()) {
12726             // Adjust user-defined destructor exception spec.
12727             if (getLangOpts().CPlusPlus11)
12728               AdjustDestructorExceptionSpec(CXXRecord,
12729                                             CXXRecord->getDestructor());
12730           }
12731 
12732           // Add any implicitly-declared members to this class.
12733           AddImplicitlyDeclaredMembersToClass(CXXRecord);
12734 
12735           // If we have virtual base classes, we may end up finding multiple
12736           // final overriders for a given virtual function. Check for this
12737           // problem now.
12738           if (CXXRecord->getNumVBases()) {
12739             CXXFinalOverriderMap FinalOverriders;
12740             CXXRecord->getFinalOverriders(FinalOverriders);
12741 
12742             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12743                                              MEnd = FinalOverriders.end();
12744                  M != MEnd; ++M) {
12745               for (OverridingMethods::iterator SO = M->second.begin(),
12746                                             SOEnd = M->second.end();
12747                    SO != SOEnd; ++SO) {
12748                 assert(SO->second.size() > 0 &&
12749                        "Virtual function without overridding functions?");
12750                 if (SO->second.size() == 1)
12751                   continue;
12752 
12753                 // C++ [class.virtual]p2:
12754                 //   In a derived class, if a virtual member function of a base
12755                 //   class subobject has more than one final overrider the
12756                 //   program is ill-formed.
12757                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
12758                   << (const NamedDecl *)M->first << Record;
12759                 Diag(M->first->getLocation(),
12760                      diag::note_overridden_virtual_function);
12761                 for (OverridingMethods::overriding_iterator
12762                           OM = SO->second.begin(),
12763                        OMEnd = SO->second.end();
12764                      OM != OMEnd; ++OM)
12765                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
12766                     << (const NamedDecl *)M->first << OM->Method->getParent();
12767 
12768                 Record->setInvalidDecl();
12769               }
12770             }
12771             CXXRecord->completeDefinition(&FinalOverriders);
12772             Completed = true;
12773           }
12774         }
12775       }
12776     }
12777 
12778     if (!Completed)
12779       Record->completeDefinition();
12780 
12781     if (Record->hasAttrs()) {
12782       CheckAlignasUnderalignment(Record);
12783 
12784       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
12785         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
12786                                            IA->getRange(), IA->getBestCase(),
12787                                            IA->getSemanticSpelling());
12788     }
12789 
12790     // Check if the structure/union declaration is a type that can have zero
12791     // size in C. For C this is a language extension, for C++ it may cause
12792     // compatibility problems.
12793     bool CheckForZeroSize;
12794     if (!getLangOpts().CPlusPlus) {
12795       CheckForZeroSize = true;
12796     } else {
12797       // For C++ filter out types that cannot be referenced in C code.
12798       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12799       CheckForZeroSize =
12800           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12801           !CXXRecord->isDependentType() &&
12802           CXXRecord->isCLike();
12803     }
12804     if (CheckForZeroSize) {
12805       bool ZeroSize = true;
12806       bool IsEmpty = true;
12807       unsigned NonBitFields = 0;
12808       for (RecordDecl::field_iterator I = Record->field_begin(),
12809                                       E = Record->field_end();
12810            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12811         IsEmpty = false;
12812         if (I->isUnnamedBitfield()) {
12813           if (I->getBitWidthValue(Context) > 0)
12814             ZeroSize = false;
12815         } else {
12816           ++NonBitFields;
12817           QualType FieldType = I->getType();
12818           if (FieldType->isIncompleteType() ||
12819               !Context.getTypeSizeInChars(FieldType).isZero())
12820             ZeroSize = false;
12821         }
12822       }
12823 
12824       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
12825       // allowed in C++, but warn if its declaration is inside
12826       // extern "C" block.
12827       if (ZeroSize) {
12828         Diag(RecLoc, getLangOpts().CPlusPlus ?
12829                          diag::warn_zero_size_struct_union_in_extern_c :
12830                          diag::warn_zero_size_struct_union_compat)
12831           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
12832       }
12833 
12834       // Structs without named members are extension in C (C99 6.7.2.1p7),
12835       // but are accepted by GCC.
12836       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
12837         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
12838                                diag::ext_no_named_members_in_struct_union)
12839           << Record->isUnion();
12840       }
12841     }
12842   } else {
12843     ObjCIvarDecl **ClsFields =
12844       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
12845     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
12846       ID->setEndOfDefinitionLoc(RBrac);
12847       // Add ivar's to class's DeclContext.
12848       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12849         ClsFields[i]->setLexicalDeclContext(ID);
12850         ID->addDecl(ClsFields[i]);
12851       }
12852       // Must enforce the rule that ivars in the base classes may not be
12853       // duplicates.
12854       if (ID->getSuperClass())
12855         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
12856     } else if (ObjCImplementationDecl *IMPDecl =
12857                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
12858       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
12859       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12860         // Ivar declared in @implementation never belongs to the implementation.
12861         // Only it is in implementation's lexical context.
12862         ClsFields[I]->setLexicalDeclContext(IMPDecl);
12863       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
12864       IMPDecl->setIvarLBraceLoc(LBrac);
12865       IMPDecl->setIvarRBraceLoc(RBrac);
12866     } else if (ObjCCategoryDecl *CDecl =
12867                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
12868       // case of ivars in class extension; all other cases have been
12869       // reported as errors elsewhere.
12870       // FIXME. Class extension does not have a LocEnd field.
12871       // CDecl->setLocEnd(RBrac);
12872       // Add ivar's to class extension's DeclContext.
12873       // Diagnose redeclaration of private ivars.
12874       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
12875       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12876         if (IDecl) {
12877           if (const ObjCIvarDecl *ClsIvar =
12878               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12879             Diag(ClsFields[i]->getLocation(),
12880                  diag::err_duplicate_ivar_declaration);
12881             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12882             continue;
12883           }
12884           for (const auto *Ext : IDecl->known_extensions()) {
12885             if (const ObjCIvarDecl *ClsExtIvar
12886                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
12887               Diag(ClsFields[i]->getLocation(),
12888                    diag::err_duplicate_ivar_declaration);
12889               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12890               continue;
12891             }
12892           }
12893         }
12894         ClsFields[i]->setLexicalDeclContext(CDecl);
12895         CDecl->addDecl(ClsFields[i]);
12896       }
12897       CDecl->setIvarLBraceLoc(LBrac);
12898       CDecl->setIvarRBraceLoc(RBrac);
12899     }
12900   }
12901 
12902   if (Attr)
12903     ProcessDeclAttributeList(S, Record, Attr);
12904 }
12905 
12906 /// \brief Determine whether the given integral value is representable within
12907 /// the given type T.
12908 static bool isRepresentableIntegerValue(ASTContext &Context,
12909                                         llvm::APSInt &Value,
12910                                         QualType T) {
12911   assert(T->isIntegralType(Context) && "Integral type required!");
12912   unsigned BitWidth = Context.getIntWidth(T);
12913 
12914   if (Value.isUnsigned() || Value.isNonNegative()) {
12915     if (T->isSignedIntegerOrEnumerationType())
12916       --BitWidth;
12917     return Value.getActiveBits() <= BitWidth;
12918   }
12919   return Value.getMinSignedBits() <= BitWidth;
12920 }
12921 
12922 // \brief Given an integral type, return the next larger integral type
12923 // (or a NULL type of no such type exists).
12924 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12925   // FIXME: Int128/UInt128 support, which also needs to be introduced into
12926   // enum checking below.
12927   assert(T->isIntegralType(Context) && "Integral type required!");
12928   const unsigned NumTypes = 4;
12929   QualType SignedIntegralTypes[NumTypes] = {
12930     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12931   };
12932   QualType UnsignedIntegralTypes[NumTypes] = {
12933     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12934     Context.UnsignedLongLongTy
12935   };
12936 
12937   unsigned BitWidth = Context.getTypeSize(T);
12938   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12939                                                         : UnsignedIntegralTypes;
12940   for (unsigned I = 0; I != NumTypes; ++I)
12941     if (Context.getTypeSize(Types[I]) > BitWidth)
12942       return Types[I];
12943 
12944   return QualType();
12945 }
12946 
12947 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12948                                           EnumConstantDecl *LastEnumConst,
12949                                           SourceLocation IdLoc,
12950                                           IdentifierInfo *Id,
12951                                           Expr *Val) {
12952   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12953   llvm::APSInt EnumVal(IntWidth);
12954   QualType EltTy;
12955 
12956   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12957     Val = nullptr;
12958 
12959   if (Val)
12960     Val = DefaultLvalueConversion(Val).get();
12961 
12962   if (Val) {
12963     if (Enum->isDependentType() || Val->isTypeDependent())
12964       EltTy = Context.DependentTy;
12965     else {
12966       SourceLocation ExpLoc;
12967       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
12968           !getLangOpts().MSVCCompat) {
12969         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12970         // constant-expression in the enumerator-definition shall be a converted
12971         // constant expression of the underlying type.
12972         EltTy = Enum->getIntegerType();
12973         ExprResult Converted =
12974           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12975                                            CCEK_Enumerator);
12976         if (Converted.isInvalid())
12977           Val = nullptr;
12978         else
12979           Val = Converted.get();
12980       } else if (!Val->isValueDependent() &&
12981                  !(Val = VerifyIntegerConstantExpression(Val,
12982                                                          &EnumVal).get())) {
12983         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
12984       } else {
12985         if (Enum->isFixed()) {
12986           EltTy = Enum->getIntegerType();
12987 
12988           // In Obj-C and Microsoft mode, require the enumeration value to be
12989           // representable in the underlying type of the enumeration. In C++11,
12990           // we perform a non-narrowing conversion as part of converted constant
12991           // expression checking.
12992           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12993             if (getLangOpts().MSVCCompat) {
12994               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
12995               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
12996             } else
12997               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
12998           } else
12999             Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13000         } else if (getLangOpts().CPlusPlus) {
13001           // C++11 [dcl.enum]p5:
13002           //   If the underlying type is not fixed, the type of each enumerator
13003           //   is the type of its initializing value:
13004           //     - If an initializer is specified for an enumerator, the
13005           //       initializing value has the same type as the expression.
13006           EltTy = Val->getType();
13007         } else {
13008           // C99 6.7.2.2p2:
13009           //   The expression that defines the value of an enumeration constant
13010           //   shall be an integer constant expression that has a value
13011           //   representable as an int.
13012 
13013           // Complain if the value is not representable in an int.
13014           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
13015             Diag(IdLoc, diag::ext_enum_value_not_int)
13016               << EnumVal.toString(10) << Val->getSourceRange()
13017               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
13018           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
13019             // Force the type of the expression to 'int'.
13020             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
13021           }
13022           EltTy = Val->getType();
13023         }
13024       }
13025     }
13026   }
13027 
13028   if (!Val) {
13029     if (Enum->isDependentType())
13030       EltTy = Context.DependentTy;
13031     else if (!LastEnumConst) {
13032       // C++0x [dcl.enum]p5:
13033       //   If the underlying type is not fixed, the type of each enumerator
13034       //   is the type of its initializing value:
13035       //     - If no initializer is specified for the first enumerator, the
13036       //       initializing value has an unspecified integral type.
13037       //
13038       // GCC uses 'int' for its unspecified integral type, as does
13039       // C99 6.7.2.2p3.
13040       if (Enum->isFixed()) {
13041         EltTy = Enum->getIntegerType();
13042       }
13043       else {
13044         EltTy = Context.IntTy;
13045       }
13046     } else {
13047       // Assign the last value + 1.
13048       EnumVal = LastEnumConst->getInitVal();
13049       ++EnumVal;
13050       EltTy = LastEnumConst->getType();
13051 
13052       // Check for overflow on increment.
13053       if (EnumVal < LastEnumConst->getInitVal()) {
13054         // C++0x [dcl.enum]p5:
13055         //   If the underlying type is not fixed, the type of each enumerator
13056         //   is the type of its initializing value:
13057         //
13058         //     - Otherwise the type of the initializing value is the same as
13059         //       the type of the initializing value of the preceding enumerator
13060         //       unless the incremented value is not representable in that type,
13061         //       in which case the type is an unspecified integral type
13062         //       sufficient to contain the incremented value. If no such type
13063         //       exists, the program is ill-formed.
13064         QualType T = getNextLargerIntegralType(Context, EltTy);
13065         if (T.isNull() || Enum->isFixed()) {
13066           // There is no integral type larger enough to represent this
13067           // value. Complain, then allow the value to wrap around.
13068           EnumVal = LastEnumConst->getInitVal();
13069           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
13070           ++EnumVal;
13071           if (Enum->isFixed())
13072             // When the underlying type is fixed, this is ill-formed.
13073             Diag(IdLoc, diag::err_enumerator_wrapped)
13074               << EnumVal.toString(10)
13075               << EltTy;
13076           else
13077             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
13078               << EnumVal.toString(10);
13079         } else {
13080           EltTy = T;
13081         }
13082 
13083         // Retrieve the last enumerator's value, extent that type to the
13084         // type that is supposed to be large enough to represent the incremented
13085         // value, then increment.
13086         EnumVal = LastEnumConst->getInitVal();
13087         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13088         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
13089         ++EnumVal;
13090 
13091         // If we're not in C++, diagnose the overflow of enumerator values,
13092         // which in C99 means that the enumerator value is not representable in
13093         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
13094         // permits enumerator values that are representable in some larger
13095         // integral type.
13096         if (!getLangOpts().CPlusPlus && !T.isNull())
13097           Diag(IdLoc, diag::warn_enum_value_overflow);
13098       } else if (!getLangOpts().CPlusPlus &&
13099                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13100         // Enforce C99 6.7.2.2p2 even when we compute the next value.
13101         Diag(IdLoc, diag::ext_enum_value_not_int)
13102           << EnumVal.toString(10) << 1;
13103       }
13104     }
13105   }
13106 
13107   if (!EltTy->isDependentType()) {
13108     // Make the enumerator value match the signedness and size of the
13109     // enumerator's type.
13110     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
13111     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13112   }
13113 
13114   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
13115                                   Val, EnumVal);
13116 }
13117 
13118 
13119 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
13120                               SourceLocation IdLoc, IdentifierInfo *Id,
13121                               AttributeList *Attr,
13122                               SourceLocation EqualLoc, Expr *Val) {
13123   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
13124   EnumConstantDecl *LastEnumConst =
13125     cast_or_null<EnumConstantDecl>(lastEnumConst);
13126 
13127   // The scope passed in may not be a decl scope.  Zip up the scope tree until
13128   // we find one that is.
13129   S = getNonFieldDeclScope(S);
13130 
13131   // Verify that there isn't already something declared with this name in this
13132   // scope.
13133   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
13134                                          ForRedeclaration);
13135   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13136     // Maybe we will complain about the shadowed template parameter.
13137     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
13138     // Just pretend that we didn't see the previous declaration.
13139     PrevDecl = nullptr;
13140   }
13141 
13142   if (PrevDecl) {
13143     // When in C++, we may get a TagDecl with the same name; in this case the
13144     // enum constant will 'hide' the tag.
13145     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
13146            "Received TagDecl when not in C++!");
13147     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
13148       if (isa<EnumConstantDecl>(PrevDecl))
13149         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
13150       else
13151         Diag(IdLoc, diag::err_redefinition) << Id;
13152       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13153       return nullptr;
13154     }
13155   }
13156 
13157   // C++ [class.mem]p15:
13158   // If T is the name of a class, then each of the following shall have a name
13159   // different from T:
13160   // - every enumerator of every member of class T that is an unscoped
13161   // enumerated type
13162   if (CXXRecordDecl *Record
13163                       = dyn_cast<CXXRecordDecl>(
13164                              TheEnumDecl->getDeclContext()->getRedeclContext()))
13165     if (!TheEnumDecl->isScoped() &&
13166         Record->getIdentifier() && Record->getIdentifier() == Id)
13167       Diag(IdLoc, diag::err_member_name_of_class) << Id;
13168 
13169   EnumConstantDecl *New =
13170     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
13171 
13172   if (New) {
13173     // Process attributes.
13174     if (Attr) ProcessDeclAttributeList(S, New, Attr);
13175 
13176     // Register this decl in the current scope stack.
13177     New->setAccess(TheEnumDecl->getAccess());
13178     PushOnScopeChains(New, S);
13179   }
13180 
13181   ActOnDocumentableDecl(New);
13182 
13183   return New;
13184 }
13185 
13186 // Returns true when the enum initial expression does not trigger the
13187 // duplicate enum warning.  A few common cases are exempted as follows:
13188 // Element2 = Element1
13189 // Element2 = Element1 + 1
13190 // Element2 = Element1 - 1
13191 // Where Element2 and Element1 are from the same enum.
13192 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
13193   Expr *InitExpr = ECD->getInitExpr();
13194   if (!InitExpr)
13195     return true;
13196   InitExpr = InitExpr->IgnoreImpCasts();
13197 
13198   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
13199     if (!BO->isAdditiveOp())
13200       return true;
13201     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
13202     if (!IL)
13203       return true;
13204     if (IL->getValue() != 1)
13205       return true;
13206 
13207     InitExpr = BO->getLHS();
13208   }
13209 
13210   // This checks if the elements are from the same enum.
13211   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
13212   if (!DRE)
13213     return true;
13214 
13215   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
13216   if (!EnumConstant)
13217     return true;
13218 
13219   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
13220       Enum)
13221     return true;
13222 
13223   return false;
13224 }
13225 
13226 struct DupKey {
13227   int64_t val;
13228   bool isTombstoneOrEmptyKey;
13229   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
13230     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
13231 };
13232 
13233 static DupKey GetDupKey(const llvm::APSInt& Val) {
13234   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
13235                 false);
13236 }
13237 
13238 struct DenseMapInfoDupKey {
13239   static DupKey getEmptyKey() { return DupKey(0, true); }
13240   static DupKey getTombstoneKey() { return DupKey(1, true); }
13241   static unsigned getHashValue(const DupKey Key) {
13242     return (unsigned)(Key.val * 37);
13243   }
13244   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
13245     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
13246            LHS.val == RHS.val;
13247   }
13248 };
13249 
13250 // Emits a warning when an element is implicitly set a value that
13251 // a previous element has already been set to.
13252 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
13253                                         EnumDecl *Enum,
13254                                         QualType EnumType) {
13255   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
13256     return;
13257   // Avoid anonymous enums
13258   if (!Enum->getIdentifier())
13259     return;
13260 
13261   // Only check for small enums.
13262   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
13263     return;
13264 
13265   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
13266   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
13267 
13268   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
13269   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
13270           ValueToVectorMap;
13271 
13272   DuplicatesVector DupVector;
13273   ValueToVectorMap EnumMap;
13274 
13275   // Populate the EnumMap with all values represented by enum constants without
13276   // an initialier.
13277   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13278     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
13279 
13280     // Null EnumConstantDecl means a previous diagnostic has been emitted for
13281     // this constant.  Skip this enum since it may be ill-formed.
13282     if (!ECD) {
13283       return;
13284     }
13285 
13286     if (ECD->getInitExpr())
13287       continue;
13288 
13289     DupKey Key = GetDupKey(ECD->getInitVal());
13290     DeclOrVector &Entry = EnumMap[Key];
13291 
13292     // First time encountering this value.
13293     if (Entry.isNull())
13294       Entry = ECD;
13295   }
13296 
13297   // Create vectors for any values that has duplicates.
13298   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13299     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
13300     if (!ValidDuplicateEnum(ECD, Enum))
13301       continue;
13302 
13303     DupKey Key = GetDupKey(ECD->getInitVal());
13304 
13305     DeclOrVector& Entry = EnumMap[Key];
13306     if (Entry.isNull())
13307       continue;
13308 
13309     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
13310       // Ensure constants are different.
13311       if (D == ECD)
13312         continue;
13313 
13314       // Create new vector and push values onto it.
13315       ECDVector *Vec = new ECDVector();
13316       Vec->push_back(D);
13317       Vec->push_back(ECD);
13318 
13319       // Update entry to point to the duplicates vector.
13320       Entry = Vec;
13321 
13322       // Store the vector somewhere we can consult later for quick emission of
13323       // diagnostics.
13324       DupVector.push_back(Vec);
13325       continue;
13326     }
13327 
13328     ECDVector *Vec = Entry.get<ECDVector*>();
13329     // Make sure constants are not added more than once.
13330     if (*Vec->begin() == ECD)
13331       continue;
13332 
13333     Vec->push_back(ECD);
13334   }
13335 
13336   // Emit diagnostics.
13337   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
13338                                   DupVectorEnd = DupVector.end();
13339        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
13340     ECDVector *Vec = *DupVectorIter;
13341     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
13342 
13343     // Emit warning for one enum constant.
13344     ECDVector::iterator I = Vec->begin();
13345     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
13346       << (*I)->getName() << (*I)->getInitVal().toString(10)
13347       << (*I)->getSourceRange();
13348     ++I;
13349 
13350     // Emit one note for each of the remaining enum constants with
13351     // the same value.
13352     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
13353       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
13354         << (*I)->getName() << (*I)->getInitVal().toString(10)
13355         << (*I)->getSourceRange();
13356     delete Vec;
13357   }
13358 }
13359 
13360 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
13361                          SourceLocation RBraceLoc, Decl *EnumDeclX,
13362                          ArrayRef<Decl *> Elements,
13363                          Scope *S, AttributeList *Attr) {
13364   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
13365   QualType EnumType = Context.getTypeDeclType(Enum);
13366 
13367   if (Attr)
13368     ProcessDeclAttributeList(S, Enum, Attr);
13369 
13370   if (Enum->isDependentType()) {
13371     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13372       EnumConstantDecl *ECD =
13373         cast_or_null<EnumConstantDecl>(Elements[i]);
13374       if (!ECD) continue;
13375 
13376       ECD->setType(EnumType);
13377     }
13378 
13379     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
13380     return;
13381   }
13382 
13383   // TODO: If the result value doesn't fit in an int, it must be a long or long
13384   // long value.  ISO C does not support this, but GCC does as an extension,
13385   // emit a warning.
13386   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
13387   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
13388   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
13389 
13390   // Verify that all the values are okay, compute the size of the values, and
13391   // reverse the list.
13392   unsigned NumNegativeBits = 0;
13393   unsigned NumPositiveBits = 0;
13394 
13395   // Keep track of whether all elements have type int.
13396   bool AllElementsInt = true;
13397 
13398   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13399     EnumConstantDecl *ECD =
13400       cast_or_null<EnumConstantDecl>(Elements[i]);
13401     if (!ECD) continue;  // Already issued a diagnostic.
13402 
13403     const llvm::APSInt &InitVal = ECD->getInitVal();
13404 
13405     // Keep track of the size of positive and negative values.
13406     if (InitVal.isUnsigned() || InitVal.isNonNegative())
13407       NumPositiveBits = std::max(NumPositiveBits,
13408                                  (unsigned)InitVal.getActiveBits());
13409     else
13410       NumNegativeBits = std::max(NumNegativeBits,
13411                                  (unsigned)InitVal.getMinSignedBits());
13412 
13413     // Keep track of whether every enum element has type int (very commmon).
13414     if (AllElementsInt)
13415       AllElementsInt = ECD->getType() == Context.IntTy;
13416   }
13417 
13418   // Figure out the type that should be used for this enum.
13419   QualType BestType;
13420   unsigned BestWidth;
13421 
13422   // C++0x N3000 [conv.prom]p3:
13423   //   An rvalue of an unscoped enumeration type whose underlying
13424   //   type is not fixed can be converted to an rvalue of the first
13425   //   of the following types that can represent all the values of
13426   //   the enumeration: int, unsigned int, long int, unsigned long
13427   //   int, long long int, or unsigned long long int.
13428   // C99 6.4.4.3p2:
13429   //   An identifier declared as an enumeration constant has type int.
13430   // The C99 rule is modified by a gcc extension
13431   QualType BestPromotionType;
13432 
13433   bool Packed = Enum->hasAttr<PackedAttr>();
13434   // -fshort-enums is the equivalent to specifying the packed attribute on all
13435   // enum definitions.
13436   if (LangOpts.ShortEnums)
13437     Packed = true;
13438 
13439   if (Enum->isFixed()) {
13440     BestType = Enum->getIntegerType();
13441     if (BestType->isPromotableIntegerType())
13442       BestPromotionType = Context.getPromotedIntegerType(BestType);
13443     else
13444       BestPromotionType = BestType;
13445     // We don't need to set BestWidth, because BestType is going to be the type
13446     // of the enumerators, but we do anyway because otherwise some compilers
13447     // warn that it might be used uninitialized.
13448     BestWidth = CharWidth;
13449   }
13450   else if (NumNegativeBits) {
13451     // If there is a negative value, figure out the smallest integer type (of
13452     // int/long/longlong) that fits.
13453     // If it's packed, check also if it fits a char or a short.
13454     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
13455       BestType = Context.SignedCharTy;
13456       BestWidth = CharWidth;
13457     } else if (Packed && NumNegativeBits <= ShortWidth &&
13458                NumPositiveBits < ShortWidth) {
13459       BestType = Context.ShortTy;
13460       BestWidth = ShortWidth;
13461     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
13462       BestType = Context.IntTy;
13463       BestWidth = IntWidth;
13464     } else {
13465       BestWidth = Context.getTargetInfo().getLongWidth();
13466 
13467       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
13468         BestType = Context.LongTy;
13469       } else {
13470         BestWidth = Context.getTargetInfo().getLongLongWidth();
13471 
13472         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
13473           Diag(Enum->getLocation(), diag::ext_enum_too_large);
13474         BestType = Context.LongLongTy;
13475       }
13476     }
13477     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
13478   } else {
13479     // If there is no negative value, figure out the smallest type that fits
13480     // all of the enumerator values.
13481     // If it's packed, check also if it fits a char or a short.
13482     if (Packed && NumPositiveBits <= CharWidth) {
13483       BestType = Context.UnsignedCharTy;
13484       BestPromotionType = Context.IntTy;
13485       BestWidth = CharWidth;
13486     } else if (Packed && NumPositiveBits <= ShortWidth) {
13487       BestType = Context.UnsignedShortTy;
13488       BestPromotionType = Context.IntTy;
13489       BestWidth = ShortWidth;
13490     } else if (NumPositiveBits <= IntWidth) {
13491       BestType = Context.UnsignedIntTy;
13492       BestWidth = IntWidth;
13493       BestPromotionType
13494         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
13495                            ? Context.UnsignedIntTy : Context.IntTy;
13496     } else if (NumPositiveBits <=
13497                (BestWidth = Context.getTargetInfo().getLongWidth())) {
13498       BestType = Context.UnsignedLongTy;
13499       BestPromotionType
13500         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
13501                            ? Context.UnsignedLongTy : Context.LongTy;
13502     } else {
13503       BestWidth = Context.getTargetInfo().getLongLongWidth();
13504       assert(NumPositiveBits <= BestWidth &&
13505              "How could an initializer get larger than ULL?");
13506       BestType = Context.UnsignedLongLongTy;
13507       BestPromotionType
13508         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
13509                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
13510     }
13511   }
13512 
13513   // Loop over all of the enumerator constants, changing their types to match
13514   // the type of the enum if needed.
13515   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13516     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
13517     if (!ECD) continue;  // Already issued a diagnostic.
13518 
13519     // Standard C says the enumerators have int type, but we allow, as an
13520     // extension, the enumerators to be larger than int size.  If each
13521     // enumerator value fits in an int, type it as an int, otherwise type it the
13522     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
13523     // that X has type 'int', not 'unsigned'.
13524 
13525     // Determine whether the value fits into an int.
13526     llvm::APSInt InitVal = ECD->getInitVal();
13527 
13528     // If it fits into an integer type, force it.  Otherwise force it to match
13529     // the enum decl type.
13530     QualType NewTy;
13531     unsigned NewWidth;
13532     bool NewSign;
13533     if (!getLangOpts().CPlusPlus &&
13534         !Enum->isFixed() &&
13535         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
13536       NewTy = Context.IntTy;
13537       NewWidth = IntWidth;
13538       NewSign = true;
13539     } else if (ECD->getType() == BestType) {
13540       // Already the right type!
13541       if (getLangOpts().CPlusPlus)
13542         // C++ [dcl.enum]p4: Following the closing brace of an
13543         // enum-specifier, each enumerator has the type of its
13544         // enumeration.
13545         ECD->setType(EnumType);
13546       continue;
13547     } else {
13548       NewTy = BestType;
13549       NewWidth = BestWidth;
13550       NewSign = BestType->isSignedIntegerOrEnumerationType();
13551     }
13552 
13553     // Adjust the APSInt value.
13554     InitVal = InitVal.extOrTrunc(NewWidth);
13555     InitVal.setIsSigned(NewSign);
13556     ECD->setInitVal(InitVal);
13557 
13558     // Adjust the Expr initializer and type.
13559     if (ECD->getInitExpr() &&
13560         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
13561       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
13562                                                 CK_IntegralCast,
13563                                                 ECD->getInitExpr(),
13564                                                 /*base paths*/ nullptr,
13565                                                 VK_RValue));
13566     if (getLangOpts().CPlusPlus)
13567       // C++ [dcl.enum]p4: Following the closing brace of an
13568       // enum-specifier, each enumerator has the type of its
13569       // enumeration.
13570       ECD->setType(EnumType);
13571     else
13572       ECD->setType(NewTy);
13573   }
13574 
13575   Enum->completeDefinition(BestType, BestPromotionType,
13576                            NumPositiveBits, NumNegativeBits);
13577 
13578   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
13579 
13580   // Now that the enum type is defined, ensure it's not been underaligned.
13581   if (Enum->hasAttrs())
13582     CheckAlignasUnderalignment(Enum);
13583 }
13584 
13585 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
13586                                   SourceLocation StartLoc,
13587                                   SourceLocation EndLoc) {
13588   StringLiteral *AsmString = cast<StringLiteral>(expr);
13589 
13590   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
13591                                                    AsmString, StartLoc,
13592                                                    EndLoc);
13593   CurContext->addDecl(New);
13594   return New;
13595 }
13596 
13597 static void checkModuleImportContext(Sema &S, Module *M,
13598                                      SourceLocation ImportLoc,
13599                                      DeclContext *DC) {
13600   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
13601     switch (LSD->getLanguage()) {
13602     case LinkageSpecDecl::lang_c:
13603       if (!M->IsExternC) {
13604         S.Diag(ImportLoc, diag::err_module_import_in_extern_c)
13605           << M->getFullModuleName();
13606         S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c);
13607         return;
13608       }
13609       break;
13610     case LinkageSpecDecl::lang_cxx:
13611       break;
13612     }
13613     DC = LSD->getParent();
13614   }
13615 
13616   while (isa<LinkageSpecDecl>(DC))
13617     DC = DC->getParent();
13618   if (!isa<TranslationUnitDecl>(DC)) {
13619     S.Diag(ImportLoc, diag::err_module_import_not_at_top_level)
13620       << M->getFullModuleName() << DC;
13621     S.Diag(cast<Decl>(DC)->getLocStart(),
13622            diag::note_module_import_not_at_top_level)
13623       << DC;
13624   }
13625 }
13626 
13627 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
13628                                    SourceLocation ImportLoc,
13629                                    ModuleIdPath Path) {
13630   Module *Mod =
13631       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
13632                                    /*IsIncludeDirective=*/false);
13633   if (!Mod)
13634     return true;
13635 
13636   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
13637 
13638   // FIXME: we should support importing a submodule within a different submodule
13639   // of the same top-level module. Until we do, make it an error rather than
13640   // silently ignoring the import.
13641   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
13642     Diag(ImportLoc, diag::err_module_self_import)
13643         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
13644   else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule)
13645     Diag(ImportLoc, diag::err_module_import_in_implementation)
13646         << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule;
13647 
13648   SmallVector<SourceLocation, 2> IdentifierLocs;
13649   Module *ModCheck = Mod;
13650   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
13651     // If we've run out of module parents, just drop the remaining identifiers.
13652     // We need the length to be consistent.
13653     if (!ModCheck)
13654       break;
13655     ModCheck = ModCheck->Parent;
13656 
13657     IdentifierLocs.push_back(Path[I].second);
13658   }
13659 
13660   ImportDecl *Import = ImportDecl::Create(Context,
13661                                           Context.getTranslationUnitDecl(),
13662                                           AtLoc.isValid()? AtLoc : ImportLoc,
13663                                           Mod, IdentifierLocs);
13664   Context.getTranslationUnitDecl()->addDecl(Import);
13665   return Import;
13666 }
13667 
13668 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
13669   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
13670 
13671   // FIXME: Should we synthesize an ImportDecl here?
13672   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
13673                                       /*Complain=*/true);
13674 }
13675 
13676 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
13677                                                       Module *Mod) {
13678   // Bail if we're not allowed to implicitly import a module here.
13679   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
13680     return;
13681 
13682   // Create the implicit import declaration.
13683   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
13684   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
13685                                                    Loc, Mod, Loc);
13686   TU->addDecl(ImportD);
13687   Consumer.HandleImplicitImportDecl(ImportD);
13688 
13689   // Make the module visible.
13690   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
13691                                       /*Complain=*/false);
13692 }
13693 
13694 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
13695                                       IdentifierInfo* AliasName,
13696                                       SourceLocation PragmaLoc,
13697                                       SourceLocation NameLoc,
13698                                       SourceLocation AliasNameLoc) {
13699   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
13700                                     LookupOrdinaryName);
13701   AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context,
13702                                                     AliasName->getName(), 0);
13703 
13704   if (PrevDecl)
13705     PrevDecl->addAttr(Attr);
13706   else
13707     (void)ExtnameUndeclaredIdentifiers.insert(
13708       std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
13709 }
13710 
13711 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
13712                              SourceLocation PragmaLoc,
13713                              SourceLocation NameLoc) {
13714   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
13715 
13716   if (PrevDecl) {
13717     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
13718   } else {
13719     (void)WeakUndeclaredIdentifiers.insert(
13720       std::pair<IdentifierInfo*,WeakInfo>
13721         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
13722   }
13723 }
13724 
13725 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
13726                                 IdentifierInfo* AliasName,
13727                                 SourceLocation PragmaLoc,
13728                                 SourceLocation NameLoc,
13729                                 SourceLocation AliasNameLoc) {
13730   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
13731                                     LookupOrdinaryName);
13732   WeakInfo W = WeakInfo(Name, NameLoc);
13733 
13734   if (PrevDecl) {
13735     if (!PrevDecl->hasAttr<AliasAttr>())
13736       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
13737         DeclApplyPragmaWeak(TUScope, ND, W);
13738   } else {
13739     (void)WeakUndeclaredIdentifiers.insert(
13740       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
13741   }
13742 }
13743 
13744 Decl *Sema::getObjCDeclContext() const {
13745   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
13746 }
13747 
13748 AvailabilityResult Sema::getCurContextAvailability() const {
13749   const Decl *D = cast<Decl>(getCurObjCLexicalContext());
13750   // If we are within an Objective-C method, we should consult
13751   // both the availability of the method as well as the
13752   // enclosing class.  If the class is (say) deprecated,
13753   // the entire method is considered deprecated from the
13754   // purpose of checking if the current context is deprecated.
13755   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
13756     AvailabilityResult R = MD->getAvailability();
13757     if (R != AR_Available)
13758       return R;
13759     D = MD->getClassInterface();
13760   }
13761   // If we are within an Objective-c @implementation, it
13762   // gets the same availability context as the @interface.
13763   else if (const ObjCImplementationDecl *ID =
13764             dyn_cast<ObjCImplementationDecl>(D)) {
13765     D = ID->getClassInterface();
13766   }
13767   // Recover from user error.
13768   return D ? D->getAvailability() : AR_Available;
13769 }
13770