1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/CommentDiagnostic.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/StmtCXX.h"
26 #include "clang/Basic/Builtins.h"
27 #include "clang/Basic/PartialDiagnostic.h"
28 #include "clang/Basic/SourceManager.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
31 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
32 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
34 #include "clang/Sema/CXXFieldCollector.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Initialization.h"
38 #include "clang/Sema/Lookup.h"
39 #include "clang/Sema/ParsedTemplate.h"
40 #include "clang/Sema/Scope.h"
41 #include "clang/Sema/ScopeInfo.h"
42 #include "clang/Sema/SemaInternal.h"
43 #include "clang/Sema/Template.h"
44 #include "llvm/ADT/SmallString.h"
45 #include "llvm/ADT/Triple.h"
46 #include <algorithm>
47 #include <cstring>
48 #include <functional>
49 
50 using namespace clang;
51 using namespace sema;
52 
53 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
54   if (OwnedType) {
55     Decl *Group[2] = { OwnedType, Ptr };
56     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
57   }
58 
59   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
60 }
61 
62 namespace {
63 
64 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
65  public:
66    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
67                         bool AllowTemplates = false,
68                         bool AllowNonTemplates = true)
69        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
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       if (!AllowInvalidDecl && ND->isInvalidDecl())
79         return false;
80 
81       if (getAsTypeTemplateDecl(ND))
82         return AllowTemplates;
83 
84       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
85       if (!IsType)
86         return false;
87 
88       if (AllowNonTemplates)
89         return true;
90 
91       // An injected-class-name of a class template (specialization) is valid
92       // as a template or as a non-template.
93       if (AllowTemplates) {
94         auto *RD = dyn_cast<CXXRecordDecl>(ND);
95         if (!RD || !RD->isInjectedClassName())
96           return false;
97         RD = cast<CXXRecordDecl>(RD->getDeclContext());
98         return RD->getDescribedClassTemplate() ||
99                isa<ClassTemplateSpecializationDecl>(RD);
100       }
101 
102       return false;
103     }
104 
105     return !WantClassName && candidate.isKeyword();
106   }
107 
108  private:
109   bool AllowInvalidDecl;
110   bool WantClassName;
111   bool AllowTemplates;
112   bool AllowNonTemplates;
113 };
114 
115 } // end anonymous namespace
116 
117 /// Determine whether the token kind starts a simple-type-specifier.
118 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
119   switch (Kind) {
120   // FIXME: Take into account the current language when deciding whether a
121   // token kind is a valid type specifier
122   case tok::kw_short:
123   case tok::kw_long:
124   case tok::kw___int64:
125   case tok::kw___int128:
126   case tok::kw_signed:
127   case tok::kw_unsigned:
128   case tok::kw_void:
129   case tok::kw_char:
130   case tok::kw_int:
131   case tok::kw_half:
132   case tok::kw_float:
133   case tok::kw_double:
134   case tok::kw__Float16:
135   case tok::kw___float128:
136   case tok::kw_wchar_t:
137   case tok::kw_bool:
138   case tok::kw___underlying_type:
139   case tok::kw___auto_type:
140     return true;
141 
142   case tok::annot_typename:
143   case tok::kw_char16_t:
144   case tok::kw_char32_t:
145   case tok::kw_typeof:
146   case tok::annot_decltype:
147   case tok::kw_decltype:
148     return getLangOpts().CPlusPlus;
149 
150   case tok::kw_char8_t:
151     return getLangOpts().Char8;
152 
153   default:
154     break;
155   }
156 
157   return false;
158 }
159 
160 namespace {
161 enum class UnqualifiedTypeNameLookupResult {
162   NotFound,
163   FoundNonType,
164   FoundType
165 };
166 } // end anonymous namespace
167 
168 /// Tries to perform unqualified lookup of the type decls in bases for
169 /// dependent class.
170 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
171 /// type decl, \a FoundType if only type decls are found.
172 static UnqualifiedTypeNameLookupResult
173 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
174                                 SourceLocation NameLoc,
175                                 const CXXRecordDecl *RD) {
176   if (!RD->hasDefinition())
177     return UnqualifiedTypeNameLookupResult::NotFound;
178   // Look for type decls in base classes.
179   UnqualifiedTypeNameLookupResult FoundTypeDecl =
180       UnqualifiedTypeNameLookupResult::NotFound;
181   for (const auto &Base : RD->bases()) {
182     const CXXRecordDecl *BaseRD = nullptr;
183     if (auto *BaseTT = Base.getType()->getAs<TagType>())
184       BaseRD = BaseTT->getAsCXXRecordDecl();
185     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
186       // Look for type decls in dependent base classes that have known primary
187       // templates.
188       if (!TST || !TST->isDependentType())
189         continue;
190       auto *TD = TST->getTemplateName().getAsTemplateDecl();
191       if (!TD)
192         continue;
193       if (auto *BasePrimaryTemplate =
194           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
195         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
196           BaseRD = BasePrimaryTemplate;
197         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
198           if (const ClassTemplatePartialSpecializationDecl *PS =
199                   CTD->findPartialSpecialization(Base.getType()))
200             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
201               BaseRD = PS;
202         }
203       }
204     }
205     if (BaseRD) {
206       for (NamedDecl *ND : BaseRD->lookup(&II)) {
207         if (!isa<TypeDecl>(ND))
208           return UnqualifiedTypeNameLookupResult::FoundNonType;
209         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
210       }
211       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
212         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
213         case UnqualifiedTypeNameLookupResult::FoundNonType:
214           return UnqualifiedTypeNameLookupResult::FoundNonType;
215         case UnqualifiedTypeNameLookupResult::FoundType:
216           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
217           break;
218         case UnqualifiedTypeNameLookupResult::NotFound:
219           break;
220         }
221       }
222     }
223   }
224 
225   return FoundTypeDecl;
226 }
227 
228 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
229                                                       const IdentifierInfo &II,
230                                                       SourceLocation NameLoc) {
231   // Lookup in the parent class template context, if any.
232   const CXXRecordDecl *RD = nullptr;
233   UnqualifiedTypeNameLookupResult FoundTypeDecl =
234       UnqualifiedTypeNameLookupResult::NotFound;
235   for (DeclContext *DC = S.CurContext;
236        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
237        DC = DC->getParent()) {
238     // Look for type decls in dependent base classes that have known primary
239     // templates.
240     RD = dyn_cast<CXXRecordDecl>(DC);
241     if (RD && RD->getDescribedClassTemplate())
242       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
243   }
244   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
245     return nullptr;
246 
247   // We found some types in dependent base classes.  Recover as if the user
248   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
249   // lookup during template instantiation.
250   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
251 
252   ASTContext &Context = S.Context;
253   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
254                                           cast<Type>(Context.getRecordType(RD)));
255   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
256 
257   CXXScopeSpec SS;
258   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
259 
260   TypeLocBuilder Builder;
261   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
262   DepTL.setNameLoc(NameLoc);
263   DepTL.setElaboratedKeywordLoc(SourceLocation());
264   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
265   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
266 }
267 
268 /// If the identifier refers to a type name within this scope,
269 /// return the declaration of that type.
270 ///
271 /// This routine performs ordinary name lookup of the identifier II
272 /// within the given scope, with optional C++ scope specifier SS, to
273 /// determine whether the name refers to a type. If so, returns an
274 /// opaque pointer (actually a QualType) corresponding to that
275 /// type. Otherwise, returns NULL.
276 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
277                              Scope *S, CXXScopeSpec *SS,
278                              bool isClassName, bool HasTrailingDot,
279                              ParsedType ObjectTypePtr,
280                              bool IsCtorOrDtorName,
281                              bool WantNontrivialTypeSourceInfo,
282                              bool IsClassTemplateDeductionContext,
283                              IdentifierInfo **CorrectedII) {
284   // FIXME: Consider allowing this outside C++1z mode as an extension.
285   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
286                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
287                               !isClassName && !HasTrailingDot;
288 
289   // Determine where we will perform name lookup.
290   DeclContext *LookupCtx = nullptr;
291   if (ObjectTypePtr) {
292     QualType ObjectType = ObjectTypePtr.get();
293     if (ObjectType->isRecordType())
294       LookupCtx = computeDeclContext(ObjectType);
295   } else if (SS && SS->isNotEmpty()) {
296     LookupCtx = computeDeclContext(*SS, false);
297 
298     if (!LookupCtx) {
299       if (isDependentScopeSpecifier(*SS)) {
300         // C++ [temp.res]p3:
301         //   A qualified-id that refers to a type and in which the
302         //   nested-name-specifier depends on a template-parameter (14.6.2)
303         //   shall be prefixed by the keyword typename to indicate that the
304         //   qualified-id denotes a type, forming an
305         //   elaborated-type-specifier (7.1.5.3).
306         //
307         // We therefore do not perform any name lookup if the result would
308         // refer to a member of an unknown specialization.
309         if (!isClassName && !IsCtorOrDtorName)
310           return nullptr;
311 
312         // We know from the grammar that this name refers to a type,
313         // so build a dependent node to describe the type.
314         if (WantNontrivialTypeSourceInfo)
315           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
316 
317         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
318         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
319                                        II, NameLoc);
320         return ParsedType::make(T);
321       }
322 
323       return nullptr;
324     }
325 
326     if (!LookupCtx->isDependentContext() &&
327         RequireCompleteDeclContext(*SS, LookupCtx))
328       return nullptr;
329   }
330 
331   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
332   // lookup for class-names.
333   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
334                                       LookupOrdinaryName;
335   LookupResult Result(*this, &II, NameLoc, Kind);
336   if (LookupCtx) {
337     // Perform "qualified" name lookup into the declaration context we
338     // computed, which is either the type of the base of a member access
339     // expression or the declaration context associated with a prior
340     // nested-name-specifier.
341     LookupQualifiedName(Result, LookupCtx);
342 
343     if (ObjectTypePtr && Result.empty()) {
344       // C++ [basic.lookup.classref]p3:
345       //   If the unqualified-id is ~type-name, the type-name is looked up
346       //   in the context of the entire postfix-expression. If the type T of
347       //   the object expression is of a class type C, the type-name is also
348       //   looked up in the scope of class C. At least one of the lookups shall
349       //   find a name that refers to (possibly cv-qualified) T.
350       LookupName(Result, S);
351     }
352   } else {
353     // Perform unqualified name lookup.
354     LookupName(Result, S);
355 
356     // For unqualified lookup in a class template in MSVC mode, look into
357     // dependent base classes where the primary class template is known.
358     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
359       if (ParsedType TypeInBase =
360               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
361         return TypeInBase;
362     }
363   }
364 
365   NamedDecl *IIDecl = nullptr;
366   switch (Result.getResultKind()) {
367   case LookupResult::NotFound:
368   case LookupResult::NotFoundInCurrentInstantiation:
369     if (CorrectedII) {
370       TypoCorrection Correction =
371           CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
372                       llvm::make_unique<TypeNameValidatorCCC>(
373                           true, isClassName, AllowDeducedTemplate),
374                       CTK_ErrorRecovery);
375       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
376       TemplateTy Template;
377       bool MemberOfUnknownSpecialization;
378       UnqualifiedId TemplateName;
379       TemplateName.setIdentifier(NewII, NameLoc);
380       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
381       CXXScopeSpec NewSS, *NewSSPtr = SS;
382       if (SS && NNS) {
383         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
384         NewSSPtr = &NewSS;
385       }
386       if (Correction && (NNS || NewII != &II) &&
387           // Ignore a correction to a template type as the to-be-corrected
388           // identifier is not a template (typo correction for template names
389           // is handled elsewhere).
390           !(getLangOpts().CPlusPlus && NewSSPtr &&
391             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
392                            Template, MemberOfUnknownSpecialization))) {
393         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
394                                     isClassName, HasTrailingDot, ObjectTypePtr,
395                                     IsCtorOrDtorName,
396                                     WantNontrivialTypeSourceInfo,
397                                     IsClassTemplateDeductionContext);
398         if (Ty) {
399           diagnoseTypo(Correction,
400                        PDiag(diag::err_unknown_type_or_class_name_suggest)
401                          << Result.getLookupName() << isClassName);
402           if (SS && NNS)
403             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
404           *CorrectedII = NewII;
405           return Ty;
406         }
407       }
408     }
409     // If typo correction failed or was not performed, fall through
410     LLVM_FALLTHROUGH;
411   case LookupResult::FoundOverloaded:
412   case LookupResult::FoundUnresolvedValue:
413     Result.suppressDiagnostics();
414     return nullptr;
415 
416   case LookupResult::Ambiguous:
417     // Recover from type-hiding ambiguities by hiding the type.  We'll
418     // do the lookup again when looking for an object, and we can
419     // diagnose the error then.  If we don't do this, then the error
420     // about hiding the type will be immediately followed by an error
421     // that only makes sense if the identifier was treated like a type.
422     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
423       Result.suppressDiagnostics();
424       return nullptr;
425     }
426 
427     // Look to see if we have a type anywhere in the list of results.
428     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
429          Res != ResEnd; ++Res) {
430       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
431           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
432         if (!IIDecl ||
433             (*Res)->getLocation().getRawEncoding() <
434               IIDecl->getLocation().getRawEncoding())
435           IIDecl = *Res;
436       }
437     }
438 
439     if (!IIDecl) {
440       // None of the entities we found is a type, so there is no way
441       // to even assume that the result is a type. In this case, don't
442       // complain about the ambiguity. The parser will either try to
443       // perform this lookup again (e.g., as an object name), which
444       // will produce the ambiguity, or will complain that it expected
445       // a type name.
446       Result.suppressDiagnostics();
447       return nullptr;
448     }
449 
450     // We found a type within the ambiguous lookup; diagnose the
451     // ambiguity and then return that type. This might be the right
452     // answer, or it might not be, but it suppresses any attempt to
453     // perform the name lookup again.
454     break;
455 
456   case LookupResult::Found:
457     IIDecl = Result.getFoundDecl();
458     break;
459   }
460 
461   assert(IIDecl && "Didn't find decl");
462 
463   QualType T;
464   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
465     // C++ [class.qual]p2: A lookup that would find the injected-class-name
466     // instead names the constructors of the class, except when naming a class.
467     // This is ill-formed when we're not actually forming a ctor or dtor name.
468     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
469     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
470     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
471         FoundRD->isInjectedClassName() &&
472         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
473       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
474           << &II << /*Type*/1;
475 
476     DiagnoseUseOfDecl(IIDecl, NameLoc);
477 
478     T = Context.getTypeDeclType(TD);
479     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
480   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
481     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
482     if (!HasTrailingDot)
483       T = Context.getObjCInterfaceType(IDecl);
484   } else if (AllowDeducedTemplate) {
485     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
486       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
487                                                        QualType(), false);
488   }
489 
490   if (T.isNull()) {
491     // If it's not plausibly a type, suppress diagnostics.
492     Result.suppressDiagnostics();
493     return nullptr;
494   }
495 
496   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
497   // constructor or destructor name (in such a case, the scope specifier
498   // will be attached to the enclosing Expr or Decl node).
499   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
500       !isa<ObjCInterfaceDecl>(IIDecl)) {
501     if (WantNontrivialTypeSourceInfo) {
502       // Construct a type with type-source information.
503       TypeLocBuilder Builder;
504       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
505 
506       T = getElaboratedType(ETK_None, *SS, T);
507       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
508       ElabTL.setElaboratedKeywordLoc(SourceLocation());
509       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
510       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
511     } else {
512       T = getElaboratedType(ETK_None, *SS, T);
513     }
514   }
515 
516   return ParsedType::make(T);
517 }
518 
519 // Builds a fake NNS for the given decl context.
520 static NestedNameSpecifier *
521 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
522   for (;; DC = DC->getLookupParent()) {
523     DC = DC->getPrimaryContext();
524     auto *ND = dyn_cast<NamespaceDecl>(DC);
525     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
526       return NestedNameSpecifier::Create(Context, nullptr, ND);
527     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
528       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
529                                          RD->getTypeForDecl());
530     else if (isa<TranslationUnitDecl>(DC))
531       return NestedNameSpecifier::GlobalSpecifier(Context);
532   }
533   llvm_unreachable("something isn't in TU scope?");
534 }
535 
536 /// Find the parent class with dependent bases of the innermost enclosing method
537 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
538 /// up allowing unqualified dependent type names at class-level, which MSVC
539 /// correctly rejects.
540 static const CXXRecordDecl *
541 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
542   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
543     DC = DC->getPrimaryContext();
544     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
545       if (MD->getParent()->hasAnyDependentBases())
546         return MD->getParent();
547   }
548   return nullptr;
549 }
550 
551 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
552                                           SourceLocation NameLoc,
553                                           bool IsTemplateTypeArg) {
554   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
555 
556   NestedNameSpecifier *NNS = nullptr;
557   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
558     // If we weren't able to parse a default template argument, delay lookup
559     // until instantiation time by making a non-dependent DependentTypeName. We
560     // pretend we saw a NestedNameSpecifier referring to the current scope, and
561     // lookup is retried.
562     // FIXME: This hurts our diagnostic quality, since we get errors like "no
563     // type named 'Foo' in 'current_namespace'" when the user didn't write any
564     // name specifiers.
565     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
566     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
567   } else if (const CXXRecordDecl *RD =
568                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
569     // Build a DependentNameType that will perform lookup into RD at
570     // instantiation time.
571     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
572                                       RD->getTypeForDecl());
573 
574     // Diagnose that this identifier was undeclared, and retry the lookup during
575     // template instantiation.
576     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
577                                                                       << RD;
578   } else {
579     // This is not a situation that we should recover from.
580     return ParsedType();
581   }
582 
583   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
584 
585   // Build type location information.  We synthesized the qualifier, so we have
586   // to build a fake NestedNameSpecifierLoc.
587   NestedNameSpecifierLocBuilder NNSLocBuilder;
588   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
589   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
590 
591   TypeLocBuilder Builder;
592   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
593   DepTL.setNameLoc(NameLoc);
594   DepTL.setElaboratedKeywordLoc(SourceLocation());
595   DepTL.setQualifierLoc(QualifierLoc);
596   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
597 }
598 
599 /// isTagName() - This method is called *for error recovery purposes only*
600 /// to determine if the specified name is a valid tag name ("struct foo").  If
601 /// so, this returns the TST for the tag corresponding to it (TST_enum,
602 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
603 /// cases in C where the user forgot to specify the tag.
604 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
605   // Do a tag name lookup in this scope.
606   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
607   LookupName(R, S, false);
608   R.suppressDiagnostics();
609   if (R.getResultKind() == LookupResult::Found)
610     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
611       switch (TD->getTagKind()) {
612       case TTK_Struct: return DeclSpec::TST_struct;
613       case TTK_Interface: return DeclSpec::TST_interface;
614       case TTK_Union:  return DeclSpec::TST_union;
615       case TTK_Class:  return DeclSpec::TST_class;
616       case TTK_Enum:   return DeclSpec::TST_enum;
617       }
618     }
619 
620   return DeclSpec::TST_unspecified;
621 }
622 
623 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
624 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
625 /// then downgrade the missing typename error to a warning.
626 /// This is needed for MSVC compatibility; Example:
627 /// @code
628 /// template<class T> class A {
629 /// public:
630 ///   typedef int TYPE;
631 /// };
632 /// template<class T> class B : public A<T> {
633 /// public:
634 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
635 /// };
636 /// @endcode
637 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
638   if (CurContext->isRecord()) {
639     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
640       return true;
641 
642     const Type *Ty = SS->getScopeRep()->getAsType();
643 
644     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
645     for (const auto &Base : RD->bases())
646       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
647         return true;
648     return S->isFunctionPrototypeScope();
649   }
650   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
651 }
652 
653 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
654                                    SourceLocation IILoc,
655                                    Scope *S,
656                                    CXXScopeSpec *SS,
657                                    ParsedType &SuggestedType,
658                                    bool IsTemplateName) {
659   // Don't report typename errors for editor placeholders.
660   if (II->isEditorPlaceholder())
661     return;
662   // We don't have anything to suggest (yet).
663   SuggestedType = nullptr;
664 
665   // There may have been a typo in the name of the type. Look up typo
666   // results, in case we have something that we can suggest.
667   if (TypoCorrection Corrected =
668           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
669                       llvm::make_unique<TypeNameValidatorCCC>(
670                           false, false, IsTemplateName, !IsTemplateName),
671                       CTK_ErrorRecovery)) {
672     // FIXME: Support error recovery for the template-name case.
673     bool CanRecover = !IsTemplateName;
674     if (Corrected.isKeyword()) {
675       // We corrected to a keyword.
676       diagnoseTypo(Corrected,
677                    PDiag(IsTemplateName ? diag::err_no_template_suggest
678                                         : diag::err_unknown_typename_suggest)
679                        << II);
680       II = Corrected.getCorrectionAsIdentifierInfo();
681     } else {
682       // We found a similarly-named type or interface; suggest that.
683       if (!SS || !SS->isSet()) {
684         diagnoseTypo(Corrected,
685                      PDiag(IsTemplateName ? diag::err_no_template_suggest
686                                           : diag::err_unknown_typename_suggest)
687                          << II, CanRecover);
688       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
689         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
690         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
691                                 II->getName().equals(CorrectedStr);
692         diagnoseTypo(Corrected,
693                      PDiag(IsTemplateName
694                                ? diag::err_no_member_template_suggest
695                                : diag::err_unknown_nested_typename_suggest)
696                          << II << DC << DroppedSpecifier << SS->getRange(),
697                      CanRecover);
698       } else {
699         llvm_unreachable("could not have corrected a typo here");
700       }
701 
702       if (!CanRecover)
703         return;
704 
705       CXXScopeSpec tmpSS;
706       if (Corrected.getCorrectionSpecifier())
707         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
708                           SourceRange(IILoc));
709       // FIXME: Support class template argument deduction here.
710       SuggestedType =
711           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
712                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
713                       /*IsCtorOrDtorName=*/false,
714                       /*NonTrivialTypeSourceInfo=*/true);
715     }
716     return;
717   }
718 
719   if (getLangOpts().CPlusPlus && !IsTemplateName) {
720     // See if II is a class template that the user forgot to pass arguments to.
721     UnqualifiedId Name;
722     Name.setIdentifier(II, IILoc);
723     CXXScopeSpec EmptySS;
724     TemplateTy TemplateResult;
725     bool MemberOfUnknownSpecialization;
726     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
727                        Name, nullptr, true, TemplateResult,
728                        MemberOfUnknownSpecialization) == TNK_Type_template) {
729       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
730       return;
731     }
732   }
733 
734   // FIXME: Should we move the logic that tries to recover from a missing tag
735   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
736 
737   if (!SS || (!SS->isSet() && !SS->isInvalid()))
738     Diag(IILoc, IsTemplateName ? diag::err_no_template
739                                : diag::err_unknown_typename)
740         << II;
741   else if (DeclContext *DC = computeDeclContext(*SS, false))
742     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
743                                : diag::err_typename_nested_not_found)
744         << II << DC << SS->getRange();
745   else if (isDependentScopeSpecifier(*SS)) {
746     unsigned DiagID = diag::err_typename_missing;
747     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
748       DiagID = diag::ext_typename_missing;
749 
750     Diag(SS->getRange().getBegin(), DiagID)
751       << SS->getScopeRep() << II->getName()
752       << SourceRange(SS->getRange().getBegin(), IILoc)
753       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
754     SuggestedType = ActOnTypenameType(S, SourceLocation(),
755                                       *SS, *II, IILoc).get();
756   } else {
757     assert(SS && SS->isInvalid() &&
758            "Invalid scope specifier has already been diagnosed");
759   }
760 }
761 
762 /// Determine whether the given result set contains either a type name
763 /// or
764 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
765   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
766                        NextToken.is(tok::less);
767 
768   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
769     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
770       return true;
771 
772     if (CheckTemplate && isa<TemplateDecl>(*I))
773       return true;
774   }
775 
776   return false;
777 }
778 
779 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
780                                     Scope *S, CXXScopeSpec &SS,
781                                     IdentifierInfo *&Name,
782                                     SourceLocation NameLoc) {
783   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
784   SemaRef.LookupParsedName(R, S, &SS);
785   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
786     StringRef FixItTagName;
787     switch (Tag->getTagKind()) {
788       case TTK_Class:
789         FixItTagName = "class ";
790         break;
791 
792       case TTK_Enum:
793         FixItTagName = "enum ";
794         break;
795 
796       case TTK_Struct:
797         FixItTagName = "struct ";
798         break;
799 
800       case TTK_Interface:
801         FixItTagName = "__interface ";
802         break;
803 
804       case TTK_Union:
805         FixItTagName = "union ";
806         break;
807     }
808 
809     StringRef TagName = FixItTagName.drop_back();
810     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
811       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
812       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
813 
814     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
815          I != IEnd; ++I)
816       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
817         << Name << TagName;
818 
819     // Replace lookup results with just the tag decl.
820     Result.clear(Sema::LookupTagName);
821     SemaRef.LookupParsedName(Result, S, &SS);
822     return true;
823   }
824 
825   return false;
826 }
827 
828 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
829 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
830                                   QualType T, SourceLocation NameLoc) {
831   ASTContext &Context = S.Context;
832 
833   TypeLocBuilder Builder;
834   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
835 
836   T = S.getElaboratedType(ETK_None, SS, T);
837   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
838   ElabTL.setElaboratedKeywordLoc(SourceLocation());
839   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
840   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
841 }
842 
843 Sema::NameClassification
844 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
845                    SourceLocation NameLoc, const Token &NextToken,
846                    bool IsAddressOfOperand,
847                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
848   DeclarationNameInfo NameInfo(Name, NameLoc);
849   ObjCMethodDecl *CurMethod = getCurMethodDecl();
850 
851   if (NextToken.is(tok::coloncolon)) {
852     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
853     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
854   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
855              isCurrentClassName(*Name, S, &SS)) {
856     // Per [class.qual]p2, this names the constructors of SS, not the
857     // injected-class-name. We don't have a classification for that.
858     // There's not much point caching this result, since the parser
859     // will reject it later.
860     return NameClassification::Unknown();
861   }
862 
863   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
864   LookupParsedName(Result, S, &SS, !CurMethod);
865 
866   // For unqualified lookup in a class template in MSVC mode, look into
867   // dependent base classes where the primary class template is known.
868   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
869     if (ParsedType TypeInBase =
870             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
871       return TypeInBase;
872   }
873 
874   // Perform lookup for Objective-C instance variables (including automatically
875   // synthesized instance variables), if we're in an Objective-C method.
876   // FIXME: This lookup really, really needs to be folded in to the normal
877   // unqualified lookup mechanism.
878   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
879     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
880     if (E.get() || E.isInvalid())
881       return E;
882   }
883 
884   bool SecondTry = false;
885   bool IsFilteredTemplateName = false;
886 
887 Corrected:
888   switch (Result.getResultKind()) {
889   case LookupResult::NotFound:
890     // If an unqualified-id is followed by a '(', then we have a function
891     // call.
892     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
893       // In C++, this is an ADL-only call.
894       // FIXME: Reference?
895       if (getLangOpts().CPlusPlus)
896         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
897 
898       // C90 6.3.2.2:
899       //   If the expression that precedes the parenthesized argument list in a
900       //   function call consists solely of an identifier, and if no
901       //   declaration is visible for this identifier, the identifier is
902       //   implicitly declared exactly as if, in the innermost block containing
903       //   the function call, the declaration
904       //
905       //     extern int identifier ();
906       //
907       //   appeared.
908       //
909       // We also allow this in C99 as an extension.
910       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
911         Result.addDecl(D);
912         Result.resolveKind();
913         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
914       }
915     }
916 
917     // In C, we first see whether there is a tag type by the same name, in
918     // which case it's likely that the user just forgot to write "enum",
919     // "struct", or "union".
920     if (!getLangOpts().CPlusPlus && !SecondTry &&
921         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
922       break;
923     }
924 
925     // Perform typo correction to determine if there is another name that is
926     // close to this name.
927     if (!SecondTry && CCC) {
928       SecondTry = true;
929       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
930                                                  Result.getLookupKind(), S,
931                                                  &SS, std::move(CCC),
932                                                  CTK_ErrorRecovery)) {
933         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
934         unsigned QualifiedDiag = diag::err_no_member_suggest;
935 
936         NamedDecl *FirstDecl = Corrected.getFoundDecl();
937         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
938         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
939             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
940           UnqualifiedDiag = diag::err_no_template_suggest;
941           QualifiedDiag = diag::err_no_member_template_suggest;
942         } else if (UnderlyingFirstDecl &&
943                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
944                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
945                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
946           UnqualifiedDiag = diag::err_unknown_typename_suggest;
947           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
948         }
949 
950         if (SS.isEmpty()) {
951           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
952         } else {// FIXME: is this even reachable? Test it.
953           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
954           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
955                                   Name->getName().equals(CorrectedStr);
956           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
957                                     << Name << computeDeclContext(SS, false)
958                                     << DroppedSpecifier << SS.getRange());
959         }
960 
961         // Update the name, so that the caller has the new name.
962         Name = Corrected.getCorrectionAsIdentifierInfo();
963 
964         // Typo correction corrected to a keyword.
965         if (Corrected.isKeyword())
966           return Name;
967 
968         // Also update the LookupResult...
969         // FIXME: This should probably go away at some point
970         Result.clear();
971         Result.setLookupName(Corrected.getCorrection());
972         if (FirstDecl)
973           Result.addDecl(FirstDecl);
974 
975         // If we found an Objective-C instance variable, let
976         // LookupInObjCMethod build the appropriate expression to
977         // reference the ivar.
978         // FIXME: This is a gross hack.
979         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
980           Result.clear();
981           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
982           return E;
983         }
984 
985         goto Corrected;
986       }
987     }
988 
989     // We failed to correct; just fall through and let the parser deal with it.
990     Result.suppressDiagnostics();
991     return NameClassification::Unknown();
992 
993   case LookupResult::NotFoundInCurrentInstantiation: {
994     // We performed name lookup into the current instantiation, and there were
995     // dependent bases, so we treat this result the same way as any other
996     // dependent nested-name-specifier.
997 
998     // C++ [temp.res]p2:
999     //   A name used in a template declaration or definition and that is
1000     //   dependent on a template-parameter is assumed not to name a type
1001     //   unless the applicable name lookup finds a type name or the name is
1002     //   qualified by the keyword typename.
1003     //
1004     // FIXME: If the next token is '<', we might want to ask the parser to
1005     // perform some heroics to see if we actually have a
1006     // template-argument-list, which would indicate a missing 'template'
1007     // keyword here.
1008     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1009                                       NameInfo, IsAddressOfOperand,
1010                                       /*TemplateArgs=*/nullptr);
1011   }
1012 
1013   case LookupResult::Found:
1014   case LookupResult::FoundOverloaded:
1015   case LookupResult::FoundUnresolvedValue:
1016     break;
1017 
1018   case LookupResult::Ambiguous:
1019     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1020         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1021                                       /*AllowDependent=*/false)) {
1022       // C++ [temp.local]p3:
1023       //   A lookup that finds an injected-class-name (10.2) can result in an
1024       //   ambiguity in certain cases (for example, if it is found in more than
1025       //   one base class). If all of the injected-class-names that are found
1026       //   refer to specializations of the same class template, and if the name
1027       //   is followed by a template-argument-list, the reference refers to the
1028       //   class template itself and not a specialization thereof, and is not
1029       //   ambiguous.
1030       //
1031       // This filtering can make an ambiguous result into an unambiguous one,
1032       // so try again after filtering out template names.
1033       FilterAcceptableTemplateNames(Result);
1034       if (!Result.isAmbiguous()) {
1035         IsFilteredTemplateName = true;
1036         break;
1037       }
1038     }
1039 
1040     // Diagnose the ambiguity and return an error.
1041     return NameClassification::Error();
1042   }
1043 
1044   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1045       (IsFilteredTemplateName ||
1046        hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1047                                      /*AllowDependent=*/false))) {
1048     // C++ [temp.names]p3:
1049     //   After name lookup (3.4) finds that a name is a template-name or that
1050     //   an operator-function-id or a literal- operator-id refers to a set of
1051     //   overloaded functions any member of which is a function template if
1052     //   this is followed by a <, the < is always taken as the delimiter of a
1053     //   template-argument-list and never as the less-than operator.
1054     if (!IsFilteredTemplateName)
1055       FilterAcceptableTemplateNames(Result);
1056 
1057     if (!Result.empty()) {
1058       bool IsFunctionTemplate;
1059       bool IsVarTemplate;
1060       TemplateName Template;
1061       if (Result.end() - Result.begin() > 1) {
1062         IsFunctionTemplate = true;
1063         Template = Context.getOverloadedTemplateName(Result.begin(),
1064                                                      Result.end());
1065       } else {
1066         auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1067             *Result.begin(), /*AllowFunctionTemplates=*/true,
1068             /*AllowDependent=*/false));
1069         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1070         IsVarTemplate = isa<VarTemplateDecl>(TD);
1071 
1072         if (SS.isSet() && !SS.isInvalid())
1073           Template =
1074               Context.getQualifiedTemplateName(SS.getScopeRep(),
1075                                                /*TemplateKeyword=*/false, TD);
1076         else
1077           Template = TemplateName(TD);
1078       }
1079 
1080       if (IsFunctionTemplate) {
1081         // Function templates always go through overload resolution, at which
1082         // point we'll perform the various checks (e.g., accessibility) we need
1083         // to based on which function we selected.
1084         Result.suppressDiagnostics();
1085 
1086         return NameClassification::FunctionTemplate(Template);
1087       }
1088 
1089       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1090                            : NameClassification::TypeTemplate(Template);
1091     }
1092   }
1093 
1094   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1095   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1096     DiagnoseUseOfDecl(Type, NameLoc);
1097     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1098     QualType T = Context.getTypeDeclType(Type);
1099     if (SS.isNotEmpty())
1100       return buildNestedType(*this, SS, T, NameLoc);
1101     return ParsedType::make(T);
1102   }
1103 
1104   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1105   if (!Class) {
1106     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1107     if (ObjCCompatibleAliasDecl *Alias =
1108             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1109       Class = Alias->getClassInterface();
1110   }
1111 
1112   if (Class) {
1113     DiagnoseUseOfDecl(Class, NameLoc);
1114 
1115     if (NextToken.is(tok::period)) {
1116       // Interface. <something> is parsed as a property reference expression.
1117       // Just return "unknown" as a fall-through for now.
1118       Result.suppressDiagnostics();
1119       return NameClassification::Unknown();
1120     }
1121 
1122     QualType T = Context.getObjCInterfaceType(Class);
1123     return ParsedType::make(T);
1124   }
1125 
1126   // We can have a type template here if we're classifying a template argument.
1127   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1128       !isa<VarTemplateDecl>(FirstDecl))
1129     return NameClassification::TypeTemplate(
1130         TemplateName(cast<TemplateDecl>(FirstDecl)));
1131 
1132   // Check for a tag type hidden by a non-type decl in a few cases where it
1133   // seems likely a type is wanted instead of the non-type that was found.
1134   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1135   if ((NextToken.is(tok::identifier) ||
1136        (NextIsOp &&
1137         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1138       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1139     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1140     DiagnoseUseOfDecl(Type, NameLoc);
1141     QualType T = Context.getTypeDeclType(Type);
1142     if (SS.isNotEmpty())
1143       return buildNestedType(*this, SS, T, NameLoc);
1144     return ParsedType::make(T);
1145   }
1146 
1147   if (FirstDecl->isCXXClassMember())
1148     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1149                                            nullptr, S);
1150 
1151   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1152   return BuildDeclarationNameExpr(SS, Result, ADL);
1153 }
1154 
1155 Sema::TemplateNameKindForDiagnostics
1156 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1157   auto *TD = Name.getAsTemplateDecl();
1158   if (!TD)
1159     return TemplateNameKindForDiagnostics::DependentTemplate;
1160   if (isa<ClassTemplateDecl>(TD))
1161     return TemplateNameKindForDiagnostics::ClassTemplate;
1162   if (isa<FunctionTemplateDecl>(TD))
1163     return TemplateNameKindForDiagnostics::FunctionTemplate;
1164   if (isa<VarTemplateDecl>(TD))
1165     return TemplateNameKindForDiagnostics::VarTemplate;
1166   if (isa<TypeAliasTemplateDecl>(TD))
1167     return TemplateNameKindForDiagnostics::AliasTemplate;
1168   if (isa<TemplateTemplateParmDecl>(TD))
1169     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1170   return TemplateNameKindForDiagnostics::DependentTemplate;
1171 }
1172 
1173 // Determines the context to return to after temporarily entering a
1174 // context.  This depends in an unnecessarily complicated way on the
1175 // exact ordering of callbacks from the parser.
1176 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1177 
1178   // Functions defined inline within classes aren't parsed until we've
1179   // finished parsing the top-level class, so the top-level class is
1180   // the context we'll need to return to.
1181   // A Lambda call operator whose parent is a class must not be treated
1182   // as an inline member function.  A Lambda can be used legally
1183   // either as an in-class member initializer or a default argument.  These
1184   // are parsed once the class has been marked complete and so the containing
1185   // context would be the nested class (when the lambda is defined in one);
1186   // If the class is not complete, then the lambda is being used in an
1187   // ill-formed fashion (such as to specify the width of a bit-field, or
1188   // in an array-bound) - in which case we still want to return the
1189   // lexically containing DC (which could be a nested class).
1190   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1191     DC = DC->getLexicalParent();
1192 
1193     // A function not defined within a class will always return to its
1194     // lexical context.
1195     if (!isa<CXXRecordDecl>(DC))
1196       return DC;
1197 
1198     // A C++ inline method/friend is parsed *after* the topmost class
1199     // it was declared in is fully parsed ("complete");  the topmost
1200     // class is the context we need to return to.
1201     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1202       DC = RD;
1203 
1204     // Return the declaration context of the topmost class the inline method is
1205     // declared in.
1206     return DC;
1207   }
1208 
1209   return DC->getLexicalParent();
1210 }
1211 
1212 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1213   assert(getContainingDC(DC) == CurContext &&
1214       "The next DeclContext should be lexically contained in the current one.");
1215   CurContext = DC;
1216   S->setEntity(DC);
1217 }
1218 
1219 void Sema::PopDeclContext() {
1220   assert(CurContext && "DeclContext imbalance!");
1221 
1222   CurContext = getContainingDC(CurContext);
1223   assert(CurContext && "Popped translation unit!");
1224 }
1225 
1226 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1227                                                                     Decl *D) {
1228   // Unlike PushDeclContext, the context to which we return is not necessarily
1229   // the containing DC of TD, because the new context will be some pre-existing
1230   // TagDecl definition instead of a fresh one.
1231   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1232   CurContext = cast<TagDecl>(D)->getDefinition();
1233   assert(CurContext && "skipping definition of undefined tag");
1234   // Start lookups from the parent of the current context; we don't want to look
1235   // into the pre-existing complete definition.
1236   S->setEntity(CurContext->getLookupParent());
1237   return Result;
1238 }
1239 
1240 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1241   CurContext = static_cast<decltype(CurContext)>(Context);
1242 }
1243 
1244 /// EnterDeclaratorContext - Used when we must lookup names in the context
1245 /// of a declarator's nested name specifier.
1246 ///
1247 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1248   // C++0x [basic.lookup.unqual]p13:
1249   //   A name used in the definition of a static data member of class
1250   //   X (after the qualified-id of the static member) is looked up as
1251   //   if the name was used in a member function of X.
1252   // C++0x [basic.lookup.unqual]p14:
1253   //   If a variable member of a namespace is defined outside of the
1254   //   scope of its namespace then any name used in the definition of
1255   //   the variable member (after the declarator-id) is looked up as
1256   //   if the definition of the variable member occurred in its
1257   //   namespace.
1258   // Both of these imply that we should push a scope whose context
1259   // is the semantic context of the declaration.  We can't use
1260   // PushDeclContext here because that context is not necessarily
1261   // lexically contained in the current context.  Fortunately,
1262   // the containing scope should have the appropriate information.
1263 
1264   assert(!S->getEntity() && "scope already has entity");
1265 
1266 #ifndef NDEBUG
1267   Scope *Ancestor = S->getParent();
1268   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1269   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1270 #endif
1271 
1272   CurContext = DC;
1273   S->setEntity(DC);
1274 }
1275 
1276 void Sema::ExitDeclaratorContext(Scope *S) {
1277   assert(S->getEntity() == CurContext && "Context imbalance!");
1278 
1279   // Switch back to the lexical context.  The safety of this is
1280   // enforced by an assert in EnterDeclaratorContext.
1281   Scope *Ancestor = S->getParent();
1282   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1283   CurContext = Ancestor->getEntity();
1284 
1285   // We don't need to do anything with the scope, which is going to
1286   // disappear.
1287 }
1288 
1289 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1290   // We assume that the caller has already called
1291   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1292   FunctionDecl *FD = D->getAsFunction();
1293   if (!FD)
1294     return;
1295 
1296   // Same implementation as PushDeclContext, but enters the context
1297   // from the lexical parent, rather than the top-level class.
1298   assert(CurContext == FD->getLexicalParent() &&
1299     "The next DeclContext should be lexically contained in the current one.");
1300   CurContext = FD;
1301   S->setEntity(CurContext);
1302 
1303   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1304     ParmVarDecl *Param = FD->getParamDecl(P);
1305     // If the parameter has an identifier, then add it to the scope
1306     if (Param->getIdentifier()) {
1307       S->AddDecl(Param);
1308       IdResolver.AddDecl(Param);
1309     }
1310   }
1311 }
1312 
1313 void Sema::ActOnExitFunctionContext() {
1314   // Same implementation as PopDeclContext, but returns to the lexical parent,
1315   // rather than the top-level class.
1316   assert(CurContext && "DeclContext imbalance!");
1317   CurContext = CurContext->getLexicalParent();
1318   assert(CurContext && "Popped translation unit!");
1319 }
1320 
1321 /// Determine whether we allow overloading of the function
1322 /// PrevDecl with another declaration.
1323 ///
1324 /// This routine determines whether overloading is possible, not
1325 /// whether some new function is actually an overload. It will return
1326 /// true in C++ (where we can always provide overloads) or, as an
1327 /// extension, in C when the previous function is already an
1328 /// overloaded function declaration or has the "overloadable"
1329 /// attribute.
1330 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1331                                        ASTContext &Context,
1332                                        const FunctionDecl *New) {
1333   if (Context.getLangOpts().CPlusPlus)
1334     return true;
1335 
1336   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1337     return true;
1338 
1339   return Previous.getResultKind() == LookupResult::Found &&
1340          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1341           New->hasAttr<OverloadableAttr>());
1342 }
1343 
1344 /// Add this decl to the scope shadowed decl chains.
1345 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1346   // Move up the scope chain until we find the nearest enclosing
1347   // non-transparent context. The declaration will be introduced into this
1348   // scope.
1349   while (S->getEntity() && S->getEntity()->isTransparentContext())
1350     S = S->getParent();
1351 
1352   // Add scoped declarations into their context, so that they can be
1353   // found later. Declarations without a context won't be inserted
1354   // into any context.
1355   if (AddToContext)
1356     CurContext->addDecl(D);
1357 
1358   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1359   // are function-local declarations.
1360   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1361       !D->getDeclContext()->getRedeclContext()->Equals(
1362         D->getLexicalDeclContext()->getRedeclContext()) &&
1363       !D->getLexicalDeclContext()->isFunctionOrMethod())
1364     return;
1365 
1366   // Template instantiations should also not be pushed into scope.
1367   if (isa<FunctionDecl>(D) &&
1368       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1369     return;
1370 
1371   // If this replaces anything in the current scope,
1372   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1373                                IEnd = IdResolver.end();
1374   for (; I != IEnd; ++I) {
1375     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1376       S->RemoveDecl(*I);
1377       IdResolver.RemoveDecl(*I);
1378 
1379       // Should only need to replace one decl.
1380       break;
1381     }
1382   }
1383 
1384   S->AddDecl(D);
1385 
1386   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1387     // Implicitly-generated labels may end up getting generated in an order that
1388     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1389     // the label at the appropriate place in the identifier chain.
1390     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1391       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1392       if (IDC == CurContext) {
1393         if (!S->isDeclScope(*I))
1394           continue;
1395       } else if (IDC->Encloses(CurContext))
1396         break;
1397     }
1398 
1399     IdResolver.InsertDeclAfter(I, D);
1400   } else {
1401     IdResolver.AddDecl(D);
1402   }
1403 }
1404 
1405 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1406   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1407     TUScope->AddDecl(D);
1408 }
1409 
1410 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1411                          bool AllowInlineNamespace) {
1412   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1413 }
1414 
1415 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1416   DeclContext *TargetDC = DC->getPrimaryContext();
1417   do {
1418     if (DeclContext *ScopeDC = S->getEntity())
1419       if (ScopeDC->getPrimaryContext() == TargetDC)
1420         return S;
1421   } while ((S = S->getParent()));
1422 
1423   return nullptr;
1424 }
1425 
1426 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1427                                             DeclContext*,
1428                                             ASTContext&);
1429 
1430 /// Filters out lookup results that don't fall within the given scope
1431 /// as determined by isDeclInScope.
1432 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1433                                 bool ConsiderLinkage,
1434                                 bool AllowInlineNamespace) {
1435   LookupResult::Filter F = R.makeFilter();
1436   while (F.hasNext()) {
1437     NamedDecl *D = F.next();
1438 
1439     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1440       continue;
1441 
1442     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1443       continue;
1444 
1445     F.erase();
1446   }
1447 
1448   F.done();
1449 }
1450 
1451 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1452 /// have compatible owning modules.
1453 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1454   // FIXME: The Modules TS is not clear about how friend declarations are
1455   // to be treated. It's not meaningful to have different owning modules for
1456   // linkage in redeclarations of the same entity, so for now allow the
1457   // redeclaration and change the owning modules to match.
1458   if (New->getFriendObjectKind() &&
1459       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1460     New->setLocalOwningModule(Old->getOwningModule());
1461     makeMergedDefinitionVisible(New);
1462     return false;
1463   }
1464 
1465   Module *NewM = New->getOwningModule();
1466   Module *OldM = Old->getOwningModule();
1467   if (NewM == OldM)
1468     return false;
1469 
1470   // FIXME: Check proclaimed-ownership-declarations here too.
1471   bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit;
1472   bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit;
1473   if (NewIsModuleInterface || OldIsModuleInterface) {
1474     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1475     //   if a declaration of D [...] appears in the purview of a module, all
1476     //   other such declarations shall appear in the purview of the same module
1477     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1478       << New
1479       << NewIsModuleInterface
1480       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1481       << OldIsModuleInterface
1482       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1483     Diag(Old->getLocation(), diag::note_previous_declaration);
1484     New->setInvalidDecl();
1485     return true;
1486   }
1487 
1488   return false;
1489 }
1490 
1491 static bool isUsingDecl(NamedDecl *D) {
1492   return isa<UsingShadowDecl>(D) ||
1493          isa<UnresolvedUsingTypenameDecl>(D) ||
1494          isa<UnresolvedUsingValueDecl>(D);
1495 }
1496 
1497 /// Removes using shadow declarations from the lookup results.
1498 static void RemoveUsingDecls(LookupResult &R) {
1499   LookupResult::Filter F = R.makeFilter();
1500   while (F.hasNext())
1501     if (isUsingDecl(F.next()))
1502       F.erase();
1503 
1504   F.done();
1505 }
1506 
1507 /// Check for this common pattern:
1508 /// @code
1509 /// class S {
1510 ///   S(const S&); // DO NOT IMPLEMENT
1511 ///   void operator=(const S&); // DO NOT IMPLEMENT
1512 /// };
1513 /// @endcode
1514 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1515   // FIXME: Should check for private access too but access is set after we get
1516   // the decl here.
1517   if (D->doesThisDeclarationHaveABody())
1518     return false;
1519 
1520   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1521     return CD->isCopyConstructor();
1522   return D->isCopyAssignmentOperator();
1523 }
1524 
1525 // We need this to handle
1526 //
1527 // typedef struct {
1528 //   void *foo() { return 0; }
1529 // } A;
1530 //
1531 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1532 // for example. If 'A', foo will have external linkage. If we have '*A',
1533 // foo will have no linkage. Since we can't know until we get to the end
1534 // of the typedef, this function finds out if D might have non-external linkage.
1535 // Callers should verify at the end of the TU if it D has external linkage or
1536 // not.
1537 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1538   const DeclContext *DC = D->getDeclContext();
1539   while (!DC->isTranslationUnit()) {
1540     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1541       if (!RD->hasNameForLinkage())
1542         return true;
1543     }
1544     DC = DC->getParent();
1545   }
1546 
1547   return !D->isExternallyVisible();
1548 }
1549 
1550 // FIXME: This needs to be refactored; some other isInMainFile users want
1551 // these semantics.
1552 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1553   if (S.TUKind != TU_Complete)
1554     return false;
1555   return S.SourceMgr.isInMainFile(Loc);
1556 }
1557 
1558 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1559   assert(D);
1560 
1561   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1562     return false;
1563 
1564   // Ignore all entities declared within templates, and out-of-line definitions
1565   // of members of class templates.
1566   if (D->getDeclContext()->isDependentContext() ||
1567       D->getLexicalDeclContext()->isDependentContext())
1568     return false;
1569 
1570   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1571     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1572       return false;
1573     // A non-out-of-line declaration of a member specialization was implicitly
1574     // instantiated; it's the out-of-line declaration that we're interested in.
1575     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1576         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1577       return false;
1578 
1579     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1580       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1581         return false;
1582     } else {
1583       // 'static inline' functions are defined in headers; don't warn.
1584       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1585         return false;
1586     }
1587 
1588     if (FD->doesThisDeclarationHaveABody() &&
1589         Context.DeclMustBeEmitted(FD))
1590       return false;
1591   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1592     // Constants and utility variables are defined in headers with internal
1593     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1594     // like "inline".)
1595     if (!isMainFileLoc(*this, VD->getLocation()))
1596       return false;
1597 
1598     if (Context.DeclMustBeEmitted(VD))
1599       return false;
1600 
1601     if (VD->isStaticDataMember() &&
1602         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1603       return false;
1604     if (VD->isStaticDataMember() &&
1605         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1606         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1607       return false;
1608 
1609     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1610       return false;
1611   } else {
1612     return false;
1613   }
1614 
1615   // Only warn for unused decls internal to the translation unit.
1616   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1617   // for inline functions defined in the main source file, for instance.
1618   return mightHaveNonExternalLinkage(D);
1619 }
1620 
1621 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1622   if (!D)
1623     return;
1624 
1625   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1626     const FunctionDecl *First = FD->getFirstDecl();
1627     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1628       return; // First should already be in the vector.
1629   }
1630 
1631   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1632     const VarDecl *First = VD->getFirstDecl();
1633     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1634       return; // First should already be in the vector.
1635   }
1636 
1637   if (ShouldWarnIfUnusedFileScopedDecl(D))
1638     UnusedFileScopedDecls.push_back(D);
1639 }
1640 
1641 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1642   if (D->isInvalidDecl())
1643     return false;
1644 
1645   bool Referenced = false;
1646   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1647     // For a decomposition declaration, warn if none of the bindings are
1648     // referenced, instead of if the variable itself is referenced (which
1649     // it is, by the bindings' expressions).
1650     for (auto *BD : DD->bindings()) {
1651       if (BD->isReferenced()) {
1652         Referenced = true;
1653         break;
1654       }
1655     }
1656   } else if (!D->getDeclName()) {
1657     return false;
1658   } else if (D->isReferenced() || D->isUsed()) {
1659     Referenced = true;
1660   }
1661 
1662   if (Referenced || D->hasAttr<UnusedAttr>() ||
1663       D->hasAttr<ObjCPreciseLifetimeAttr>())
1664     return false;
1665 
1666   if (isa<LabelDecl>(D))
1667     return true;
1668 
1669   // Except for labels, we only care about unused decls that are local to
1670   // functions.
1671   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1672   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1673     // For dependent types, the diagnostic is deferred.
1674     WithinFunction =
1675         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1676   if (!WithinFunction)
1677     return false;
1678 
1679   if (isa<TypedefNameDecl>(D))
1680     return true;
1681 
1682   // White-list anything that isn't a local variable.
1683   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1684     return false;
1685 
1686   // Types of valid local variables should be complete, so this should succeed.
1687   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1688 
1689     // White-list anything with an __attribute__((unused)) type.
1690     const auto *Ty = VD->getType().getTypePtr();
1691 
1692     // Only look at the outermost level of typedef.
1693     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1694       if (TT->getDecl()->hasAttr<UnusedAttr>())
1695         return false;
1696     }
1697 
1698     // If we failed to complete the type for some reason, or if the type is
1699     // dependent, don't diagnose the variable.
1700     if (Ty->isIncompleteType() || Ty->isDependentType())
1701       return false;
1702 
1703     // Look at the element type to ensure that the warning behaviour is
1704     // consistent for both scalars and arrays.
1705     Ty = Ty->getBaseElementTypeUnsafe();
1706 
1707     if (const TagType *TT = Ty->getAs<TagType>()) {
1708       const TagDecl *Tag = TT->getDecl();
1709       if (Tag->hasAttr<UnusedAttr>())
1710         return false;
1711 
1712       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1713         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1714           return false;
1715 
1716         if (const Expr *Init = VD->getInit()) {
1717           if (const ExprWithCleanups *Cleanups =
1718                   dyn_cast<ExprWithCleanups>(Init))
1719             Init = Cleanups->getSubExpr();
1720           const CXXConstructExpr *Construct =
1721             dyn_cast<CXXConstructExpr>(Init);
1722           if (Construct && !Construct->isElidable()) {
1723             CXXConstructorDecl *CD = Construct->getConstructor();
1724             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1725                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1726               return false;
1727           }
1728         }
1729       }
1730     }
1731 
1732     // TODO: __attribute__((unused)) templates?
1733   }
1734 
1735   return true;
1736 }
1737 
1738 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1739                                      FixItHint &Hint) {
1740   if (isa<LabelDecl>(D)) {
1741     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1742         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1743         true);
1744     if (AfterColon.isInvalid())
1745       return;
1746     Hint = FixItHint::CreateRemoval(
1747         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1748   }
1749 }
1750 
1751 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1752   if (D->getTypeForDecl()->isDependentType())
1753     return;
1754 
1755   for (auto *TmpD : D->decls()) {
1756     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1757       DiagnoseUnusedDecl(T);
1758     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1759       DiagnoseUnusedNestedTypedefs(R);
1760   }
1761 }
1762 
1763 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1764 /// unless they are marked attr(unused).
1765 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1766   if (!ShouldDiagnoseUnusedDecl(D))
1767     return;
1768 
1769   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1770     // typedefs can be referenced later on, so the diagnostics are emitted
1771     // at end-of-translation-unit.
1772     UnusedLocalTypedefNameCandidates.insert(TD);
1773     return;
1774   }
1775 
1776   FixItHint Hint;
1777   GenerateFixForUnusedDecl(D, Context, Hint);
1778 
1779   unsigned DiagID;
1780   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1781     DiagID = diag::warn_unused_exception_param;
1782   else if (isa<LabelDecl>(D))
1783     DiagID = diag::warn_unused_label;
1784   else
1785     DiagID = diag::warn_unused_variable;
1786 
1787   Diag(D->getLocation(), DiagID) << D << Hint;
1788 }
1789 
1790 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1791   // Verify that we have no forward references left.  If so, there was a goto
1792   // or address of a label taken, but no definition of it.  Label fwd
1793   // definitions are indicated with a null substmt which is also not a resolved
1794   // MS inline assembly label name.
1795   bool Diagnose = false;
1796   if (L->isMSAsmLabel())
1797     Diagnose = !L->isResolvedMSAsmLabel();
1798   else
1799     Diagnose = L->getStmt() == nullptr;
1800   if (Diagnose)
1801     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1802 }
1803 
1804 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1805   S->mergeNRVOIntoParent();
1806 
1807   if (S->decl_empty()) return;
1808   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1809          "Scope shouldn't contain decls!");
1810 
1811   for (auto *TmpD : S->decls()) {
1812     assert(TmpD && "This decl didn't get pushed??");
1813 
1814     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1815     NamedDecl *D = cast<NamedDecl>(TmpD);
1816 
1817     // Diagnose unused variables in this scope.
1818     if (!S->hasUnrecoverableErrorOccurred()) {
1819       DiagnoseUnusedDecl(D);
1820       if (const auto *RD = dyn_cast<RecordDecl>(D))
1821         DiagnoseUnusedNestedTypedefs(RD);
1822     }
1823 
1824     if (!D->getDeclName()) continue;
1825 
1826     // If this was a forward reference to a label, verify it was defined.
1827     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1828       CheckPoppedLabel(LD, *this);
1829 
1830     // Remove this name from our lexical scope, and warn on it if we haven't
1831     // already.
1832     IdResolver.RemoveDecl(D);
1833     auto ShadowI = ShadowingDecls.find(D);
1834     if (ShadowI != ShadowingDecls.end()) {
1835       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1836         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1837             << D << FD << FD->getParent();
1838         Diag(FD->getLocation(), diag::note_previous_declaration);
1839       }
1840       ShadowingDecls.erase(ShadowI);
1841     }
1842   }
1843 }
1844 
1845 /// Look for an Objective-C class in the translation unit.
1846 ///
1847 /// \param Id The name of the Objective-C class we're looking for. If
1848 /// typo-correction fixes this name, the Id will be updated
1849 /// to the fixed name.
1850 ///
1851 /// \param IdLoc The location of the name in the translation unit.
1852 ///
1853 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1854 /// if there is no class with the given name.
1855 ///
1856 /// \returns The declaration of the named Objective-C class, or NULL if the
1857 /// class could not be found.
1858 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1859                                               SourceLocation IdLoc,
1860                                               bool DoTypoCorrection) {
1861   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1862   // creation from this context.
1863   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1864 
1865   if (!IDecl && DoTypoCorrection) {
1866     // Perform typo correction at the given location, but only if we
1867     // find an Objective-C class name.
1868     if (TypoCorrection C = CorrectTypo(
1869             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1870             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1871             CTK_ErrorRecovery)) {
1872       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1873       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1874       Id = IDecl->getIdentifier();
1875     }
1876   }
1877   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1878   // This routine must always return a class definition, if any.
1879   if (Def && Def->getDefinition())
1880       Def = Def->getDefinition();
1881   return Def;
1882 }
1883 
1884 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1885 /// from S, where a non-field would be declared. This routine copes
1886 /// with the difference between C and C++ scoping rules in structs and
1887 /// unions. For example, the following code is well-formed in C but
1888 /// ill-formed in C++:
1889 /// @code
1890 /// struct S6 {
1891 ///   enum { BAR } e;
1892 /// };
1893 ///
1894 /// void test_S6() {
1895 ///   struct S6 a;
1896 ///   a.e = BAR;
1897 /// }
1898 /// @endcode
1899 /// For the declaration of BAR, this routine will return a different
1900 /// scope. The scope S will be the scope of the unnamed enumeration
1901 /// within S6. In C++, this routine will return the scope associated
1902 /// with S6, because the enumeration's scope is a transparent
1903 /// context but structures can contain non-field names. In C, this
1904 /// routine will return the translation unit scope, since the
1905 /// enumeration's scope is a transparent context and structures cannot
1906 /// contain non-field names.
1907 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1908   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1909          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1910          (S->isClassScope() && !getLangOpts().CPlusPlus))
1911     S = S->getParent();
1912   return S;
1913 }
1914 
1915 /// Looks up the declaration of "struct objc_super" and
1916 /// saves it for later use in building builtin declaration of
1917 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1918 /// pre-existing declaration exists no action takes place.
1919 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1920                                         IdentifierInfo *II) {
1921   if (!II->isStr("objc_msgSendSuper"))
1922     return;
1923   ASTContext &Context = ThisSema.Context;
1924 
1925   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1926                       SourceLocation(), Sema::LookupTagName);
1927   ThisSema.LookupName(Result, S);
1928   if (Result.getResultKind() == LookupResult::Found)
1929     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1930       Context.setObjCSuperType(Context.getTagDeclType(TD));
1931 }
1932 
1933 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
1934                                ASTContext::GetBuiltinTypeError Error) {
1935   switch (Error) {
1936   case ASTContext::GE_None:
1937     return "";
1938   case ASTContext::GE_Missing_type:
1939     return BuiltinInfo.getHeaderName(ID);
1940   case ASTContext::GE_Missing_stdio:
1941     return "stdio.h";
1942   case ASTContext::GE_Missing_setjmp:
1943     return "setjmp.h";
1944   case ASTContext::GE_Missing_ucontext:
1945     return "ucontext.h";
1946   }
1947   llvm_unreachable("unhandled error kind");
1948 }
1949 
1950 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1951 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1952 /// if we're creating this built-in in anticipation of redeclaring the
1953 /// built-in.
1954 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1955                                      Scope *S, bool ForRedeclaration,
1956                                      SourceLocation Loc) {
1957   LookupPredefedObjCSuperType(*this, S, II);
1958 
1959   ASTContext::GetBuiltinTypeError Error;
1960   QualType R = Context.GetBuiltinType(ID, Error);
1961   if (Error) {
1962     if (ForRedeclaration)
1963       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1964           << getHeaderName(Context.BuiltinInfo, ID, Error)
1965           << Context.BuiltinInfo.getName(ID);
1966     return nullptr;
1967   }
1968 
1969   if (!ForRedeclaration &&
1970       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1971        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1972     Diag(Loc, diag::ext_implicit_lib_function_decl)
1973         << Context.BuiltinInfo.getName(ID) << R;
1974     if (Context.BuiltinInfo.getHeaderName(ID) &&
1975         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1976       Diag(Loc, diag::note_include_header_or_declare)
1977           << Context.BuiltinInfo.getHeaderName(ID)
1978           << Context.BuiltinInfo.getName(ID);
1979   }
1980 
1981   if (R.isNull())
1982     return nullptr;
1983 
1984   DeclContext *Parent = Context.getTranslationUnitDecl();
1985   if (getLangOpts().CPlusPlus) {
1986     LinkageSpecDecl *CLinkageDecl =
1987         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1988                                 LinkageSpecDecl::lang_c, false);
1989     CLinkageDecl->setImplicit();
1990     Parent->addDecl(CLinkageDecl);
1991     Parent = CLinkageDecl;
1992   }
1993 
1994   FunctionDecl *New = FunctionDecl::Create(Context,
1995                                            Parent,
1996                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1997                                            SC_Extern,
1998                                            false,
1999                                            R->isFunctionProtoType());
2000   New->setImplicit();
2001 
2002   // Create Decl objects for each parameter, adding them to the
2003   // FunctionDecl.
2004   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2005     SmallVector<ParmVarDecl*, 16> Params;
2006     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2007       ParmVarDecl *parm =
2008           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2009                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2010                               SC_None, nullptr);
2011       parm->setScopeInfo(0, i);
2012       Params.push_back(parm);
2013     }
2014     New->setParams(Params);
2015   }
2016 
2017   AddKnownFunctionAttributes(New);
2018   RegisterLocallyScopedExternCDecl(New, S);
2019 
2020   // TUScope is the translation-unit scope to insert this function into.
2021   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2022   // relate Scopes to DeclContexts, and probably eliminate CurContext
2023   // entirely, but we're not there yet.
2024   DeclContext *SavedContext = CurContext;
2025   CurContext = Parent;
2026   PushOnScopeChains(New, TUScope);
2027   CurContext = SavedContext;
2028   return New;
2029 }
2030 
2031 /// Typedef declarations don't have linkage, but they still denote the same
2032 /// entity if their types are the same.
2033 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2034 /// isSameEntity.
2035 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2036                                                      TypedefNameDecl *Decl,
2037                                                      LookupResult &Previous) {
2038   // This is only interesting when modules are enabled.
2039   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2040     return;
2041 
2042   // Empty sets are uninteresting.
2043   if (Previous.empty())
2044     return;
2045 
2046   LookupResult::Filter Filter = Previous.makeFilter();
2047   while (Filter.hasNext()) {
2048     NamedDecl *Old = Filter.next();
2049 
2050     // Non-hidden declarations are never ignored.
2051     if (S.isVisible(Old))
2052       continue;
2053 
2054     // Declarations of the same entity are not ignored, even if they have
2055     // different linkages.
2056     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2057       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2058                                 Decl->getUnderlyingType()))
2059         continue;
2060 
2061       // If both declarations give a tag declaration a typedef name for linkage
2062       // purposes, then they declare the same entity.
2063       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2064           Decl->getAnonDeclWithTypedefName())
2065         continue;
2066     }
2067 
2068     Filter.erase();
2069   }
2070 
2071   Filter.done();
2072 }
2073 
2074 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2075   QualType OldType;
2076   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2077     OldType = OldTypedef->getUnderlyingType();
2078   else
2079     OldType = Context.getTypeDeclType(Old);
2080   QualType NewType = New->getUnderlyingType();
2081 
2082   if (NewType->isVariablyModifiedType()) {
2083     // Must not redefine a typedef with a variably-modified type.
2084     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2085     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2086       << Kind << NewType;
2087     if (Old->getLocation().isValid())
2088       notePreviousDefinition(Old, New->getLocation());
2089     New->setInvalidDecl();
2090     return true;
2091   }
2092 
2093   if (OldType != NewType &&
2094       !OldType->isDependentType() &&
2095       !NewType->isDependentType() &&
2096       !Context.hasSameType(OldType, NewType)) {
2097     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2098     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2099       << Kind << NewType << OldType;
2100     if (Old->getLocation().isValid())
2101       notePreviousDefinition(Old, New->getLocation());
2102     New->setInvalidDecl();
2103     return true;
2104   }
2105   return false;
2106 }
2107 
2108 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2109 /// same name and scope as a previous declaration 'Old'.  Figure out
2110 /// how to resolve this situation, merging decls or emitting
2111 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2112 ///
2113 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2114                                 LookupResult &OldDecls) {
2115   // If the new decl is known invalid already, don't bother doing any
2116   // merging checks.
2117   if (New->isInvalidDecl()) return;
2118 
2119   // Allow multiple definitions for ObjC built-in typedefs.
2120   // FIXME: Verify the underlying types are equivalent!
2121   if (getLangOpts().ObjC) {
2122     const IdentifierInfo *TypeID = New->getIdentifier();
2123     switch (TypeID->getLength()) {
2124     default: break;
2125     case 2:
2126       {
2127         if (!TypeID->isStr("id"))
2128           break;
2129         QualType T = New->getUnderlyingType();
2130         if (!T->isPointerType())
2131           break;
2132         if (!T->isVoidPointerType()) {
2133           QualType PT = T->getAs<PointerType>()->getPointeeType();
2134           if (!PT->isStructureType())
2135             break;
2136         }
2137         Context.setObjCIdRedefinitionType(T);
2138         // Install the built-in type for 'id', ignoring the current definition.
2139         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2140         return;
2141       }
2142     case 5:
2143       if (!TypeID->isStr("Class"))
2144         break;
2145       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2146       // Install the built-in type for 'Class', ignoring the current definition.
2147       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2148       return;
2149     case 3:
2150       if (!TypeID->isStr("SEL"))
2151         break;
2152       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2153       // Install the built-in type for 'SEL', ignoring the current definition.
2154       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2155       return;
2156     }
2157     // Fall through - the typedef name was not a builtin type.
2158   }
2159 
2160   // Verify the old decl was also a type.
2161   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2162   if (!Old) {
2163     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2164       << New->getDeclName();
2165 
2166     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2167     if (OldD->getLocation().isValid())
2168       notePreviousDefinition(OldD, New->getLocation());
2169 
2170     return New->setInvalidDecl();
2171   }
2172 
2173   // If the old declaration is invalid, just give up here.
2174   if (Old->isInvalidDecl())
2175     return New->setInvalidDecl();
2176 
2177   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2178     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2179     auto *NewTag = New->getAnonDeclWithTypedefName();
2180     NamedDecl *Hidden = nullptr;
2181     if (OldTag && NewTag &&
2182         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2183         !hasVisibleDefinition(OldTag, &Hidden)) {
2184       // There is a definition of this tag, but it is not visible. Use it
2185       // instead of our tag.
2186       New->setTypeForDecl(OldTD->getTypeForDecl());
2187       if (OldTD->isModed())
2188         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2189                                     OldTD->getUnderlyingType());
2190       else
2191         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2192 
2193       // Make the old tag definition visible.
2194       makeMergedDefinitionVisible(Hidden);
2195 
2196       // If this was an unscoped enumeration, yank all of its enumerators
2197       // out of the scope.
2198       if (isa<EnumDecl>(NewTag)) {
2199         Scope *EnumScope = getNonFieldDeclScope(S);
2200         for (auto *D : NewTag->decls()) {
2201           auto *ED = cast<EnumConstantDecl>(D);
2202           assert(EnumScope->isDeclScope(ED));
2203           EnumScope->RemoveDecl(ED);
2204           IdResolver.RemoveDecl(ED);
2205           ED->getLexicalDeclContext()->removeDecl(ED);
2206         }
2207       }
2208     }
2209   }
2210 
2211   // If the typedef types are not identical, reject them in all languages and
2212   // with any extensions enabled.
2213   if (isIncompatibleTypedef(Old, New))
2214     return;
2215 
2216   // The types match.  Link up the redeclaration chain and merge attributes if
2217   // the old declaration was a typedef.
2218   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2219     New->setPreviousDecl(Typedef);
2220     mergeDeclAttributes(New, Old);
2221   }
2222 
2223   if (getLangOpts().MicrosoftExt)
2224     return;
2225 
2226   if (getLangOpts().CPlusPlus) {
2227     // C++ [dcl.typedef]p2:
2228     //   In a given non-class scope, a typedef specifier can be used to
2229     //   redefine the name of any type declared in that scope to refer
2230     //   to the type to which it already refers.
2231     if (!isa<CXXRecordDecl>(CurContext))
2232       return;
2233 
2234     // C++0x [dcl.typedef]p4:
2235     //   In a given class scope, a typedef specifier can be used to redefine
2236     //   any class-name declared in that scope that is not also a typedef-name
2237     //   to refer to the type to which it already refers.
2238     //
2239     // This wording came in via DR424, which was a correction to the
2240     // wording in DR56, which accidentally banned code like:
2241     //
2242     //   struct S {
2243     //     typedef struct A { } A;
2244     //   };
2245     //
2246     // in the C++03 standard. We implement the C++0x semantics, which
2247     // allow the above but disallow
2248     //
2249     //   struct S {
2250     //     typedef int I;
2251     //     typedef int I;
2252     //   };
2253     //
2254     // since that was the intent of DR56.
2255     if (!isa<TypedefNameDecl>(Old))
2256       return;
2257 
2258     Diag(New->getLocation(), diag::err_redefinition)
2259       << New->getDeclName();
2260     notePreviousDefinition(Old, New->getLocation());
2261     return New->setInvalidDecl();
2262   }
2263 
2264   // Modules always permit redefinition of typedefs, as does C11.
2265   if (getLangOpts().Modules || getLangOpts().C11)
2266     return;
2267 
2268   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2269   // is normally mapped to an error, but can be controlled with
2270   // -Wtypedef-redefinition.  If either the original or the redefinition is
2271   // in a system header, don't emit this for compatibility with GCC.
2272   if (getDiagnostics().getSuppressSystemWarnings() &&
2273       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2274       (Old->isImplicit() ||
2275        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2276        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2277     return;
2278 
2279   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2280     << New->getDeclName();
2281   notePreviousDefinition(Old, New->getLocation());
2282 }
2283 
2284 /// DeclhasAttr - returns true if decl Declaration already has the target
2285 /// attribute.
2286 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2287   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2288   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2289   for (const auto *i : D->attrs())
2290     if (i->getKind() == A->getKind()) {
2291       if (Ann) {
2292         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2293           return true;
2294         continue;
2295       }
2296       // FIXME: Don't hardcode this check
2297       if (OA && isa<OwnershipAttr>(i))
2298         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2299       return true;
2300     }
2301 
2302   return false;
2303 }
2304 
2305 static bool isAttributeTargetADefinition(Decl *D) {
2306   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2307     return VD->isThisDeclarationADefinition();
2308   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2309     return TD->isCompleteDefinition() || TD->isBeingDefined();
2310   return true;
2311 }
2312 
2313 /// Merge alignment attributes from \p Old to \p New, taking into account the
2314 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2315 ///
2316 /// \return \c true if any attributes were added to \p New.
2317 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2318   // Look for alignas attributes on Old, and pick out whichever attribute
2319   // specifies the strictest alignment requirement.
2320   AlignedAttr *OldAlignasAttr = nullptr;
2321   AlignedAttr *OldStrictestAlignAttr = nullptr;
2322   unsigned OldAlign = 0;
2323   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2324     // FIXME: We have no way of representing inherited dependent alignments
2325     // in a case like:
2326     //   template<int A, int B> struct alignas(A) X;
2327     //   template<int A, int B> struct alignas(B) X {};
2328     // For now, we just ignore any alignas attributes which are not on the
2329     // definition in such a case.
2330     if (I->isAlignmentDependent())
2331       return false;
2332 
2333     if (I->isAlignas())
2334       OldAlignasAttr = I;
2335 
2336     unsigned Align = I->getAlignment(S.Context);
2337     if (Align > OldAlign) {
2338       OldAlign = Align;
2339       OldStrictestAlignAttr = I;
2340     }
2341   }
2342 
2343   // Look for alignas attributes on New.
2344   AlignedAttr *NewAlignasAttr = nullptr;
2345   unsigned NewAlign = 0;
2346   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2347     if (I->isAlignmentDependent())
2348       return false;
2349 
2350     if (I->isAlignas())
2351       NewAlignasAttr = I;
2352 
2353     unsigned Align = I->getAlignment(S.Context);
2354     if (Align > NewAlign)
2355       NewAlign = Align;
2356   }
2357 
2358   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2359     // Both declarations have 'alignas' attributes. We require them to match.
2360     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2361     // fall short. (If two declarations both have alignas, they must both match
2362     // every definition, and so must match each other if there is a definition.)
2363 
2364     // If either declaration only contains 'alignas(0)' specifiers, then it
2365     // specifies the natural alignment for the type.
2366     if (OldAlign == 0 || NewAlign == 0) {
2367       QualType Ty;
2368       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2369         Ty = VD->getType();
2370       else
2371         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2372 
2373       if (OldAlign == 0)
2374         OldAlign = S.Context.getTypeAlign(Ty);
2375       if (NewAlign == 0)
2376         NewAlign = S.Context.getTypeAlign(Ty);
2377     }
2378 
2379     if (OldAlign != NewAlign) {
2380       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2381         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2382         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2383       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2384     }
2385   }
2386 
2387   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2388     // C++11 [dcl.align]p6:
2389     //   if any declaration of an entity has an alignment-specifier,
2390     //   every defining declaration of that entity shall specify an
2391     //   equivalent alignment.
2392     // C11 6.7.5/7:
2393     //   If the definition of an object does not have an alignment
2394     //   specifier, any other declaration of that object shall also
2395     //   have no alignment specifier.
2396     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2397       << OldAlignasAttr;
2398     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2399       << OldAlignasAttr;
2400   }
2401 
2402   bool AnyAdded = false;
2403 
2404   // Ensure we have an attribute representing the strictest alignment.
2405   if (OldAlign > NewAlign) {
2406     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2407     Clone->setInherited(true);
2408     New->addAttr(Clone);
2409     AnyAdded = true;
2410   }
2411 
2412   // Ensure we have an alignas attribute if the old declaration had one.
2413   if (OldAlignasAttr && !NewAlignasAttr &&
2414       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2415     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2416     Clone->setInherited(true);
2417     New->addAttr(Clone);
2418     AnyAdded = true;
2419   }
2420 
2421   return AnyAdded;
2422 }
2423 
2424 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2425                                const InheritableAttr *Attr,
2426                                Sema::AvailabilityMergeKind AMK) {
2427   // This function copies an attribute Attr from a previous declaration to the
2428   // new declaration D if the new declaration doesn't itself have that attribute
2429   // yet or if that attribute allows duplicates.
2430   // If you're adding a new attribute that requires logic different from
2431   // "use explicit attribute on decl if present, else use attribute from
2432   // previous decl", for example if the attribute needs to be consistent
2433   // between redeclarations, you need to call a custom merge function here.
2434   InheritableAttr *NewAttr = nullptr;
2435   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2436   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2437     NewAttr = S.mergeAvailabilityAttr(
2438         D, AA->getRange(), AA->getPlatform(), AA->isImplicit(),
2439         AA->getIntroduced(), AA->getDeprecated(), AA->getObsoleted(),
2440         AA->getUnavailable(), AA->getMessage(), AA->getStrict(),
2441         AA->getReplacement(), AMK, AA->getPriority(), AttrSpellingListIndex);
2442   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2443     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2444                                     AttrSpellingListIndex);
2445   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2446     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2447                                         AttrSpellingListIndex);
2448   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2449     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2450                                    AttrSpellingListIndex);
2451   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2452     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2453                                    AttrSpellingListIndex);
2454   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2455     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2456                                 FA->getFormatIdx(), FA->getFirstArg(),
2457                                 AttrSpellingListIndex);
2458   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2459     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2460                                  AttrSpellingListIndex);
2461   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2462     NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(),
2463                                  AttrSpellingListIndex);
2464   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2465     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2466                                        AttrSpellingListIndex,
2467                                        IA->getSemanticSpelling());
2468   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2469     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2470                                       &S.Context.Idents.get(AA->getSpelling()),
2471                                       AttrSpellingListIndex);
2472   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2473            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2474             isa<CUDAGlobalAttr>(Attr))) {
2475     // CUDA target attributes are part of function signature for
2476     // overloading purposes and must not be merged.
2477     return false;
2478   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2479     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2480   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2481     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2482   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2483     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2484   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2485     NewAttr = S.mergeCommonAttr(D, *CommonA);
2486   else if (isa<AlignedAttr>(Attr))
2487     // AlignedAttrs are handled separately, because we need to handle all
2488     // such attributes on a declaration at the same time.
2489     NewAttr = nullptr;
2490   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2491            (AMK == Sema::AMK_Override ||
2492             AMK == Sema::AMK_ProtocolImplementation))
2493     NewAttr = nullptr;
2494   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2495     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2496                               UA->getGuid());
2497   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2498     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2499   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2500     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2501   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2502     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2503 
2504   if (NewAttr) {
2505     NewAttr->setInherited(true);
2506     D->addAttr(NewAttr);
2507     if (isa<MSInheritanceAttr>(NewAttr))
2508       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2509     return true;
2510   }
2511 
2512   return false;
2513 }
2514 
2515 static const NamedDecl *getDefinition(const Decl *D) {
2516   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2517     return TD->getDefinition();
2518   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2519     const VarDecl *Def = VD->getDefinition();
2520     if (Def)
2521       return Def;
2522     return VD->getActingDefinition();
2523   }
2524   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2525     return FD->getDefinition();
2526   return nullptr;
2527 }
2528 
2529 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2530   for (const auto *Attribute : D->attrs())
2531     if (Attribute->getKind() == Kind)
2532       return true;
2533   return false;
2534 }
2535 
2536 /// checkNewAttributesAfterDef - If we already have a definition, check that
2537 /// there are no new attributes in this declaration.
2538 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2539   if (!New->hasAttrs())
2540     return;
2541 
2542   const NamedDecl *Def = getDefinition(Old);
2543   if (!Def || Def == New)
2544     return;
2545 
2546   AttrVec &NewAttributes = New->getAttrs();
2547   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2548     const Attr *NewAttribute = NewAttributes[I];
2549 
2550     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2551       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2552         Sema::SkipBodyInfo SkipBody;
2553         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2554 
2555         // If we're skipping this definition, drop the "alias" attribute.
2556         if (SkipBody.ShouldSkip) {
2557           NewAttributes.erase(NewAttributes.begin() + I);
2558           --E;
2559           continue;
2560         }
2561       } else {
2562         VarDecl *VD = cast<VarDecl>(New);
2563         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2564                                 VarDecl::TentativeDefinition
2565                             ? diag::err_alias_after_tentative
2566                             : diag::err_redefinition;
2567         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2568         if (Diag == diag::err_redefinition)
2569           S.notePreviousDefinition(Def, VD->getLocation());
2570         else
2571           S.Diag(Def->getLocation(), diag::note_previous_definition);
2572         VD->setInvalidDecl();
2573       }
2574       ++I;
2575       continue;
2576     }
2577 
2578     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2579       // Tentative definitions are only interesting for the alias check above.
2580       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2581         ++I;
2582         continue;
2583       }
2584     }
2585 
2586     if (hasAttribute(Def, NewAttribute->getKind())) {
2587       ++I;
2588       continue; // regular attr merging will take care of validating this.
2589     }
2590 
2591     if (isa<C11NoReturnAttr>(NewAttribute)) {
2592       // C's _Noreturn is allowed to be added to a function after it is defined.
2593       ++I;
2594       continue;
2595     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2596       if (AA->isAlignas()) {
2597         // C++11 [dcl.align]p6:
2598         //   if any declaration of an entity has an alignment-specifier,
2599         //   every defining declaration of that entity shall specify an
2600         //   equivalent alignment.
2601         // C11 6.7.5/7:
2602         //   If the definition of an object does not have an alignment
2603         //   specifier, any other declaration of that object shall also
2604         //   have no alignment specifier.
2605         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2606           << AA;
2607         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2608           << AA;
2609         NewAttributes.erase(NewAttributes.begin() + I);
2610         --E;
2611         continue;
2612       }
2613     }
2614 
2615     S.Diag(NewAttribute->getLocation(),
2616            diag::warn_attribute_precede_definition);
2617     S.Diag(Def->getLocation(), diag::note_previous_definition);
2618     NewAttributes.erase(NewAttributes.begin() + I);
2619     --E;
2620   }
2621 }
2622 
2623 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2624 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2625                                AvailabilityMergeKind AMK) {
2626   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2627     UsedAttr *NewAttr = OldAttr->clone(Context);
2628     NewAttr->setInherited(true);
2629     New->addAttr(NewAttr);
2630   }
2631 
2632   if (!Old->hasAttrs() && !New->hasAttrs())
2633     return;
2634 
2635   // Attributes declared post-definition are currently ignored.
2636   checkNewAttributesAfterDef(*this, New, Old);
2637 
2638   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2639     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2640       if (OldA->getLabel() != NewA->getLabel()) {
2641         // This redeclaration changes __asm__ label.
2642         Diag(New->getLocation(), diag::err_different_asm_label);
2643         Diag(OldA->getLocation(), diag::note_previous_declaration);
2644       }
2645     } else if (Old->isUsed()) {
2646       // This redeclaration adds an __asm__ label to a declaration that has
2647       // already been ODR-used.
2648       Diag(New->getLocation(), diag::err_late_asm_label_name)
2649         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2650     }
2651   }
2652 
2653   // Re-declaration cannot add abi_tag's.
2654   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2655     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2656       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2657         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2658                       NewTag) == OldAbiTagAttr->tags_end()) {
2659           Diag(NewAbiTagAttr->getLocation(),
2660                diag::err_new_abi_tag_on_redeclaration)
2661               << NewTag;
2662           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2663         }
2664       }
2665     } else {
2666       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2667       Diag(Old->getLocation(), diag::note_previous_declaration);
2668     }
2669   }
2670 
2671   // This redeclaration adds a section attribute.
2672   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2673     if (auto *VD = dyn_cast<VarDecl>(New)) {
2674       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2675         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2676         Diag(Old->getLocation(), diag::note_previous_declaration);
2677       }
2678     }
2679   }
2680 
2681   // Redeclaration adds code-seg attribute.
2682   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2683   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2684       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2685     Diag(New->getLocation(), diag::warn_mismatched_section)
2686          << 0 /*codeseg*/;
2687     Diag(Old->getLocation(), diag::note_previous_declaration);
2688   }
2689 
2690   if (!Old->hasAttrs())
2691     return;
2692 
2693   bool foundAny = New->hasAttrs();
2694 
2695   // Ensure that any moving of objects within the allocated map is done before
2696   // we process them.
2697   if (!foundAny) New->setAttrs(AttrVec());
2698 
2699   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2700     // Ignore deprecated/unavailable/availability attributes if requested.
2701     AvailabilityMergeKind LocalAMK = AMK_None;
2702     if (isa<DeprecatedAttr>(I) ||
2703         isa<UnavailableAttr>(I) ||
2704         isa<AvailabilityAttr>(I)) {
2705       switch (AMK) {
2706       case AMK_None:
2707         continue;
2708 
2709       case AMK_Redeclaration:
2710       case AMK_Override:
2711       case AMK_ProtocolImplementation:
2712         LocalAMK = AMK;
2713         break;
2714       }
2715     }
2716 
2717     // Already handled.
2718     if (isa<UsedAttr>(I))
2719       continue;
2720 
2721     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2722       foundAny = true;
2723   }
2724 
2725   if (mergeAlignedAttrs(*this, New, Old))
2726     foundAny = true;
2727 
2728   if (!foundAny) New->dropAttrs();
2729 }
2730 
2731 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2732 /// to the new one.
2733 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2734                                      const ParmVarDecl *oldDecl,
2735                                      Sema &S) {
2736   // C++11 [dcl.attr.depend]p2:
2737   //   The first declaration of a function shall specify the
2738   //   carries_dependency attribute for its declarator-id if any declaration
2739   //   of the function specifies the carries_dependency attribute.
2740   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2741   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2742     S.Diag(CDA->getLocation(),
2743            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2744     // Find the first declaration of the parameter.
2745     // FIXME: Should we build redeclaration chains for function parameters?
2746     const FunctionDecl *FirstFD =
2747       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2748     const ParmVarDecl *FirstVD =
2749       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2750     S.Diag(FirstVD->getLocation(),
2751            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2752   }
2753 
2754   if (!oldDecl->hasAttrs())
2755     return;
2756 
2757   bool foundAny = newDecl->hasAttrs();
2758 
2759   // Ensure that any moving of objects within the allocated map is
2760   // done before we process them.
2761   if (!foundAny) newDecl->setAttrs(AttrVec());
2762 
2763   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2764     if (!DeclHasAttr(newDecl, I)) {
2765       InheritableAttr *newAttr =
2766         cast<InheritableParamAttr>(I->clone(S.Context));
2767       newAttr->setInherited(true);
2768       newDecl->addAttr(newAttr);
2769       foundAny = true;
2770     }
2771   }
2772 
2773   if (!foundAny) newDecl->dropAttrs();
2774 }
2775 
2776 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2777                                 const ParmVarDecl *OldParam,
2778                                 Sema &S) {
2779   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2780     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2781       if (*Oldnullability != *Newnullability) {
2782         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2783           << DiagNullabilityKind(
2784                *Newnullability,
2785                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2786                 != 0))
2787           << DiagNullabilityKind(
2788                *Oldnullability,
2789                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2790                 != 0));
2791         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2792       }
2793     } else {
2794       QualType NewT = NewParam->getType();
2795       NewT = S.Context.getAttributedType(
2796                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2797                          NewT, NewT);
2798       NewParam->setType(NewT);
2799     }
2800   }
2801 }
2802 
2803 namespace {
2804 
2805 /// Used in MergeFunctionDecl to keep track of function parameters in
2806 /// C.
2807 struct GNUCompatibleParamWarning {
2808   ParmVarDecl *OldParm;
2809   ParmVarDecl *NewParm;
2810   QualType PromotedType;
2811 };
2812 
2813 } // end anonymous namespace
2814 
2815 /// getSpecialMember - get the special member enum for a method.
2816 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2817   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2818     if (Ctor->isDefaultConstructor())
2819       return Sema::CXXDefaultConstructor;
2820 
2821     if (Ctor->isCopyConstructor())
2822       return Sema::CXXCopyConstructor;
2823 
2824     if (Ctor->isMoveConstructor())
2825       return Sema::CXXMoveConstructor;
2826   } else if (isa<CXXDestructorDecl>(MD)) {
2827     return Sema::CXXDestructor;
2828   } else if (MD->isCopyAssignmentOperator()) {
2829     return Sema::CXXCopyAssignment;
2830   } else if (MD->isMoveAssignmentOperator()) {
2831     return Sema::CXXMoveAssignment;
2832   }
2833 
2834   return Sema::CXXInvalid;
2835 }
2836 
2837 // Determine whether the previous declaration was a definition, implicit
2838 // declaration, or a declaration.
2839 template <typename T>
2840 static std::pair<diag::kind, SourceLocation>
2841 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2842   diag::kind PrevDiag;
2843   SourceLocation OldLocation = Old->getLocation();
2844   if (Old->isThisDeclarationADefinition())
2845     PrevDiag = diag::note_previous_definition;
2846   else if (Old->isImplicit()) {
2847     PrevDiag = diag::note_previous_implicit_declaration;
2848     if (OldLocation.isInvalid())
2849       OldLocation = New->getLocation();
2850   } else
2851     PrevDiag = diag::note_previous_declaration;
2852   return std::make_pair(PrevDiag, OldLocation);
2853 }
2854 
2855 /// canRedefineFunction - checks if a function can be redefined. Currently,
2856 /// only extern inline functions can be redefined, and even then only in
2857 /// GNU89 mode.
2858 static bool canRedefineFunction(const FunctionDecl *FD,
2859                                 const LangOptions& LangOpts) {
2860   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2861           !LangOpts.CPlusPlus &&
2862           FD->isInlineSpecified() &&
2863           FD->getStorageClass() == SC_Extern);
2864 }
2865 
2866 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2867   const AttributedType *AT = T->getAs<AttributedType>();
2868   while (AT && !AT->isCallingConv())
2869     AT = AT->getModifiedType()->getAs<AttributedType>();
2870   return AT;
2871 }
2872 
2873 template <typename T>
2874 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2875   const DeclContext *DC = Old->getDeclContext();
2876   if (DC->isRecord())
2877     return false;
2878 
2879   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2880   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2881     return true;
2882   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2883     return true;
2884   return false;
2885 }
2886 
2887 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2888 static bool isExternC(VarTemplateDecl *) { return false; }
2889 
2890 /// Check whether a redeclaration of an entity introduced by a
2891 /// using-declaration is valid, given that we know it's not an overload
2892 /// (nor a hidden tag declaration).
2893 template<typename ExpectedDecl>
2894 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2895                                    ExpectedDecl *New) {
2896   // C++11 [basic.scope.declarative]p4:
2897   //   Given a set of declarations in a single declarative region, each of
2898   //   which specifies the same unqualified name,
2899   //   -- they shall all refer to the same entity, or all refer to functions
2900   //      and function templates; or
2901   //   -- exactly one declaration shall declare a class name or enumeration
2902   //      name that is not a typedef name and the other declarations shall all
2903   //      refer to the same variable or enumerator, or all refer to functions
2904   //      and function templates; in this case the class name or enumeration
2905   //      name is hidden (3.3.10).
2906 
2907   // C++11 [namespace.udecl]p14:
2908   //   If a function declaration in namespace scope or block scope has the
2909   //   same name and the same parameter-type-list as a function introduced
2910   //   by a using-declaration, and the declarations do not declare the same
2911   //   function, the program is ill-formed.
2912 
2913   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2914   if (Old &&
2915       !Old->getDeclContext()->getRedeclContext()->Equals(
2916           New->getDeclContext()->getRedeclContext()) &&
2917       !(isExternC(Old) && isExternC(New)))
2918     Old = nullptr;
2919 
2920   if (!Old) {
2921     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2922     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2923     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2924     return true;
2925   }
2926   return false;
2927 }
2928 
2929 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2930                                             const FunctionDecl *B) {
2931   assert(A->getNumParams() == B->getNumParams());
2932 
2933   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2934     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2935     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2936     if (AttrA == AttrB)
2937       return true;
2938     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
2939            AttrA->isDynamic() == AttrB->isDynamic();
2940   };
2941 
2942   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2943 }
2944 
2945 /// If necessary, adjust the semantic declaration context for a qualified
2946 /// declaration to name the correct inline namespace within the qualifier.
2947 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
2948                                                DeclaratorDecl *OldD) {
2949   // The only case where we need to update the DeclContext is when
2950   // redeclaration lookup for a qualified name finds a declaration
2951   // in an inline namespace within the context named by the qualifier:
2952   //
2953   //   inline namespace N { int f(); }
2954   //   int ::f(); // Sema DC needs adjusting from :: to N::.
2955   //
2956   // For unqualified declarations, the semantic context *can* change
2957   // along the redeclaration chain (for local extern declarations,
2958   // extern "C" declarations, and friend declarations in particular).
2959   if (!NewD->getQualifier())
2960     return;
2961 
2962   // NewD is probably already in the right context.
2963   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
2964   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
2965   if (NamedDC->Equals(SemaDC))
2966     return;
2967 
2968   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
2969           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
2970          "unexpected context for redeclaration");
2971 
2972   auto *LexDC = NewD->getLexicalDeclContext();
2973   auto FixSemaDC = [=](NamedDecl *D) {
2974     if (!D)
2975       return;
2976     D->setDeclContext(SemaDC);
2977     D->setLexicalDeclContext(LexDC);
2978   };
2979 
2980   FixSemaDC(NewD);
2981   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
2982     FixSemaDC(FD->getDescribedFunctionTemplate());
2983   else if (auto *VD = dyn_cast<VarDecl>(NewD))
2984     FixSemaDC(VD->getDescribedVarTemplate());
2985 }
2986 
2987 /// MergeFunctionDecl - We just parsed a function 'New' from
2988 /// declarator D which has the same name and scope as a previous
2989 /// declaration 'Old'.  Figure out how to resolve this situation,
2990 /// merging decls or emitting diagnostics as appropriate.
2991 ///
2992 /// In C++, New and Old must be declarations that are not
2993 /// overloaded. Use IsOverload to determine whether New and Old are
2994 /// overloaded, and to select the Old declaration that New should be
2995 /// merged with.
2996 ///
2997 /// Returns true if there was an error, false otherwise.
2998 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2999                              Scope *S, bool MergeTypeWithOld) {
3000   // Verify the old decl was also a function.
3001   FunctionDecl *Old = OldD->getAsFunction();
3002   if (!Old) {
3003     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3004       if (New->getFriendObjectKind()) {
3005         Diag(New->getLocation(), diag::err_using_decl_friend);
3006         Diag(Shadow->getTargetDecl()->getLocation(),
3007              diag::note_using_decl_target);
3008         Diag(Shadow->getUsingDecl()->getLocation(),
3009              diag::note_using_decl) << 0;
3010         return true;
3011       }
3012 
3013       // Check whether the two declarations might declare the same function.
3014       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3015         return true;
3016       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3017     } else {
3018       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3019         << New->getDeclName();
3020       notePreviousDefinition(OldD, New->getLocation());
3021       return true;
3022     }
3023   }
3024 
3025   // If the old declaration is invalid, just give up here.
3026   if (Old->isInvalidDecl())
3027     return true;
3028 
3029   // Disallow redeclaration of some builtins.
3030   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3031     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3032     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3033         << Old << Old->getType();
3034     return true;
3035   }
3036 
3037   diag::kind PrevDiag;
3038   SourceLocation OldLocation;
3039   std::tie(PrevDiag, OldLocation) =
3040       getNoteDiagForInvalidRedeclaration(Old, New);
3041 
3042   // Don't complain about this if we're in GNU89 mode and the old function
3043   // is an extern inline function.
3044   // Don't complain about specializations. They are not supposed to have
3045   // storage classes.
3046   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3047       New->getStorageClass() == SC_Static &&
3048       Old->hasExternalFormalLinkage() &&
3049       !New->getTemplateSpecializationInfo() &&
3050       !canRedefineFunction(Old, getLangOpts())) {
3051     if (getLangOpts().MicrosoftExt) {
3052       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3053       Diag(OldLocation, PrevDiag);
3054     } else {
3055       Diag(New->getLocation(), diag::err_static_non_static) << New;
3056       Diag(OldLocation, PrevDiag);
3057       return true;
3058     }
3059   }
3060 
3061   if (New->hasAttr<InternalLinkageAttr>() &&
3062       !Old->hasAttr<InternalLinkageAttr>()) {
3063     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3064         << New->getDeclName();
3065     notePreviousDefinition(Old, New->getLocation());
3066     New->dropAttr<InternalLinkageAttr>();
3067   }
3068 
3069   if (CheckRedeclarationModuleOwnership(New, Old))
3070     return true;
3071 
3072   if (!getLangOpts().CPlusPlus) {
3073     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3074     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3075       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3076         << New << OldOvl;
3077 
3078       // Try our best to find a decl that actually has the overloadable
3079       // attribute for the note. In most cases (e.g. programs with only one
3080       // broken declaration/definition), this won't matter.
3081       //
3082       // FIXME: We could do this if we juggled some extra state in
3083       // OverloadableAttr, rather than just removing it.
3084       const Decl *DiagOld = Old;
3085       if (OldOvl) {
3086         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3087           const auto *A = D->getAttr<OverloadableAttr>();
3088           return A && !A->isImplicit();
3089         });
3090         // If we've implicitly added *all* of the overloadable attrs to this
3091         // chain, emitting a "previous redecl" note is pointless.
3092         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3093       }
3094 
3095       if (DiagOld)
3096         Diag(DiagOld->getLocation(),
3097              diag::note_attribute_overloadable_prev_overload)
3098           << OldOvl;
3099 
3100       if (OldOvl)
3101         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3102       else
3103         New->dropAttr<OverloadableAttr>();
3104     }
3105   }
3106 
3107   // If a function is first declared with a calling convention, but is later
3108   // declared or defined without one, all following decls assume the calling
3109   // convention of the first.
3110   //
3111   // It's OK if a function is first declared without a calling convention,
3112   // but is later declared or defined with the default calling convention.
3113   //
3114   // To test if either decl has an explicit calling convention, we look for
3115   // AttributedType sugar nodes on the type as written.  If they are missing or
3116   // were canonicalized away, we assume the calling convention was implicit.
3117   //
3118   // Note also that we DO NOT return at this point, because we still have
3119   // other tests to run.
3120   QualType OldQType = Context.getCanonicalType(Old->getType());
3121   QualType NewQType = Context.getCanonicalType(New->getType());
3122   const FunctionType *OldType = cast<FunctionType>(OldQType);
3123   const FunctionType *NewType = cast<FunctionType>(NewQType);
3124   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3125   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3126   bool RequiresAdjustment = false;
3127 
3128   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3129     FunctionDecl *First = Old->getFirstDecl();
3130     const FunctionType *FT =
3131         First->getType().getCanonicalType()->castAs<FunctionType>();
3132     FunctionType::ExtInfo FI = FT->getExtInfo();
3133     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3134     if (!NewCCExplicit) {
3135       // Inherit the CC from the previous declaration if it was specified
3136       // there but not here.
3137       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3138       RequiresAdjustment = true;
3139     } else if (New->getBuiltinID()) {
3140       // Calling Conventions on a Builtin aren't really useful and setting a
3141       // default calling convention and cdecl'ing some builtin redeclarations is
3142       // common, so warn and ignore the calling convention on the redeclaration.
3143       Diag(New->getLocation(), diag::warn_cconv_ignored)
3144           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3145           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3146       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3147       RequiresAdjustment = true;
3148     } else {
3149       // Calling conventions aren't compatible, so complain.
3150       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3151       Diag(New->getLocation(), diag::err_cconv_change)
3152         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3153         << !FirstCCExplicit
3154         << (!FirstCCExplicit ? "" :
3155             FunctionType::getNameForCallConv(FI.getCC()));
3156 
3157       // Put the note on the first decl, since it is the one that matters.
3158       Diag(First->getLocation(), diag::note_previous_declaration);
3159       return true;
3160     }
3161   }
3162 
3163   // FIXME: diagnose the other way around?
3164   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3165     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3166     RequiresAdjustment = true;
3167   }
3168 
3169   // Merge regparm attribute.
3170   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3171       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3172     if (NewTypeInfo.getHasRegParm()) {
3173       Diag(New->getLocation(), diag::err_regparm_mismatch)
3174         << NewType->getRegParmType()
3175         << OldType->getRegParmType();
3176       Diag(OldLocation, diag::note_previous_declaration);
3177       return true;
3178     }
3179 
3180     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3181     RequiresAdjustment = true;
3182   }
3183 
3184   // Merge ns_returns_retained attribute.
3185   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3186     if (NewTypeInfo.getProducesResult()) {
3187       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3188           << "'ns_returns_retained'";
3189       Diag(OldLocation, diag::note_previous_declaration);
3190       return true;
3191     }
3192 
3193     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3194     RequiresAdjustment = true;
3195   }
3196 
3197   if (OldTypeInfo.getNoCallerSavedRegs() !=
3198       NewTypeInfo.getNoCallerSavedRegs()) {
3199     if (NewTypeInfo.getNoCallerSavedRegs()) {
3200       AnyX86NoCallerSavedRegistersAttr *Attr =
3201         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3202       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3203       Diag(OldLocation, diag::note_previous_declaration);
3204       return true;
3205     }
3206 
3207     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3208     RequiresAdjustment = true;
3209   }
3210 
3211   if (RequiresAdjustment) {
3212     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3213     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3214     New->setType(QualType(AdjustedType, 0));
3215     NewQType = Context.getCanonicalType(New->getType());
3216     NewType = cast<FunctionType>(NewQType);
3217   }
3218 
3219   // If this redeclaration makes the function inline, we may need to add it to
3220   // UndefinedButUsed.
3221   if (!Old->isInlined() && New->isInlined() &&
3222       !New->hasAttr<GNUInlineAttr>() &&
3223       !getLangOpts().GNUInline &&
3224       Old->isUsed(false) &&
3225       !Old->isDefined() && !New->isThisDeclarationADefinition())
3226     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3227                                            SourceLocation()));
3228 
3229   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3230   // about it.
3231   if (New->hasAttr<GNUInlineAttr>() &&
3232       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3233     UndefinedButUsed.erase(Old->getCanonicalDecl());
3234   }
3235 
3236   // If pass_object_size params don't match up perfectly, this isn't a valid
3237   // redeclaration.
3238   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3239       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3240     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3241         << New->getDeclName();
3242     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3243     return true;
3244   }
3245 
3246   if (getLangOpts().CPlusPlus) {
3247     // C++1z [over.load]p2
3248     //   Certain function declarations cannot be overloaded:
3249     //     -- Function declarations that differ only in the return type,
3250     //        the exception specification, or both cannot be overloaded.
3251 
3252     // Check the exception specifications match. This may recompute the type of
3253     // both Old and New if it resolved exception specifications, so grab the
3254     // types again after this. Because this updates the type, we do this before
3255     // any of the other checks below, which may update the "de facto" NewQType
3256     // but do not necessarily update the type of New.
3257     if (CheckEquivalentExceptionSpec(Old, New))
3258       return true;
3259     OldQType = Context.getCanonicalType(Old->getType());
3260     NewQType = Context.getCanonicalType(New->getType());
3261 
3262     // Go back to the type source info to compare the declared return types,
3263     // per C++1y [dcl.type.auto]p13:
3264     //   Redeclarations or specializations of a function or function template
3265     //   with a declared return type that uses a placeholder type shall also
3266     //   use that placeholder, not a deduced type.
3267     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3268     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3269     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3270         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3271                                        OldDeclaredReturnType)) {
3272       QualType ResQT;
3273       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3274           OldDeclaredReturnType->isObjCObjectPointerType())
3275         // FIXME: This does the wrong thing for a deduced return type.
3276         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3277       if (ResQT.isNull()) {
3278         if (New->isCXXClassMember() && New->isOutOfLine())
3279           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3280               << New << New->getReturnTypeSourceRange();
3281         else
3282           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3283               << New->getReturnTypeSourceRange();
3284         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3285                                     << Old->getReturnTypeSourceRange();
3286         return true;
3287       }
3288       else
3289         NewQType = ResQT;
3290     }
3291 
3292     QualType OldReturnType = OldType->getReturnType();
3293     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3294     if (OldReturnType != NewReturnType) {
3295       // If this function has a deduced return type and has already been
3296       // defined, copy the deduced value from the old declaration.
3297       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3298       if (OldAT && OldAT->isDeduced()) {
3299         New->setType(
3300             SubstAutoType(New->getType(),
3301                           OldAT->isDependentType() ? Context.DependentTy
3302                                                    : OldAT->getDeducedType()));
3303         NewQType = Context.getCanonicalType(
3304             SubstAutoType(NewQType,
3305                           OldAT->isDependentType() ? Context.DependentTy
3306                                                    : OldAT->getDeducedType()));
3307       }
3308     }
3309 
3310     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3311     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3312     if (OldMethod && NewMethod) {
3313       // Preserve triviality.
3314       NewMethod->setTrivial(OldMethod->isTrivial());
3315 
3316       // MSVC allows explicit template specialization at class scope:
3317       // 2 CXXMethodDecls referring to the same function will be injected.
3318       // We don't want a redeclaration error.
3319       bool IsClassScopeExplicitSpecialization =
3320                               OldMethod->isFunctionTemplateSpecialization() &&
3321                               NewMethod->isFunctionTemplateSpecialization();
3322       bool isFriend = NewMethod->getFriendObjectKind();
3323 
3324       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3325           !IsClassScopeExplicitSpecialization) {
3326         //    -- Member function declarations with the same name and the
3327         //       same parameter types cannot be overloaded if any of them
3328         //       is a static member function declaration.
3329         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3330           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3331           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3332           return true;
3333         }
3334 
3335         // C++ [class.mem]p1:
3336         //   [...] A member shall not be declared twice in the
3337         //   member-specification, except that a nested class or member
3338         //   class template can be declared and then later defined.
3339         if (!inTemplateInstantiation()) {
3340           unsigned NewDiag;
3341           if (isa<CXXConstructorDecl>(OldMethod))
3342             NewDiag = diag::err_constructor_redeclared;
3343           else if (isa<CXXDestructorDecl>(NewMethod))
3344             NewDiag = diag::err_destructor_redeclared;
3345           else if (isa<CXXConversionDecl>(NewMethod))
3346             NewDiag = diag::err_conv_function_redeclared;
3347           else
3348             NewDiag = diag::err_member_redeclared;
3349 
3350           Diag(New->getLocation(), NewDiag);
3351         } else {
3352           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3353             << New << New->getType();
3354         }
3355         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3356         return true;
3357 
3358       // Complain if this is an explicit declaration of a special
3359       // member that was initially declared implicitly.
3360       //
3361       // As an exception, it's okay to befriend such methods in order
3362       // to permit the implicit constructor/destructor/operator calls.
3363       } else if (OldMethod->isImplicit()) {
3364         if (isFriend) {
3365           NewMethod->setImplicit();
3366         } else {
3367           Diag(NewMethod->getLocation(),
3368                diag::err_definition_of_implicitly_declared_member)
3369             << New << getSpecialMember(OldMethod);
3370           return true;
3371         }
3372       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3373         Diag(NewMethod->getLocation(),
3374              diag::err_definition_of_explicitly_defaulted_member)
3375           << getSpecialMember(OldMethod);
3376         return true;
3377       }
3378     }
3379 
3380     // C++11 [dcl.attr.noreturn]p1:
3381     //   The first declaration of a function shall specify the noreturn
3382     //   attribute if any declaration of that function specifies the noreturn
3383     //   attribute.
3384     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3385     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3386       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3387       Diag(Old->getFirstDecl()->getLocation(),
3388            diag::note_noreturn_missing_first_decl);
3389     }
3390 
3391     // C++11 [dcl.attr.depend]p2:
3392     //   The first declaration of a function shall specify the
3393     //   carries_dependency attribute for its declarator-id if any declaration
3394     //   of the function specifies the carries_dependency attribute.
3395     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3396     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3397       Diag(CDA->getLocation(),
3398            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3399       Diag(Old->getFirstDecl()->getLocation(),
3400            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3401     }
3402 
3403     // (C++98 8.3.5p3):
3404     //   All declarations for a function shall agree exactly in both the
3405     //   return type and the parameter-type-list.
3406     // We also want to respect all the extended bits except noreturn.
3407 
3408     // noreturn should now match unless the old type info didn't have it.
3409     QualType OldQTypeForComparison = OldQType;
3410     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3411       auto *OldType = OldQType->castAs<FunctionProtoType>();
3412       const FunctionType *OldTypeForComparison
3413         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3414       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3415       assert(OldQTypeForComparison.isCanonical());
3416     }
3417 
3418     if (haveIncompatibleLanguageLinkages(Old, New)) {
3419       // As a special case, retain the language linkage from previous
3420       // declarations of a friend function as an extension.
3421       //
3422       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3423       // and is useful because there's otherwise no way to specify language
3424       // linkage within class scope.
3425       //
3426       // Check cautiously as the friend object kind isn't yet complete.
3427       if (New->getFriendObjectKind() != Decl::FOK_None) {
3428         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3429         Diag(OldLocation, PrevDiag);
3430       } else {
3431         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3432         Diag(OldLocation, PrevDiag);
3433         return true;
3434       }
3435     }
3436 
3437     if (OldQTypeForComparison == NewQType)
3438       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3439 
3440     // If the types are imprecise (due to dependent constructs in friends or
3441     // local extern declarations), it's OK if they differ. We'll check again
3442     // during instantiation.
3443     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3444       return false;
3445 
3446     // Fall through for conflicting redeclarations and redefinitions.
3447   }
3448 
3449   // C: Function types need to be compatible, not identical. This handles
3450   // duplicate function decls like "void f(int); void f(enum X);" properly.
3451   if (!getLangOpts().CPlusPlus &&
3452       Context.typesAreCompatible(OldQType, NewQType)) {
3453     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3454     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3455     const FunctionProtoType *OldProto = nullptr;
3456     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3457         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3458       // The old declaration provided a function prototype, but the
3459       // new declaration does not. Merge in the prototype.
3460       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3461       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3462       NewQType =
3463           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3464                                   OldProto->getExtProtoInfo());
3465       New->setType(NewQType);
3466       New->setHasInheritedPrototype();
3467 
3468       // Synthesize parameters with the same types.
3469       SmallVector<ParmVarDecl*, 16> Params;
3470       for (const auto &ParamType : OldProto->param_types()) {
3471         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3472                                                  SourceLocation(), nullptr,
3473                                                  ParamType, /*TInfo=*/nullptr,
3474                                                  SC_None, nullptr);
3475         Param->setScopeInfo(0, Params.size());
3476         Param->setImplicit();
3477         Params.push_back(Param);
3478       }
3479 
3480       New->setParams(Params);
3481     }
3482 
3483     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3484   }
3485 
3486   // GNU C permits a K&R definition to follow a prototype declaration
3487   // if the declared types of the parameters in the K&R definition
3488   // match the types in the prototype declaration, even when the
3489   // promoted types of the parameters from the K&R definition differ
3490   // from the types in the prototype. GCC then keeps the types from
3491   // the prototype.
3492   //
3493   // If a variadic prototype is followed by a non-variadic K&R definition,
3494   // the K&R definition becomes variadic.  This is sort of an edge case, but
3495   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3496   // C99 6.9.1p8.
3497   if (!getLangOpts().CPlusPlus &&
3498       Old->hasPrototype() && !New->hasPrototype() &&
3499       New->getType()->getAs<FunctionProtoType>() &&
3500       Old->getNumParams() == New->getNumParams()) {
3501     SmallVector<QualType, 16> ArgTypes;
3502     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3503     const FunctionProtoType *OldProto
3504       = Old->getType()->getAs<FunctionProtoType>();
3505     const FunctionProtoType *NewProto
3506       = New->getType()->getAs<FunctionProtoType>();
3507 
3508     // Determine whether this is the GNU C extension.
3509     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3510                                                NewProto->getReturnType());
3511     bool LooseCompatible = !MergedReturn.isNull();
3512     for (unsigned Idx = 0, End = Old->getNumParams();
3513          LooseCompatible && Idx != End; ++Idx) {
3514       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3515       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3516       if (Context.typesAreCompatible(OldParm->getType(),
3517                                      NewProto->getParamType(Idx))) {
3518         ArgTypes.push_back(NewParm->getType());
3519       } else if (Context.typesAreCompatible(OldParm->getType(),
3520                                             NewParm->getType(),
3521                                             /*CompareUnqualified=*/true)) {
3522         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3523                                            NewProto->getParamType(Idx) };
3524         Warnings.push_back(Warn);
3525         ArgTypes.push_back(NewParm->getType());
3526       } else
3527         LooseCompatible = false;
3528     }
3529 
3530     if (LooseCompatible) {
3531       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3532         Diag(Warnings[Warn].NewParm->getLocation(),
3533              diag::ext_param_promoted_not_compatible_with_prototype)
3534           << Warnings[Warn].PromotedType
3535           << Warnings[Warn].OldParm->getType();
3536         if (Warnings[Warn].OldParm->getLocation().isValid())
3537           Diag(Warnings[Warn].OldParm->getLocation(),
3538                diag::note_previous_declaration);
3539       }
3540 
3541       if (MergeTypeWithOld)
3542         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3543                                              OldProto->getExtProtoInfo()));
3544       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3545     }
3546 
3547     // Fall through to diagnose conflicting types.
3548   }
3549 
3550   // A function that has already been declared has been redeclared or
3551   // defined with a different type; show an appropriate diagnostic.
3552 
3553   // If the previous declaration was an implicitly-generated builtin
3554   // declaration, then at the very least we should use a specialized note.
3555   unsigned BuiltinID;
3556   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3557     // If it's actually a library-defined builtin function like 'malloc'
3558     // or 'printf', just warn about the incompatible redeclaration.
3559     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3560       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3561       Diag(OldLocation, diag::note_previous_builtin_declaration)
3562         << Old << Old->getType();
3563 
3564       // If this is a global redeclaration, just forget hereafter
3565       // about the "builtin-ness" of the function.
3566       //
3567       // Doing this for local extern declarations is problematic.  If
3568       // the builtin declaration remains visible, a second invalid
3569       // local declaration will produce a hard error; if it doesn't
3570       // remain visible, a single bogus local redeclaration (which is
3571       // actually only a warning) could break all the downstream code.
3572       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3573         New->getIdentifier()->revertBuiltin();
3574 
3575       return false;
3576     }
3577 
3578     PrevDiag = diag::note_previous_builtin_declaration;
3579   }
3580 
3581   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3582   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3583   return true;
3584 }
3585 
3586 /// Completes the merge of two function declarations that are
3587 /// known to be compatible.
3588 ///
3589 /// This routine handles the merging of attributes and other
3590 /// properties of function declarations from the old declaration to
3591 /// the new declaration, once we know that New is in fact a
3592 /// redeclaration of Old.
3593 ///
3594 /// \returns false
3595 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3596                                         Scope *S, bool MergeTypeWithOld) {
3597   // Merge the attributes
3598   mergeDeclAttributes(New, Old);
3599 
3600   // Merge "pure" flag.
3601   if (Old->isPure())
3602     New->setPure();
3603 
3604   // Merge "used" flag.
3605   if (Old->getMostRecentDecl()->isUsed(false))
3606     New->setIsUsed();
3607 
3608   // Merge attributes from the parameters.  These can mismatch with K&R
3609   // declarations.
3610   if (New->getNumParams() == Old->getNumParams())
3611       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3612         ParmVarDecl *NewParam = New->getParamDecl(i);
3613         ParmVarDecl *OldParam = Old->getParamDecl(i);
3614         mergeParamDeclAttributes(NewParam, OldParam, *this);
3615         mergeParamDeclTypes(NewParam, OldParam, *this);
3616       }
3617 
3618   if (getLangOpts().CPlusPlus)
3619     return MergeCXXFunctionDecl(New, Old, S);
3620 
3621   // Merge the function types so the we get the composite types for the return
3622   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3623   // was visible.
3624   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3625   if (!Merged.isNull() && MergeTypeWithOld)
3626     New->setType(Merged);
3627 
3628   return false;
3629 }
3630 
3631 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3632                                 ObjCMethodDecl *oldMethod) {
3633   // Merge the attributes, including deprecated/unavailable
3634   AvailabilityMergeKind MergeKind =
3635     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3636       ? AMK_ProtocolImplementation
3637       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3638                                                        : AMK_Override;
3639 
3640   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3641 
3642   // Merge attributes from the parameters.
3643   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3644                                        oe = oldMethod->param_end();
3645   for (ObjCMethodDecl::param_iterator
3646          ni = newMethod->param_begin(), ne = newMethod->param_end();
3647        ni != ne && oi != oe; ++ni, ++oi)
3648     mergeParamDeclAttributes(*ni, *oi, *this);
3649 
3650   CheckObjCMethodOverride(newMethod, oldMethod);
3651 }
3652 
3653 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3654   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3655 
3656   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3657          ? diag::err_redefinition_different_type
3658          : diag::err_redeclaration_different_type)
3659     << New->getDeclName() << New->getType() << Old->getType();
3660 
3661   diag::kind PrevDiag;
3662   SourceLocation OldLocation;
3663   std::tie(PrevDiag, OldLocation)
3664     = getNoteDiagForInvalidRedeclaration(Old, New);
3665   S.Diag(OldLocation, PrevDiag);
3666   New->setInvalidDecl();
3667 }
3668 
3669 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3670 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3671 /// emitting diagnostics as appropriate.
3672 ///
3673 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3674 /// to here in AddInitializerToDecl. We can't check them before the initializer
3675 /// is attached.
3676 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3677                              bool MergeTypeWithOld) {
3678   if (New->isInvalidDecl() || Old->isInvalidDecl())
3679     return;
3680 
3681   QualType MergedT;
3682   if (getLangOpts().CPlusPlus) {
3683     if (New->getType()->isUndeducedType()) {
3684       // We don't know what the new type is until the initializer is attached.
3685       return;
3686     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3687       // These could still be something that needs exception specs checked.
3688       return MergeVarDeclExceptionSpecs(New, Old);
3689     }
3690     // C++ [basic.link]p10:
3691     //   [...] the types specified by all declarations referring to a given
3692     //   object or function shall be identical, except that declarations for an
3693     //   array object can specify array types that differ by the presence or
3694     //   absence of a major array bound (8.3.4).
3695     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3696       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3697       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3698 
3699       // We are merging a variable declaration New into Old. If it has an array
3700       // bound, and that bound differs from Old's bound, we should diagnose the
3701       // mismatch.
3702       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3703         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3704              PrevVD = PrevVD->getPreviousDecl()) {
3705           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3706           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3707             continue;
3708 
3709           if (!Context.hasSameType(NewArray, PrevVDTy))
3710             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3711         }
3712       }
3713 
3714       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3715         if (Context.hasSameType(OldArray->getElementType(),
3716                                 NewArray->getElementType()))
3717           MergedT = New->getType();
3718       }
3719       // FIXME: Check visibility. New is hidden but has a complete type. If New
3720       // has no array bound, it should not inherit one from Old, if Old is not
3721       // visible.
3722       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3723         if (Context.hasSameType(OldArray->getElementType(),
3724                                 NewArray->getElementType()))
3725           MergedT = Old->getType();
3726       }
3727     }
3728     else if (New->getType()->isObjCObjectPointerType() &&
3729                Old->getType()->isObjCObjectPointerType()) {
3730       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3731                                               Old->getType());
3732     }
3733   } else {
3734     // C 6.2.7p2:
3735     //   All declarations that refer to the same object or function shall have
3736     //   compatible type.
3737     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3738   }
3739   if (MergedT.isNull()) {
3740     // It's OK if we couldn't merge types if either type is dependent, for a
3741     // block-scope variable. In other cases (static data members of class
3742     // templates, variable templates, ...), we require the types to be
3743     // equivalent.
3744     // FIXME: The C++ standard doesn't say anything about this.
3745     if ((New->getType()->isDependentType() ||
3746          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3747       // If the old type was dependent, we can't merge with it, so the new type
3748       // becomes dependent for now. We'll reproduce the original type when we
3749       // instantiate the TypeSourceInfo for the variable.
3750       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3751         New->setType(Context.DependentTy);
3752       return;
3753     }
3754     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3755   }
3756 
3757   // Don't actually update the type on the new declaration if the old
3758   // declaration was an extern declaration in a different scope.
3759   if (MergeTypeWithOld)
3760     New->setType(MergedT);
3761 }
3762 
3763 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3764                                   LookupResult &Previous) {
3765   // C11 6.2.7p4:
3766   //   For an identifier with internal or external linkage declared
3767   //   in a scope in which a prior declaration of that identifier is
3768   //   visible, if the prior declaration specifies internal or
3769   //   external linkage, the type of the identifier at the later
3770   //   declaration becomes the composite type.
3771   //
3772   // If the variable isn't visible, we do not merge with its type.
3773   if (Previous.isShadowed())
3774     return false;
3775 
3776   if (S.getLangOpts().CPlusPlus) {
3777     // C++11 [dcl.array]p3:
3778     //   If there is a preceding declaration of the entity in the same
3779     //   scope in which the bound was specified, an omitted array bound
3780     //   is taken to be the same as in that earlier declaration.
3781     return NewVD->isPreviousDeclInSameBlockScope() ||
3782            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3783             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3784   } else {
3785     // If the old declaration was function-local, don't merge with its
3786     // type unless we're in the same function.
3787     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3788            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3789   }
3790 }
3791 
3792 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3793 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3794 /// situation, merging decls or emitting diagnostics as appropriate.
3795 ///
3796 /// Tentative definition rules (C99 6.9.2p2) are checked by
3797 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3798 /// definitions here, since the initializer hasn't been attached.
3799 ///
3800 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3801   // If the new decl is already invalid, don't do any other checking.
3802   if (New->isInvalidDecl())
3803     return;
3804 
3805   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3806     return;
3807 
3808   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3809 
3810   // Verify the old decl was also a variable or variable template.
3811   VarDecl *Old = nullptr;
3812   VarTemplateDecl *OldTemplate = nullptr;
3813   if (Previous.isSingleResult()) {
3814     if (NewTemplate) {
3815       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3816       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3817 
3818       if (auto *Shadow =
3819               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3820         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3821           return New->setInvalidDecl();
3822     } else {
3823       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3824 
3825       if (auto *Shadow =
3826               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3827         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3828           return New->setInvalidDecl();
3829     }
3830   }
3831   if (!Old) {
3832     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3833         << New->getDeclName();
3834     notePreviousDefinition(Previous.getRepresentativeDecl(),
3835                            New->getLocation());
3836     return New->setInvalidDecl();
3837   }
3838 
3839   // Ensure the template parameters are compatible.
3840   if (NewTemplate &&
3841       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3842                                       OldTemplate->getTemplateParameters(),
3843                                       /*Complain=*/true, TPL_TemplateMatch))
3844     return New->setInvalidDecl();
3845 
3846   // C++ [class.mem]p1:
3847   //   A member shall not be declared twice in the member-specification [...]
3848   //
3849   // Here, we need only consider static data members.
3850   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3851     Diag(New->getLocation(), diag::err_duplicate_member)
3852       << New->getIdentifier();
3853     Diag(Old->getLocation(), diag::note_previous_declaration);
3854     New->setInvalidDecl();
3855   }
3856 
3857   mergeDeclAttributes(New, Old);
3858   // Warn if an already-declared variable is made a weak_import in a subsequent
3859   // declaration
3860   if (New->hasAttr<WeakImportAttr>() &&
3861       Old->getStorageClass() == SC_None &&
3862       !Old->hasAttr<WeakImportAttr>()) {
3863     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3864     notePreviousDefinition(Old, New->getLocation());
3865     // Remove weak_import attribute on new declaration.
3866     New->dropAttr<WeakImportAttr>();
3867   }
3868 
3869   if (New->hasAttr<InternalLinkageAttr>() &&
3870       !Old->hasAttr<InternalLinkageAttr>()) {
3871     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3872         << New->getDeclName();
3873     notePreviousDefinition(Old, New->getLocation());
3874     New->dropAttr<InternalLinkageAttr>();
3875   }
3876 
3877   // Merge the types.
3878   VarDecl *MostRecent = Old->getMostRecentDecl();
3879   if (MostRecent != Old) {
3880     MergeVarDeclTypes(New, MostRecent,
3881                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3882     if (New->isInvalidDecl())
3883       return;
3884   }
3885 
3886   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3887   if (New->isInvalidDecl())
3888     return;
3889 
3890   diag::kind PrevDiag;
3891   SourceLocation OldLocation;
3892   std::tie(PrevDiag, OldLocation) =
3893       getNoteDiagForInvalidRedeclaration(Old, New);
3894 
3895   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3896   if (New->getStorageClass() == SC_Static &&
3897       !New->isStaticDataMember() &&
3898       Old->hasExternalFormalLinkage()) {
3899     if (getLangOpts().MicrosoftExt) {
3900       Diag(New->getLocation(), diag::ext_static_non_static)
3901           << New->getDeclName();
3902       Diag(OldLocation, PrevDiag);
3903     } else {
3904       Diag(New->getLocation(), diag::err_static_non_static)
3905           << New->getDeclName();
3906       Diag(OldLocation, PrevDiag);
3907       return New->setInvalidDecl();
3908     }
3909   }
3910   // C99 6.2.2p4:
3911   //   For an identifier declared with the storage-class specifier
3912   //   extern in a scope in which a prior declaration of that
3913   //   identifier is visible,23) if the prior declaration specifies
3914   //   internal or external linkage, the linkage of the identifier at
3915   //   the later declaration is the same as the linkage specified at
3916   //   the prior declaration. If no prior declaration is visible, or
3917   //   if the prior declaration specifies no linkage, then the
3918   //   identifier has external linkage.
3919   if (New->hasExternalStorage() && Old->hasLinkage())
3920     /* Okay */;
3921   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3922            !New->isStaticDataMember() &&
3923            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3924     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3925     Diag(OldLocation, PrevDiag);
3926     return New->setInvalidDecl();
3927   }
3928 
3929   // Check if extern is followed by non-extern and vice-versa.
3930   if (New->hasExternalStorage() &&
3931       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3932     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3933     Diag(OldLocation, PrevDiag);
3934     return New->setInvalidDecl();
3935   }
3936   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3937       !New->hasExternalStorage()) {
3938     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3939     Diag(OldLocation, PrevDiag);
3940     return New->setInvalidDecl();
3941   }
3942 
3943   if (CheckRedeclarationModuleOwnership(New, Old))
3944     return;
3945 
3946   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3947 
3948   // FIXME: The test for external storage here seems wrong? We still
3949   // need to check for mismatches.
3950   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3951       // Don't complain about out-of-line definitions of static members.
3952       !(Old->getLexicalDeclContext()->isRecord() &&
3953         !New->getLexicalDeclContext()->isRecord())) {
3954     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3955     Diag(OldLocation, PrevDiag);
3956     return New->setInvalidDecl();
3957   }
3958 
3959   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3960     if (VarDecl *Def = Old->getDefinition()) {
3961       // C++1z [dcl.fcn.spec]p4:
3962       //   If the definition of a variable appears in a translation unit before
3963       //   its first declaration as inline, the program is ill-formed.
3964       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3965       Diag(Def->getLocation(), diag::note_previous_definition);
3966     }
3967   }
3968 
3969   // If this redeclaration makes the variable inline, we may need to add it to
3970   // UndefinedButUsed.
3971   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3972       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3973     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3974                                            SourceLocation()));
3975 
3976   if (New->getTLSKind() != Old->getTLSKind()) {
3977     if (!Old->getTLSKind()) {
3978       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3979       Diag(OldLocation, PrevDiag);
3980     } else if (!New->getTLSKind()) {
3981       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3982       Diag(OldLocation, PrevDiag);
3983     } else {
3984       // Do not allow redeclaration to change the variable between requiring
3985       // static and dynamic initialization.
3986       // FIXME: GCC allows this, but uses the TLS keyword on the first
3987       // declaration to determine the kind. Do we need to be compatible here?
3988       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3989         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3990       Diag(OldLocation, PrevDiag);
3991     }
3992   }
3993 
3994   // C++ doesn't have tentative definitions, so go right ahead and check here.
3995   if (getLangOpts().CPlusPlus &&
3996       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3997     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3998         Old->getCanonicalDecl()->isConstexpr()) {
3999       // This definition won't be a definition any more once it's been merged.
4000       Diag(New->getLocation(),
4001            diag::warn_deprecated_redundant_constexpr_static_def);
4002     } else if (VarDecl *Def = Old->getDefinition()) {
4003       if (checkVarDeclRedefinition(Def, New))
4004         return;
4005     }
4006   }
4007 
4008   if (haveIncompatibleLanguageLinkages(Old, New)) {
4009     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4010     Diag(OldLocation, PrevDiag);
4011     New->setInvalidDecl();
4012     return;
4013   }
4014 
4015   // Merge "used" flag.
4016   if (Old->getMostRecentDecl()->isUsed(false))
4017     New->setIsUsed();
4018 
4019   // Keep a chain of previous declarations.
4020   New->setPreviousDecl(Old);
4021   if (NewTemplate)
4022     NewTemplate->setPreviousDecl(OldTemplate);
4023   adjustDeclContextForDeclaratorDecl(New, Old);
4024 
4025   // Inherit access appropriately.
4026   New->setAccess(Old->getAccess());
4027   if (NewTemplate)
4028     NewTemplate->setAccess(New->getAccess());
4029 
4030   if (Old->isInline())
4031     New->setImplicitlyInline();
4032 }
4033 
4034 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4035   SourceManager &SrcMgr = getSourceManager();
4036   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4037   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4038   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4039   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4040   auto &HSI = PP.getHeaderSearchInfo();
4041   StringRef HdrFilename =
4042       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4043 
4044   auto noteFromModuleOrInclude = [&](Module *Mod,
4045                                      SourceLocation IncLoc) -> bool {
4046     // Redefinition errors with modules are common with non modular mapped
4047     // headers, example: a non-modular header H in module A that also gets
4048     // included directly in a TU. Pointing twice to the same header/definition
4049     // is confusing, try to get better diagnostics when modules is on.
4050     if (IncLoc.isValid()) {
4051       if (Mod) {
4052         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4053             << HdrFilename.str() << Mod->getFullModuleName();
4054         if (!Mod->DefinitionLoc.isInvalid())
4055           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4056               << Mod->getFullModuleName();
4057       } else {
4058         Diag(IncLoc, diag::note_redefinition_include_same_file)
4059             << HdrFilename.str();
4060       }
4061       return true;
4062     }
4063 
4064     return false;
4065   };
4066 
4067   // Is it the same file and same offset? Provide more information on why
4068   // this leads to a redefinition error.
4069   bool EmittedDiag = false;
4070   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4071     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4072     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4073     EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4074     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4075 
4076     // If the header has no guards, emit a note suggesting one.
4077     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4078       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4079 
4080     if (EmittedDiag)
4081       return;
4082   }
4083 
4084   // Redefinition coming from different files or couldn't do better above.
4085   if (Old->getLocation().isValid())
4086     Diag(Old->getLocation(), diag::note_previous_definition);
4087 }
4088 
4089 /// We've just determined that \p Old and \p New both appear to be definitions
4090 /// of the same variable. Either diagnose or fix the problem.
4091 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4092   if (!hasVisibleDefinition(Old) &&
4093       (New->getFormalLinkage() == InternalLinkage ||
4094        New->isInline() ||
4095        New->getDescribedVarTemplate() ||
4096        New->getNumTemplateParameterLists() ||
4097        New->getDeclContext()->isDependentContext())) {
4098     // The previous definition is hidden, and multiple definitions are
4099     // permitted (in separate TUs). Demote this to a declaration.
4100     New->demoteThisDefinitionToDeclaration();
4101 
4102     // Make the canonical definition visible.
4103     if (auto *OldTD = Old->getDescribedVarTemplate())
4104       makeMergedDefinitionVisible(OldTD);
4105     makeMergedDefinitionVisible(Old);
4106     return false;
4107   } else {
4108     Diag(New->getLocation(), diag::err_redefinition) << New;
4109     notePreviousDefinition(Old, New->getLocation());
4110     New->setInvalidDecl();
4111     return true;
4112   }
4113 }
4114 
4115 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4116 /// no declarator (e.g. "struct foo;") is parsed.
4117 Decl *
4118 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4119                                  RecordDecl *&AnonRecord) {
4120   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4121                                     AnonRecord);
4122 }
4123 
4124 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4125 // disambiguate entities defined in different scopes.
4126 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4127 // compatibility.
4128 // We will pick our mangling number depending on which version of MSVC is being
4129 // targeted.
4130 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4131   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4132              ? S->getMSCurManglingNumber()
4133              : S->getMSLastManglingNumber();
4134 }
4135 
4136 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4137   if (!Context.getLangOpts().CPlusPlus)
4138     return;
4139 
4140   if (isa<CXXRecordDecl>(Tag->getParent())) {
4141     // If this tag is the direct child of a class, number it if
4142     // it is anonymous.
4143     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4144       return;
4145     MangleNumberingContext &MCtx =
4146         Context.getManglingNumberContext(Tag->getParent());
4147     Context.setManglingNumber(
4148         Tag, MCtx.getManglingNumber(
4149                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4150     return;
4151   }
4152 
4153   // If this tag isn't a direct child of a class, number it if it is local.
4154   Decl *ManglingContextDecl;
4155   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4156           Tag->getDeclContext(), ManglingContextDecl)) {
4157     Context.setManglingNumber(
4158         Tag, MCtx->getManglingNumber(
4159                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4160   }
4161 }
4162 
4163 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4164                                         TypedefNameDecl *NewTD) {
4165   if (TagFromDeclSpec->isInvalidDecl())
4166     return;
4167 
4168   // Do nothing if the tag already has a name for linkage purposes.
4169   if (TagFromDeclSpec->hasNameForLinkage())
4170     return;
4171 
4172   // A well-formed anonymous tag must always be a TUK_Definition.
4173   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4174 
4175   // The type must match the tag exactly;  no qualifiers allowed.
4176   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4177                            Context.getTagDeclType(TagFromDeclSpec))) {
4178     if (getLangOpts().CPlusPlus)
4179       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4180     return;
4181   }
4182 
4183   // If we've already computed linkage for the anonymous tag, then
4184   // adding a typedef name for the anonymous decl can change that
4185   // linkage, which might be a serious problem.  Diagnose this as
4186   // unsupported and ignore the typedef name.  TODO: we should
4187   // pursue this as a language defect and establish a formal rule
4188   // for how to handle it.
4189   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4190     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4191 
4192     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4193     tagLoc = getLocForEndOfToken(tagLoc);
4194 
4195     llvm::SmallString<40> textToInsert;
4196     textToInsert += ' ';
4197     textToInsert += NewTD->getIdentifier()->getName();
4198     Diag(tagLoc, diag::note_typedef_changes_linkage)
4199         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4200     return;
4201   }
4202 
4203   // Otherwise, set this is the anon-decl typedef for the tag.
4204   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4205 }
4206 
4207 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4208   switch (T) {
4209   case DeclSpec::TST_class:
4210     return 0;
4211   case DeclSpec::TST_struct:
4212     return 1;
4213   case DeclSpec::TST_interface:
4214     return 2;
4215   case DeclSpec::TST_union:
4216     return 3;
4217   case DeclSpec::TST_enum:
4218     return 4;
4219   default:
4220     llvm_unreachable("unexpected type specifier");
4221   }
4222 }
4223 
4224 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4225 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4226 /// parameters to cope with template friend declarations.
4227 Decl *
4228 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4229                                  MultiTemplateParamsArg TemplateParams,
4230                                  bool IsExplicitInstantiation,
4231                                  RecordDecl *&AnonRecord) {
4232   Decl *TagD = nullptr;
4233   TagDecl *Tag = nullptr;
4234   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4235       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4236       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4237       DS.getTypeSpecType() == DeclSpec::TST_union ||
4238       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4239     TagD = DS.getRepAsDecl();
4240 
4241     if (!TagD) // We probably had an error
4242       return nullptr;
4243 
4244     // Note that the above type specs guarantee that the
4245     // type rep is a Decl, whereas in many of the others
4246     // it's a Type.
4247     if (isa<TagDecl>(TagD))
4248       Tag = cast<TagDecl>(TagD);
4249     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4250       Tag = CTD->getTemplatedDecl();
4251   }
4252 
4253   if (Tag) {
4254     handleTagNumbering(Tag, S);
4255     Tag->setFreeStanding();
4256     if (Tag->isInvalidDecl())
4257       return Tag;
4258   }
4259 
4260   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4261     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4262     // or incomplete types shall not be restrict-qualified."
4263     if (TypeQuals & DeclSpec::TQ_restrict)
4264       Diag(DS.getRestrictSpecLoc(),
4265            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4266            << DS.getSourceRange();
4267   }
4268 
4269   if (DS.isInlineSpecified())
4270     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4271         << getLangOpts().CPlusPlus17;
4272 
4273   if (DS.isConstexprSpecified()) {
4274     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4275     // and definitions of functions and variables.
4276     if (Tag)
4277       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4278           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4279     else
4280       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4281     // Don't emit warnings after this error.
4282     return TagD;
4283   }
4284 
4285   DiagnoseFunctionSpecifiers(DS);
4286 
4287   if (DS.isFriendSpecified()) {
4288     // If we're dealing with a decl but not a TagDecl, assume that
4289     // whatever routines created it handled the friendship aspect.
4290     if (TagD && !Tag)
4291       return nullptr;
4292     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4293   }
4294 
4295   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4296   bool IsExplicitSpecialization =
4297     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4298   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4299       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4300       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4301     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4302     // nested-name-specifier unless it is an explicit instantiation
4303     // or an explicit specialization.
4304     //
4305     // FIXME: We allow class template partial specializations here too, per the
4306     // obvious intent of DR1819.
4307     //
4308     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4309     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4310         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4311     return nullptr;
4312   }
4313 
4314   // Track whether this decl-specifier declares anything.
4315   bool DeclaresAnything = true;
4316 
4317   // Handle anonymous struct definitions.
4318   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4319     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4320         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4321       if (getLangOpts().CPlusPlus ||
4322           Record->getDeclContext()->isRecord()) {
4323         // If CurContext is a DeclContext that can contain statements,
4324         // RecursiveASTVisitor won't visit the decls that
4325         // BuildAnonymousStructOrUnion() will put into CurContext.
4326         // Also store them here so that they can be part of the
4327         // DeclStmt that gets created in this case.
4328         // FIXME: Also return the IndirectFieldDecls created by
4329         // BuildAnonymousStructOr union, for the same reason?
4330         if (CurContext->isFunctionOrMethod())
4331           AnonRecord = Record;
4332         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4333                                            Context.getPrintingPolicy());
4334       }
4335 
4336       DeclaresAnything = false;
4337     }
4338   }
4339 
4340   // C11 6.7.2.1p2:
4341   //   A struct-declaration that does not declare an anonymous structure or
4342   //   anonymous union shall contain a struct-declarator-list.
4343   //
4344   // This rule also existed in C89 and C99; the grammar for struct-declaration
4345   // did not permit a struct-declaration without a struct-declarator-list.
4346   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4347       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4348     // Check for Microsoft C extension: anonymous struct/union member.
4349     // Handle 2 kinds of anonymous struct/union:
4350     //   struct STRUCT;
4351     //   union UNION;
4352     // and
4353     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4354     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4355     if ((Tag && Tag->getDeclName()) ||
4356         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4357       RecordDecl *Record = nullptr;
4358       if (Tag)
4359         Record = dyn_cast<RecordDecl>(Tag);
4360       else if (const RecordType *RT =
4361                    DS.getRepAsType().get()->getAsStructureType())
4362         Record = RT->getDecl();
4363       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4364         Record = UT->getDecl();
4365 
4366       if (Record && getLangOpts().MicrosoftExt) {
4367         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4368             << Record->isUnion() << DS.getSourceRange();
4369         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4370       }
4371 
4372       DeclaresAnything = false;
4373     }
4374   }
4375 
4376   // Skip all the checks below if we have a type error.
4377   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4378       (TagD && TagD->isInvalidDecl()))
4379     return TagD;
4380 
4381   if (getLangOpts().CPlusPlus &&
4382       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4383     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4384       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4385           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4386         DeclaresAnything = false;
4387 
4388   if (!DS.isMissingDeclaratorOk()) {
4389     // Customize diagnostic for a typedef missing a name.
4390     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4391       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4392           << DS.getSourceRange();
4393     else
4394       DeclaresAnything = false;
4395   }
4396 
4397   if (DS.isModulePrivateSpecified() &&
4398       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4399     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4400       << Tag->getTagKind()
4401       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4402 
4403   ActOnDocumentableDecl(TagD);
4404 
4405   // C 6.7/2:
4406   //   A declaration [...] shall declare at least a declarator [...], a tag,
4407   //   or the members of an enumeration.
4408   // C++ [dcl.dcl]p3:
4409   //   [If there are no declarators], and except for the declaration of an
4410   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4411   //   names into the program, or shall redeclare a name introduced by a
4412   //   previous declaration.
4413   if (!DeclaresAnything) {
4414     // In C, we allow this as a (popular) extension / bug. Don't bother
4415     // producing further diagnostics for redundant qualifiers after this.
4416     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4417     return TagD;
4418   }
4419 
4420   // C++ [dcl.stc]p1:
4421   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4422   //   init-declarator-list of the declaration shall not be empty.
4423   // C++ [dcl.fct.spec]p1:
4424   //   If a cv-qualifier appears in a decl-specifier-seq, the
4425   //   init-declarator-list of the declaration shall not be empty.
4426   //
4427   // Spurious qualifiers here appear to be valid in C.
4428   unsigned DiagID = diag::warn_standalone_specifier;
4429   if (getLangOpts().CPlusPlus)
4430     DiagID = diag::ext_standalone_specifier;
4431 
4432   // Note that a linkage-specification sets a storage class, but
4433   // 'extern "C" struct foo;' is actually valid and not theoretically
4434   // useless.
4435   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4436     if (SCS == DeclSpec::SCS_mutable)
4437       // Since mutable is not a viable storage class specifier in C, there is
4438       // no reason to treat it as an extension. Instead, diagnose as an error.
4439       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4440     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4441       Diag(DS.getStorageClassSpecLoc(), DiagID)
4442         << DeclSpec::getSpecifierName(SCS);
4443   }
4444 
4445   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4446     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4447       << DeclSpec::getSpecifierName(TSCS);
4448   if (DS.getTypeQualifiers()) {
4449     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4450       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4451     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4452       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4453     // Restrict is covered above.
4454     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4455       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4456     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4457       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4458   }
4459 
4460   // Warn about ignored type attributes, for example:
4461   // __attribute__((aligned)) struct A;
4462   // Attributes should be placed after tag to apply to type declaration.
4463   if (!DS.getAttributes().empty()) {
4464     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4465     if (TypeSpecType == DeclSpec::TST_class ||
4466         TypeSpecType == DeclSpec::TST_struct ||
4467         TypeSpecType == DeclSpec::TST_interface ||
4468         TypeSpecType == DeclSpec::TST_union ||
4469         TypeSpecType == DeclSpec::TST_enum) {
4470       for (const ParsedAttr &AL : DS.getAttributes())
4471         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4472             << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4473     }
4474   }
4475 
4476   return TagD;
4477 }
4478 
4479 /// We are trying to inject an anonymous member into the given scope;
4480 /// check if there's an existing declaration that can't be overloaded.
4481 ///
4482 /// \return true if this is a forbidden redeclaration
4483 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4484                                          Scope *S,
4485                                          DeclContext *Owner,
4486                                          DeclarationName Name,
4487                                          SourceLocation NameLoc,
4488                                          bool IsUnion) {
4489   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4490                  Sema::ForVisibleRedeclaration);
4491   if (!SemaRef.LookupName(R, S)) return false;
4492 
4493   // Pick a representative declaration.
4494   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4495   assert(PrevDecl && "Expected a non-null Decl");
4496 
4497   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4498     return false;
4499 
4500   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4501     << IsUnion << Name;
4502   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4503 
4504   return true;
4505 }
4506 
4507 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4508 /// anonymous struct or union AnonRecord into the owning context Owner
4509 /// and scope S. This routine will be invoked just after we realize
4510 /// that an unnamed union or struct is actually an anonymous union or
4511 /// struct, e.g.,
4512 ///
4513 /// @code
4514 /// union {
4515 ///   int i;
4516 ///   float f;
4517 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4518 ///    // f into the surrounding scope.x
4519 /// @endcode
4520 ///
4521 /// This routine is recursive, injecting the names of nested anonymous
4522 /// structs/unions into the owning context and scope as well.
4523 static bool
4524 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4525                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4526                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4527   bool Invalid = false;
4528 
4529   // Look every FieldDecl and IndirectFieldDecl with a name.
4530   for (auto *D : AnonRecord->decls()) {
4531     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4532         cast<NamedDecl>(D)->getDeclName()) {
4533       ValueDecl *VD = cast<ValueDecl>(D);
4534       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4535                                        VD->getLocation(),
4536                                        AnonRecord->isUnion())) {
4537         // C++ [class.union]p2:
4538         //   The names of the members of an anonymous union shall be
4539         //   distinct from the names of any other entity in the
4540         //   scope in which the anonymous union is declared.
4541         Invalid = true;
4542       } else {
4543         // C++ [class.union]p2:
4544         //   For the purpose of name lookup, after the anonymous union
4545         //   definition, the members of the anonymous union are
4546         //   considered to have been defined in the scope in which the
4547         //   anonymous union is declared.
4548         unsigned OldChainingSize = Chaining.size();
4549         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4550           Chaining.append(IF->chain_begin(), IF->chain_end());
4551         else
4552           Chaining.push_back(VD);
4553 
4554         assert(Chaining.size() >= 2);
4555         NamedDecl **NamedChain =
4556           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4557         for (unsigned i = 0; i < Chaining.size(); i++)
4558           NamedChain[i] = Chaining[i];
4559 
4560         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4561             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4562             VD->getType(), {NamedChain, Chaining.size()});
4563 
4564         for (const auto *Attr : VD->attrs())
4565           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4566 
4567         IndirectField->setAccess(AS);
4568         IndirectField->setImplicit();
4569         SemaRef.PushOnScopeChains(IndirectField, S);
4570 
4571         // That includes picking up the appropriate access specifier.
4572         if (AS != AS_none) IndirectField->setAccess(AS);
4573 
4574         Chaining.resize(OldChainingSize);
4575       }
4576     }
4577   }
4578 
4579   return Invalid;
4580 }
4581 
4582 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4583 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4584 /// illegal input values are mapped to SC_None.
4585 static StorageClass
4586 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4587   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4588   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4589          "Parser allowed 'typedef' as storage class VarDecl.");
4590   switch (StorageClassSpec) {
4591   case DeclSpec::SCS_unspecified:    return SC_None;
4592   case DeclSpec::SCS_extern:
4593     if (DS.isExternInLinkageSpec())
4594       return SC_None;
4595     return SC_Extern;
4596   case DeclSpec::SCS_static:         return SC_Static;
4597   case DeclSpec::SCS_auto:           return SC_Auto;
4598   case DeclSpec::SCS_register:       return SC_Register;
4599   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4600     // Illegal SCSs map to None: error reporting is up to the caller.
4601   case DeclSpec::SCS_mutable:        // Fall through.
4602   case DeclSpec::SCS_typedef:        return SC_None;
4603   }
4604   llvm_unreachable("unknown storage class specifier");
4605 }
4606 
4607 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4608   assert(Record->hasInClassInitializer());
4609 
4610   for (const auto *I : Record->decls()) {
4611     const auto *FD = dyn_cast<FieldDecl>(I);
4612     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4613       FD = IFD->getAnonField();
4614     if (FD && FD->hasInClassInitializer())
4615       return FD->getLocation();
4616   }
4617 
4618   llvm_unreachable("couldn't find in-class initializer");
4619 }
4620 
4621 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4622                                       SourceLocation DefaultInitLoc) {
4623   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4624     return;
4625 
4626   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4627   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4628 }
4629 
4630 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4631                                       CXXRecordDecl *AnonUnion) {
4632   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4633     return;
4634 
4635   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4636 }
4637 
4638 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4639 /// anonymous structure or union. Anonymous unions are a C++ feature
4640 /// (C++ [class.union]) and a C11 feature; anonymous structures
4641 /// are a C11 feature and GNU C++ extension.
4642 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4643                                         AccessSpecifier AS,
4644                                         RecordDecl *Record,
4645                                         const PrintingPolicy &Policy) {
4646   DeclContext *Owner = Record->getDeclContext();
4647 
4648   // Diagnose whether this anonymous struct/union is an extension.
4649   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4650     Diag(Record->getLocation(), diag::ext_anonymous_union);
4651   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4652     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4653   else if (!Record->isUnion() && !getLangOpts().C11)
4654     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4655 
4656   // C and C++ require different kinds of checks for anonymous
4657   // structs/unions.
4658   bool Invalid = false;
4659   if (getLangOpts().CPlusPlus) {
4660     const char *PrevSpec = nullptr;
4661     unsigned DiagID;
4662     if (Record->isUnion()) {
4663       // C++ [class.union]p6:
4664       // C++17 [class.union.anon]p2:
4665       //   Anonymous unions declared in a named namespace or in the
4666       //   global namespace shall be declared static.
4667       DeclContext *OwnerScope = Owner->getRedeclContext();
4668       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4669           (OwnerScope->isTranslationUnit() ||
4670            (OwnerScope->isNamespace() &&
4671             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4672         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4673           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4674 
4675         // Recover by adding 'static'.
4676         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4677                                PrevSpec, DiagID, Policy);
4678       }
4679       // C++ [class.union]p6:
4680       //   A storage class is not allowed in a declaration of an
4681       //   anonymous union in a class scope.
4682       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4683                isa<RecordDecl>(Owner)) {
4684         Diag(DS.getStorageClassSpecLoc(),
4685              diag::err_anonymous_union_with_storage_spec)
4686           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4687 
4688         // Recover by removing the storage specifier.
4689         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4690                                SourceLocation(),
4691                                PrevSpec, DiagID, Context.getPrintingPolicy());
4692       }
4693     }
4694 
4695     // Ignore const/volatile/restrict qualifiers.
4696     if (DS.getTypeQualifiers()) {
4697       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4698         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4699           << Record->isUnion() << "const"
4700           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4701       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4702         Diag(DS.getVolatileSpecLoc(),
4703              diag::ext_anonymous_struct_union_qualified)
4704           << Record->isUnion() << "volatile"
4705           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4706       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4707         Diag(DS.getRestrictSpecLoc(),
4708              diag::ext_anonymous_struct_union_qualified)
4709           << Record->isUnion() << "restrict"
4710           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4711       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4712         Diag(DS.getAtomicSpecLoc(),
4713              diag::ext_anonymous_struct_union_qualified)
4714           << Record->isUnion() << "_Atomic"
4715           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4716       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4717         Diag(DS.getUnalignedSpecLoc(),
4718              diag::ext_anonymous_struct_union_qualified)
4719           << Record->isUnion() << "__unaligned"
4720           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4721 
4722       DS.ClearTypeQualifiers();
4723     }
4724 
4725     // C++ [class.union]p2:
4726     //   The member-specification of an anonymous union shall only
4727     //   define non-static data members. [Note: nested types and
4728     //   functions cannot be declared within an anonymous union. ]
4729     for (auto *Mem : Record->decls()) {
4730       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4731         // C++ [class.union]p3:
4732         //   An anonymous union shall not have private or protected
4733         //   members (clause 11).
4734         assert(FD->getAccess() != AS_none);
4735         if (FD->getAccess() != AS_public) {
4736           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4737             << Record->isUnion() << (FD->getAccess() == AS_protected);
4738           Invalid = true;
4739         }
4740 
4741         // C++ [class.union]p1
4742         //   An object of a class with a non-trivial constructor, a non-trivial
4743         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4744         //   assignment operator cannot be a member of a union, nor can an
4745         //   array of such objects.
4746         if (CheckNontrivialField(FD))
4747           Invalid = true;
4748       } else if (Mem->isImplicit()) {
4749         // Any implicit members are fine.
4750       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4751         // This is a type that showed up in an
4752         // elaborated-type-specifier inside the anonymous struct or
4753         // union, but which actually declares a type outside of the
4754         // anonymous struct or union. It's okay.
4755       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4756         if (!MemRecord->isAnonymousStructOrUnion() &&
4757             MemRecord->getDeclName()) {
4758           // Visual C++ allows type definition in anonymous struct or union.
4759           if (getLangOpts().MicrosoftExt)
4760             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4761               << Record->isUnion();
4762           else {
4763             // This is a nested type declaration.
4764             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4765               << Record->isUnion();
4766             Invalid = true;
4767           }
4768         } else {
4769           // This is an anonymous type definition within another anonymous type.
4770           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4771           // not part of standard C++.
4772           Diag(MemRecord->getLocation(),
4773                diag::ext_anonymous_record_with_anonymous_type)
4774             << Record->isUnion();
4775         }
4776       } else if (isa<AccessSpecDecl>(Mem)) {
4777         // Any access specifier is fine.
4778       } else if (isa<StaticAssertDecl>(Mem)) {
4779         // In C++1z, static_assert declarations are also fine.
4780       } else {
4781         // We have something that isn't a non-static data
4782         // member. Complain about it.
4783         unsigned DK = diag::err_anonymous_record_bad_member;
4784         if (isa<TypeDecl>(Mem))
4785           DK = diag::err_anonymous_record_with_type;
4786         else if (isa<FunctionDecl>(Mem))
4787           DK = diag::err_anonymous_record_with_function;
4788         else if (isa<VarDecl>(Mem))
4789           DK = diag::err_anonymous_record_with_static;
4790 
4791         // Visual C++ allows type definition in anonymous struct or union.
4792         if (getLangOpts().MicrosoftExt &&
4793             DK == diag::err_anonymous_record_with_type)
4794           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4795             << Record->isUnion();
4796         else {
4797           Diag(Mem->getLocation(), DK) << Record->isUnion();
4798           Invalid = true;
4799         }
4800       }
4801     }
4802 
4803     // C++11 [class.union]p8 (DR1460):
4804     //   At most one variant member of a union may have a
4805     //   brace-or-equal-initializer.
4806     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4807         Owner->isRecord())
4808       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4809                                 cast<CXXRecordDecl>(Record));
4810   }
4811 
4812   if (!Record->isUnion() && !Owner->isRecord()) {
4813     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4814       << getLangOpts().CPlusPlus;
4815     Invalid = true;
4816   }
4817 
4818   // Mock up a declarator.
4819   Declarator Dc(DS, DeclaratorContext::MemberContext);
4820   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4821   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4822 
4823   // Create a declaration for this anonymous struct/union.
4824   NamedDecl *Anon = nullptr;
4825   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4826     Anon = FieldDecl::Create(
4827         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
4828         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
4829         /*BitWidth=*/nullptr, /*Mutable=*/false,
4830         /*InitStyle=*/ICIS_NoInit);
4831     Anon->setAccess(AS);
4832     if (getLangOpts().CPlusPlus)
4833       FieldCollector->Add(cast<FieldDecl>(Anon));
4834   } else {
4835     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4836     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4837     if (SCSpec == DeclSpec::SCS_mutable) {
4838       // mutable can only appear on non-static class members, so it's always
4839       // an error here
4840       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4841       Invalid = true;
4842       SC = SC_None;
4843     }
4844 
4845     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
4846                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4847                            Context.getTypeDeclType(Record), TInfo, SC);
4848 
4849     // Default-initialize the implicit variable. This initialization will be
4850     // trivial in almost all cases, except if a union member has an in-class
4851     // initializer:
4852     //   union { int n = 0; };
4853     ActOnUninitializedDecl(Anon);
4854   }
4855   Anon->setImplicit();
4856 
4857   // Mark this as an anonymous struct/union type.
4858   Record->setAnonymousStructOrUnion(true);
4859 
4860   // Add the anonymous struct/union object to the current
4861   // context. We'll be referencing this object when we refer to one of
4862   // its members.
4863   Owner->addDecl(Anon);
4864 
4865   // Inject the members of the anonymous struct/union into the owning
4866   // context and into the identifier resolver chain for name lookup
4867   // purposes.
4868   SmallVector<NamedDecl*, 2> Chain;
4869   Chain.push_back(Anon);
4870 
4871   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4872     Invalid = true;
4873 
4874   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4875     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4876       Decl *ManglingContextDecl;
4877       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4878               NewVD->getDeclContext(), ManglingContextDecl)) {
4879         Context.setManglingNumber(
4880             NewVD, MCtx->getManglingNumber(
4881                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4882         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4883       }
4884     }
4885   }
4886 
4887   if (Invalid)
4888     Anon->setInvalidDecl();
4889 
4890   return Anon;
4891 }
4892 
4893 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4894 /// Microsoft C anonymous structure.
4895 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4896 /// Example:
4897 ///
4898 /// struct A { int a; };
4899 /// struct B { struct A; int b; };
4900 ///
4901 /// void foo() {
4902 ///   B var;
4903 ///   var.a = 3;
4904 /// }
4905 ///
4906 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4907                                            RecordDecl *Record) {
4908   assert(Record && "expected a record!");
4909 
4910   // Mock up a declarator.
4911   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
4912   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4913   assert(TInfo && "couldn't build declarator info for anonymous struct");
4914 
4915   auto *ParentDecl = cast<RecordDecl>(CurContext);
4916   QualType RecTy = Context.getTypeDeclType(Record);
4917 
4918   // Create a declaration for this anonymous struct.
4919   NamedDecl *Anon =
4920       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
4921                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
4922                         /*BitWidth=*/nullptr, /*Mutable=*/false,
4923                         /*InitStyle=*/ICIS_NoInit);
4924   Anon->setImplicit();
4925 
4926   // Add the anonymous struct object to the current context.
4927   CurContext->addDecl(Anon);
4928 
4929   // Inject the members of the anonymous struct into the current
4930   // context and into the identifier resolver chain for name lookup
4931   // purposes.
4932   SmallVector<NamedDecl*, 2> Chain;
4933   Chain.push_back(Anon);
4934 
4935   RecordDecl *RecordDef = Record->getDefinition();
4936   if (RequireCompleteType(Anon->getLocation(), RecTy,
4937                           diag::err_field_incomplete) ||
4938       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4939                                           AS_none, Chain)) {
4940     Anon->setInvalidDecl();
4941     ParentDecl->setInvalidDecl();
4942   }
4943 
4944   return Anon;
4945 }
4946 
4947 /// GetNameForDeclarator - Determine the full declaration name for the
4948 /// given Declarator.
4949 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4950   return GetNameFromUnqualifiedId(D.getName());
4951 }
4952 
4953 /// Retrieves the declaration name from a parsed unqualified-id.
4954 DeclarationNameInfo
4955 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4956   DeclarationNameInfo NameInfo;
4957   NameInfo.setLoc(Name.StartLocation);
4958 
4959   switch (Name.getKind()) {
4960 
4961   case UnqualifiedIdKind::IK_ImplicitSelfParam:
4962   case UnqualifiedIdKind::IK_Identifier:
4963     NameInfo.setName(Name.Identifier);
4964     return NameInfo;
4965 
4966   case UnqualifiedIdKind::IK_DeductionGuideName: {
4967     // C++ [temp.deduct.guide]p3:
4968     //   The simple-template-id shall name a class template specialization.
4969     //   The template-name shall be the same identifier as the template-name
4970     //   of the simple-template-id.
4971     // These together intend to imply that the template-name shall name a
4972     // class template.
4973     // FIXME: template<typename T> struct X {};
4974     //        template<typename T> using Y = X<T>;
4975     //        Y(int) -> Y<int>;
4976     //   satisfies these rules but does not name a class template.
4977     TemplateName TN = Name.TemplateName.get().get();
4978     auto *Template = TN.getAsTemplateDecl();
4979     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4980       Diag(Name.StartLocation,
4981            diag::err_deduction_guide_name_not_class_template)
4982         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4983       if (Template)
4984         Diag(Template->getLocation(), diag::note_template_decl_here);
4985       return DeclarationNameInfo();
4986     }
4987 
4988     NameInfo.setName(
4989         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4990     return NameInfo;
4991   }
4992 
4993   case UnqualifiedIdKind::IK_OperatorFunctionId:
4994     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4995                                            Name.OperatorFunctionId.Operator));
4996     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4997       = Name.OperatorFunctionId.SymbolLocations[0];
4998     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4999       = Name.EndLocation.getRawEncoding();
5000     return NameInfo;
5001 
5002   case UnqualifiedIdKind::IK_LiteralOperatorId:
5003     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5004                                                            Name.Identifier));
5005     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5006     return NameInfo;
5007 
5008   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5009     TypeSourceInfo *TInfo;
5010     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5011     if (Ty.isNull())
5012       return DeclarationNameInfo();
5013     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5014                                                Context.getCanonicalType(Ty)));
5015     NameInfo.setNamedTypeInfo(TInfo);
5016     return NameInfo;
5017   }
5018 
5019   case UnqualifiedIdKind::IK_ConstructorName: {
5020     TypeSourceInfo *TInfo;
5021     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5022     if (Ty.isNull())
5023       return DeclarationNameInfo();
5024     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5025                                               Context.getCanonicalType(Ty)));
5026     NameInfo.setNamedTypeInfo(TInfo);
5027     return NameInfo;
5028   }
5029 
5030   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5031     // In well-formed code, we can only have a constructor
5032     // template-id that refers to the current context, so go there
5033     // to find the actual type being constructed.
5034     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5035     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5036       return DeclarationNameInfo();
5037 
5038     // Determine the type of the class being constructed.
5039     QualType CurClassType = Context.getTypeDeclType(CurClass);
5040 
5041     // FIXME: Check two things: that the template-id names the same type as
5042     // CurClassType, and that the template-id does not occur when the name
5043     // was qualified.
5044 
5045     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5046                                     Context.getCanonicalType(CurClassType)));
5047     // FIXME: should we retrieve TypeSourceInfo?
5048     NameInfo.setNamedTypeInfo(nullptr);
5049     return NameInfo;
5050   }
5051 
5052   case UnqualifiedIdKind::IK_DestructorName: {
5053     TypeSourceInfo *TInfo;
5054     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5055     if (Ty.isNull())
5056       return DeclarationNameInfo();
5057     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5058                                               Context.getCanonicalType(Ty)));
5059     NameInfo.setNamedTypeInfo(TInfo);
5060     return NameInfo;
5061   }
5062 
5063   case UnqualifiedIdKind::IK_TemplateId: {
5064     TemplateName TName = Name.TemplateId->Template.get();
5065     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5066     return Context.getNameForTemplate(TName, TNameLoc);
5067   }
5068 
5069   } // switch (Name.getKind())
5070 
5071   llvm_unreachable("Unknown name kind");
5072 }
5073 
5074 static QualType getCoreType(QualType Ty) {
5075   do {
5076     if (Ty->isPointerType() || Ty->isReferenceType())
5077       Ty = Ty->getPointeeType();
5078     else if (Ty->isArrayType())
5079       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5080     else
5081       return Ty.withoutLocalFastQualifiers();
5082   } while (true);
5083 }
5084 
5085 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5086 /// and Definition have "nearly" matching parameters. This heuristic is
5087 /// used to improve diagnostics in the case where an out-of-line function
5088 /// definition doesn't match any declaration within the class or namespace.
5089 /// Also sets Params to the list of indices to the parameters that differ
5090 /// between the declaration and the definition. If hasSimilarParameters
5091 /// returns true and Params is empty, then all of the parameters match.
5092 static bool hasSimilarParameters(ASTContext &Context,
5093                                      FunctionDecl *Declaration,
5094                                      FunctionDecl *Definition,
5095                                      SmallVectorImpl<unsigned> &Params) {
5096   Params.clear();
5097   if (Declaration->param_size() != Definition->param_size())
5098     return false;
5099   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5100     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5101     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5102 
5103     // The parameter types are identical
5104     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5105       continue;
5106 
5107     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5108     QualType DefParamBaseTy = getCoreType(DefParamTy);
5109     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5110     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5111 
5112     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5113         (DeclTyName && DeclTyName == DefTyName))
5114       Params.push_back(Idx);
5115     else  // The two parameters aren't even close
5116       return false;
5117   }
5118 
5119   return true;
5120 }
5121 
5122 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5123 /// declarator needs to be rebuilt in the current instantiation.
5124 /// Any bits of declarator which appear before the name are valid for
5125 /// consideration here.  That's specifically the type in the decl spec
5126 /// and the base type in any member-pointer chunks.
5127 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5128                                                     DeclarationName Name) {
5129   // The types we specifically need to rebuild are:
5130   //   - typenames, typeofs, and decltypes
5131   //   - types which will become injected class names
5132   // Of course, we also need to rebuild any type referencing such a
5133   // type.  It's safest to just say "dependent", but we call out a
5134   // few cases here.
5135 
5136   DeclSpec &DS = D.getMutableDeclSpec();
5137   switch (DS.getTypeSpecType()) {
5138   case DeclSpec::TST_typename:
5139   case DeclSpec::TST_typeofType:
5140   case DeclSpec::TST_underlyingType:
5141   case DeclSpec::TST_atomic: {
5142     // Grab the type from the parser.
5143     TypeSourceInfo *TSI = nullptr;
5144     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5145     if (T.isNull() || !T->isDependentType()) break;
5146 
5147     // Make sure there's a type source info.  This isn't really much
5148     // of a waste; most dependent types should have type source info
5149     // attached already.
5150     if (!TSI)
5151       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5152 
5153     // Rebuild the type in the current instantiation.
5154     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5155     if (!TSI) return true;
5156 
5157     // Store the new type back in the decl spec.
5158     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5159     DS.UpdateTypeRep(LocType);
5160     break;
5161   }
5162 
5163   case DeclSpec::TST_decltype:
5164   case DeclSpec::TST_typeofExpr: {
5165     Expr *E = DS.getRepAsExpr();
5166     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5167     if (Result.isInvalid()) return true;
5168     DS.UpdateExprRep(Result.get());
5169     break;
5170   }
5171 
5172   default:
5173     // Nothing to do for these decl specs.
5174     break;
5175   }
5176 
5177   // It doesn't matter what order we do this in.
5178   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5179     DeclaratorChunk &Chunk = D.getTypeObject(I);
5180 
5181     // The only type information in the declarator which can come
5182     // before the declaration name is the base type of a member
5183     // pointer.
5184     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5185       continue;
5186 
5187     // Rebuild the scope specifier in-place.
5188     CXXScopeSpec &SS = Chunk.Mem.Scope();
5189     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5190       return true;
5191   }
5192 
5193   return false;
5194 }
5195 
5196 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5197   D.setFunctionDefinitionKind(FDK_Declaration);
5198   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5199 
5200   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5201       Dcl && Dcl->getDeclContext()->isFileContext())
5202     Dcl->setTopLevelDeclInObjCContainer();
5203 
5204   if (getLangOpts().OpenCL)
5205     setCurrentOpenCLExtensionForDecl(Dcl);
5206 
5207   return Dcl;
5208 }
5209 
5210 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5211 ///   If T is the name of a class, then each of the following shall have a
5212 ///   name different from T:
5213 ///     - every static data member of class T;
5214 ///     - every member function of class T
5215 ///     - every member of class T that is itself a type;
5216 /// \returns true if the declaration name violates these rules.
5217 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5218                                    DeclarationNameInfo NameInfo) {
5219   DeclarationName Name = NameInfo.getName();
5220 
5221   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5222   while (Record && Record->isAnonymousStructOrUnion())
5223     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5224   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5225     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5226     return true;
5227   }
5228 
5229   return false;
5230 }
5231 
5232 /// Diagnose a declaration whose declarator-id has the given
5233 /// nested-name-specifier.
5234 ///
5235 /// \param SS The nested-name-specifier of the declarator-id.
5236 ///
5237 /// \param DC The declaration context to which the nested-name-specifier
5238 /// resolves.
5239 ///
5240 /// \param Name The name of the entity being declared.
5241 ///
5242 /// \param Loc The location of the name of the entity being declared.
5243 ///
5244 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5245 /// we're declaring an explicit / partial specialization / instantiation.
5246 ///
5247 /// \returns true if we cannot safely recover from this error, false otherwise.
5248 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5249                                         DeclarationName Name,
5250                                         SourceLocation Loc, bool IsTemplateId) {
5251   DeclContext *Cur = CurContext;
5252   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5253     Cur = Cur->getParent();
5254 
5255   // If the user provided a superfluous scope specifier that refers back to the
5256   // class in which the entity is already declared, diagnose and ignore it.
5257   //
5258   // class X {
5259   //   void X::f();
5260   // };
5261   //
5262   // Note, it was once ill-formed to give redundant qualification in all
5263   // contexts, but that rule was removed by DR482.
5264   if (Cur->Equals(DC)) {
5265     if (Cur->isRecord()) {
5266       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5267                                       : diag::err_member_extra_qualification)
5268         << Name << FixItHint::CreateRemoval(SS.getRange());
5269       SS.clear();
5270     } else {
5271       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5272     }
5273     return false;
5274   }
5275 
5276   // Check whether the qualifying scope encloses the scope of the original
5277   // declaration. For a template-id, we perform the checks in
5278   // CheckTemplateSpecializationScope.
5279   if (!Cur->Encloses(DC) && !IsTemplateId) {
5280     if (Cur->isRecord())
5281       Diag(Loc, diag::err_member_qualification)
5282         << Name << SS.getRange();
5283     else if (isa<TranslationUnitDecl>(DC))
5284       Diag(Loc, diag::err_invalid_declarator_global_scope)
5285         << Name << SS.getRange();
5286     else if (isa<FunctionDecl>(Cur))
5287       Diag(Loc, diag::err_invalid_declarator_in_function)
5288         << Name << SS.getRange();
5289     else if (isa<BlockDecl>(Cur))
5290       Diag(Loc, diag::err_invalid_declarator_in_block)
5291         << Name << SS.getRange();
5292     else
5293       Diag(Loc, diag::err_invalid_declarator_scope)
5294       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5295 
5296     return true;
5297   }
5298 
5299   if (Cur->isRecord()) {
5300     // Cannot qualify members within a class.
5301     Diag(Loc, diag::err_member_qualification)
5302       << Name << SS.getRange();
5303     SS.clear();
5304 
5305     // C++ constructors and destructors with incorrect scopes can break
5306     // our AST invariants by having the wrong underlying types. If
5307     // that's the case, then drop this declaration entirely.
5308     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5309          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5310         !Context.hasSameType(Name.getCXXNameType(),
5311                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5312       return true;
5313 
5314     return false;
5315   }
5316 
5317   // C++11 [dcl.meaning]p1:
5318   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5319   //   not begin with a decltype-specifer"
5320   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5321   while (SpecLoc.getPrefix())
5322     SpecLoc = SpecLoc.getPrefix();
5323   if (dyn_cast_or_null<DecltypeType>(
5324         SpecLoc.getNestedNameSpecifier()->getAsType()))
5325     Diag(Loc, diag::err_decltype_in_declarator)
5326       << SpecLoc.getTypeLoc().getSourceRange();
5327 
5328   return false;
5329 }
5330 
5331 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5332                                   MultiTemplateParamsArg TemplateParamLists) {
5333   // TODO: consider using NameInfo for diagnostic.
5334   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5335   DeclarationName Name = NameInfo.getName();
5336 
5337   // All of these full declarators require an identifier.  If it doesn't have
5338   // one, the ParsedFreeStandingDeclSpec action should be used.
5339   if (D.isDecompositionDeclarator()) {
5340     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5341   } else if (!Name) {
5342     if (!D.isInvalidType())  // Reject this if we think it is valid.
5343       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5344           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5345     return nullptr;
5346   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5347     return nullptr;
5348 
5349   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5350   // we find one that is.
5351   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5352          (S->getFlags() & Scope::TemplateParamScope) != 0)
5353     S = S->getParent();
5354 
5355   DeclContext *DC = CurContext;
5356   if (D.getCXXScopeSpec().isInvalid())
5357     D.setInvalidType();
5358   else if (D.getCXXScopeSpec().isSet()) {
5359     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5360                                         UPPC_DeclarationQualifier))
5361       return nullptr;
5362 
5363     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5364     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5365     if (!DC || isa<EnumDecl>(DC)) {
5366       // If we could not compute the declaration context, it's because the
5367       // declaration context is dependent but does not refer to a class,
5368       // class template, or class template partial specialization. Complain
5369       // and return early, to avoid the coming semantic disaster.
5370       Diag(D.getIdentifierLoc(),
5371            diag::err_template_qualified_declarator_no_match)
5372         << D.getCXXScopeSpec().getScopeRep()
5373         << D.getCXXScopeSpec().getRange();
5374       return nullptr;
5375     }
5376     bool IsDependentContext = DC->isDependentContext();
5377 
5378     if (!IsDependentContext &&
5379         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5380       return nullptr;
5381 
5382     // If a class is incomplete, do not parse entities inside it.
5383     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5384       Diag(D.getIdentifierLoc(),
5385            diag::err_member_def_undefined_record)
5386         << Name << DC << D.getCXXScopeSpec().getRange();
5387       return nullptr;
5388     }
5389     if (!D.getDeclSpec().isFriendSpecified()) {
5390       if (diagnoseQualifiedDeclaration(
5391               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5392               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5393         if (DC->isRecord())
5394           return nullptr;
5395 
5396         D.setInvalidType();
5397       }
5398     }
5399 
5400     // Check whether we need to rebuild the type of the given
5401     // declaration in the current instantiation.
5402     if (EnteringContext && IsDependentContext &&
5403         TemplateParamLists.size() != 0) {
5404       ContextRAII SavedContext(*this, DC);
5405       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5406         D.setInvalidType();
5407     }
5408   }
5409 
5410   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5411   QualType R = TInfo->getType();
5412 
5413   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5414                                       UPPC_DeclarationType))
5415     D.setInvalidType();
5416 
5417   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5418                         forRedeclarationInCurContext());
5419 
5420   // See if this is a redefinition of a variable in the same scope.
5421   if (!D.getCXXScopeSpec().isSet()) {
5422     bool IsLinkageLookup = false;
5423     bool CreateBuiltins = false;
5424 
5425     // If the declaration we're planning to build will be a function
5426     // or object with linkage, then look for another declaration with
5427     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5428     //
5429     // If the declaration we're planning to build will be declared with
5430     // external linkage in the translation unit, create any builtin with
5431     // the same name.
5432     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5433       /* Do nothing*/;
5434     else if (CurContext->isFunctionOrMethod() &&
5435              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5436               R->isFunctionType())) {
5437       IsLinkageLookup = true;
5438       CreateBuiltins =
5439           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5440     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5441                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5442       CreateBuiltins = true;
5443 
5444     if (IsLinkageLookup) {
5445       Previous.clear(LookupRedeclarationWithLinkage);
5446       Previous.setRedeclarationKind(ForExternalRedeclaration);
5447     }
5448 
5449     LookupName(Previous, S, CreateBuiltins);
5450   } else { // Something like "int foo::x;"
5451     LookupQualifiedName(Previous, DC);
5452 
5453     // C++ [dcl.meaning]p1:
5454     //   When the declarator-id is qualified, the declaration shall refer to a
5455     //  previously declared member of the class or namespace to which the
5456     //  qualifier refers (or, in the case of a namespace, of an element of the
5457     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5458     //  thereof; [...]
5459     //
5460     // Note that we already checked the context above, and that we do not have
5461     // enough information to make sure that Previous contains the declaration
5462     // we want to match. For example, given:
5463     //
5464     //   class X {
5465     //     void f();
5466     //     void f(float);
5467     //   };
5468     //
5469     //   void X::f(int) { } // ill-formed
5470     //
5471     // In this case, Previous will point to the overload set
5472     // containing the two f's declared in X, but neither of them
5473     // matches.
5474 
5475     // C++ [dcl.meaning]p1:
5476     //   [...] the member shall not merely have been introduced by a
5477     //   using-declaration in the scope of the class or namespace nominated by
5478     //   the nested-name-specifier of the declarator-id.
5479     RemoveUsingDecls(Previous);
5480   }
5481 
5482   if (Previous.isSingleResult() &&
5483       Previous.getFoundDecl()->isTemplateParameter()) {
5484     // Maybe we will complain about the shadowed template parameter.
5485     if (!D.isInvalidType())
5486       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5487                                       Previous.getFoundDecl());
5488 
5489     // Just pretend that we didn't see the previous declaration.
5490     Previous.clear();
5491   }
5492 
5493   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5494     // Forget that the previous declaration is the injected-class-name.
5495     Previous.clear();
5496 
5497   // In C++, the previous declaration we find might be a tag type
5498   // (class or enum). In this case, the new declaration will hide the
5499   // tag type. Note that this applies to functions, function templates, and
5500   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5501   if (Previous.isSingleTagDecl() &&
5502       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5503       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5504     Previous.clear();
5505 
5506   // Check that there are no default arguments other than in the parameters
5507   // of a function declaration (C++ only).
5508   if (getLangOpts().CPlusPlus)
5509     CheckExtraCXXDefaultArguments(D);
5510 
5511   NamedDecl *New;
5512 
5513   bool AddToScope = true;
5514   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5515     if (TemplateParamLists.size()) {
5516       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5517       return nullptr;
5518     }
5519 
5520     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5521   } else if (R->isFunctionType()) {
5522     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5523                                   TemplateParamLists,
5524                                   AddToScope);
5525   } else {
5526     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5527                                   AddToScope);
5528   }
5529 
5530   if (!New)
5531     return nullptr;
5532 
5533   // If this has an identifier and is not a function template specialization,
5534   // add it to the scope stack.
5535   if (New->getDeclName() && AddToScope)
5536     PushOnScopeChains(New, S);
5537 
5538   if (isInOpenMPDeclareTargetContext())
5539     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5540 
5541   return New;
5542 }
5543 
5544 /// Helper method to turn variable array types into constant array
5545 /// types in certain situations which would otherwise be errors (for
5546 /// GCC compatibility).
5547 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5548                                                     ASTContext &Context,
5549                                                     bool &SizeIsNegative,
5550                                                     llvm::APSInt &Oversized) {
5551   // This method tries to turn a variable array into a constant
5552   // array even when the size isn't an ICE.  This is necessary
5553   // for compatibility with code that depends on gcc's buggy
5554   // constant expression folding, like struct {char x[(int)(char*)2];}
5555   SizeIsNegative = false;
5556   Oversized = 0;
5557 
5558   if (T->isDependentType())
5559     return QualType();
5560 
5561   QualifierCollector Qs;
5562   const Type *Ty = Qs.strip(T);
5563 
5564   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5565     QualType Pointee = PTy->getPointeeType();
5566     QualType FixedType =
5567         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5568                                             Oversized);
5569     if (FixedType.isNull()) return FixedType;
5570     FixedType = Context.getPointerType(FixedType);
5571     return Qs.apply(Context, FixedType);
5572   }
5573   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5574     QualType Inner = PTy->getInnerType();
5575     QualType FixedType =
5576         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5577                                             Oversized);
5578     if (FixedType.isNull()) return FixedType;
5579     FixedType = Context.getParenType(FixedType);
5580     return Qs.apply(Context, FixedType);
5581   }
5582 
5583   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5584   if (!VLATy)
5585     return QualType();
5586   // FIXME: We should probably handle this case
5587   if (VLATy->getElementType()->isVariablyModifiedType())
5588     return QualType();
5589 
5590   Expr::EvalResult Result;
5591   if (!VLATy->getSizeExpr() ||
5592       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5593     return QualType();
5594 
5595   llvm::APSInt Res = Result.Val.getInt();
5596 
5597   // Check whether the array size is negative.
5598   if (Res.isSigned() && Res.isNegative()) {
5599     SizeIsNegative = true;
5600     return QualType();
5601   }
5602 
5603   // Check whether the array is too large to be addressed.
5604   unsigned ActiveSizeBits
5605     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5606                                               Res);
5607   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5608     Oversized = Res;
5609     return QualType();
5610   }
5611 
5612   return Context.getConstantArrayType(VLATy->getElementType(),
5613                                       Res, ArrayType::Normal, 0);
5614 }
5615 
5616 static void
5617 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5618   SrcTL = SrcTL.getUnqualifiedLoc();
5619   DstTL = DstTL.getUnqualifiedLoc();
5620   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5621     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5622     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5623                                       DstPTL.getPointeeLoc());
5624     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5625     return;
5626   }
5627   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5628     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5629     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5630                                       DstPTL.getInnerLoc());
5631     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5632     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5633     return;
5634   }
5635   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5636   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5637   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5638   TypeLoc DstElemTL = DstATL.getElementLoc();
5639   DstElemTL.initializeFullCopy(SrcElemTL);
5640   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5641   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5642   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5643 }
5644 
5645 /// Helper method to turn variable array types into constant array
5646 /// types in certain situations which would otherwise be errors (for
5647 /// GCC compatibility).
5648 static TypeSourceInfo*
5649 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5650                                               ASTContext &Context,
5651                                               bool &SizeIsNegative,
5652                                               llvm::APSInt &Oversized) {
5653   QualType FixedTy
5654     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5655                                           SizeIsNegative, Oversized);
5656   if (FixedTy.isNull())
5657     return nullptr;
5658   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5659   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5660                                     FixedTInfo->getTypeLoc());
5661   return FixedTInfo;
5662 }
5663 
5664 /// Register the given locally-scoped extern "C" declaration so
5665 /// that it can be found later for redeclarations. We include any extern "C"
5666 /// declaration that is not visible in the translation unit here, not just
5667 /// function-scope declarations.
5668 void
5669 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5670   if (!getLangOpts().CPlusPlus &&
5671       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5672     // Don't need to track declarations in the TU in C.
5673     return;
5674 
5675   // Note that we have a locally-scoped external with this name.
5676   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5677 }
5678 
5679 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5680   // FIXME: We can have multiple results via __attribute__((overloadable)).
5681   auto Result = Context.getExternCContextDecl()->lookup(Name);
5682   return Result.empty() ? nullptr : *Result.begin();
5683 }
5684 
5685 /// Diagnose function specifiers on a declaration of an identifier that
5686 /// does not identify a function.
5687 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5688   // FIXME: We should probably indicate the identifier in question to avoid
5689   // confusion for constructs like "virtual int a(), b;"
5690   if (DS.isVirtualSpecified())
5691     Diag(DS.getVirtualSpecLoc(),
5692          diag::err_virtual_non_function);
5693 
5694   if (DS.isExplicitSpecified())
5695     Diag(DS.getExplicitSpecLoc(),
5696          diag::err_explicit_non_function);
5697 
5698   if (DS.isNoreturnSpecified())
5699     Diag(DS.getNoreturnSpecLoc(),
5700          diag::err_noreturn_non_function);
5701 }
5702 
5703 NamedDecl*
5704 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5705                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5706   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5707   if (D.getCXXScopeSpec().isSet()) {
5708     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5709       << D.getCXXScopeSpec().getRange();
5710     D.setInvalidType();
5711     // Pretend we didn't see the scope specifier.
5712     DC = CurContext;
5713     Previous.clear();
5714   }
5715 
5716   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5717 
5718   if (D.getDeclSpec().isInlineSpecified())
5719     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5720         << getLangOpts().CPlusPlus17;
5721   if (D.getDeclSpec().isConstexprSpecified())
5722     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5723       << 1;
5724 
5725   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5726     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5727       Diag(D.getName().StartLocation,
5728            diag::err_deduction_guide_invalid_specifier)
5729           << "typedef";
5730     else
5731       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5732           << D.getName().getSourceRange();
5733     return nullptr;
5734   }
5735 
5736   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5737   if (!NewTD) return nullptr;
5738 
5739   // Handle attributes prior to checking for duplicates in MergeVarDecl
5740   ProcessDeclAttributes(S, NewTD, D);
5741 
5742   CheckTypedefForVariablyModifiedType(S, NewTD);
5743 
5744   bool Redeclaration = D.isRedeclaration();
5745   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5746   D.setRedeclaration(Redeclaration);
5747   return ND;
5748 }
5749 
5750 void
5751 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5752   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5753   // then it shall have block scope.
5754   // Note that variably modified types must be fixed before merging the decl so
5755   // that redeclarations will match.
5756   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5757   QualType T = TInfo->getType();
5758   if (T->isVariablyModifiedType()) {
5759     setFunctionHasBranchProtectedScope();
5760 
5761     if (S->getFnParent() == nullptr) {
5762       bool SizeIsNegative;
5763       llvm::APSInt Oversized;
5764       TypeSourceInfo *FixedTInfo =
5765         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5766                                                       SizeIsNegative,
5767                                                       Oversized);
5768       if (FixedTInfo) {
5769         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5770         NewTD->setTypeSourceInfo(FixedTInfo);
5771       } else {
5772         if (SizeIsNegative)
5773           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5774         else if (T->isVariableArrayType())
5775           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5776         else if (Oversized.getBoolValue())
5777           Diag(NewTD->getLocation(), diag::err_array_too_large)
5778             << Oversized.toString(10);
5779         else
5780           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5781         NewTD->setInvalidDecl();
5782       }
5783     }
5784   }
5785 }
5786 
5787 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5788 /// declares a typedef-name, either using the 'typedef' type specifier or via
5789 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5790 NamedDecl*
5791 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5792                            LookupResult &Previous, bool &Redeclaration) {
5793 
5794   // Find the shadowed declaration before filtering for scope.
5795   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5796 
5797   // Merge the decl with the existing one if appropriate. If the decl is
5798   // in an outer scope, it isn't the same thing.
5799   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5800                        /*AllowInlineNamespace*/false);
5801   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5802   if (!Previous.empty()) {
5803     Redeclaration = true;
5804     MergeTypedefNameDecl(S, NewTD, Previous);
5805   }
5806 
5807   if (ShadowedDecl && !Redeclaration)
5808     CheckShadow(NewTD, ShadowedDecl, Previous);
5809 
5810   // If this is the C FILE type, notify the AST context.
5811   if (IdentifierInfo *II = NewTD->getIdentifier())
5812     if (!NewTD->isInvalidDecl() &&
5813         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5814       if (II->isStr("FILE"))
5815         Context.setFILEDecl(NewTD);
5816       else if (II->isStr("jmp_buf"))
5817         Context.setjmp_bufDecl(NewTD);
5818       else if (II->isStr("sigjmp_buf"))
5819         Context.setsigjmp_bufDecl(NewTD);
5820       else if (II->isStr("ucontext_t"))
5821         Context.setucontext_tDecl(NewTD);
5822     }
5823 
5824   return NewTD;
5825 }
5826 
5827 /// Determines whether the given declaration is an out-of-scope
5828 /// previous declaration.
5829 ///
5830 /// This routine should be invoked when name lookup has found a
5831 /// previous declaration (PrevDecl) that is not in the scope where a
5832 /// new declaration by the same name is being introduced. If the new
5833 /// declaration occurs in a local scope, previous declarations with
5834 /// linkage may still be considered previous declarations (C99
5835 /// 6.2.2p4-5, C++ [basic.link]p6).
5836 ///
5837 /// \param PrevDecl the previous declaration found by name
5838 /// lookup
5839 ///
5840 /// \param DC the context in which the new declaration is being
5841 /// declared.
5842 ///
5843 /// \returns true if PrevDecl is an out-of-scope previous declaration
5844 /// for a new delcaration with the same name.
5845 static bool
5846 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5847                                 ASTContext &Context) {
5848   if (!PrevDecl)
5849     return false;
5850 
5851   if (!PrevDecl->hasLinkage())
5852     return false;
5853 
5854   if (Context.getLangOpts().CPlusPlus) {
5855     // C++ [basic.link]p6:
5856     //   If there is a visible declaration of an entity with linkage
5857     //   having the same name and type, ignoring entities declared
5858     //   outside the innermost enclosing namespace scope, the block
5859     //   scope declaration declares that same entity and receives the
5860     //   linkage of the previous declaration.
5861     DeclContext *OuterContext = DC->getRedeclContext();
5862     if (!OuterContext->isFunctionOrMethod())
5863       // This rule only applies to block-scope declarations.
5864       return false;
5865 
5866     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5867     if (PrevOuterContext->isRecord())
5868       // We found a member function: ignore it.
5869       return false;
5870 
5871     // Find the innermost enclosing namespace for the new and
5872     // previous declarations.
5873     OuterContext = OuterContext->getEnclosingNamespaceContext();
5874     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5875 
5876     // The previous declaration is in a different namespace, so it
5877     // isn't the same function.
5878     if (!OuterContext->Equals(PrevOuterContext))
5879       return false;
5880   }
5881 
5882   return true;
5883 }
5884 
5885 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
5886   CXXScopeSpec &SS = D.getCXXScopeSpec();
5887   if (!SS.isSet()) return;
5888   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
5889 }
5890 
5891 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5892   QualType type = decl->getType();
5893   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5894   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5895     // Various kinds of declaration aren't allowed to be __autoreleasing.
5896     unsigned kind = -1U;
5897     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5898       if (var->hasAttr<BlocksAttr>())
5899         kind = 0; // __block
5900       else if (!var->hasLocalStorage())
5901         kind = 1; // global
5902     } else if (isa<ObjCIvarDecl>(decl)) {
5903       kind = 3; // ivar
5904     } else if (isa<FieldDecl>(decl)) {
5905       kind = 2; // field
5906     }
5907 
5908     if (kind != -1U) {
5909       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5910         << kind;
5911     }
5912   } else if (lifetime == Qualifiers::OCL_None) {
5913     // Try to infer lifetime.
5914     if (!type->isObjCLifetimeType())
5915       return false;
5916 
5917     lifetime = type->getObjCARCImplicitLifetime();
5918     type = Context.getLifetimeQualifiedType(type, lifetime);
5919     decl->setType(type);
5920   }
5921 
5922   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5923     // Thread-local variables cannot have lifetime.
5924     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5925         var->getTLSKind()) {
5926       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5927         << var->getType();
5928       return true;
5929     }
5930   }
5931 
5932   return false;
5933 }
5934 
5935 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5936   // Ensure that an auto decl is deduced otherwise the checks below might cache
5937   // the wrong linkage.
5938   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5939 
5940   // 'weak' only applies to declarations with external linkage.
5941   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5942     if (!ND.isExternallyVisible()) {
5943       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5944       ND.dropAttr<WeakAttr>();
5945     }
5946   }
5947   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5948     if (ND.isExternallyVisible()) {
5949       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5950       ND.dropAttr<WeakRefAttr>();
5951       ND.dropAttr<AliasAttr>();
5952     }
5953   }
5954 
5955   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5956     if (VD->hasInit()) {
5957       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5958         assert(VD->isThisDeclarationADefinition() &&
5959                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5960         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5961         VD->dropAttr<AliasAttr>();
5962       }
5963     }
5964   }
5965 
5966   // 'selectany' only applies to externally visible variable declarations.
5967   // It does not apply to functions.
5968   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5969     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5970       S.Diag(Attr->getLocation(),
5971              diag::err_attribute_selectany_non_extern_data);
5972       ND.dropAttr<SelectAnyAttr>();
5973     }
5974   }
5975 
5976   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5977     auto *VD = dyn_cast<VarDecl>(&ND);
5978     bool IsAnonymousNS = false;
5979     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5980     if (VD) {
5981       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
5982       while (NS && !IsAnonymousNS) {
5983         IsAnonymousNS = NS->isAnonymousNamespace();
5984         NS = dyn_cast<NamespaceDecl>(NS->getParent());
5985       }
5986     }
5987     // dll attributes require external linkage. Static locals may have external
5988     // linkage but still cannot be explicitly imported or exported.
5989     // In Microsoft mode, a variable defined in anonymous namespace must have
5990     // external linkage in order to be exported.
5991     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
5992     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
5993         (!AnonNSInMicrosoftMode &&
5994          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
5995       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5996         << &ND << Attr;
5997       ND.setInvalidDecl();
5998     }
5999   }
6000 
6001   // Virtual functions cannot be marked as 'notail'.
6002   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6003     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6004       if (MD->isVirtual()) {
6005         S.Diag(ND.getLocation(),
6006                diag::err_invalid_attribute_on_virtual_function)
6007             << Attr;
6008         ND.dropAttr<NotTailCalledAttr>();
6009       }
6010 
6011   // Check the attributes on the function type, if any.
6012   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6013     // Don't declare this variable in the second operand of the for-statement;
6014     // GCC miscompiles that by ending its lifetime before evaluating the
6015     // third operand. See gcc.gnu.org/PR86769.
6016     AttributedTypeLoc ATL;
6017     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6018          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6019          TL = ATL.getModifiedLoc()) {
6020       // The [[lifetimebound]] attribute can be applied to the implicit object
6021       // parameter of a non-static member function (other than a ctor or dtor)
6022       // by applying it to the function type.
6023       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6024         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6025         if (!MD || MD->isStatic()) {
6026           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6027               << !MD << A->getRange();
6028         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6029           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6030               << isa<CXXDestructorDecl>(MD) << A->getRange();
6031         }
6032       }
6033     }
6034   }
6035 }
6036 
6037 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6038                                            NamedDecl *NewDecl,
6039                                            bool IsSpecialization,
6040                                            bool IsDefinition) {
6041   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6042     return;
6043 
6044   bool IsTemplate = false;
6045   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6046     OldDecl = OldTD->getTemplatedDecl();
6047     IsTemplate = true;
6048     if (!IsSpecialization)
6049       IsDefinition = false;
6050   }
6051   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6052     NewDecl = NewTD->getTemplatedDecl();
6053     IsTemplate = true;
6054   }
6055 
6056   if (!OldDecl || !NewDecl)
6057     return;
6058 
6059   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6060   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6061   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6062   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6063 
6064   // dllimport and dllexport are inheritable attributes so we have to exclude
6065   // inherited attribute instances.
6066   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6067                     (NewExportAttr && !NewExportAttr->isInherited());
6068 
6069   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6070   // the only exception being explicit specializations.
6071   // Implicitly generated declarations are also excluded for now because there
6072   // is no other way to switch these to use dllimport or dllexport.
6073   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6074 
6075   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6076     // Allow with a warning for free functions and global variables.
6077     bool JustWarn = false;
6078     if (!OldDecl->isCXXClassMember()) {
6079       auto *VD = dyn_cast<VarDecl>(OldDecl);
6080       if (VD && !VD->getDescribedVarTemplate())
6081         JustWarn = true;
6082       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6083       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6084         JustWarn = true;
6085     }
6086 
6087     // We cannot change a declaration that's been used because IR has already
6088     // been emitted. Dllimported functions will still work though (modulo
6089     // address equality) as they can use the thunk.
6090     if (OldDecl->isUsed())
6091       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6092         JustWarn = false;
6093 
6094     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6095                                : diag::err_attribute_dll_redeclaration;
6096     S.Diag(NewDecl->getLocation(), DiagID)
6097         << NewDecl
6098         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6099     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6100     if (!JustWarn) {
6101       NewDecl->setInvalidDecl();
6102       return;
6103     }
6104   }
6105 
6106   // A redeclaration is not allowed to drop a dllimport attribute, the only
6107   // exceptions being inline function definitions (except for function
6108   // templates), local extern declarations, qualified friend declarations or
6109   // special MSVC extension: in the last case, the declaration is treated as if
6110   // it were marked dllexport.
6111   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6112   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6113   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6114     // Ignore static data because out-of-line definitions are diagnosed
6115     // separately.
6116     IsStaticDataMember = VD->isStaticDataMember();
6117     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6118                    VarDecl::DeclarationOnly;
6119   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6120     IsInline = FD->isInlined();
6121     IsQualifiedFriend = FD->getQualifier() &&
6122                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6123   }
6124 
6125   if (OldImportAttr && !HasNewAttr &&
6126       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6127       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6128     if (IsMicrosoft && IsDefinition) {
6129       S.Diag(NewDecl->getLocation(),
6130              diag::warn_redeclaration_without_import_attribute)
6131           << NewDecl;
6132       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6133       NewDecl->dropAttr<DLLImportAttr>();
6134       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6135           NewImportAttr->getRange(), S.Context,
6136           NewImportAttr->getSpellingListIndex()));
6137     } else {
6138       S.Diag(NewDecl->getLocation(),
6139              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6140           << NewDecl << OldImportAttr;
6141       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6142       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6143       OldDecl->dropAttr<DLLImportAttr>();
6144       NewDecl->dropAttr<DLLImportAttr>();
6145     }
6146   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6147     // In MinGW, seeing a function declared inline drops the dllimport
6148     // attribute.
6149     OldDecl->dropAttr<DLLImportAttr>();
6150     NewDecl->dropAttr<DLLImportAttr>();
6151     S.Diag(NewDecl->getLocation(),
6152            diag::warn_dllimport_dropped_from_inline_function)
6153         << NewDecl << OldImportAttr;
6154   }
6155 
6156   // A specialization of a class template member function is processed here
6157   // since it's a redeclaration. If the parent class is dllexport, the
6158   // specialization inherits that attribute. This doesn't happen automatically
6159   // since the parent class isn't instantiated until later.
6160   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6161     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6162         !NewImportAttr && !NewExportAttr) {
6163       if (const DLLExportAttr *ParentExportAttr =
6164               MD->getParent()->getAttr<DLLExportAttr>()) {
6165         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6166         NewAttr->setInherited(true);
6167         NewDecl->addAttr(NewAttr);
6168       }
6169     }
6170   }
6171 }
6172 
6173 /// Given that we are within the definition of the given function,
6174 /// will that definition behave like C99's 'inline', where the
6175 /// definition is discarded except for optimization purposes?
6176 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6177   // Try to avoid calling GetGVALinkageForFunction.
6178 
6179   // All cases of this require the 'inline' keyword.
6180   if (!FD->isInlined()) return false;
6181 
6182   // This is only possible in C++ with the gnu_inline attribute.
6183   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6184     return false;
6185 
6186   // Okay, go ahead and call the relatively-more-expensive function.
6187   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6188 }
6189 
6190 /// Determine whether a variable is extern "C" prior to attaching
6191 /// an initializer. We can't just call isExternC() here, because that
6192 /// will also compute and cache whether the declaration is externally
6193 /// visible, which might change when we attach the initializer.
6194 ///
6195 /// This can only be used if the declaration is known to not be a
6196 /// redeclaration of an internal linkage declaration.
6197 ///
6198 /// For instance:
6199 ///
6200 ///   auto x = []{};
6201 ///
6202 /// Attaching the initializer here makes this declaration not externally
6203 /// visible, because its type has internal linkage.
6204 ///
6205 /// FIXME: This is a hack.
6206 template<typename T>
6207 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6208   if (S.getLangOpts().CPlusPlus) {
6209     // In C++, the overloadable attribute negates the effects of extern "C".
6210     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6211       return false;
6212 
6213     // So do CUDA's host/device attributes.
6214     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6215                                  D->template hasAttr<CUDAHostAttr>()))
6216       return false;
6217   }
6218   return D->isExternC();
6219 }
6220 
6221 static bool shouldConsiderLinkage(const VarDecl *VD) {
6222   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6223   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6224       isa<OMPDeclareMapperDecl>(DC))
6225     return VD->hasExternalStorage();
6226   if (DC->isFileContext())
6227     return true;
6228   if (DC->isRecord())
6229     return false;
6230   llvm_unreachable("Unexpected context");
6231 }
6232 
6233 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6234   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6235   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6236       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6237     return true;
6238   if (DC->isRecord())
6239     return false;
6240   llvm_unreachable("Unexpected context");
6241 }
6242 
6243 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6244                           ParsedAttr::Kind Kind) {
6245   // Check decl attributes on the DeclSpec.
6246   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6247     return true;
6248 
6249   // Walk the declarator structure, checking decl attributes that were in a type
6250   // position to the decl itself.
6251   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6252     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6253       return true;
6254   }
6255 
6256   // Finally, check attributes on the decl itself.
6257   return PD.getAttributes().hasAttribute(Kind);
6258 }
6259 
6260 /// Adjust the \c DeclContext for a function or variable that might be a
6261 /// function-local external declaration.
6262 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6263   if (!DC->isFunctionOrMethod())
6264     return false;
6265 
6266   // If this is a local extern function or variable declared within a function
6267   // template, don't add it into the enclosing namespace scope until it is
6268   // instantiated; it might have a dependent type right now.
6269   if (DC->isDependentContext())
6270     return true;
6271 
6272   // C++11 [basic.link]p7:
6273   //   When a block scope declaration of an entity with linkage is not found to
6274   //   refer to some other declaration, then that entity is a member of the
6275   //   innermost enclosing namespace.
6276   //
6277   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6278   // semantically-enclosing namespace, not a lexically-enclosing one.
6279   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6280     DC = DC->getParent();
6281   return true;
6282 }
6283 
6284 /// Returns true if given declaration has external C language linkage.
6285 static bool isDeclExternC(const Decl *D) {
6286   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6287     return FD->isExternC();
6288   if (const auto *VD = dyn_cast<VarDecl>(D))
6289     return VD->isExternC();
6290 
6291   llvm_unreachable("Unknown type of decl!");
6292 }
6293 
6294 NamedDecl *Sema::ActOnVariableDeclarator(
6295     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6296     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6297     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6298   QualType R = TInfo->getType();
6299   DeclarationName Name = GetNameForDeclarator(D).getName();
6300 
6301   IdentifierInfo *II = Name.getAsIdentifierInfo();
6302 
6303   if (D.isDecompositionDeclarator()) {
6304     // Take the name of the first declarator as our name for diagnostic
6305     // purposes.
6306     auto &Decomp = D.getDecompositionDeclarator();
6307     if (!Decomp.bindings().empty()) {
6308       II = Decomp.bindings()[0].Name;
6309       Name = II;
6310     }
6311   } else if (!II) {
6312     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6313     return nullptr;
6314   }
6315 
6316   if (getLangOpts().OpenCL) {
6317     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6318     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6319     // argument.
6320     if (R->isImageType() || R->isPipeType()) {
6321       Diag(D.getIdentifierLoc(),
6322            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6323           << R;
6324       D.setInvalidType();
6325       return nullptr;
6326     }
6327 
6328     // OpenCL v1.2 s6.9.r:
6329     // The event type cannot be used to declare a program scope variable.
6330     // OpenCL v2.0 s6.9.q:
6331     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6332     if (NULL == S->getParent()) {
6333       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6334         Diag(D.getIdentifierLoc(),
6335              diag::err_invalid_type_for_program_scope_var) << R;
6336         D.setInvalidType();
6337         return nullptr;
6338       }
6339     }
6340 
6341     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6342     QualType NR = R;
6343     while (NR->isPointerType()) {
6344       if (NR->isFunctionPointerType()) {
6345         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6346         D.setInvalidType();
6347         break;
6348       }
6349       NR = NR->getPointeeType();
6350     }
6351 
6352     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6353       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6354       // half array type (unless the cl_khr_fp16 extension is enabled).
6355       if (Context.getBaseElementType(R)->isHalfType()) {
6356         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6357         D.setInvalidType();
6358       }
6359     }
6360 
6361     if (R->isSamplerT()) {
6362       // OpenCL v1.2 s6.9.b p4:
6363       // The sampler type cannot be used with the __local and __global address
6364       // space qualifiers.
6365       if (R.getAddressSpace() == LangAS::opencl_local ||
6366           R.getAddressSpace() == LangAS::opencl_global) {
6367         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6368       }
6369 
6370       // OpenCL v1.2 s6.12.14.1:
6371       // A global sampler must be declared with either the constant address
6372       // space qualifier or with the const qualifier.
6373       if (DC->isTranslationUnit() &&
6374           !(R.getAddressSpace() == LangAS::opencl_constant ||
6375           R.isConstQualified())) {
6376         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6377         D.setInvalidType();
6378       }
6379     }
6380 
6381     // OpenCL v1.2 s6.9.r:
6382     // The event type cannot be used with the __local, __constant and __global
6383     // address space qualifiers.
6384     if (R->isEventT()) {
6385       if (R.getAddressSpace() != LangAS::opencl_private) {
6386         Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6387         D.setInvalidType();
6388       }
6389     }
6390 
6391     // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not
6392     // supported.  OpenCL C does not support thread_local either, and
6393     // also reject all other thread storage class specifiers.
6394     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6395     if (TSC != TSCS_unspecified) {
6396       bool IsCXX = getLangOpts().OpenCLCPlusPlus;
6397       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6398            diag::err_opencl_unknown_type_specifier)
6399           << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
6400           << DeclSpec::getSpecifierName(TSC) << 1;
6401       D.setInvalidType();
6402       return nullptr;
6403     }
6404   }
6405 
6406   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6407   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6408 
6409   // dllimport globals without explicit storage class are treated as extern. We
6410   // have to change the storage class this early to get the right DeclContext.
6411   if (SC == SC_None && !DC->isRecord() &&
6412       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6413       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6414     SC = SC_Extern;
6415 
6416   DeclContext *OriginalDC = DC;
6417   bool IsLocalExternDecl = SC == SC_Extern &&
6418                            adjustContextForLocalExternDecl(DC);
6419 
6420   if (SCSpec == DeclSpec::SCS_mutable) {
6421     // mutable can only appear on non-static class members, so it's always
6422     // an error here
6423     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6424     D.setInvalidType();
6425     SC = SC_None;
6426   }
6427 
6428   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6429       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6430                               D.getDeclSpec().getStorageClassSpecLoc())) {
6431     // In C++11, the 'register' storage class specifier is deprecated.
6432     // Suppress the warning in system macros, it's used in macros in some
6433     // popular C system headers, such as in glibc's htonl() macro.
6434     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6435          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6436                                    : diag::warn_deprecated_register)
6437       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6438   }
6439 
6440   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6441 
6442   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6443     // C99 6.9p2: The storage-class specifiers auto and register shall not
6444     // appear in the declaration specifiers in an external declaration.
6445     // Global Register+Asm is a GNU extension we support.
6446     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6447       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6448       D.setInvalidType();
6449     }
6450   }
6451 
6452   bool IsMemberSpecialization = false;
6453   bool IsVariableTemplateSpecialization = false;
6454   bool IsPartialSpecialization = false;
6455   bool IsVariableTemplate = false;
6456   VarDecl *NewVD = nullptr;
6457   VarTemplateDecl *NewTemplate = nullptr;
6458   TemplateParameterList *TemplateParams = nullptr;
6459   if (!getLangOpts().CPlusPlus) {
6460     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6461                             II, R, TInfo, SC);
6462 
6463     if (R->getContainedDeducedType())
6464       ParsingInitForAutoVars.insert(NewVD);
6465 
6466     if (D.isInvalidType())
6467       NewVD->setInvalidDecl();
6468   } else {
6469     bool Invalid = false;
6470 
6471     if (DC->isRecord() && !CurContext->isRecord()) {
6472       // This is an out-of-line definition of a static data member.
6473       switch (SC) {
6474       case SC_None:
6475         break;
6476       case SC_Static:
6477         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6478              diag::err_static_out_of_line)
6479           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6480         break;
6481       case SC_Auto:
6482       case SC_Register:
6483       case SC_Extern:
6484         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6485         // to names of variables declared in a block or to function parameters.
6486         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6487         // of class members
6488 
6489         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6490              diag::err_storage_class_for_static_member)
6491           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6492         break;
6493       case SC_PrivateExtern:
6494         llvm_unreachable("C storage class in c++!");
6495       }
6496     }
6497 
6498     if (SC == SC_Static && CurContext->isRecord()) {
6499       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6500         if (RD->isLocalClass())
6501           Diag(D.getIdentifierLoc(),
6502                diag::err_static_data_member_not_allowed_in_local_class)
6503             << Name << RD->getDeclName();
6504 
6505         // C++98 [class.union]p1: If a union contains a static data member,
6506         // the program is ill-formed. C++11 drops this restriction.
6507         if (RD->isUnion())
6508           Diag(D.getIdentifierLoc(),
6509                getLangOpts().CPlusPlus11
6510                  ? diag::warn_cxx98_compat_static_data_member_in_union
6511                  : diag::ext_static_data_member_in_union) << Name;
6512         // We conservatively disallow static data members in anonymous structs.
6513         else if (!RD->getDeclName())
6514           Diag(D.getIdentifierLoc(),
6515                diag::err_static_data_member_not_allowed_in_anon_struct)
6516             << Name << RD->isUnion();
6517       }
6518     }
6519 
6520     // Match up the template parameter lists with the scope specifier, then
6521     // determine whether we have a template or a template specialization.
6522     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6523         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6524         D.getCXXScopeSpec(),
6525         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6526             ? D.getName().TemplateId
6527             : nullptr,
6528         TemplateParamLists,
6529         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6530 
6531     if (TemplateParams) {
6532       if (!TemplateParams->size() &&
6533           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6534         // There is an extraneous 'template<>' for this variable. Complain
6535         // about it, but allow the declaration of the variable.
6536         Diag(TemplateParams->getTemplateLoc(),
6537              diag::err_template_variable_noparams)
6538           << II
6539           << SourceRange(TemplateParams->getTemplateLoc(),
6540                          TemplateParams->getRAngleLoc());
6541         TemplateParams = nullptr;
6542       } else {
6543         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6544           // This is an explicit specialization or a partial specialization.
6545           // FIXME: Check that we can declare a specialization here.
6546           IsVariableTemplateSpecialization = true;
6547           IsPartialSpecialization = TemplateParams->size() > 0;
6548         } else { // if (TemplateParams->size() > 0)
6549           // This is a template declaration.
6550           IsVariableTemplate = true;
6551 
6552           // Check that we can declare a template here.
6553           if (CheckTemplateDeclScope(S, TemplateParams))
6554             return nullptr;
6555 
6556           // Only C++1y supports variable templates (N3651).
6557           Diag(D.getIdentifierLoc(),
6558                getLangOpts().CPlusPlus14
6559                    ? diag::warn_cxx11_compat_variable_template
6560                    : diag::ext_variable_template);
6561         }
6562       }
6563     } else {
6564       assert((Invalid ||
6565               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6566              "should have a 'template<>' for this decl");
6567     }
6568 
6569     if (IsVariableTemplateSpecialization) {
6570       SourceLocation TemplateKWLoc =
6571           TemplateParamLists.size() > 0
6572               ? TemplateParamLists[0]->getTemplateLoc()
6573               : SourceLocation();
6574       DeclResult Res = ActOnVarTemplateSpecialization(
6575           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6576           IsPartialSpecialization);
6577       if (Res.isInvalid())
6578         return nullptr;
6579       NewVD = cast<VarDecl>(Res.get());
6580       AddToScope = false;
6581     } else if (D.isDecompositionDeclarator()) {
6582       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6583                                         D.getIdentifierLoc(), R, TInfo, SC,
6584                                         Bindings);
6585     } else
6586       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6587                               D.getIdentifierLoc(), II, R, TInfo, SC);
6588 
6589     // If this is supposed to be a variable template, create it as such.
6590     if (IsVariableTemplate) {
6591       NewTemplate =
6592           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6593                                   TemplateParams, NewVD);
6594       NewVD->setDescribedVarTemplate(NewTemplate);
6595     }
6596 
6597     // If this decl has an auto type in need of deduction, make a note of the
6598     // Decl so we can diagnose uses of it in its own initializer.
6599     if (R->getContainedDeducedType())
6600       ParsingInitForAutoVars.insert(NewVD);
6601 
6602     if (D.isInvalidType() || Invalid) {
6603       NewVD->setInvalidDecl();
6604       if (NewTemplate)
6605         NewTemplate->setInvalidDecl();
6606     }
6607 
6608     SetNestedNameSpecifier(*this, NewVD, D);
6609 
6610     // If we have any template parameter lists that don't directly belong to
6611     // the variable (matching the scope specifier), store them.
6612     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6613     if (TemplateParamLists.size() > VDTemplateParamLists)
6614       NewVD->setTemplateParameterListsInfo(
6615           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6616 
6617     if (D.getDeclSpec().isConstexprSpecified()) {
6618       NewVD->setConstexpr(true);
6619       // C++1z [dcl.spec.constexpr]p1:
6620       //   A static data member declared with the constexpr specifier is
6621       //   implicitly an inline variable.
6622       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
6623         NewVD->setImplicitlyInline();
6624     }
6625   }
6626 
6627   if (D.getDeclSpec().isInlineSpecified()) {
6628     if (!getLangOpts().CPlusPlus) {
6629       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6630           << 0;
6631     } else if (CurContext->isFunctionOrMethod()) {
6632       // 'inline' is not allowed on block scope variable declaration.
6633       Diag(D.getDeclSpec().getInlineSpecLoc(),
6634            diag::err_inline_declaration_block_scope) << Name
6635         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6636     } else {
6637       Diag(D.getDeclSpec().getInlineSpecLoc(),
6638            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6639                                      : diag::ext_inline_variable);
6640       NewVD->setInlineSpecified();
6641     }
6642   }
6643 
6644   // Set the lexical context. If the declarator has a C++ scope specifier, the
6645   // lexical context will be different from the semantic context.
6646   NewVD->setLexicalDeclContext(CurContext);
6647   if (NewTemplate)
6648     NewTemplate->setLexicalDeclContext(CurContext);
6649 
6650   if (IsLocalExternDecl) {
6651     if (D.isDecompositionDeclarator())
6652       for (auto *B : Bindings)
6653         B->setLocalExternDecl();
6654     else
6655       NewVD->setLocalExternDecl();
6656   }
6657 
6658   bool EmitTLSUnsupportedError = false;
6659   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6660     // C++11 [dcl.stc]p4:
6661     //   When thread_local is applied to a variable of block scope the
6662     //   storage-class-specifier static is implied if it does not appear
6663     //   explicitly.
6664     // Core issue: 'static' is not implied if the variable is declared
6665     //   'extern'.
6666     if (NewVD->hasLocalStorage() &&
6667         (SCSpec != DeclSpec::SCS_unspecified ||
6668          TSCS != DeclSpec::TSCS_thread_local ||
6669          !DC->isFunctionOrMethod()))
6670       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6671            diag::err_thread_non_global)
6672         << DeclSpec::getSpecifierName(TSCS);
6673     else if (!Context.getTargetInfo().isTLSSupported()) {
6674       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6675         // Postpone error emission until we've collected attributes required to
6676         // figure out whether it's a host or device variable and whether the
6677         // error should be ignored.
6678         EmitTLSUnsupportedError = true;
6679         // We still need to mark the variable as TLS so it shows up in AST with
6680         // proper storage class for other tools to use even if we're not going
6681         // to emit any code for it.
6682         NewVD->setTSCSpec(TSCS);
6683       } else
6684         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6685              diag::err_thread_unsupported);
6686     } else
6687       NewVD->setTSCSpec(TSCS);
6688   }
6689 
6690   // C99 6.7.4p3
6691   //   An inline definition of a function with external linkage shall
6692   //   not contain a definition of a modifiable object with static or
6693   //   thread storage duration...
6694   // We only apply this when the function is required to be defined
6695   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6696   // that a local variable with thread storage duration still has to
6697   // be marked 'static'.  Also note that it's possible to get these
6698   // semantics in C++ using __attribute__((gnu_inline)).
6699   if (SC == SC_Static && S->getFnParent() != nullptr &&
6700       !NewVD->getType().isConstQualified()) {
6701     FunctionDecl *CurFD = getCurFunctionDecl();
6702     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6703       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6704            diag::warn_static_local_in_extern_inline);
6705       MaybeSuggestAddingStaticToDecl(CurFD);
6706     }
6707   }
6708 
6709   if (D.getDeclSpec().isModulePrivateSpecified()) {
6710     if (IsVariableTemplateSpecialization)
6711       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6712           << (IsPartialSpecialization ? 1 : 0)
6713           << FixItHint::CreateRemoval(
6714                  D.getDeclSpec().getModulePrivateSpecLoc());
6715     else if (IsMemberSpecialization)
6716       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6717         << 2
6718         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6719     else if (NewVD->hasLocalStorage())
6720       Diag(NewVD->getLocation(), diag::err_module_private_local)
6721         << 0 << NewVD->getDeclName()
6722         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6723         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6724     else {
6725       NewVD->setModulePrivate();
6726       if (NewTemplate)
6727         NewTemplate->setModulePrivate();
6728       for (auto *B : Bindings)
6729         B->setModulePrivate();
6730     }
6731   }
6732 
6733   // Handle attributes prior to checking for duplicates in MergeVarDecl
6734   ProcessDeclAttributes(S, NewVD, D);
6735 
6736   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6737     if (EmitTLSUnsupportedError &&
6738         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6739          (getLangOpts().OpenMPIsDevice &&
6740           NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6741       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6742            diag::err_thread_unsupported);
6743     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6744     // storage [duration]."
6745     if (SC == SC_None && S->getFnParent() != nullptr &&
6746         (NewVD->hasAttr<CUDASharedAttr>() ||
6747          NewVD->hasAttr<CUDAConstantAttr>())) {
6748       NewVD->setStorageClass(SC_Static);
6749     }
6750   }
6751 
6752   // Ensure that dllimport globals without explicit storage class are treated as
6753   // extern. The storage class is set above using parsed attributes. Now we can
6754   // check the VarDecl itself.
6755   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6756          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6757          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6758 
6759   // In auto-retain/release, infer strong retension for variables of
6760   // retainable type.
6761   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6762     NewVD->setInvalidDecl();
6763 
6764   // Handle GNU asm-label extension (encoded as an attribute).
6765   if (Expr *E = (Expr*)D.getAsmLabel()) {
6766     // The parser guarantees this is a string.
6767     StringLiteral *SE = cast<StringLiteral>(E);
6768     StringRef Label = SE->getString();
6769     if (S->getFnParent() != nullptr) {
6770       switch (SC) {
6771       case SC_None:
6772       case SC_Auto:
6773         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6774         break;
6775       case SC_Register:
6776         // Local Named register
6777         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6778             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6779           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6780         break;
6781       case SC_Static:
6782       case SC_Extern:
6783       case SC_PrivateExtern:
6784         break;
6785       }
6786     } else if (SC == SC_Register) {
6787       // Global Named register
6788       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6789         const auto &TI = Context.getTargetInfo();
6790         bool HasSizeMismatch;
6791 
6792         if (!TI.isValidGCCRegisterName(Label))
6793           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6794         else if (!TI.validateGlobalRegisterVariable(Label,
6795                                                     Context.getTypeSize(R),
6796                                                     HasSizeMismatch))
6797           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6798         else if (HasSizeMismatch)
6799           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6800       }
6801 
6802       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6803         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
6804         NewVD->setInvalidDecl(true);
6805       }
6806     }
6807 
6808     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6809                                                 Context, Label, 0));
6810   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6811     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6812       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6813     if (I != ExtnameUndeclaredIdentifiers.end()) {
6814       if (isDeclExternC(NewVD)) {
6815         NewVD->addAttr(I->second);
6816         ExtnameUndeclaredIdentifiers.erase(I);
6817       } else
6818         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6819             << /*Variable*/1 << NewVD;
6820     }
6821   }
6822 
6823   // Find the shadowed declaration before filtering for scope.
6824   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6825                                 ? getShadowedDeclaration(NewVD, Previous)
6826                                 : nullptr;
6827 
6828   // Don't consider existing declarations that are in a different
6829   // scope and are out-of-semantic-context declarations (if the new
6830   // declaration has linkage).
6831   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6832                        D.getCXXScopeSpec().isNotEmpty() ||
6833                        IsMemberSpecialization ||
6834                        IsVariableTemplateSpecialization);
6835 
6836   // Check whether the previous declaration is in the same block scope. This
6837   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6838   if (getLangOpts().CPlusPlus &&
6839       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6840     NewVD->setPreviousDeclInSameBlockScope(
6841         Previous.isSingleResult() && !Previous.isShadowed() &&
6842         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6843 
6844   if (!getLangOpts().CPlusPlus) {
6845     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6846   } else {
6847     // If this is an explicit specialization of a static data member, check it.
6848     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6849         CheckMemberSpecialization(NewVD, Previous))
6850       NewVD->setInvalidDecl();
6851 
6852     // Merge the decl with the existing one if appropriate.
6853     if (!Previous.empty()) {
6854       if (Previous.isSingleResult() &&
6855           isa<FieldDecl>(Previous.getFoundDecl()) &&
6856           D.getCXXScopeSpec().isSet()) {
6857         // The user tried to define a non-static data member
6858         // out-of-line (C++ [dcl.meaning]p1).
6859         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6860           << D.getCXXScopeSpec().getRange();
6861         Previous.clear();
6862         NewVD->setInvalidDecl();
6863       }
6864     } else if (D.getCXXScopeSpec().isSet()) {
6865       // No previous declaration in the qualifying scope.
6866       Diag(D.getIdentifierLoc(), diag::err_no_member)
6867         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6868         << D.getCXXScopeSpec().getRange();
6869       NewVD->setInvalidDecl();
6870     }
6871 
6872     if (!IsVariableTemplateSpecialization)
6873       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6874 
6875     if (NewTemplate) {
6876       VarTemplateDecl *PrevVarTemplate =
6877           NewVD->getPreviousDecl()
6878               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6879               : nullptr;
6880 
6881       // Check the template parameter list of this declaration, possibly
6882       // merging in the template parameter list from the previous variable
6883       // template declaration.
6884       if (CheckTemplateParameterList(
6885               TemplateParams,
6886               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6887                               : nullptr,
6888               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6889                DC->isDependentContext())
6890                   ? TPC_ClassTemplateMember
6891                   : TPC_VarTemplate))
6892         NewVD->setInvalidDecl();
6893 
6894       // If we are providing an explicit specialization of a static variable
6895       // template, make a note of that.
6896       if (PrevVarTemplate &&
6897           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6898         PrevVarTemplate->setMemberSpecialization();
6899     }
6900   }
6901 
6902   // Diagnose shadowed variables iff this isn't a redeclaration.
6903   if (ShadowedDecl && !D.isRedeclaration())
6904     CheckShadow(NewVD, ShadowedDecl, Previous);
6905 
6906   ProcessPragmaWeak(S, NewVD);
6907 
6908   // If this is the first declaration of an extern C variable, update
6909   // the map of such variables.
6910   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6911       isIncompleteDeclExternC(*this, NewVD))
6912     RegisterLocallyScopedExternCDecl(NewVD, S);
6913 
6914   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6915     Decl *ManglingContextDecl;
6916     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6917             NewVD->getDeclContext(), ManglingContextDecl)) {
6918       Context.setManglingNumber(
6919           NewVD, MCtx->getManglingNumber(
6920                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6921       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6922     }
6923   }
6924 
6925   // Special handling of variable named 'main'.
6926   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6927       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6928       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6929 
6930     // C++ [basic.start.main]p3
6931     // A program that declares a variable main at global scope is ill-formed.
6932     if (getLangOpts().CPlusPlus)
6933       Diag(D.getBeginLoc(), diag::err_main_global_variable);
6934 
6935     // In C, and external-linkage variable named main results in undefined
6936     // behavior.
6937     else if (NewVD->hasExternalFormalLinkage())
6938       Diag(D.getBeginLoc(), diag::warn_main_redefined);
6939   }
6940 
6941   if (D.isRedeclaration() && !Previous.empty()) {
6942     NamedDecl *Prev = Previous.getRepresentativeDecl();
6943     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
6944                                    D.isFunctionDefinition());
6945   }
6946 
6947   if (NewTemplate) {
6948     if (NewVD->isInvalidDecl())
6949       NewTemplate->setInvalidDecl();
6950     ActOnDocumentableDecl(NewTemplate);
6951     return NewTemplate;
6952   }
6953 
6954   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6955     CompleteMemberSpecialization(NewVD, Previous);
6956 
6957   return NewVD;
6958 }
6959 
6960 /// Enum describing the %select options in diag::warn_decl_shadow.
6961 enum ShadowedDeclKind {
6962   SDK_Local,
6963   SDK_Global,
6964   SDK_StaticMember,
6965   SDK_Field,
6966   SDK_Typedef,
6967   SDK_Using
6968 };
6969 
6970 /// Determine what kind of declaration we're shadowing.
6971 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6972                                                 const DeclContext *OldDC) {
6973   if (isa<TypeAliasDecl>(ShadowedDecl))
6974     return SDK_Using;
6975   else if (isa<TypedefDecl>(ShadowedDecl))
6976     return SDK_Typedef;
6977   else if (isa<RecordDecl>(OldDC))
6978     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6979 
6980   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6981 }
6982 
6983 /// Return the location of the capture if the given lambda captures the given
6984 /// variable \p VD, or an invalid source location otherwise.
6985 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6986                                          const VarDecl *VD) {
6987   for (const Capture &Capture : LSI->Captures) {
6988     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6989       return Capture.getLocation();
6990   }
6991   return SourceLocation();
6992 }
6993 
6994 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6995                                      const LookupResult &R) {
6996   // Only diagnose if we're shadowing an unambiguous field or variable.
6997   if (R.getResultKind() != LookupResult::Found)
6998     return false;
6999 
7000   // Return false if warning is ignored.
7001   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7002 }
7003 
7004 /// Return the declaration shadowed by the given variable \p D, or null
7005 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7006 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7007                                         const LookupResult &R) {
7008   if (!shouldWarnIfShadowedDecl(Diags, R))
7009     return nullptr;
7010 
7011   // Don't diagnose declarations at file scope.
7012   if (D->hasGlobalStorage())
7013     return nullptr;
7014 
7015   NamedDecl *ShadowedDecl = R.getFoundDecl();
7016   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7017              ? ShadowedDecl
7018              : nullptr;
7019 }
7020 
7021 /// Return the declaration shadowed by the given typedef \p D, or null
7022 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7023 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7024                                         const LookupResult &R) {
7025   // Don't warn if typedef declaration is part of a class
7026   if (D->getDeclContext()->isRecord())
7027     return nullptr;
7028 
7029   if (!shouldWarnIfShadowedDecl(Diags, R))
7030     return nullptr;
7031 
7032   NamedDecl *ShadowedDecl = R.getFoundDecl();
7033   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7034 }
7035 
7036 /// Diagnose variable or built-in function shadowing.  Implements
7037 /// -Wshadow.
7038 ///
7039 /// This method is called whenever a VarDecl is added to a "useful"
7040 /// scope.
7041 ///
7042 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7043 /// \param R the lookup of the name
7044 ///
7045 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7046                        const LookupResult &R) {
7047   DeclContext *NewDC = D->getDeclContext();
7048 
7049   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7050     // Fields are not shadowed by variables in C++ static methods.
7051     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7052       if (MD->isStatic())
7053         return;
7054 
7055     // Fields shadowed by constructor parameters are a special case. Usually
7056     // the constructor initializes the field with the parameter.
7057     if (isa<CXXConstructorDecl>(NewDC))
7058       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7059         // Remember that this was shadowed so we can either warn about its
7060         // modification or its existence depending on warning settings.
7061         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7062         return;
7063       }
7064   }
7065 
7066   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7067     if (shadowedVar->isExternC()) {
7068       // For shadowing external vars, make sure that we point to the global
7069       // declaration, not a locally scoped extern declaration.
7070       for (auto I : shadowedVar->redecls())
7071         if (I->isFileVarDecl()) {
7072           ShadowedDecl = I;
7073           break;
7074         }
7075     }
7076 
7077   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7078 
7079   unsigned WarningDiag = diag::warn_decl_shadow;
7080   SourceLocation CaptureLoc;
7081   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7082       isa<CXXMethodDecl>(NewDC)) {
7083     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7084       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7085         if (RD->getLambdaCaptureDefault() == LCD_None) {
7086           // Try to avoid warnings for lambdas with an explicit capture list.
7087           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7088           // Warn only when the lambda captures the shadowed decl explicitly.
7089           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7090           if (CaptureLoc.isInvalid())
7091             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7092         } else {
7093           // Remember that this was shadowed so we can avoid the warning if the
7094           // shadowed decl isn't captured and the warning settings allow it.
7095           cast<LambdaScopeInfo>(getCurFunction())
7096               ->ShadowingDecls.push_back(
7097                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7098           return;
7099         }
7100       }
7101 
7102       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7103         // A variable can't shadow a local variable in an enclosing scope, if
7104         // they are separated by a non-capturing declaration context.
7105         for (DeclContext *ParentDC = NewDC;
7106              ParentDC && !ParentDC->Equals(OldDC);
7107              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7108           // Only block literals, captured statements, and lambda expressions
7109           // can capture; other scopes don't.
7110           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7111               !isLambdaCallOperator(ParentDC)) {
7112             return;
7113           }
7114         }
7115       }
7116     }
7117   }
7118 
7119   // Only warn about certain kinds of shadowing for class members.
7120   if (NewDC && NewDC->isRecord()) {
7121     // In particular, don't warn about shadowing non-class members.
7122     if (!OldDC->isRecord())
7123       return;
7124 
7125     // TODO: should we warn about static data members shadowing
7126     // static data members from base classes?
7127 
7128     // TODO: don't diagnose for inaccessible shadowed members.
7129     // This is hard to do perfectly because we might friend the
7130     // shadowing context, but that's just a false negative.
7131   }
7132 
7133 
7134   DeclarationName Name = R.getLookupName();
7135 
7136   // Emit warning and note.
7137   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7138     return;
7139   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7140   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7141   if (!CaptureLoc.isInvalid())
7142     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7143         << Name << /*explicitly*/ 1;
7144   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7145 }
7146 
7147 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7148 /// when these variables are captured by the lambda.
7149 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7150   for (const auto &Shadow : LSI->ShadowingDecls) {
7151     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7152     // Try to avoid the warning when the shadowed decl isn't captured.
7153     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7154     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7155     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7156                                        ? diag::warn_decl_shadow_uncaptured_local
7157                                        : diag::warn_decl_shadow)
7158         << Shadow.VD->getDeclName()
7159         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7160     if (!CaptureLoc.isInvalid())
7161       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7162           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7163     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7164   }
7165 }
7166 
7167 /// Check -Wshadow without the advantage of a previous lookup.
7168 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7169   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7170     return;
7171 
7172   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7173                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7174   LookupName(R, S);
7175   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7176     CheckShadow(D, ShadowedDecl, R);
7177 }
7178 
7179 /// Check if 'E', which is an expression that is about to be modified, refers
7180 /// to a constructor parameter that shadows a field.
7181 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7182   // Quickly ignore expressions that can't be shadowing ctor parameters.
7183   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7184     return;
7185   E = E->IgnoreParenImpCasts();
7186   auto *DRE = dyn_cast<DeclRefExpr>(E);
7187   if (!DRE)
7188     return;
7189   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7190   auto I = ShadowingDecls.find(D);
7191   if (I == ShadowingDecls.end())
7192     return;
7193   const NamedDecl *ShadowedDecl = I->second;
7194   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7195   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7196   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7197   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7198 
7199   // Avoid issuing multiple warnings about the same decl.
7200   ShadowingDecls.erase(I);
7201 }
7202 
7203 /// Check for conflict between this global or extern "C" declaration and
7204 /// previous global or extern "C" declarations. This is only used in C++.
7205 template<typename T>
7206 static bool checkGlobalOrExternCConflict(
7207     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7208   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7209   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7210 
7211   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7212     // The common case: this global doesn't conflict with any extern "C"
7213     // declaration.
7214     return false;
7215   }
7216 
7217   if (Prev) {
7218     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7219       // Both the old and new declarations have C language linkage. This is a
7220       // redeclaration.
7221       Previous.clear();
7222       Previous.addDecl(Prev);
7223       return true;
7224     }
7225 
7226     // This is a global, non-extern "C" declaration, and there is a previous
7227     // non-global extern "C" declaration. Diagnose if this is a variable
7228     // declaration.
7229     if (!isa<VarDecl>(ND))
7230       return false;
7231   } else {
7232     // The declaration is extern "C". Check for any declaration in the
7233     // translation unit which might conflict.
7234     if (IsGlobal) {
7235       // We have already performed the lookup into the translation unit.
7236       IsGlobal = false;
7237       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7238            I != E; ++I) {
7239         if (isa<VarDecl>(*I)) {
7240           Prev = *I;
7241           break;
7242         }
7243       }
7244     } else {
7245       DeclContext::lookup_result R =
7246           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7247       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7248            I != E; ++I) {
7249         if (isa<VarDecl>(*I)) {
7250           Prev = *I;
7251           break;
7252         }
7253         // FIXME: If we have any other entity with this name in global scope,
7254         // the declaration is ill-formed, but that is a defect: it breaks the
7255         // 'stat' hack, for instance. Only variables can have mangled name
7256         // clashes with extern "C" declarations, so only they deserve a
7257         // diagnostic.
7258       }
7259     }
7260 
7261     if (!Prev)
7262       return false;
7263   }
7264 
7265   // Use the first declaration's location to ensure we point at something which
7266   // is lexically inside an extern "C" linkage-spec.
7267   assert(Prev && "should have found a previous declaration to diagnose");
7268   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7269     Prev = FD->getFirstDecl();
7270   else
7271     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7272 
7273   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7274     << IsGlobal << ND;
7275   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7276     << IsGlobal;
7277   return false;
7278 }
7279 
7280 /// Apply special rules for handling extern "C" declarations. Returns \c true
7281 /// if we have found that this is a redeclaration of some prior entity.
7282 ///
7283 /// Per C++ [dcl.link]p6:
7284 ///   Two declarations [for a function or variable] with C language linkage
7285 ///   with the same name that appear in different scopes refer to the same
7286 ///   [entity]. An entity with C language linkage shall not be declared with
7287 ///   the same name as an entity in global scope.
7288 template<typename T>
7289 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7290                                                   LookupResult &Previous) {
7291   if (!S.getLangOpts().CPlusPlus) {
7292     // In C, when declaring a global variable, look for a corresponding 'extern'
7293     // variable declared in function scope. We don't need this in C++, because
7294     // we find local extern decls in the surrounding file-scope DeclContext.
7295     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7296       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7297         Previous.clear();
7298         Previous.addDecl(Prev);
7299         return true;
7300       }
7301     }
7302     return false;
7303   }
7304 
7305   // A declaration in the translation unit can conflict with an extern "C"
7306   // declaration.
7307   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7308     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7309 
7310   // An extern "C" declaration can conflict with a declaration in the
7311   // translation unit or can be a redeclaration of an extern "C" declaration
7312   // in another scope.
7313   if (isIncompleteDeclExternC(S,ND))
7314     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7315 
7316   // Neither global nor extern "C": nothing to do.
7317   return false;
7318 }
7319 
7320 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7321   // If the decl is already known invalid, don't check it.
7322   if (NewVD->isInvalidDecl())
7323     return;
7324 
7325   QualType T = NewVD->getType();
7326 
7327   // Defer checking an 'auto' type until its initializer is attached.
7328   if (T->isUndeducedType())
7329     return;
7330 
7331   if (NewVD->hasAttrs())
7332     CheckAlignasUnderalignment(NewVD);
7333 
7334   if (T->isObjCObjectType()) {
7335     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7336       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7337     T = Context.getObjCObjectPointerType(T);
7338     NewVD->setType(T);
7339   }
7340 
7341   // Emit an error if an address space was applied to decl with local storage.
7342   // This includes arrays of objects with address space qualifiers, but not
7343   // automatic variables that point to other address spaces.
7344   // ISO/IEC TR 18037 S5.1.2
7345   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7346       T.getAddressSpace() != LangAS::Default) {
7347     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7348     NewVD->setInvalidDecl();
7349     return;
7350   }
7351 
7352   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7353   // scope.
7354   if (getLangOpts().OpenCLVersion == 120 &&
7355       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7356       NewVD->isStaticLocal()) {
7357     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7358     NewVD->setInvalidDecl();
7359     return;
7360   }
7361 
7362   if (getLangOpts().OpenCL) {
7363     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7364     if (NewVD->hasAttr<BlocksAttr>()) {
7365       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7366       return;
7367     }
7368 
7369     if (T->isBlockPointerType()) {
7370       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7371       // can't use 'extern' storage class.
7372       if (!T.isConstQualified()) {
7373         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7374             << 0 /*const*/;
7375         NewVD->setInvalidDecl();
7376         return;
7377       }
7378       if (NewVD->hasExternalStorage()) {
7379         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7380         NewVD->setInvalidDecl();
7381         return;
7382       }
7383     }
7384     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7385     // __constant address space.
7386     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7387     // variables inside a function can also be declared in the global
7388     // address space.
7389     // OpenCL C++ v1.0 s2.5 inherits rule from OpenCL C v2.0 and allows local
7390     // address space additionally.
7391     // FIXME: Add local AS for OpenCL C++.
7392     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7393         NewVD->hasExternalStorage()) {
7394       if (!T->isSamplerT() &&
7395           !(T.getAddressSpace() == LangAS::opencl_constant ||
7396             (T.getAddressSpace() == LangAS::opencl_global &&
7397              (getLangOpts().OpenCLVersion == 200 ||
7398               getLangOpts().OpenCLCPlusPlus)))) {
7399         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7400         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7401           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7402               << Scope << "global or constant";
7403         else
7404           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7405               << Scope << "constant";
7406         NewVD->setInvalidDecl();
7407         return;
7408       }
7409     } else {
7410       if (T.getAddressSpace() == LangAS::opencl_global) {
7411         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7412             << 1 /*is any function*/ << "global";
7413         NewVD->setInvalidDecl();
7414         return;
7415       }
7416       if (T.getAddressSpace() == LangAS::opencl_constant ||
7417           T.getAddressSpace() == LangAS::opencl_local) {
7418         FunctionDecl *FD = getCurFunctionDecl();
7419         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7420         // in functions.
7421         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7422           if (T.getAddressSpace() == LangAS::opencl_constant)
7423             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7424                 << 0 /*non-kernel only*/ << "constant";
7425           else
7426             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7427                 << 0 /*non-kernel only*/ << "local";
7428           NewVD->setInvalidDecl();
7429           return;
7430         }
7431         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7432         // in the outermost scope of a kernel function.
7433         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7434           if (!getCurScope()->isFunctionScope()) {
7435             if (T.getAddressSpace() == LangAS::opencl_constant)
7436               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7437                   << "constant";
7438             else
7439               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7440                   << "local";
7441             NewVD->setInvalidDecl();
7442             return;
7443           }
7444         }
7445       } else if (T.getAddressSpace() != LangAS::opencl_private) {
7446         // Do not allow other address spaces on automatic variable.
7447         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7448         NewVD->setInvalidDecl();
7449         return;
7450       }
7451     }
7452   }
7453 
7454   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7455       && !NewVD->hasAttr<BlocksAttr>()) {
7456     if (getLangOpts().getGC() != LangOptions::NonGC)
7457       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7458     else {
7459       assert(!getLangOpts().ObjCAutoRefCount);
7460       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7461     }
7462   }
7463 
7464   bool isVM = T->isVariablyModifiedType();
7465   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7466       NewVD->hasAttr<BlocksAttr>())
7467     setFunctionHasBranchProtectedScope();
7468 
7469   if ((isVM && NewVD->hasLinkage()) ||
7470       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7471     bool SizeIsNegative;
7472     llvm::APSInt Oversized;
7473     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7474         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7475     QualType FixedT;
7476     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7477       FixedT = FixedTInfo->getType();
7478     else if (FixedTInfo) {
7479       // Type and type-as-written are canonically different. We need to fix up
7480       // both types separately.
7481       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7482                                                    Oversized);
7483     }
7484     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7485       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7486       // FIXME: This won't give the correct result for
7487       // int a[10][n];
7488       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7489 
7490       if (NewVD->isFileVarDecl())
7491         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7492         << SizeRange;
7493       else if (NewVD->isStaticLocal())
7494         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7495         << SizeRange;
7496       else
7497         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7498         << SizeRange;
7499       NewVD->setInvalidDecl();
7500       return;
7501     }
7502 
7503     if (!FixedTInfo) {
7504       if (NewVD->isFileVarDecl())
7505         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7506       else
7507         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7508       NewVD->setInvalidDecl();
7509       return;
7510     }
7511 
7512     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7513     NewVD->setType(FixedT);
7514     NewVD->setTypeSourceInfo(FixedTInfo);
7515   }
7516 
7517   if (T->isVoidType()) {
7518     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7519     //                    of objects and functions.
7520     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7521       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7522         << T;
7523       NewVD->setInvalidDecl();
7524       return;
7525     }
7526   }
7527 
7528   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7529     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7530     NewVD->setInvalidDecl();
7531     return;
7532   }
7533 
7534   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7535     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7536     NewVD->setInvalidDecl();
7537     return;
7538   }
7539 
7540   if (NewVD->isConstexpr() && !T->isDependentType() &&
7541       RequireLiteralType(NewVD->getLocation(), T,
7542                          diag::err_constexpr_var_non_literal)) {
7543     NewVD->setInvalidDecl();
7544     return;
7545   }
7546 }
7547 
7548 /// Perform semantic checking on a newly-created variable
7549 /// declaration.
7550 ///
7551 /// This routine performs all of the type-checking required for a
7552 /// variable declaration once it has been built. It is used both to
7553 /// check variables after they have been parsed and their declarators
7554 /// have been translated into a declaration, and to check variables
7555 /// that have been instantiated from a template.
7556 ///
7557 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7558 ///
7559 /// Returns true if the variable declaration is a redeclaration.
7560 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7561   CheckVariableDeclarationType(NewVD);
7562 
7563   // If the decl is already known invalid, don't check it.
7564   if (NewVD->isInvalidDecl())
7565     return false;
7566 
7567   // If we did not find anything by this name, look for a non-visible
7568   // extern "C" declaration with the same name.
7569   if (Previous.empty() &&
7570       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7571     Previous.setShadowed();
7572 
7573   if (!Previous.empty()) {
7574     MergeVarDecl(NewVD, Previous);
7575     return true;
7576   }
7577   return false;
7578 }
7579 
7580 namespace {
7581 struct FindOverriddenMethod {
7582   Sema *S;
7583   CXXMethodDecl *Method;
7584 
7585   /// Member lookup function that determines whether a given C++
7586   /// method overrides a method in a base class, to be used with
7587   /// CXXRecordDecl::lookupInBases().
7588   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7589     RecordDecl *BaseRecord =
7590         Specifier->getType()->getAs<RecordType>()->getDecl();
7591 
7592     DeclarationName Name = Method->getDeclName();
7593 
7594     // FIXME: Do we care about other names here too?
7595     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7596       // We really want to find the base class destructor here.
7597       QualType T = S->Context.getTypeDeclType(BaseRecord);
7598       CanQualType CT = S->Context.getCanonicalType(T);
7599 
7600       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7601     }
7602 
7603     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7604          Path.Decls = Path.Decls.slice(1)) {
7605       NamedDecl *D = Path.Decls.front();
7606       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7607         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7608           return true;
7609       }
7610     }
7611 
7612     return false;
7613   }
7614 };
7615 
7616 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7617 } // end anonymous namespace
7618 
7619 /// Report an error regarding overriding, along with any relevant
7620 /// overridden methods.
7621 ///
7622 /// \param DiagID the primary error to report.
7623 /// \param MD the overriding method.
7624 /// \param OEK which overrides to include as notes.
7625 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7626                             OverrideErrorKind OEK = OEK_All) {
7627   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7628   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7629     // This check (& the OEK parameter) could be replaced by a predicate, but
7630     // without lambdas that would be overkill. This is still nicer than writing
7631     // out the diag loop 3 times.
7632     if ((OEK == OEK_All) ||
7633         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7634         (OEK == OEK_Deleted && O->isDeleted()))
7635       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7636   }
7637 }
7638 
7639 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7640 /// and if so, check that it's a valid override and remember it.
7641 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7642   // Look for methods in base classes that this method might override.
7643   CXXBasePaths Paths;
7644   FindOverriddenMethod FOM;
7645   FOM.Method = MD;
7646   FOM.S = this;
7647   bool hasDeletedOverridenMethods = false;
7648   bool hasNonDeletedOverridenMethods = false;
7649   bool AddedAny = false;
7650   if (DC->lookupInBases(FOM, Paths)) {
7651     for (auto *I : Paths.found_decls()) {
7652       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7653         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7654         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7655             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7656             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7657             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7658           hasDeletedOverridenMethods |= OldMD->isDeleted();
7659           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7660           AddedAny = true;
7661         }
7662       }
7663     }
7664   }
7665 
7666   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7667     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7668   }
7669   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7670     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7671   }
7672 
7673   return AddedAny;
7674 }
7675 
7676 namespace {
7677   // Struct for holding all of the extra arguments needed by
7678   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7679   struct ActOnFDArgs {
7680     Scope *S;
7681     Declarator &D;
7682     MultiTemplateParamsArg TemplateParamLists;
7683     bool AddToScope;
7684   };
7685 } // end anonymous namespace
7686 
7687 namespace {
7688 
7689 // Callback to only accept typo corrections that have a non-zero edit distance.
7690 // Also only accept corrections that have the same parent decl.
7691 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7692  public:
7693   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7694                             CXXRecordDecl *Parent)
7695       : Context(Context), OriginalFD(TypoFD),
7696         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7697 
7698   bool ValidateCandidate(const TypoCorrection &candidate) override {
7699     if (candidate.getEditDistance() == 0)
7700       return false;
7701 
7702     SmallVector<unsigned, 1> MismatchedParams;
7703     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7704                                           CDeclEnd = candidate.end();
7705          CDecl != CDeclEnd; ++CDecl) {
7706       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7707 
7708       if (FD && !FD->hasBody() &&
7709           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7710         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7711           CXXRecordDecl *Parent = MD->getParent();
7712           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7713             return true;
7714         } else if (!ExpectedParent) {
7715           return true;
7716         }
7717       }
7718     }
7719 
7720     return false;
7721   }
7722 
7723  private:
7724   ASTContext &Context;
7725   FunctionDecl *OriginalFD;
7726   CXXRecordDecl *ExpectedParent;
7727 };
7728 
7729 } // end anonymous namespace
7730 
7731 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7732   TypoCorrectedFunctionDefinitions.insert(F);
7733 }
7734 
7735 /// Generate diagnostics for an invalid function redeclaration.
7736 ///
7737 /// This routine handles generating the diagnostic messages for an invalid
7738 /// function redeclaration, including finding possible similar declarations
7739 /// or performing typo correction if there are no previous declarations with
7740 /// the same name.
7741 ///
7742 /// Returns a NamedDecl iff typo correction was performed and substituting in
7743 /// the new declaration name does not cause new errors.
7744 static NamedDecl *DiagnoseInvalidRedeclaration(
7745     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7746     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7747   DeclarationName Name = NewFD->getDeclName();
7748   DeclContext *NewDC = NewFD->getDeclContext();
7749   SmallVector<unsigned, 1> MismatchedParams;
7750   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7751   TypoCorrection Correction;
7752   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7753   unsigned DiagMsg =
7754     IsLocalFriend ? diag::err_no_matching_local_friend :
7755     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
7756     diag::err_member_decl_does_not_match;
7757   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7758                     IsLocalFriend ? Sema::LookupLocalFriendName
7759                                   : Sema::LookupOrdinaryName,
7760                     Sema::ForVisibleRedeclaration);
7761 
7762   NewFD->setInvalidDecl();
7763   if (IsLocalFriend)
7764     SemaRef.LookupName(Prev, S);
7765   else
7766     SemaRef.LookupQualifiedName(Prev, NewDC);
7767   assert(!Prev.isAmbiguous() &&
7768          "Cannot have an ambiguity in previous-declaration lookup");
7769   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7770   if (!Prev.empty()) {
7771     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7772          Func != FuncEnd; ++Func) {
7773       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7774       if (FD &&
7775           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7776         // Add 1 to the index so that 0 can mean the mismatch didn't
7777         // involve a parameter
7778         unsigned ParamNum =
7779             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7780         NearMatches.push_back(std::make_pair(FD, ParamNum));
7781       }
7782     }
7783   // If the qualified name lookup yielded nothing, try typo correction
7784   } else if ((Correction = SemaRef.CorrectTypo(
7785                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7786                   &ExtraArgs.D.getCXXScopeSpec(),
7787                   llvm::make_unique<DifferentNameValidatorCCC>(
7788                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7789                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7790     // Set up everything for the call to ActOnFunctionDeclarator
7791     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7792                               ExtraArgs.D.getIdentifierLoc());
7793     Previous.clear();
7794     Previous.setLookupName(Correction.getCorrection());
7795     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7796                                     CDeclEnd = Correction.end();
7797          CDecl != CDeclEnd; ++CDecl) {
7798       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7799       if (FD && !FD->hasBody() &&
7800           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7801         Previous.addDecl(FD);
7802       }
7803     }
7804     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7805 
7806     NamedDecl *Result;
7807     // Retry building the function declaration with the new previous
7808     // declarations, and with errors suppressed.
7809     {
7810       // Trap errors.
7811       Sema::SFINAETrap Trap(SemaRef);
7812 
7813       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7814       // pieces need to verify the typo-corrected C++ declaration and hopefully
7815       // eliminate the need for the parameter pack ExtraArgs.
7816       Result = SemaRef.ActOnFunctionDeclarator(
7817           ExtraArgs.S, ExtraArgs.D,
7818           Correction.getCorrectionDecl()->getDeclContext(),
7819           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7820           ExtraArgs.AddToScope);
7821 
7822       if (Trap.hasErrorOccurred())
7823         Result = nullptr;
7824     }
7825 
7826     if (Result) {
7827       // Determine which correction we picked.
7828       Decl *Canonical = Result->getCanonicalDecl();
7829       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7830            I != E; ++I)
7831         if ((*I)->getCanonicalDecl() == Canonical)
7832           Correction.setCorrectionDecl(*I);
7833 
7834       // Let Sema know about the correction.
7835       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7836       SemaRef.diagnoseTypo(
7837           Correction,
7838           SemaRef.PDiag(IsLocalFriend
7839                           ? diag::err_no_matching_local_friend_suggest
7840                           : diag::err_member_decl_does_not_match_suggest)
7841             << Name << NewDC << IsDefinition);
7842       return Result;
7843     }
7844 
7845     // Pretend the typo correction never occurred
7846     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7847                               ExtraArgs.D.getIdentifierLoc());
7848     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7849     Previous.clear();
7850     Previous.setLookupName(Name);
7851   }
7852 
7853   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7854       << Name << NewDC << IsDefinition << NewFD->getLocation();
7855 
7856   bool NewFDisConst = false;
7857   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7858     NewFDisConst = NewMD->isConst();
7859 
7860   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7861        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7862        NearMatch != NearMatchEnd; ++NearMatch) {
7863     FunctionDecl *FD = NearMatch->first;
7864     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7865     bool FDisConst = MD && MD->isConst();
7866     bool IsMember = MD || !IsLocalFriend;
7867 
7868     // FIXME: These notes are poorly worded for the local friend case.
7869     if (unsigned Idx = NearMatch->second) {
7870       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7871       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7872       if (Loc.isInvalid()) Loc = FD->getLocation();
7873       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7874                                  : diag::note_local_decl_close_param_match)
7875         << Idx << FDParam->getType()
7876         << NewFD->getParamDecl(Idx - 1)->getType();
7877     } else if (FDisConst != NewFDisConst) {
7878       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7879           << NewFDisConst << FD->getSourceRange().getEnd();
7880     } else
7881       SemaRef.Diag(FD->getLocation(),
7882                    IsMember ? diag::note_member_def_close_match
7883                             : diag::note_local_decl_close_match);
7884   }
7885   return nullptr;
7886 }
7887 
7888 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7889   switch (D.getDeclSpec().getStorageClassSpec()) {
7890   default: llvm_unreachable("Unknown storage class!");
7891   case DeclSpec::SCS_auto:
7892   case DeclSpec::SCS_register:
7893   case DeclSpec::SCS_mutable:
7894     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7895                  diag::err_typecheck_sclass_func);
7896     D.getMutableDeclSpec().ClearStorageClassSpecs();
7897     D.setInvalidType();
7898     break;
7899   case DeclSpec::SCS_unspecified: break;
7900   case DeclSpec::SCS_extern:
7901     if (D.getDeclSpec().isExternInLinkageSpec())
7902       return SC_None;
7903     return SC_Extern;
7904   case DeclSpec::SCS_static: {
7905     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7906       // C99 6.7.1p5:
7907       //   The declaration of an identifier for a function that has
7908       //   block scope shall have no explicit storage-class specifier
7909       //   other than extern
7910       // See also (C++ [dcl.stc]p4).
7911       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7912                    diag::err_static_block_func);
7913       break;
7914     } else
7915       return SC_Static;
7916   }
7917   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7918   }
7919 
7920   // No explicit storage class has already been returned
7921   return SC_None;
7922 }
7923 
7924 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7925                                            DeclContext *DC, QualType &R,
7926                                            TypeSourceInfo *TInfo,
7927                                            StorageClass SC,
7928                                            bool &IsVirtualOkay) {
7929   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7930   DeclarationName Name = NameInfo.getName();
7931 
7932   FunctionDecl *NewFD = nullptr;
7933   bool isInline = D.getDeclSpec().isInlineSpecified();
7934 
7935   if (!SemaRef.getLangOpts().CPlusPlus) {
7936     // Determine whether the function was written with a
7937     // prototype. This true when:
7938     //   - there is a prototype in the declarator, or
7939     //   - the type R of the function is some kind of typedef or other non-
7940     //     attributed reference to a type name (which eventually refers to a
7941     //     function type).
7942     bool HasPrototype =
7943       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7944       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7945 
7946     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
7947                                  R, TInfo, SC, isInline, HasPrototype, false);
7948     if (D.isInvalidType())
7949       NewFD->setInvalidDecl();
7950 
7951     return NewFD;
7952   }
7953 
7954   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7955   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7956 
7957   // Check that the return type is not an abstract class type.
7958   // For record types, this is done by the AbstractClassUsageDiagnoser once
7959   // the class has been completely parsed.
7960   if (!DC->isRecord() &&
7961       SemaRef.RequireNonAbstractType(
7962           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7963           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7964     D.setInvalidType();
7965 
7966   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7967     // This is a C++ constructor declaration.
7968     assert(DC->isRecord() &&
7969            "Constructors can only be declared in a member context");
7970 
7971     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7972     return CXXConstructorDecl::Create(
7973         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
7974         TInfo, isExplicit, isInline,
7975         /*isImplicitlyDeclared=*/false, isConstexpr);
7976 
7977   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7978     // This is a C++ destructor declaration.
7979     if (DC->isRecord()) {
7980       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7981       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7982       CXXDestructorDecl *NewDD =
7983           CXXDestructorDecl::Create(SemaRef.Context, Record, D.getBeginLoc(),
7984                                     NameInfo, R, TInfo, isInline,
7985                                     /*isImplicitlyDeclared=*/false);
7986 
7987       // If the destructor needs an implicit exception specification, set it
7988       // now. FIXME: It'd be nice to be able to create the right type to start
7989       // with, but the type needs to reference the destructor declaration.
7990       if (SemaRef.getLangOpts().CPlusPlus11)
7991         SemaRef.AdjustDestructorExceptionSpec(NewDD);
7992 
7993       IsVirtualOkay = true;
7994       return NewDD;
7995 
7996     } else {
7997       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7998       D.setInvalidType();
7999 
8000       // Create a FunctionDecl to satisfy the function definition parsing
8001       // code path.
8002       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8003                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8004                                   isInline,
8005                                   /*hasPrototype=*/true, isConstexpr);
8006     }
8007 
8008   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8009     if (!DC->isRecord()) {
8010       SemaRef.Diag(D.getIdentifierLoc(),
8011            diag::err_conv_function_not_member);
8012       return nullptr;
8013     }
8014 
8015     SemaRef.CheckConversionDeclarator(D, R, SC);
8016     IsVirtualOkay = true;
8017     return CXXConversionDecl::Create(
8018         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8019         TInfo, isInline, isExplicit, isConstexpr, SourceLocation());
8020 
8021   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8022     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8023 
8024     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8025                                          isExplicit, NameInfo, R, TInfo,
8026                                          D.getEndLoc());
8027   } else if (DC->isRecord()) {
8028     // If the name of the function is the same as the name of the record,
8029     // then this must be an invalid constructor that has a return type.
8030     // (The parser checks for a return type and makes the declarator a
8031     // constructor if it has no return type).
8032     if (Name.getAsIdentifierInfo() &&
8033         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8034       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8035         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8036         << SourceRange(D.getIdentifierLoc());
8037       return nullptr;
8038     }
8039 
8040     // This is a C++ method declaration.
8041     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8042         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8043         TInfo, SC, isInline, isConstexpr, SourceLocation());
8044     IsVirtualOkay = !Ret->isStatic();
8045     return Ret;
8046   } else {
8047     bool isFriend =
8048         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8049     if (!isFriend && SemaRef.CurContext->isRecord())
8050       return nullptr;
8051 
8052     // Determine whether the function was written with a
8053     // prototype. This true when:
8054     //   - we're in C++ (where every function has a prototype),
8055     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8056                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8057                                 isConstexpr);
8058   }
8059 }
8060 
8061 enum OpenCLParamType {
8062   ValidKernelParam,
8063   PtrPtrKernelParam,
8064   PtrKernelParam,
8065   InvalidAddrSpacePtrKernelParam,
8066   InvalidKernelParam,
8067   RecordKernelParam
8068 };
8069 
8070 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8071   // Size dependent types are just typedefs to normal integer types
8072   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8073   // integers other than by their names.
8074   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8075 
8076   // Remove typedefs one by one until we reach a typedef
8077   // for a size dependent type.
8078   QualType DesugaredTy = Ty;
8079   do {
8080     ArrayRef<StringRef> Names(SizeTypeNames);
8081     auto Match =
8082         std::find(Names.begin(), Names.end(), DesugaredTy.getAsString());
8083     if (Names.end() != Match)
8084       return true;
8085 
8086     Ty = DesugaredTy;
8087     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8088   } while (DesugaredTy != Ty);
8089 
8090   return false;
8091 }
8092 
8093 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8094   if (PT->isPointerType()) {
8095     QualType PointeeType = PT->getPointeeType();
8096     if (PointeeType->isPointerType())
8097       return PtrPtrKernelParam;
8098     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8099         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8100         PointeeType.getAddressSpace() == LangAS::Default)
8101       return InvalidAddrSpacePtrKernelParam;
8102     return PtrKernelParam;
8103   }
8104 
8105   // OpenCL v1.2 s6.9.k:
8106   // Arguments to kernel functions in a program cannot be declared with the
8107   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8108   // uintptr_t or a struct and/or union that contain fields declared to be one
8109   // of these built-in scalar types.
8110   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8111     return InvalidKernelParam;
8112 
8113   if (PT->isImageType())
8114     return PtrKernelParam;
8115 
8116   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8117     return InvalidKernelParam;
8118 
8119   // OpenCL extension spec v1.2 s9.5:
8120   // This extension adds support for half scalar and vector types as built-in
8121   // types that can be used for arithmetic operations, conversions etc.
8122   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8123     return InvalidKernelParam;
8124 
8125   if (PT->isRecordType())
8126     return RecordKernelParam;
8127 
8128   // Look into an array argument to check if it has a forbidden type.
8129   if (PT->isArrayType()) {
8130     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8131     // Call ourself to check an underlying type of an array. Since the
8132     // getPointeeOrArrayElementType returns an innermost type which is not an
8133     // array, this recursive call only happens once.
8134     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8135   }
8136 
8137   return ValidKernelParam;
8138 }
8139 
8140 static void checkIsValidOpenCLKernelParameter(
8141   Sema &S,
8142   Declarator &D,
8143   ParmVarDecl *Param,
8144   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8145   QualType PT = Param->getType();
8146 
8147   // Cache the valid types we encounter to avoid rechecking structs that are
8148   // used again
8149   if (ValidTypes.count(PT.getTypePtr()))
8150     return;
8151 
8152   switch (getOpenCLKernelParameterType(S, PT)) {
8153   case PtrPtrKernelParam:
8154     // OpenCL v1.2 s6.9.a:
8155     // A kernel function argument cannot be declared as a
8156     // pointer to a pointer type.
8157     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8158     D.setInvalidType();
8159     return;
8160 
8161   case InvalidAddrSpacePtrKernelParam:
8162     // OpenCL v1.0 s6.5:
8163     // __kernel function arguments declared to be a pointer of a type can point
8164     // to one of the following address spaces only : __global, __local or
8165     // __constant.
8166     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8167     D.setInvalidType();
8168     return;
8169 
8170     // OpenCL v1.2 s6.9.k:
8171     // Arguments to kernel functions in a program cannot be declared with the
8172     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8173     // uintptr_t or a struct and/or union that contain fields declared to be
8174     // one of these built-in scalar types.
8175 
8176   case InvalidKernelParam:
8177     // OpenCL v1.2 s6.8 n:
8178     // A kernel function argument cannot be declared
8179     // of event_t type.
8180     // Do not diagnose half type since it is diagnosed as invalid argument
8181     // type for any function elsewhere.
8182     if (!PT->isHalfType()) {
8183       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8184 
8185       // Explain what typedefs are involved.
8186       const TypedefType *Typedef = nullptr;
8187       while ((Typedef = PT->getAs<TypedefType>())) {
8188         SourceLocation Loc = Typedef->getDecl()->getLocation();
8189         // SourceLocation may be invalid for a built-in type.
8190         if (Loc.isValid())
8191           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8192         PT = Typedef->desugar();
8193       }
8194     }
8195 
8196     D.setInvalidType();
8197     return;
8198 
8199   case PtrKernelParam:
8200   case ValidKernelParam:
8201     ValidTypes.insert(PT.getTypePtr());
8202     return;
8203 
8204   case RecordKernelParam:
8205     break;
8206   }
8207 
8208   // Track nested structs we will inspect
8209   SmallVector<const Decl *, 4> VisitStack;
8210 
8211   // Track where we are in the nested structs. Items will migrate from
8212   // VisitStack to HistoryStack as we do the DFS for bad field.
8213   SmallVector<const FieldDecl *, 4> HistoryStack;
8214   HistoryStack.push_back(nullptr);
8215 
8216   // At this point we already handled everything except of a RecordType or
8217   // an ArrayType of a RecordType.
8218   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8219   const RecordType *RecTy =
8220       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8221   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8222 
8223   VisitStack.push_back(RecTy->getDecl());
8224   assert(VisitStack.back() && "First decl null?");
8225 
8226   do {
8227     const Decl *Next = VisitStack.pop_back_val();
8228     if (!Next) {
8229       assert(!HistoryStack.empty());
8230       // Found a marker, we have gone up a level
8231       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8232         ValidTypes.insert(Hist->getType().getTypePtr());
8233 
8234       continue;
8235     }
8236 
8237     // Adds everything except the original parameter declaration (which is not a
8238     // field itself) to the history stack.
8239     const RecordDecl *RD;
8240     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8241       HistoryStack.push_back(Field);
8242 
8243       QualType FieldTy = Field->getType();
8244       // Other field types (known to be valid or invalid) are handled while we
8245       // walk around RecordDecl::fields().
8246       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8247              "Unexpected type.");
8248       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8249 
8250       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8251     } else {
8252       RD = cast<RecordDecl>(Next);
8253     }
8254 
8255     // Add a null marker so we know when we've gone back up a level
8256     VisitStack.push_back(nullptr);
8257 
8258     for (const auto *FD : RD->fields()) {
8259       QualType QT = FD->getType();
8260 
8261       if (ValidTypes.count(QT.getTypePtr()))
8262         continue;
8263 
8264       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8265       if (ParamType == ValidKernelParam)
8266         continue;
8267 
8268       if (ParamType == RecordKernelParam) {
8269         VisitStack.push_back(FD);
8270         continue;
8271       }
8272 
8273       // OpenCL v1.2 s6.9.p:
8274       // Arguments to kernel functions that are declared to be a struct or union
8275       // do not allow OpenCL objects to be passed as elements of the struct or
8276       // union.
8277       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8278           ParamType == InvalidAddrSpacePtrKernelParam) {
8279         S.Diag(Param->getLocation(),
8280                diag::err_record_with_pointers_kernel_param)
8281           << PT->isUnionType()
8282           << PT;
8283       } else {
8284         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8285       }
8286 
8287       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8288           << OrigRecDecl->getDeclName();
8289 
8290       // We have an error, now let's go back up through history and show where
8291       // the offending field came from
8292       for (ArrayRef<const FieldDecl *>::const_iterator
8293                I = HistoryStack.begin() + 1,
8294                E = HistoryStack.end();
8295            I != E; ++I) {
8296         const FieldDecl *OuterField = *I;
8297         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8298           << OuterField->getType();
8299       }
8300 
8301       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8302         << QT->isPointerType()
8303         << QT;
8304       D.setInvalidType();
8305       return;
8306     }
8307   } while (!VisitStack.empty());
8308 }
8309 
8310 /// Find the DeclContext in which a tag is implicitly declared if we see an
8311 /// elaborated type specifier in the specified context, and lookup finds
8312 /// nothing.
8313 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8314   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8315     DC = DC->getParent();
8316   return DC;
8317 }
8318 
8319 /// Find the Scope in which a tag is implicitly declared if we see an
8320 /// elaborated type specifier in the specified context, and lookup finds
8321 /// nothing.
8322 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8323   while (S->isClassScope() ||
8324          (LangOpts.CPlusPlus &&
8325           S->isFunctionPrototypeScope()) ||
8326          ((S->getFlags() & Scope::DeclScope) == 0) ||
8327          (S->getEntity() && S->getEntity()->isTransparentContext()))
8328     S = S->getParent();
8329   return S;
8330 }
8331 
8332 NamedDecl*
8333 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8334                               TypeSourceInfo *TInfo, LookupResult &Previous,
8335                               MultiTemplateParamsArg TemplateParamLists,
8336                               bool &AddToScope) {
8337   QualType R = TInfo->getType();
8338 
8339   assert(R->isFunctionType());
8340 
8341   // TODO: consider using NameInfo for diagnostic.
8342   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8343   DeclarationName Name = NameInfo.getName();
8344   StorageClass SC = getFunctionStorageClass(*this, D);
8345 
8346   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8347     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8348          diag::err_invalid_thread)
8349       << DeclSpec::getSpecifierName(TSCS);
8350 
8351   if (D.isFirstDeclarationOfMember())
8352     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8353                            D.getIdentifierLoc());
8354 
8355   bool isFriend = false;
8356   FunctionTemplateDecl *FunctionTemplate = nullptr;
8357   bool isMemberSpecialization = false;
8358   bool isFunctionTemplateSpecialization = false;
8359 
8360   bool isDependentClassScopeExplicitSpecialization = false;
8361   bool HasExplicitTemplateArgs = false;
8362   TemplateArgumentListInfo TemplateArgs;
8363 
8364   bool isVirtualOkay = false;
8365 
8366   DeclContext *OriginalDC = DC;
8367   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8368 
8369   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8370                                               isVirtualOkay);
8371   if (!NewFD) return nullptr;
8372 
8373   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8374     NewFD->setTopLevelDeclInObjCContainer();
8375 
8376   // Set the lexical context. If this is a function-scope declaration, or has a
8377   // C++ scope specifier, or is the object of a friend declaration, the lexical
8378   // context will be different from the semantic context.
8379   NewFD->setLexicalDeclContext(CurContext);
8380 
8381   if (IsLocalExternDecl)
8382     NewFD->setLocalExternDecl();
8383 
8384   if (getLangOpts().CPlusPlus) {
8385     bool isInline = D.getDeclSpec().isInlineSpecified();
8386     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8387     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8388     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8389     isFriend = D.getDeclSpec().isFriendSpecified();
8390     if (isFriend && !isInline && D.isFunctionDefinition()) {
8391       // C++ [class.friend]p5
8392       //   A function can be defined in a friend declaration of a
8393       //   class . . . . Such a function is implicitly inline.
8394       NewFD->setImplicitlyInline();
8395     }
8396 
8397     // If this is a method defined in an __interface, and is not a constructor
8398     // or an overloaded operator, then set the pure flag (isVirtual will already
8399     // return true).
8400     if (const CXXRecordDecl *Parent =
8401           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8402       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8403         NewFD->setPure(true);
8404 
8405       // C++ [class.union]p2
8406       //   A union can have member functions, but not virtual functions.
8407       if (isVirtual && Parent->isUnion())
8408         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8409     }
8410 
8411     SetNestedNameSpecifier(*this, NewFD, D);
8412     isMemberSpecialization = false;
8413     isFunctionTemplateSpecialization = false;
8414     if (D.isInvalidType())
8415       NewFD->setInvalidDecl();
8416 
8417     // Match up the template parameter lists with the scope specifier, then
8418     // determine whether we have a template or a template specialization.
8419     bool Invalid = false;
8420     if (TemplateParameterList *TemplateParams =
8421             MatchTemplateParametersToScopeSpecifier(
8422                 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8423                 D.getCXXScopeSpec(),
8424                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8425                     ? D.getName().TemplateId
8426                     : nullptr,
8427                 TemplateParamLists, isFriend, isMemberSpecialization,
8428                 Invalid)) {
8429       if (TemplateParams->size() > 0) {
8430         // This is a function template
8431 
8432         // Check that we can declare a template here.
8433         if (CheckTemplateDeclScope(S, TemplateParams))
8434           NewFD->setInvalidDecl();
8435 
8436         // A destructor cannot be a template.
8437         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8438           Diag(NewFD->getLocation(), diag::err_destructor_template);
8439           NewFD->setInvalidDecl();
8440         }
8441 
8442         // If we're adding a template to a dependent context, we may need to
8443         // rebuilding some of the types used within the template parameter list,
8444         // now that we know what the current instantiation is.
8445         if (DC->isDependentContext()) {
8446           ContextRAII SavedContext(*this, DC);
8447           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8448             Invalid = true;
8449         }
8450 
8451         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8452                                                         NewFD->getLocation(),
8453                                                         Name, TemplateParams,
8454                                                         NewFD);
8455         FunctionTemplate->setLexicalDeclContext(CurContext);
8456         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8457 
8458         // For source fidelity, store the other template param lists.
8459         if (TemplateParamLists.size() > 1) {
8460           NewFD->setTemplateParameterListsInfo(Context,
8461                                                TemplateParamLists.drop_back(1));
8462         }
8463       } else {
8464         // This is a function template specialization.
8465         isFunctionTemplateSpecialization = true;
8466         // For source fidelity, store all the template param lists.
8467         if (TemplateParamLists.size() > 0)
8468           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8469 
8470         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8471         if (isFriend) {
8472           // We want to remove the "template<>", found here.
8473           SourceRange RemoveRange = TemplateParams->getSourceRange();
8474 
8475           // If we remove the template<> and the name is not a
8476           // template-id, we're actually silently creating a problem:
8477           // the friend declaration will refer to an untemplated decl,
8478           // and clearly the user wants a template specialization.  So
8479           // we need to insert '<>' after the name.
8480           SourceLocation InsertLoc;
8481           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8482             InsertLoc = D.getName().getSourceRange().getEnd();
8483             InsertLoc = getLocForEndOfToken(InsertLoc);
8484           }
8485 
8486           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8487             << Name << RemoveRange
8488             << FixItHint::CreateRemoval(RemoveRange)
8489             << FixItHint::CreateInsertion(InsertLoc, "<>");
8490         }
8491       }
8492     } else {
8493       // All template param lists were matched against the scope specifier:
8494       // this is NOT (an explicit specialization of) a template.
8495       if (TemplateParamLists.size() > 0)
8496         // For source fidelity, store all the template param lists.
8497         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8498     }
8499 
8500     if (Invalid) {
8501       NewFD->setInvalidDecl();
8502       if (FunctionTemplate)
8503         FunctionTemplate->setInvalidDecl();
8504     }
8505 
8506     // C++ [dcl.fct.spec]p5:
8507     //   The virtual specifier shall only be used in declarations of
8508     //   nonstatic class member functions that appear within a
8509     //   member-specification of a class declaration; see 10.3.
8510     //
8511     if (isVirtual && !NewFD->isInvalidDecl()) {
8512       if (!isVirtualOkay) {
8513         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8514              diag::err_virtual_non_function);
8515       } else if (!CurContext->isRecord()) {
8516         // 'virtual' was specified outside of the class.
8517         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8518              diag::err_virtual_out_of_class)
8519           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8520       } else if (NewFD->getDescribedFunctionTemplate()) {
8521         // C++ [temp.mem]p3:
8522         //  A member function template shall not be virtual.
8523         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8524              diag::err_virtual_member_function_template)
8525           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8526       } else {
8527         // Okay: Add virtual to the method.
8528         NewFD->setVirtualAsWritten(true);
8529       }
8530 
8531       if (getLangOpts().CPlusPlus14 &&
8532           NewFD->getReturnType()->isUndeducedType())
8533         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8534     }
8535 
8536     if (getLangOpts().CPlusPlus14 &&
8537         (NewFD->isDependentContext() ||
8538          (isFriend && CurContext->isDependentContext())) &&
8539         NewFD->getReturnType()->isUndeducedType()) {
8540       // If the function template is referenced directly (for instance, as a
8541       // member of the current instantiation), pretend it has a dependent type.
8542       // This is not really justified by the standard, but is the only sane
8543       // thing to do.
8544       // FIXME: For a friend function, we have not marked the function as being
8545       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8546       const FunctionProtoType *FPT =
8547           NewFD->getType()->castAs<FunctionProtoType>();
8548       QualType Result =
8549           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8550       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8551                                              FPT->getExtProtoInfo()));
8552     }
8553 
8554     // C++ [dcl.fct.spec]p3:
8555     //  The inline specifier shall not appear on a block scope function
8556     //  declaration.
8557     if (isInline && !NewFD->isInvalidDecl()) {
8558       if (CurContext->isFunctionOrMethod()) {
8559         // 'inline' is not allowed on block scope function declaration.
8560         Diag(D.getDeclSpec().getInlineSpecLoc(),
8561              diag::err_inline_declaration_block_scope) << Name
8562           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8563       }
8564     }
8565 
8566     // C++ [dcl.fct.spec]p6:
8567     //  The explicit specifier shall be used only in the declaration of a
8568     //  constructor or conversion function within its class definition;
8569     //  see 12.3.1 and 12.3.2.
8570     if (isExplicit && !NewFD->isInvalidDecl() &&
8571         !isa<CXXDeductionGuideDecl>(NewFD)) {
8572       if (!CurContext->isRecord()) {
8573         // 'explicit' was specified outside of the class.
8574         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8575              diag::err_explicit_out_of_class)
8576           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8577       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8578                  !isa<CXXConversionDecl>(NewFD)) {
8579         // 'explicit' was specified on a function that wasn't a constructor
8580         // or conversion function.
8581         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8582              diag::err_explicit_non_ctor_or_conv_function)
8583           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8584       }
8585     }
8586 
8587     if (isConstexpr) {
8588       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8589       // are implicitly inline.
8590       NewFD->setImplicitlyInline();
8591 
8592       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8593       // be either constructors or to return a literal type. Therefore,
8594       // destructors cannot be declared constexpr.
8595       if (isa<CXXDestructorDecl>(NewFD))
8596         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8597     }
8598 
8599     // If __module_private__ was specified, mark the function accordingly.
8600     if (D.getDeclSpec().isModulePrivateSpecified()) {
8601       if (isFunctionTemplateSpecialization) {
8602         SourceLocation ModulePrivateLoc
8603           = D.getDeclSpec().getModulePrivateSpecLoc();
8604         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8605           << 0
8606           << FixItHint::CreateRemoval(ModulePrivateLoc);
8607       } else {
8608         NewFD->setModulePrivate();
8609         if (FunctionTemplate)
8610           FunctionTemplate->setModulePrivate();
8611       }
8612     }
8613 
8614     if (isFriend) {
8615       if (FunctionTemplate) {
8616         FunctionTemplate->setObjectOfFriendDecl();
8617         FunctionTemplate->setAccess(AS_public);
8618       }
8619       NewFD->setObjectOfFriendDecl();
8620       NewFD->setAccess(AS_public);
8621     }
8622 
8623     // If a function is defined as defaulted or deleted, mark it as such now.
8624     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8625     // definition kind to FDK_Definition.
8626     switch (D.getFunctionDefinitionKind()) {
8627       case FDK_Declaration:
8628       case FDK_Definition:
8629         break;
8630 
8631       case FDK_Defaulted:
8632         NewFD->setDefaulted();
8633         break;
8634 
8635       case FDK_Deleted:
8636         NewFD->setDeletedAsWritten();
8637         break;
8638     }
8639 
8640     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8641         D.isFunctionDefinition()) {
8642       // C++ [class.mfct]p2:
8643       //   A member function may be defined (8.4) in its class definition, in
8644       //   which case it is an inline member function (7.1.2)
8645       NewFD->setImplicitlyInline();
8646     }
8647 
8648     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8649         !CurContext->isRecord()) {
8650       // C++ [class.static]p1:
8651       //   A data or function member of a class may be declared static
8652       //   in a class definition, in which case it is a static member of
8653       //   the class.
8654 
8655       // Complain about the 'static' specifier if it's on an out-of-line
8656       // member function definition.
8657 
8658       // MSVC permits the use of a 'static' storage specifier on an out-of-line
8659       // member function template declaration, warn about this.
8660       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8661            NewFD->getDescribedFunctionTemplate() && getLangOpts().MSVCCompat
8662            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
8663         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8664     }
8665 
8666     // C++11 [except.spec]p15:
8667     //   A deallocation function with no exception-specification is treated
8668     //   as if it were specified with noexcept(true).
8669     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8670     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8671          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8672         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8673       NewFD->setType(Context.getFunctionType(
8674           FPT->getReturnType(), FPT->getParamTypes(),
8675           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8676   }
8677 
8678   // Filter out previous declarations that don't match the scope.
8679   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8680                        D.getCXXScopeSpec().isNotEmpty() ||
8681                        isMemberSpecialization ||
8682                        isFunctionTemplateSpecialization);
8683 
8684   // Handle GNU asm-label extension (encoded as an attribute).
8685   if (Expr *E = (Expr*) D.getAsmLabel()) {
8686     // The parser guarantees this is a string.
8687     StringLiteral *SE = cast<StringLiteral>(E);
8688     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8689                                                 SE->getString(), 0));
8690   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8691     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8692       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8693     if (I != ExtnameUndeclaredIdentifiers.end()) {
8694       if (isDeclExternC(NewFD)) {
8695         NewFD->addAttr(I->second);
8696         ExtnameUndeclaredIdentifiers.erase(I);
8697       } else
8698         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8699             << /*Variable*/0 << NewFD;
8700     }
8701   }
8702 
8703   // Copy the parameter declarations from the declarator D to the function
8704   // declaration NewFD, if they are available.  First scavenge them into Params.
8705   SmallVector<ParmVarDecl*, 16> Params;
8706   unsigned FTIIdx;
8707   if (D.isFunctionDeclarator(FTIIdx)) {
8708     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8709 
8710     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8711     // function that takes no arguments, not a function that takes a
8712     // single void argument.
8713     // We let through "const void" here because Sema::GetTypeForDeclarator
8714     // already checks for that case.
8715     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8716       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8717         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8718         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8719         Param->setDeclContext(NewFD);
8720         Params.push_back(Param);
8721 
8722         if (Param->isInvalidDecl())
8723           NewFD->setInvalidDecl();
8724       }
8725     }
8726 
8727     if (!getLangOpts().CPlusPlus) {
8728       // In C, find all the tag declarations from the prototype and move them
8729       // into the function DeclContext. Remove them from the surrounding tag
8730       // injection context of the function, which is typically but not always
8731       // the TU.
8732       DeclContext *PrototypeTagContext =
8733           getTagInjectionContext(NewFD->getLexicalDeclContext());
8734       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8735         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8736 
8737         // We don't want to reparent enumerators. Look at their parent enum
8738         // instead.
8739         if (!TD) {
8740           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8741             TD = cast<EnumDecl>(ECD->getDeclContext());
8742         }
8743         if (!TD)
8744           continue;
8745         DeclContext *TagDC = TD->getLexicalDeclContext();
8746         if (!TagDC->containsDecl(TD))
8747           continue;
8748         TagDC->removeDecl(TD);
8749         TD->setDeclContext(NewFD);
8750         NewFD->addDecl(TD);
8751 
8752         // Preserve the lexical DeclContext if it is not the surrounding tag
8753         // injection context of the FD. In this example, the semantic context of
8754         // E will be f and the lexical context will be S, while both the
8755         // semantic and lexical contexts of S will be f:
8756         //   void f(struct S { enum E { a } f; } s);
8757         if (TagDC != PrototypeTagContext)
8758           TD->setLexicalDeclContext(TagDC);
8759       }
8760     }
8761   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8762     // When we're declaring a function with a typedef, typeof, etc as in the
8763     // following example, we'll need to synthesize (unnamed)
8764     // parameters for use in the declaration.
8765     //
8766     // @code
8767     // typedef void fn(int);
8768     // fn f;
8769     // @endcode
8770 
8771     // Synthesize a parameter for each argument type.
8772     for (const auto &AI : FT->param_types()) {
8773       ParmVarDecl *Param =
8774           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8775       Param->setScopeInfo(0, Params.size());
8776       Params.push_back(Param);
8777     }
8778   } else {
8779     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8780            "Should not need args for typedef of non-prototype fn");
8781   }
8782 
8783   // Finally, we know we have the right number of parameters, install them.
8784   NewFD->setParams(Params);
8785 
8786   if (D.getDeclSpec().isNoreturnSpecified())
8787     NewFD->addAttr(
8788         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8789                                        Context, 0));
8790 
8791   // Functions returning a variably modified type violate C99 6.7.5.2p2
8792   // because all functions have linkage.
8793   if (!NewFD->isInvalidDecl() &&
8794       NewFD->getReturnType()->isVariablyModifiedType()) {
8795     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8796     NewFD->setInvalidDecl();
8797   }
8798 
8799   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8800   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8801       !NewFD->hasAttr<SectionAttr>()) {
8802     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8803                                                  PragmaClangTextSection.SectionName,
8804                                                  PragmaClangTextSection.PragmaLocation));
8805   }
8806 
8807   // Apply an implicit SectionAttr if #pragma code_seg is active.
8808   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8809       !NewFD->hasAttr<SectionAttr>()) {
8810     NewFD->addAttr(
8811         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8812                                     CodeSegStack.CurrentValue->getString(),
8813                                     CodeSegStack.CurrentPragmaLocation));
8814     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8815                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8816                          ASTContext::PSF_Read,
8817                      NewFD))
8818       NewFD->dropAttr<SectionAttr>();
8819   }
8820 
8821   // Apply an implicit CodeSegAttr from class declspec or
8822   // apply an implicit SectionAttr from #pragma code_seg if active.
8823   if (!NewFD->hasAttr<CodeSegAttr>()) {
8824     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
8825                                                                  D.isFunctionDefinition())) {
8826       NewFD->addAttr(SAttr);
8827     }
8828   }
8829 
8830   // Handle attributes.
8831   ProcessDeclAttributes(S, NewFD, D);
8832 
8833   if (getLangOpts().OpenCL) {
8834     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8835     // type declaration will generate a compilation error.
8836     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
8837     if (AddressSpace != LangAS::Default) {
8838       Diag(NewFD->getLocation(),
8839            diag::err_opencl_return_value_with_address_space);
8840       NewFD->setInvalidDecl();
8841     }
8842   }
8843 
8844   if (!getLangOpts().CPlusPlus) {
8845     // Perform semantic checking on the function declaration.
8846     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8847       CheckMain(NewFD, D.getDeclSpec());
8848 
8849     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8850       CheckMSVCRTEntryPoint(NewFD);
8851 
8852     if (!NewFD->isInvalidDecl())
8853       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8854                                                   isMemberSpecialization));
8855     else if (!Previous.empty())
8856       // Recover gracefully from an invalid redeclaration.
8857       D.setRedeclaration(true);
8858     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8859             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8860            "previous declaration set still overloaded");
8861 
8862     // Diagnose no-prototype function declarations with calling conventions that
8863     // don't support variadic calls. Only do this in C and do it after merging
8864     // possibly prototyped redeclarations.
8865     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8866     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8867       CallingConv CC = FT->getExtInfo().getCC();
8868       if (!supportsVariadicCall(CC)) {
8869         // Windows system headers sometimes accidentally use stdcall without
8870         // (void) parameters, so we relax this to a warning.
8871         int DiagID =
8872             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8873         Diag(NewFD->getLocation(), DiagID)
8874             << FunctionType::getNameForCallConv(CC);
8875       }
8876     }
8877   } else {
8878     // C++11 [replacement.functions]p3:
8879     //  The program's definitions shall not be specified as inline.
8880     //
8881     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8882     //
8883     // Suppress the diagnostic if the function is __attribute__((used)), since
8884     // that forces an external definition to be emitted.
8885     if (D.getDeclSpec().isInlineSpecified() &&
8886         NewFD->isReplaceableGlobalAllocationFunction() &&
8887         !NewFD->hasAttr<UsedAttr>())
8888       Diag(D.getDeclSpec().getInlineSpecLoc(),
8889            diag::ext_operator_new_delete_declared_inline)
8890         << NewFD->getDeclName();
8891 
8892     // If the declarator is a template-id, translate the parser's template
8893     // argument list into our AST format.
8894     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
8895       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8896       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8897       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8898       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8899                                          TemplateId->NumArgs);
8900       translateTemplateArguments(TemplateArgsPtr,
8901                                  TemplateArgs);
8902 
8903       HasExplicitTemplateArgs = true;
8904 
8905       if (NewFD->isInvalidDecl()) {
8906         HasExplicitTemplateArgs = false;
8907       } else if (FunctionTemplate) {
8908         // Function template with explicit template arguments.
8909         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8910           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8911 
8912         HasExplicitTemplateArgs = false;
8913       } else {
8914         assert((isFunctionTemplateSpecialization ||
8915                 D.getDeclSpec().isFriendSpecified()) &&
8916                "should have a 'template<>' for this decl");
8917         // "friend void foo<>(int);" is an implicit specialization decl.
8918         isFunctionTemplateSpecialization = true;
8919       }
8920     } else if (isFriend && isFunctionTemplateSpecialization) {
8921       // This combination is only possible in a recovery case;  the user
8922       // wrote something like:
8923       //   template <> friend void foo(int);
8924       // which we're recovering from as if the user had written:
8925       //   friend void foo<>(int);
8926       // Go ahead and fake up a template id.
8927       HasExplicitTemplateArgs = true;
8928       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8929       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8930     }
8931 
8932     // We do not add HD attributes to specializations here because
8933     // they may have different constexpr-ness compared to their
8934     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8935     // may end up with different effective targets. Instead, a
8936     // specialization inherits its target attributes from its template
8937     // in the CheckFunctionTemplateSpecialization() call below.
8938     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8939       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8940 
8941     // If it's a friend (and only if it's a friend), it's possible
8942     // that either the specialized function type or the specialized
8943     // template is dependent, and therefore matching will fail.  In
8944     // this case, don't check the specialization yet.
8945     bool InstantiationDependent = false;
8946     if (isFunctionTemplateSpecialization && isFriend &&
8947         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8948          TemplateSpecializationType::anyDependentTemplateArguments(
8949             TemplateArgs,
8950             InstantiationDependent))) {
8951       assert(HasExplicitTemplateArgs &&
8952              "friend function specialization without template args");
8953       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8954                                                        Previous))
8955         NewFD->setInvalidDecl();
8956     } else if (isFunctionTemplateSpecialization) {
8957       if (CurContext->isDependentContext() && CurContext->isRecord()
8958           && !isFriend) {
8959         isDependentClassScopeExplicitSpecialization = true;
8960       } else if (!NewFD->isInvalidDecl() &&
8961                  CheckFunctionTemplateSpecialization(
8962                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
8963                      Previous))
8964         NewFD->setInvalidDecl();
8965 
8966       // C++ [dcl.stc]p1:
8967       //   A storage-class-specifier shall not be specified in an explicit
8968       //   specialization (14.7.3)
8969       FunctionTemplateSpecializationInfo *Info =
8970           NewFD->getTemplateSpecializationInfo();
8971       if (Info && SC != SC_None) {
8972         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8973           Diag(NewFD->getLocation(),
8974                diag::err_explicit_specialization_inconsistent_storage_class)
8975             << SC
8976             << FixItHint::CreateRemoval(
8977                                       D.getDeclSpec().getStorageClassSpecLoc());
8978 
8979         else
8980           Diag(NewFD->getLocation(),
8981                diag::ext_explicit_specialization_storage_class)
8982             << FixItHint::CreateRemoval(
8983                                       D.getDeclSpec().getStorageClassSpecLoc());
8984       }
8985     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8986       if (CheckMemberSpecialization(NewFD, Previous))
8987           NewFD->setInvalidDecl();
8988     }
8989 
8990     // Perform semantic checking on the function declaration.
8991     if (!isDependentClassScopeExplicitSpecialization) {
8992       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8993         CheckMain(NewFD, D.getDeclSpec());
8994 
8995       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8996         CheckMSVCRTEntryPoint(NewFD);
8997 
8998       if (!NewFD->isInvalidDecl())
8999         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9000                                                     isMemberSpecialization));
9001       else if (!Previous.empty())
9002         // Recover gracefully from an invalid redeclaration.
9003         D.setRedeclaration(true);
9004     }
9005 
9006     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9007             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9008            "previous declaration set still overloaded");
9009 
9010     NamedDecl *PrincipalDecl = (FunctionTemplate
9011                                 ? cast<NamedDecl>(FunctionTemplate)
9012                                 : NewFD);
9013 
9014     if (isFriend && NewFD->getPreviousDecl()) {
9015       AccessSpecifier Access = AS_public;
9016       if (!NewFD->isInvalidDecl())
9017         Access = NewFD->getPreviousDecl()->getAccess();
9018 
9019       NewFD->setAccess(Access);
9020       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9021     }
9022 
9023     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9024         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9025       PrincipalDecl->setNonMemberOperator();
9026 
9027     // If we have a function template, check the template parameter
9028     // list. This will check and merge default template arguments.
9029     if (FunctionTemplate) {
9030       FunctionTemplateDecl *PrevTemplate =
9031                                      FunctionTemplate->getPreviousDecl();
9032       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9033                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9034                                     : nullptr,
9035                             D.getDeclSpec().isFriendSpecified()
9036                               ? (D.isFunctionDefinition()
9037                                    ? TPC_FriendFunctionTemplateDefinition
9038                                    : TPC_FriendFunctionTemplate)
9039                               : (D.getCXXScopeSpec().isSet() &&
9040                                  DC && DC->isRecord() &&
9041                                  DC->isDependentContext())
9042                                   ? TPC_ClassTemplateMember
9043                                   : TPC_FunctionTemplate);
9044     }
9045 
9046     if (NewFD->isInvalidDecl()) {
9047       // Ignore all the rest of this.
9048     } else if (!D.isRedeclaration()) {
9049       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9050                                        AddToScope };
9051       // Fake up an access specifier if it's supposed to be a class member.
9052       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9053         NewFD->setAccess(AS_public);
9054 
9055       // Qualified decls generally require a previous declaration.
9056       if (D.getCXXScopeSpec().isSet()) {
9057         // ...with the major exception of templated-scope or
9058         // dependent-scope friend declarations.
9059 
9060         // TODO: we currently also suppress this check in dependent
9061         // contexts because (1) the parameter depth will be off when
9062         // matching friend templates and (2) we might actually be
9063         // selecting a friend based on a dependent factor.  But there
9064         // are situations where these conditions don't apply and we
9065         // can actually do this check immediately.
9066         //
9067         // Unless the scope is dependent, it's always an error if qualified
9068         // redeclaration lookup found nothing at all. Diagnose that now;
9069         // nothing will diagnose that error later.
9070         if (isFriend &&
9071             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9072              (!Previous.empty() && (TemplateParamLists.size() ||
9073                                     CurContext->isDependentContext())))) {
9074           // ignore these
9075         } else {
9076           // The user tried to provide an out-of-line definition for a
9077           // function that is a member of a class or namespace, but there
9078           // was no such member function declared (C++ [class.mfct]p2,
9079           // C++ [namespace.memdef]p2). For example:
9080           //
9081           // class X {
9082           //   void f() const;
9083           // };
9084           //
9085           // void X::f() { } // ill-formed
9086           //
9087           // Complain about this problem, and attempt to suggest close
9088           // matches (e.g., those that differ only in cv-qualifiers and
9089           // whether the parameter types are references).
9090 
9091           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9092                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9093             AddToScope = ExtraArgs.AddToScope;
9094             return Result;
9095           }
9096         }
9097 
9098         // Unqualified local friend declarations are required to resolve
9099         // to something.
9100       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9101         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9102                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9103           AddToScope = ExtraArgs.AddToScope;
9104           return Result;
9105         }
9106       }
9107     } else if (!D.isFunctionDefinition() &&
9108                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9109                !isFriend && !isFunctionTemplateSpecialization &&
9110                !isMemberSpecialization) {
9111       // An out-of-line member function declaration must also be a
9112       // definition (C++ [class.mfct]p2).
9113       // Note that this is not the case for explicit specializations of
9114       // function templates or member functions of class templates, per
9115       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9116       // extension for compatibility with old SWIG code which likes to
9117       // generate them.
9118       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9119         << D.getCXXScopeSpec().getRange();
9120     }
9121   }
9122 
9123   ProcessPragmaWeak(S, NewFD);
9124   checkAttributesAfterMerging(*this, *NewFD);
9125 
9126   AddKnownFunctionAttributes(NewFD);
9127 
9128   if (NewFD->hasAttr<OverloadableAttr>() &&
9129       !NewFD->getType()->getAs<FunctionProtoType>()) {
9130     Diag(NewFD->getLocation(),
9131          diag::err_attribute_overloadable_no_prototype)
9132       << NewFD;
9133 
9134     // Turn this into a variadic function with no parameters.
9135     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9136     FunctionProtoType::ExtProtoInfo EPI(
9137         Context.getDefaultCallingConvention(true, false));
9138     EPI.Variadic = true;
9139     EPI.ExtInfo = FT->getExtInfo();
9140 
9141     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9142     NewFD->setType(R);
9143   }
9144 
9145   // If there's a #pragma GCC visibility in scope, and this isn't a class
9146   // member, set the visibility of this function.
9147   if (!DC->isRecord() && NewFD->isExternallyVisible())
9148     AddPushedVisibilityAttribute(NewFD);
9149 
9150   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9151   // marking the function.
9152   AddCFAuditedAttribute(NewFD);
9153 
9154   // If this is a function definition, check if we have to apply optnone due to
9155   // a pragma.
9156   if(D.isFunctionDefinition())
9157     AddRangeBasedOptnone(NewFD);
9158 
9159   // If this is the first declaration of an extern C variable, update
9160   // the map of such variables.
9161   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9162       isIncompleteDeclExternC(*this, NewFD))
9163     RegisterLocallyScopedExternCDecl(NewFD, S);
9164 
9165   // Set this FunctionDecl's range up to the right paren.
9166   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9167 
9168   if (D.isRedeclaration() && !Previous.empty()) {
9169     NamedDecl *Prev = Previous.getRepresentativeDecl();
9170     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9171                                    isMemberSpecialization ||
9172                                        isFunctionTemplateSpecialization,
9173                                    D.isFunctionDefinition());
9174   }
9175 
9176   if (getLangOpts().CUDA) {
9177     IdentifierInfo *II = NewFD->getIdentifier();
9178     if (II && II->isStr(getCudaConfigureFuncName()) &&
9179         !NewFD->isInvalidDecl() &&
9180         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9181       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9182         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9183             << getCudaConfigureFuncName();
9184       Context.setcudaConfigureCallDecl(NewFD);
9185     }
9186 
9187     // Variadic functions, other than a *declaration* of printf, are not allowed
9188     // in device-side CUDA code, unless someone passed
9189     // -fcuda-allow-variadic-functions.
9190     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9191         (NewFD->hasAttr<CUDADeviceAttr>() ||
9192          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9193         !(II && II->isStr("printf") && NewFD->isExternC() &&
9194           !D.isFunctionDefinition())) {
9195       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9196     }
9197   }
9198 
9199   MarkUnusedFileScopedDecl(NewFD);
9200 
9201   if (getLangOpts().CPlusPlus) {
9202     if (FunctionTemplate) {
9203       if (NewFD->isInvalidDecl())
9204         FunctionTemplate->setInvalidDecl();
9205       return FunctionTemplate;
9206     }
9207 
9208     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9209       CompleteMemberSpecialization(NewFD, Previous);
9210   }
9211 
9212   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9213     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9214     if ((getLangOpts().OpenCLVersion >= 120)
9215         && (SC == SC_Static)) {
9216       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9217       D.setInvalidType();
9218     }
9219 
9220     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9221     if (!NewFD->getReturnType()->isVoidType()) {
9222       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9223       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9224           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9225                                 : FixItHint());
9226       D.setInvalidType();
9227     }
9228 
9229     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9230     for (auto Param : NewFD->parameters())
9231       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9232   }
9233   for (const ParmVarDecl *Param : NewFD->parameters()) {
9234     QualType PT = Param->getType();
9235 
9236     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9237     // types.
9238     if (getLangOpts().OpenCLVersion >= 200) {
9239       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9240         QualType ElemTy = PipeTy->getElementType();
9241           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9242             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9243             D.setInvalidType();
9244           }
9245       }
9246     }
9247   }
9248 
9249   // Here we have an function template explicit specialization at class scope.
9250   // The actual specialization will be postponed to template instatiation
9251   // time via the ClassScopeFunctionSpecializationDecl node.
9252   if (isDependentClassScopeExplicitSpecialization) {
9253     ClassScopeFunctionSpecializationDecl *NewSpec =
9254                          ClassScopeFunctionSpecializationDecl::Create(
9255                                 Context, CurContext, NewFD->getLocation(),
9256                                 cast<CXXMethodDecl>(NewFD),
9257                                 HasExplicitTemplateArgs, TemplateArgs);
9258     CurContext->addDecl(NewSpec);
9259     AddToScope = false;
9260   }
9261 
9262   // Diagnose availability attributes. Availability cannot be used on functions
9263   // that are run during load/unload.
9264   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9265     if (NewFD->hasAttr<ConstructorAttr>()) {
9266       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9267           << 1;
9268       NewFD->dropAttr<AvailabilityAttr>();
9269     }
9270     if (NewFD->hasAttr<DestructorAttr>()) {
9271       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9272           << 2;
9273       NewFD->dropAttr<AvailabilityAttr>();
9274     }
9275   }
9276 
9277   return NewFD;
9278 }
9279 
9280 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9281 /// when __declspec(code_seg) "is applied to a class, all member functions of
9282 /// the class and nested classes -- this includes compiler-generated special
9283 /// member functions -- are put in the specified segment."
9284 /// The actual behavior is a little more complicated. The Microsoft compiler
9285 /// won't check outer classes if there is an active value from #pragma code_seg.
9286 /// The CodeSeg is always applied from the direct parent but only from outer
9287 /// classes when the #pragma code_seg stack is empty. See:
9288 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9289 /// available since MS has removed the page.
9290 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9291   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9292   if (!Method)
9293     return nullptr;
9294   const CXXRecordDecl *Parent = Method->getParent();
9295   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9296     Attr *NewAttr = SAttr->clone(S.getASTContext());
9297     NewAttr->setImplicit(true);
9298     return NewAttr;
9299   }
9300 
9301   // The Microsoft compiler won't check outer classes for the CodeSeg
9302   // when the #pragma code_seg stack is active.
9303   if (S.CodeSegStack.CurrentValue)
9304    return nullptr;
9305 
9306   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9307     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9308       Attr *NewAttr = SAttr->clone(S.getASTContext());
9309       NewAttr->setImplicit(true);
9310       return NewAttr;
9311     }
9312   }
9313   return nullptr;
9314 }
9315 
9316 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9317 /// containing class. Otherwise it will return implicit SectionAttr if the
9318 /// function is a definition and there is an active value on CodeSegStack
9319 /// (from the current #pragma code-seg value).
9320 ///
9321 /// \param FD Function being declared.
9322 /// \param IsDefinition Whether it is a definition or just a declarartion.
9323 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9324 ///          nullptr if no attribute should be added.
9325 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9326                                                        bool IsDefinition) {
9327   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9328     return A;
9329   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9330       CodeSegStack.CurrentValue) {
9331     return SectionAttr::CreateImplicit(getASTContext(),
9332                                        SectionAttr::Declspec_allocate,
9333                                        CodeSegStack.CurrentValue->getString(),
9334                                        CodeSegStack.CurrentPragmaLocation);
9335   }
9336   return nullptr;
9337 }
9338 
9339 /// Determines if we can perform a correct type check for \p D as a
9340 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9341 /// best-effort check.
9342 ///
9343 /// \param NewD The new declaration.
9344 /// \param OldD The old declaration.
9345 /// \param NewT The portion of the type of the new declaration to check.
9346 /// \param OldT The portion of the type of the old declaration to check.
9347 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9348                                           QualType NewT, QualType OldT) {
9349   if (!NewD->getLexicalDeclContext()->isDependentContext())
9350     return true;
9351 
9352   // For dependently-typed local extern declarations and friends, we can't
9353   // perform a correct type check in general until instantiation:
9354   //
9355   //   int f();
9356   //   template<typename T> void g() { T f(); }
9357   //
9358   // (valid if g() is only instantiated with T = int).
9359   if (NewT->isDependentType() &&
9360       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9361     return false;
9362 
9363   // Similarly, if the previous declaration was a dependent local extern
9364   // declaration, we don't really know its type yet.
9365   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9366     return false;
9367 
9368   return true;
9369 }
9370 
9371 /// Checks if the new declaration declared in dependent context must be
9372 /// put in the same redeclaration chain as the specified declaration.
9373 ///
9374 /// \param D Declaration that is checked.
9375 /// \param PrevDecl Previous declaration found with proper lookup method for the
9376 ///                 same declaration name.
9377 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9378 ///          belongs to.
9379 ///
9380 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9381   if (!D->getLexicalDeclContext()->isDependentContext())
9382     return true;
9383 
9384   // Don't chain dependent friend function definitions until instantiation, to
9385   // permit cases like
9386   //
9387   //   void func();
9388   //   template<typename T> class C1 { friend void func() {} };
9389   //   template<typename T> class C2 { friend void func() {} };
9390   //
9391   // ... which is valid if only one of C1 and C2 is ever instantiated.
9392   //
9393   // FIXME: This need only apply to function definitions. For now, we proxy
9394   // this by checking for a file-scope function. We do not want this to apply
9395   // to friend declarations nominating member functions, because that gets in
9396   // the way of access checks.
9397   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9398     return false;
9399 
9400   auto *VD = dyn_cast<ValueDecl>(D);
9401   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9402   return !VD || !PrevVD ||
9403          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9404                                         PrevVD->getType());
9405 }
9406 
9407 /// Check the target attribute of the function for MultiVersion
9408 /// validity.
9409 ///
9410 /// Returns true if there was an error, false otherwise.
9411 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9412   const auto *TA = FD->getAttr<TargetAttr>();
9413   assert(TA && "MultiVersion Candidate requires a target attribute");
9414   TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9415   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9416   enum ErrType { Feature = 0, Architecture = 1 };
9417 
9418   if (!ParseInfo.Architecture.empty() &&
9419       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9420     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9421         << Architecture << ParseInfo.Architecture;
9422     return true;
9423   }
9424 
9425   for (const auto &Feat : ParseInfo.Features) {
9426     auto BareFeat = StringRef{Feat}.substr(1);
9427     if (Feat[0] == '-') {
9428       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9429           << Feature << ("no-" + BareFeat).str();
9430       return true;
9431     }
9432 
9433     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9434         !TargetInfo.isValidFeatureName(BareFeat)) {
9435       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9436           << Feature << BareFeat;
9437       return true;
9438     }
9439   }
9440   return false;
9441 }
9442 
9443 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9444                                          MultiVersionKind MVType) {
9445   for (const Attr *A : FD->attrs()) {
9446     switch (A->getKind()) {
9447     case attr::CPUDispatch:
9448     case attr::CPUSpecific:
9449       if (MVType != MultiVersionKind::CPUDispatch &&
9450           MVType != MultiVersionKind::CPUSpecific)
9451         return true;
9452       break;
9453     case attr::Target:
9454       if (MVType != MultiVersionKind::Target)
9455         return true;
9456       break;
9457     default:
9458       return true;
9459     }
9460   }
9461   return false;
9462 }
9463 
9464 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9465                                              const FunctionDecl *NewFD,
9466                                              bool CausesMV,
9467                                              MultiVersionKind MVType) {
9468   enum DoesntSupport {
9469     FuncTemplates = 0,
9470     VirtFuncs = 1,
9471     DeducedReturn = 2,
9472     Constructors = 3,
9473     Destructors = 4,
9474     DeletedFuncs = 5,
9475     DefaultedFuncs = 6,
9476     ConstexprFuncs = 7,
9477   };
9478   enum Different {
9479     CallingConv = 0,
9480     ReturnType = 1,
9481     ConstexprSpec = 2,
9482     InlineSpec = 3,
9483     StorageClass = 4,
9484     Linkage = 5
9485   };
9486 
9487   bool IsCPUSpecificCPUDispatchMVType =
9488       MVType == MultiVersionKind::CPUDispatch ||
9489       MVType == MultiVersionKind::CPUSpecific;
9490 
9491   if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
9492     S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
9493     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9494     return true;
9495   }
9496 
9497   if (!NewFD->getType()->getAs<FunctionProtoType>())
9498     return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
9499 
9500   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9501     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9502     if (OldFD)
9503       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9504     return true;
9505   }
9506 
9507   // For now, disallow all other attributes.  These should be opt-in, but
9508   // an analysis of all of them is a future FIXME.
9509   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
9510     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9511         << IsCPUSpecificCPUDispatchMVType;
9512     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9513     return true;
9514   }
9515 
9516   if (HasNonMultiVersionAttributes(NewFD, MVType))
9517     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9518            << IsCPUSpecificCPUDispatchMVType;
9519 
9520   if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9521     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9522            << IsCPUSpecificCPUDispatchMVType << FuncTemplates;
9523 
9524   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9525     if (NewCXXFD->isVirtual())
9526       return S.Diag(NewCXXFD->getLocation(),
9527                     diag::err_multiversion_doesnt_support)
9528              << IsCPUSpecificCPUDispatchMVType << VirtFuncs;
9529 
9530     if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
9531       return S.Diag(NewCXXCtor->getLocation(),
9532                     diag::err_multiversion_doesnt_support)
9533              << IsCPUSpecificCPUDispatchMVType << Constructors;
9534 
9535     if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
9536       return S.Diag(NewCXXDtor->getLocation(),
9537                     diag::err_multiversion_doesnt_support)
9538              << IsCPUSpecificCPUDispatchMVType << Destructors;
9539   }
9540 
9541   if (NewFD->isDeleted())
9542     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9543            << IsCPUSpecificCPUDispatchMVType << DeletedFuncs;
9544 
9545   if (NewFD->isDefaulted())
9546     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9547            << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs;
9548 
9549   if (NewFD->isConstexpr() && (MVType == MultiVersionKind::CPUDispatch ||
9550                                MVType == MultiVersionKind::CPUSpecific))
9551     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9552            << IsCPUSpecificCPUDispatchMVType << ConstexprFuncs;
9553 
9554   QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
9555   const auto *NewType = cast<FunctionType>(NewQType);
9556   QualType NewReturnType = NewType->getReturnType();
9557 
9558   if (NewReturnType->isUndeducedType())
9559     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9560            << IsCPUSpecificCPUDispatchMVType << DeducedReturn;
9561 
9562   // Only allow transition to MultiVersion if it hasn't been used.
9563   if (OldFD && CausesMV && OldFD->isUsed(false))
9564     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9565 
9566   // Ensure the return type is identical.
9567   if (OldFD) {
9568     QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
9569     const auto *OldType = cast<FunctionType>(OldQType);
9570     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9571     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9572 
9573     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9574       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9575              << CallingConv;
9576 
9577     QualType OldReturnType = OldType->getReturnType();
9578 
9579     if (OldReturnType != NewReturnType)
9580       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9581              << ReturnType;
9582 
9583     if (OldFD->isConstexpr() != NewFD->isConstexpr())
9584       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9585              << ConstexprSpec;
9586 
9587     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9588       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9589              << InlineSpec;
9590 
9591     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9592       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9593              << StorageClass;
9594 
9595     if (OldFD->isExternC() != NewFD->isExternC())
9596       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9597              << Linkage;
9598 
9599     if (S.CheckEquivalentExceptionSpec(
9600             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9601             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9602       return true;
9603   }
9604   return false;
9605 }
9606 
9607 /// Check the validity of a multiversion function declaration that is the
9608 /// first of its kind. Also sets the multiversion'ness' of the function itself.
9609 ///
9610 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9611 ///
9612 /// Returns true if there was an error, false otherwise.
9613 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
9614                                            MultiVersionKind MVType,
9615                                            const TargetAttr *TA,
9616                                            const CPUDispatchAttr *CPUDisp,
9617                                            const CPUSpecificAttr *CPUSpec) {
9618   assert(MVType != MultiVersionKind::None &&
9619          "Function lacks multiversion attribute");
9620 
9621   // Target only causes MV if it is default, otherwise this is a normal
9622   // function.
9623   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
9624     return false;
9625 
9626   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
9627     FD->setInvalidDecl();
9628     return true;
9629   }
9630 
9631   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
9632     FD->setInvalidDecl();
9633     return true;
9634   }
9635 
9636   FD->setIsMultiVersion();
9637   return false;
9638 }
9639 
9640 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
9641   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
9642     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
9643       return true;
9644   }
9645 
9646   return false;
9647 }
9648 
9649 static bool CheckTargetCausesMultiVersioning(
9650     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
9651     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9652     LookupResult &Previous) {
9653   const auto *OldTA = OldFD->getAttr<TargetAttr>();
9654   TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9655   // Sort order doesn't matter, it just needs to be consistent.
9656   llvm::sort(NewParsed.Features);
9657 
9658   // If the old decl is NOT MultiVersioned yet, and we don't cause that
9659   // to change, this is a simple redeclaration.
9660   if (!NewTA->isDefaultVersion() &&
9661       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
9662     return false;
9663 
9664   // Otherwise, this decl causes MultiVersioning.
9665   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9666     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9667     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9668     NewFD->setInvalidDecl();
9669     return true;
9670   }
9671 
9672   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
9673                                        MultiVersionKind::Target)) {
9674     NewFD->setInvalidDecl();
9675     return true;
9676   }
9677 
9678   if (CheckMultiVersionValue(S, NewFD)) {
9679     NewFD->setInvalidDecl();
9680     return true;
9681   }
9682 
9683   // If this is 'default', permit the forward declaration.
9684   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
9685     Redeclaration = true;
9686     OldDecl = OldFD;
9687     OldFD->setIsMultiVersion();
9688     NewFD->setIsMultiVersion();
9689     return false;
9690   }
9691 
9692   if (CheckMultiVersionValue(S, OldFD)) {
9693     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9694     NewFD->setInvalidDecl();
9695     return true;
9696   }
9697 
9698   TargetAttr::ParsedTargetAttr OldParsed =
9699       OldTA->parse(std::less<std::string>());
9700 
9701   if (OldParsed == NewParsed) {
9702     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9703     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9704     NewFD->setInvalidDecl();
9705     return true;
9706   }
9707 
9708   for (const auto *FD : OldFD->redecls()) {
9709     const auto *CurTA = FD->getAttr<TargetAttr>();
9710     // We allow forward declarations before ANY multiversioning attributes, but
9711     // nothing after the fact.
9712     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
9713         (!CurTA || CurTA->isInherited())) {
9714       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
9715           << 0;
9716       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9717       NewFD->setInvalidDecl();
9718       return true;
9719     }
9720   }
9721 
9722   OldFD->setIsMultiVersion();
9723   NewFD->setIsMultiVersion();
9724   Redeclaration = false;
9725   MergeTypeWithPrevious = false;
9726   OldDecl = nullptr;
9727   Previous.clear();
9728   return false;
9729 }
9730 
9731 /// Check the validity of a new function declaration being added to an existing
9732 /// multiversioned declaration collection.
9733 static bool CheckMultiVersionAdditionalDecl(
9734     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
9735     MultiVersionKind NewMVType, const TargetAttr *NewTA,
9736     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
9737     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9738     LookupResult &Previous) {
9739 
9740   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
9741   // Disallow mixing of multiversioning types.
9742   if ((OldMVType == MultiVersionKind::Target &&
9743        NewMVType != MultiVersionKind::Target) ||
9744       (NewMVType == MultiVersionKind::Target &&
9745        OldMVType != MultiVersionKind::Target)) {
9746     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9747     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9748     NewFD->setInvalidDecl();
9749     return true;
9750   }
9751 
9752   TargetAttr::ParsedTargetAttr NewParsed;
9753   if (NewTA) {
9754     NewParsed = NewTA->parse();
9755     llvm::sort(NewParsed.Features);
9756   }
9757 
9758   bool UseMemberUsingDeclRules =
9759       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
9760 
9761   // Next, check ALL non-overloads to see if this is a redeclaration of a
9762   // previous member of the MultiVersion set.
9763   for (NamedDecl *ND : Previous) {
9764     FunctionDecl *CurFD = ND->getAsFunction();
9765     if (!CurFD)
9766       continue;
9767     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
9768       continue;
9769 
9770     if (NewMVType == MultiVersionKind::Target) {
9771       const auto *CurTA = CurFD->getAttr<TargetAttr>();
9772       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
9773         NewFD->setIsMultiVersion();
9774         Redeclaration = true;
9775         OldDecl = ND;
9776         return false;
9777       }
9778 
9779       TargetAttr::ParsedTargetAttr CurParsed =
9780           CurTA->parse(std::less<std::string>());
9781       if (CurParsed == NewParsed) {
9782         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9783         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9784         NewFD->setInvalidDecl();
9785         return true;
9786       }
9787     } else {
9788       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
9789       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
9790       // Handle CPUDispatch/CPUSpecific versions.
9791       // Only 1 CPUDispatch function is allowed, this will make it go through
9792       // the redeclaration errors.
9793       if (NewMVType == MultiVersionKind::CPUDispatch &&
9794           CurFD->hasAttr<CPUDispatchAttr>()) {
9795         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
9796             std::equal(
9797                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
9798                 NewCPUDisp->cpus_begin(),
9799                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9800                   return Cur->getName() == New->getName();
9801                 })) {
9802           NewFD->setIsMultiVersion();
9803           Redeclaration = true;
9804           OldDecl = ND;
9805           return false;
9806         }
9807 
9808         // If the declarations don't match, this is an error condition.
9809         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
9810         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9811         NewFD->setInvalidDecl();
9812         return true;
9813       }
9814       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
9815 
9816         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
9817             std::equal(
9818                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
9819                 NewCPUSpec->cpus_begin(),
9820                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9821                   return Cur->getName() == New->getName();
9822                 })) {
9823           NewFD->setIsMultiVersion();
9824           Redeclaration = true;
9825           OldDecl = ND;
9826           return false;
9827         }
9828 
9829         // Only 1 version of CPUSpecific is allowed for each CPU.
9830         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
9831           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
9832             if (CurII == NewII) {
9833               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
9834                   << NewII;
9835               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9836               NewFD->setInvalidDecl();
9837               return true;
9838             }
9839           }
9840         }
9841       }
9842       // If the two decls aren't the same MVType, there is no possible error
9843       // condition.
9844     }
9845   }
9846 
9847   // Else, this is simply a non-redecl case.  Checking the 'value' is only
9848   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
9849   // handled in the attribute adding step.
9850   if (NewMVType == MultiVersionKind::Target &&
9851       CheckMultiVersionValue(S, NewFD)) {
9852     NewFD->setInvalidDecl();
9853     return true;
9854   }
9855 
9856   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
9857                                        !OldFD->isMultiVersion(), NewMVType)) {
9858     NewFD->setInvalidDecl();
9859     return true;
9860   }
9861 
9862   // Permit forward declarations in the case where these two are compatible.
9863   if (!OldFD->isMultiVersion()) {
9864     OldFD->setIsMultiVersion();
9865     NewFD->setIsMultiVersion();
9866     Redeclaration = true;
9867     OldDecl = OldFD;
9868     return false;
9869   }
9870 
9871   NewFD->setIsMultiVersion();
9872   Redeclaration = false;
9873   MergeTypeWithPrevious = false;
9874   OldDecl = nullptr;
9875   Previous.clear();
9876   return false;
9877 }
9878 
9879 
9880 /// Check the validity of a mulitversion function declaration.
9881 /// Also sets the multiversion'ness' of the function itself.
9882 ///
9883 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9884 ///
9885 /// Returns true if there was an error, false otherwise.
9886 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
9887                                       bool &Redeclaration, NamedDecl *&OldDecl,
9888                                       bool &MergeTypeWithPrevious,
9889                                       LookupResult &Previous) {
9890   const auto *NewTA = NewFD->getAttr<TargetAttr>();
9891   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
9892   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
9893 
9894   // Mixing Multiversioning types is prohibited.
9895   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
9896       (NewCPUDisp && NewCPUSpec)) {
9897     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9898     NewFD->setInvalidDecl();
9899     return true;
9900   }
9901 
9902   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
9903 
9904   // Main isn't allowed to become a multiversion function, however it IS
9905   // permitted to have 'main' be marked with the 'target' optimization hint.
9906   if (NewFD->isMain()) {
9907     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
9908         MVType == MultiVersionKind::CPUDispatch ||
9909         MVType == MultiVersionKind::CPUSpecific) {
9910       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
9911       NewFD->setInvalidDecl();
9912       return true;
9913     }
9914     return false;
9915   }
9916 
9917   if (!OldDecl || !OldDecl->getAsFunction() ||
9918       OldDecl->getDeclContext()->getRedeclContext() !=
9919           NewFD->getDeclContext()->getRedeclContext()) {
9920     // If there's no previous declaration, AND this isn't attempting to cause
9921     // multiversioning, this isn't an error condition.
9922     if (MVType == MultiVersionKind::None)
9923       return false;
9924     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA, NewCPUDisp,
9925                                           NewCPUSpec);
9926   }
9927 
9928   FunctionDecl *OldFD = OldDecl->getAsFunction();
9929 
9930   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
9931     return false;
9932 
9933   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
9934     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
9935         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
9936     NewFD->setInvalidDecl();
9937     return true;
9938   }
9939 
9940   // Handle the target potentially causes multiversioning case.
9941   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
9942     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
9943                                             Redeclaration, OldDecl,
9944                                             MergeTypeWithPrevious, Previous);
9945 
9946   // At this point, we have a multiversion function decl (in OldFD) AND an
9947   // appropriate attribute in the current function decl.  Resolve that these are
9948   // still compatible with previous declarations.
9949   return CheckMultiVersionAdditionalDecl(
9950       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
9951       OldDecl, MergeTypeWithPrevious, Previous);
9952 }
9953 
9954 /// Perform semantic checking of a new function declaration.
9955 ///
9956 /// Performs semantic analysis of the new function declaration
9957 /// NewFD. This routine performs all semantic checking that does not
9958 /// require the actual declarator involved in the declaration, and is
9959 /// used both for the declaration of functions as they are parsed
9960 /// (called via ActOnDeclarator) and for the declaration of functions
9961 /// that have been instantiated via C++ template instantiation (called
9962 /// via InstantiateDecl).
9963 ///
9964 /// \param IsMemberSpecialization whether this new function declaration is
9965 /// a member specialization (that replaces any definition provided by the
9966 /// previous declaration).
9967 ///
9968 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9969 ///
9970 /// \returns true if the function declaration is a redeclaration.
9971 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9972                                     LookupResult &Previous,
9973                                     bool IsMemberSpecialization) {
9974   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9975          "Variably modified return types are not handled here");
9976 
9977   // Determine whether the type of this function should be merged with
9978   // a previous visible declaration. This never happens for functions in C++,
9979   // and always happens in C if the previous declaration was visible.
9980   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9981                                !Previous.isShadowed();
9982 
9983   bool Redeclaration = false;
9984   NamedDecl *OldDecl = nullptr;
9985   bool MayNeedOverloadableChecks = false;
9986 
9987   // Merge or overload the declaration with an existing declaration of
9988   // the same name, if appropriate.
9989   if (!Previous.empty()) {
9990     // Determine whether NewFD is an overload of PrevDecl or
9991     // a declaration that requires merging. If it's an overload,
9992     // there's no more work to do here; we'll just add the new
9993     // function to the scope.
9994     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
9995       NamedDecl *Candidate = Previous.getRepresentativeDecl();
9996       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9997         Redeclaration = true;
9998         OldDecl = Candidate;
9999       }
10000     } else {
10001       MayNeedOverloadableChecks = true;
10002       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10003                             /*NewIsUsingDecl*/ false)) {
10004       case Ovl_Match:
10005         Redeclaration = true;
10006         break;
10007 
10008       case Ovl_NonFunction:
10009         Redeclaration = true;
10010         break;
10011 
10012       case Ovl_Overload:
10013         Redeclaration = false;
10014         break;
10015       }
10016     }
10017   }
10018 
10019   // Check for a previous extern "C" declaration with this name.
10020   if (!Redeclaration &&
10021       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10022     if (!Previous.empty()) {
10023       // This is an extern "C" declaration with the same name as a previous
10024       // declaration, and thus redeclares that entity...
10025       Redeclaration = true;
10026       OldDecl = Previous.getFoundDecl();
10027       MergeTypeWithPrevious = false;
10028 
10029       // ... except in the presence of __attribute__((overloadable)).
10030       if (OldDecl->hasAttr<OverloadableAttr>() ||
10031           NewFD->hasAttr<OverloadableAttr>()) {
10032         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10033           MayNeedOverloadableChecks = true;
10034           Redeclaration = false;
10035           OldDecl = nullptr;
10036         }
10037       }
10038     }
10039   }
10040 
10041   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10042                                 MergeTypeWithPrevious, Previous))
10043     return Redeclaration;
10044 
10045   // C++11 [dcl.constexpr]p8:
10046   //   A constexpr specifier for a non-static member function that is not
10047   //   a constructor declares that member function to be const.
10048   //
10049   // This needs to be delayed until we know whether this is an out-of-line
10050   // definition of a static member function.
10051   //
10052   // This rule is not present in C++1y, so we produce a backwards
10053   // compatibility warning whenever it happens in C++11.
10054   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10055   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10056       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10057       !MD->getMethodQualifiers().hasConst()) {
10058     CXXMethodDecl *OldMD = nullptr;
10059     if (OldDecl)
10060       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10061     if (!OldMD || !OldMD->isStatic()) {
10062       const FunctionProtoType *FPT =
10063         MD->getType()->castAs<FunctionProtoType>();
10064       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10065       EPI.TypeQuals.addConst();
10066       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10067                                           FPT->getParamTypes(), EPI));
10068 
10069       // Warn that we did this, if we're not performing template instantiation.
10070       // In that case, we'll have warned already when the template was defined.
10071       if (!inTemplateInstantiation()) {
10072         SourceLocation AddConstLoc;
10073         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10074                 .IgnoreParens().getAs<FunctionTypeLoc>())
10075           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10076 
10077         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10078           << FixItHint::CreateInsertion(AddConstLoc, " const");
10079       }
10080     }
10081   }
10082 
10083   if (Redeclaration) {
10084     // NewFD and OldDecl represent declarations that need to be
10085     // merged.
10086     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10087       NewFD->setInvalidDecl();
10088       return Redeclaration;
10089     }
10090 
10091     Previous.clear();
10092     Previous.addDecl(OldDecl);
10093 
10094     if (FunctionTemplateDecl *OldTemplateDecl =
10095             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10096       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10097       FunctionTemplateDecl *NewTemplateDecl
10098         = NewFD->getDescribedFunctionTemplate();
10099       assert(NewTemplateDecl && "Template/non-template mismatch");
10100 
10101       // The call to MergeFunctionDecl above may have created some state in
10102       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10103       // can add it as a redeclaration.
10104       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10105 
10106       NewFD->setPreviousDeclaration(OldFD);
10107       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10108       if (NewFD->isCXXClassMember()) {
10109         NewFD->setAccess(OldTemplateDecl->getAccess());
10110         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10111       }
10112 
10113       // If this is an explicit specialization of a member that is a function
10114       // template, mark it as a member specialization.
10115       if (IsMemberSpecialization &&
10116           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10117         NewTemplateDecl->setMemberSpecialization();
10118         assert(OldTemplateDecl->isMemberSpecialization());
10119         // Explicit specializations of a member template do not inherit deleted
10120         // status from the parent member template that they are specializing.
10121         if (OldFD->isDeleted()) {
10122           // FIXME: This assert will not hold in the presence of modules.
10123           assert(OldFD->getCanonicalDecl() == OldFD);
10124           // FIXME: We need an update record for this AST mutation.
10125           OldFD->setDeletedAsWritten(false);
10126         }
10127       }
10128 
10129     } else {
10130       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10131         auto *OldFD = cast<FunctionDecl>(OldDecl);
10132         // This needs to happen first so that 'inline' propagates.
10133         NewFD->setPreviousDeclaration(OldFD);
10134         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10135         if (NewFD->isCXXClassMember())
10136           NewFD->setAccess(OldFD->getAccess());
10137       }
10138     }
10139   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10140              !NewFD->getAttr<OverloadableAttr>()) {
10141     assert((Previous.empty() ||
10142             llvm::any_of(Previous,
10143                          [](const NamedDecl *ND) {
10144                            return ND->hasAttr<OverloadableAttr>();
10145                          })) &&
10146            "Non-redecls shouldn't happen without overloadable present");
10147 
10148     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10149       const auto *FD = dyn_cast<FunctionDecl>(ND);
10150       return FD && !FD->hasAttr<OverloadableAttr>();
10151     });
10152 
10153     if (OtherUnmarkedIter != Previous.end()) {
10154       Diag(NewFD->getLocation(),
10155            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10156       Diag((*OtherUnmarkedIter)->getLocation(),
10157            diag::note_attribute_overloadable_prev_overload)
10158           << false;
10159 
10160       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10161     }
10162   }
10163 
10164   // Semantic checking for this function declaration (in isolation).
10165 
10166   if (getLangOpts().CPlusPlus) {
10167     // C++-specific checks.
10168     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10169       CheckConstructor(Constructor);
10170     } else if (CXXDestructorDecl *Destructor =
10171                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10172       CXXRecordDecl *Record = Destructor->getParent();
10173       QualType ClassType = Context.getTypeDeclType(Record);
10174 
10175       // FIXME: Shouldn't we be able to perform this check even when the class
10176       // type is dependent? Both gcc and edg can handle that.
10177       if (!ClassType->isDependentType()) {
10178         DeclarationName Name
10179           = Context.DeclarationNames.getCXXDestructorName(
10180                                         Context.getCanonicalType(ClassType));
10181         if (NewFD->getDeclName() != Name) {
10182           Diag(NewFD->getLocation(), diag::err_destructor_name);
10183           NewFD->setInvalidDecl();
10184           return Redeclaration;
10185         }
10186       }
10187     } else if (CXXConversionDecl *Conversion
10188                = dyn_cast<CXXConversionDecl>(NewFD)) {
10189       ActOnConversionDeclarator(Conversion);
10190     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10191       if (auto *TD = Guide->getDescribedFunctionTemplate())
10192         CheckDeductionGuideTemplate(TD);
10193 
10194       // A deduction guide is not on the list of entities that can be
10195       // explicitly specialized.
10196       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10197         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10198             << /*explicit specialization*/ 1;
10199     }
10200 
10201     // Find any virtual functions that this function overrides.
10202     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10203       if (!Method->isFunctionTemplateSpecialization() &&
10204           !Method->getDescribedFunctionTemplate() &&
10205           Method->isCanonicalDecl()) {
10206         if (AddOverriddenMethods(Method->getParent(), Method)) {
10207           // If the function was marked as "static", we have a problem.
10208           if (NewFD->getStorageClass() == SC_Static) {
10209             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10210           }
10211         }
10212       }
10213 
10214       if (Method->isStatic())
10215         checkThisInStaticMemberFunctionType(Method);
10216     }
10217 
10218     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10219     if (NewFD->isOverloadedOperator() &&
10220         CheckOverloadedOperatorDeclaration(NewFD)) {
10221       NewFD->setInvalidDecl();
10222       return Redeclaration;
10223     }
10224 
10225     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10226     if (NewFD->getLiteralIdentifier() &&
10227         CheckLiteralOperatorDeclaration(NewFD)) {
10228       NewFD->setInvalidDecl();
10229       return Redeclaration;
10230     }
10231 
10232     // In C++, check default arguments now that we have merged decls. Unless
10233     // the lexical context is the class, because in this case this is done
10234     // during delayed parsing anyway.
10235     if (!CurContext->isRecord())
10236       CheckCXXDefaultArguments(NewFD);
10237 
10238     // If this function declares a builtin function, check the type of this
10239     // declaration against the expected type for the builtin.
10240     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10241       ASTContext::GetBuiltinTypeError Error;
10242       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10243       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10244       // If the type of the builtin differs only in its exception
10245       // specification, that's OK.
10246       // FIXME: If the types do differ in this way, it would be better to
10247       // retain the 'noexcept' form of the type.
10248       if (!T.isNull() &&
10249           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10250                                                             NewFD->getType()))
10251         // The type of this function differs from the type of the builtin,
10252         // so forget about the builtin entirely.
10253         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10254     }
10255 
10256     // If this function is declared as being extern "C", then check to see if
10257     // the function returns a UDT (class, struct, or union type) that is not C
10258     // compatible, and if it does, warn the user.
10259     // But, issue any diagnostic on the first declaration only.
10260     if (Previous.empty() && NewFD->isExternC()) {
10261       QualType R = NewFD->getReturnType();
10262       if (R->isIncompleteType() && !R->isVoidType())
10263         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10264             << NewFD << R;
10265       else if (!R.isPODType(Context) && !R->isVoidType() &&
10266                !R->isObjCObjectPointerType())
10267         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10268     }
10269 
10270     // C++1z [dcl.fct]p6:
10271     //   [...] whether the function has a non-throwing exception-specification
10272     //   [is] part of the function type
10273     //
10274     // This results in an ABI break between C++14 and C++17 for functions whose
10275     // declared type includes an exception-specification in a parameter or
10276     // return type. (Exception specifications on the function itself are OK in
10277     // most cases, and exception specifications are not permitted in most other
10278     // contexts where they could make it into a mangling.)
10279     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10280       auto HasNoexcept = [&](QualType T) -> bool {
10281         // Strip off declarator chunks that could be between us and a function
10282         // type. We don't need to look far, exception specifications are very
10283         // restricted prior to C++17.
10284         if (auto *RT = T->getAs<ReferenceType>())
10285           T = RT->getPointeeType();
10286         else if (T->isAnyPointerType())
10287           T = T->getPointeeType();
10288         else if (auto *MPT = T->getAs<MemberPointerType>())
10289           T = MPT->getPointeeType();
10290         if (auto *FPT = T->getAs<FunctionProtoType>())
10291           if (FPT->isNothrow())
10292             return true;
10293         return false;
10294       };
10295 
10296       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10297       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10298       for (QualType T : FPT->param_types())
10299         AnyNoexcept |= HasNoexcept(T);
10300       if (AnyNoexcept)
10301         Diag(NewFD->getLocation(),
10302              diag::warn_cxx17_compat_exception_spec_in_signature)
10303             << NewFD;
10304     }
10305 
10306     if (!Redeclaration && LangOpts.CUDA)
10307       checkCUDATargetOverload(NewFD, Previous);
10308   }
10309   return Redeclaration;
10310 }
10311 
10312 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10313   // C++11 [basic.start.main]p3:
10314   //   A program that [...] declares main to be inline, static or
10315   //   constexpr is ill-formed.
10316   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10317   //   appear in a declaration of main.
10318   // static main is not an error under C99, but we should warn about it.
10319   // We accept _Noreturn main as an extension.
10320   if (FD->getStorageClass() == SC_Static)
10321     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10322          ? diag::err_static_main : diag::warn_static_main)
10323       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10324   if (FD->isInlineSpecified())
10325     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10326       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10327   if (DS.isNoreturnSpecified()) {
10328     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10329     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10330     Diag(NoreturnLoc, diag::ext_noreturn_main);
10331     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10332       << FixItHint::CreateRemoval(NoreturnRange);
10333   }
10334   if (FD->isConstexpr()) {
10335     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10336       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10337     FD->setConstexpr(false);
10338   }
10339 
10340   if (getLangOpts().OpenCL) {
10341     Diag(FD->getLocation(), diag::err_opencl_no_main)
10342         << FD->hasAttr<OpenCLKernelAttr>();
10343     FD->setInvalidDecl();
10344     return;
10345   }
10346 
10347   QualType T = FD->getType();
10348   assert(T->isFunctionType() && "function decl is not of function type");
10349   const FunctionType* FT = T->castAs<FunctionType>();
10350 
10351   // Set default calling convention for main()
10352   if (FT->getCallConv() != CC_C) {
10353     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10354     FD->setType(QualType(FT, 0));
10355     T = Context.getCanonicalType(FD->getType());
10356   }
10357 
10358   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10359     // In C with GNU extensions we allow main() to have non-integer return
10360     // type, but we should warn about the extension, and we disable the
10361     // implicit-return-zero rule.
10362 
10363     // GCC in C mode accepts qualified 'int'.
10364     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10365       FD->setHasImplicitReturnZero(true);
10366     else {
10367       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10368       SourceRange RTRange = FD->getReturnTypeSourceRange();
10369       if (RTRange.isValid())
10370         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10371             << FixItHint::CreateReplacement(RTRange, "int");
10372     }
10373   } else {
10374     // In C and C++, main magically returns 0 if you fall off the end;
10375     // set the flag which tells us that.
10376     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10377 
10378     // All the standards say that main() should return 'int'.
10379     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10380       FD->setHasImplicitReturnZero(true);
10381     else {
10382       // Otherwise, this is just a flat-out error.
10383       SourceRange RTRange = FD->getReturnTypeSourceRange();
10384       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10385           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10386                                 : FixItHint());
10387       FD->setInvalidDecl(true);
10388     }
10389   }
10390 
10391   // Treat protoless main() as nullary.
10392   if (isa<FunctionNoProtoType>(FT)) return;
10393 
10394   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10395   unsigned nparams = FTP->getNumParams();
10396   assert(FD->getNumParams() == nparams);
10397 
10398   bool HasExtraParameters = (nparams > 3);
10399 
10400   if (FTP->isVariadic()) {
10401     Diag(FD->getLocation(), diag::ext_variadic_main);
10402     // FIXME: if we had information about the location of the ellipsis, we
10403     // could add a FixIt hint to remove it as a parameter.
10404   }
10405 
10406   // Darwin passes an undocumented fourth argument of type char**.  If
10407   // other platforms start sprouting these, the logic below will start
10408   // getting shifty.
10409   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10410     HasExtraParameters = false;
10411 
10412   if (HasExtraParameters) {
10413     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10414     FD->setInvalidDecl(true);
10415     nparams = 3;
10416   }
10417 
10418   // FIXME: a lot of the following diagnostics would be improved
10419   // if we had some location information about types.
10420 
10421   QualType CharPP =
10422     Context.getPointerType(Context.getPointerType(Context.CharTy));
10423   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10424 
10425   for (unsigned i = 0; i < nparams; ++i) {
10426     QualType AT = FTP->getParamType(i);
10427 
10428     bool mismatch = true;
10429 
10430     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10431       mismatch = false;
10432     else if (Expected[i] == CharPP) {
10433       // As an extension, the following forms are okay:
10434       //   char const **
10435       //   char const * const *
10436       //   char * const *
10437 
10438       QualifierCollector qs;
10439       const PointerType* PT;
10440       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10441           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10442           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10443                               Context.CharTy)) {
10444         qs.removeConst();
10445         mismatch = !qs.empty();
10446       }
10447     }
10448 
10449     if (mismatch) {
10450       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10451       // TODO: suggest replacing given type with expected type
10452       FD->setInvalidDecl(true);
10453     }
10454   }
10455 
10456   if (nparams == 1 && !FD->isInvalidDecl()) {
10457     Diag(FD->getLocation(), diag::warn_main_one_arg);
10458   }
10459 
10460   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10461     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10462     FD->setInvalidDecl();
10463   }
10464 }
10465 
10466 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10467   QualType T = FD->getType();
10468   assert(T->isFunctionType() && "function decl is not of function type");
10469   const FunctionType *FT = T->castAs<FunctionType>();
10470 
10471   // Set an implicit return of 'zero' if the function can return some integral,
10472   // enumeration, pointer or nullptr type.
10473   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10474       FT->getReturnType()->isAnyPointerType() ||
10475       FT->getReturnType()->isNullPtrType())
10476     // DllMain is exempt because a return value of zero means it failed.
10477     if (FD->getName() != "DllMain")
10478       FD->setHasImplicitReturnZero(true);
10479 
10480   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10481     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10482     FD->setInvalidDecl();
10483   }
10484 }
10485 
10486 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10487   // FIXME: Need strict checking.  In C89, we need to check for
10488   // any assignment, increment, decrement, function-calls, or
10489   // commas outside of a sizeof.  In C99, it's the same list,
10490   // except that the aforementioned are allowed in unevaluated
10491   // expressions.  Everything else falls under the
10492   // "may accept other forms of constant expressions" exception.
10493   // (We never end up here for C++, so the constant expression
10494   // rules there don't matter.)
10495   const Expr *Culprit;
10496   if (Init->isConstantInitializer(Context, false, &Culprit))
10497     return false;
10498   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10499     << Culprit->getSourceRange();
10500   return true;
10501 }
10502 
10503 namespace {
10504   // Visits an initialization expression to see if OrigDecl is evaluated in
10505   // its own initialization and throws a warning if it does.
10506   class SelfReferenceChecker
10507       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10508     Sema &S;
10509     Decl *OrigDecl;
10510     bool isRecordType;
10511     bool isPODType;
10512     bool isReferenceType;
10513 
10514     bool isInitList;
10515     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10516 
10517   public:
10518     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10519 
10520     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10521                                                     S(S), OrigDecl(OrigDecl) {
10522       isPODType = false;
10523       isRecordType = false;
10524       isReferenceType = false;
10525       isInitList = false;
10526       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10527         isPODType = VD->getType().isPODType(S.Context);
10528         isRecordType = VD->getType()->isRecordType();
10529         isReferenceType = VD->getType()->isReferenceType();
10530       }
10531     }
10532 
10533     // For most expressions, just call the visitor.  For initializer lists,
10534     // track the index of the field being initialized since fields are
10535     // initialized in order allowing use of previously initialized fields.
10536     void CheckExpr(Expr *E) {
10537       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10538       if (!InitList) {
10539         Visit(E);
10540         return;
10541       }
10542 
10543       // Track and increment the index here.
10544       isInitList = true;
10545       InitFieldIndex.push_back(0);
10546       for (auto Child : InitList->children()) {
10547         CheckExpr(cast<Expr>(Child));
10548         ++InitFieldIndex.back();
10549       }
10550       InitFieldIndex.pop_back();
10551     }
10552 
10553     // Returns true if MemberExpr is checked and no further checking is needed.
10554     // Returns false if additional checking is required.
10555     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10556       llvm::SmallVector<FieldDecl*, 4> Fields;
10557       Expr *Base = E;
10558       bool ReferenceField = false;
10559 
10560       // Get the field members used.
10561       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10562         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10563         if (!FD)
10564           return false;
10565         Fields.push_back(FD);
10566         if (FD->getType()->isReferenceType())
10567           ReferenceField = true;
10568         Base = ME->getBase()->IgnoreParenImpCasts();
10569       }
10570 
10571       // Keep checking only if the base Decl is the same.
10572       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10573       if (!DRE || DRE->getDecl() != OrigDecl)
10574         return false;
10575 
10576       // A reference field can be bound to an unininitialized field.
10577       if (CheckReference && !ReferenceField)
10578         return true;
10579 
10580       // Convert FieldDecls to their index number.
10581       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10582       for (const FieldDecl *I : llvm::reverse(Fields))
10583         UsedFieldIndex.push_back(I->getFieldIndex());
10584 
10585       // See if a warning is needed by checking the first difference in index
10586       // numbers.  If field being used has index less than the field being
10587       // initialized, then the use is safe.
10588       for (auto UsedIter = UsedFieldIndex.begin(),
10589                 UsedEnd = UsedFieldIndex.end(),
10590                 OrigIter = InitFieldIndex.begin(),
10591                 OrigEnd = InitFieldIndex.end();
10592            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10593         if (*UsedIter < *OrigIter)
10594           return true;
10595         if (*UsedIter > *OrigIter)
10596           break;
10597       }
10598 
10599       // TODO: Add a different warning which will print the field names.
10600       HandleDeclRefExpr(DRE);
10601       return true;
10602     }
10603 
10604     // For most expressions, the cast is directly above the DeclRefExpr.
10605     // For conditional operators, the cast can be outside the conditional
10606     // operator if both expressions are DeclRefExpr's.
10607     void HandleValue(Expr *E) {
10608       E = E->IgnoreParens();
10609       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10610         HandleDeclRefExpr(DRE);
10611         return;
10612       }
10613 
10614       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10615         Visit(CO->getCond());
10616         HandleValue(CO->getTrueExpr());
10617         HandleValue(CO->getFalseExpr());
10618         return;
10619       }
10620 
10621       if (BinaryConditionalOperator *BCO =
10622               dyn_cast<BinaryConditionalOperator>(E)) {
10623         Visit(BCO->getCond());
10624         HandleValue(BCO->getFalseExpr());
10625         return;
10626       }
10627 
10628       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10629         HandleValue(OVE->getSourceExpr());
10630         return;
10631       }
10632 
10633       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10634         if (BO->getOpcode() == BO_Comma) {
10635           Visit(BO->getLHS());
10636           HandleValue(BO->getRHS());
10637           return;
10638         }
10639       }
10640 
10641       if (isa<MemberExpr>(E)) {
10642         if (isInitList) {
10643           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10644                                       false /*CheckReference*/))
10645             return;
10646         }
10647 
10648         Expr *Base = E->IgnoreParenImpCasts();
10649         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10650           // Check for static member variables and don't warn on them.
10651           if (!isa<FieldDecl>(ME->getMemberDecl()))
10652             return;
10653           Base = ME->getBase()->IgnoreParenImpCasts();
10654         }
10655         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10656           HandleDeclRefExpr(DRE);
10657         return;
10658       }
10659 
10660       Visit(E);
10661     }
10662 
10663     // Reference types not handled in HandleValue are handled here since all
10664     // uses of references are bad, not just r-value uses.
10665     void VisitDeclRefExpr(DeclRefExpr *E) {
10666       if (isReferenceType)
10667         HandleDeclRefExpr(E);
10668     }
10669 
10670     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10671       if (E->getCastKind() == CK_LValueToRValue) {
10672         HandleValue(E->getSubExpr());
10673         return;
10674       }
10675 
10676       Inherited::VisitImplicitCastExpr(E);
10677     }
10678 
10679     void VisitMemberExpr(MemberExpr *E) {
10680       if (isInitList) {
10681         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
10682           return;
10683       }
10684 
10685       // Don't warn on arrays since they can be treated as pointers.
10686       if (E->getType()->canDecayToPointerType()) return;
10687 
10688       // Warn when a non-static method call is followed by non-static member
10689       // field accesses, which is followed by a DeclRefExpr.
10690       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10691       bool Warn = (MD && !MD->isStatic());
10692       Expr *Base = E->getBase()->IgnoreParenImpCasts();
10693       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10694         if (!isa<FieldDecl>(ME->getMemberDecl()))
10695           Warn = false;
10696         Base = ME->getBase()->IgnoreParenImpCasts();
10697       }
10698 
10699       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10700         if (Warn)
10701           HandleDeclRefExpr(DRE);
10702         return;
10703       }
10704 
10705       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10706       // Visit that expression.
10707       Visit(Base);
10708     }
10709 
10710     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10711       Expr *Callee = E->getCallee();
10712 
10713       if (isa<UnresolvedLookupExpr>(Callee))
10714         return Inherited::VisitCXXOperatorCallExpr(E);
10715 
10716       Visit(Callee);
10717       for (auto Arg: E->arguments())
10718         HandleValue(Arg->IgnoreParenImpCasts());
10719     }
10720 
10721     void VisitUnaryOperator(UnaryOperator *E) {
10722       // For POD record types, addresses of its own members are well-defined.
10723       if (E->getOpcode() == UO_AddrOf && isRecordType &&
10724           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
10725         if (!isPODType)
10726           HandleValue(E->getSubExpr());
10727         return;
10728       }
10729 
10730       if (E->isIncrementDecrementOp()) {
10731         HandleValue(E->getSubExpr());
10732         return;
10733       }
10734 
10735       Inherited::VisitUnaryOperator(E);
10736     }
10737 
10738     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
10739 
10740     void VisitCXXConstructExpr(CXXConstructExpr *E) {
10741       if (E->getConstructor()->isCopyConstructor()) {
10742         Expr *ArgExpr = E->getArg(0);
10743         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
10744           if (ILE->getNumInits() == 1)
10745             ArgExpr = ILE->getInit(0);
10746         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
10747           if (ICE->getCastKind() == CK_NoOp)
10748             ArgExpr = ICE->getSubExpr();
10749         HandleValue(ArgExpr);
10750         return;
10751       }
10752       Inherited::VisitCXXConstructExpr(E);
10753     }
10754 
10755     void VisitCallExpr(CallExpr *E) {
10756       // Treat std::move as a use.
10757       if (E->isCallToStdMove()) {
10758         HandleValue(E->getArg(0));
10759         return;
10760       }
10761 
10762       Inherited::VisitCallExpr(E);
10763     }
10764 
10765     void VisitBinaryOperator(BinaryOperator *E) {
10766       if (E->isCompoundAssignmentOp()) {
10767         HandleValue(E->getLHS());
10768         Visit(E->getRHS());
10769         return;
10770       }
10771 
10772       Inherited::VisitBinaryOperator(E);
10773     }
10774 
10775     // A custom visitor for BinaryConditionalOperator is needed because the
10776     // regular visitor would check the condition and true expression separately
10777     // but both point to the same place giving duplicate diagnostics.
10778     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10779       Visit(E->getCond());
10780       Visit(E->getFalseExpr());
10781     }
10782 
10783     void HandleDeclRefExpr(DeclRefExpr *DRE) {
10784       Decl* ReferenceDecl = DRE->getDecl();
10785       if (OrigDecl != ReferenceDecl) return;
10786       unsigned diag;
10787       if (isReferenceType) {
10788         diag = diag::warn_uninit_self_reference_in_reference_init;
10789       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10790         diag = diag::warn_static_self_reference_in_init;
10791       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10792                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10793                  DRE->getDecl()->getType()->isRecordType()) {
10794         diag = diag::warn_uninit_self_reference_in_init;
10795       } else {
10796         // Local variables will be handled by the CFG analysis.
10797         return;
10798       }
10799 
10800       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
10801                             S.PDiag(diag)
10802                                 << DRE->getDecl() << OrigDecl->getLocation()
10803                                 << DRE->getSourceRange());
10804     }
10805   };
10806 
10807   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10808   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10809                                  bool DirectInit) {
10810     // Parameters arguments are occassionially constructed with itself,
10811     // for instance, in recursive functions.  Skip them.
10812     if (isa<ParmVarDecl>(OrigDecl))
10813       return;
10814 
10815     E = E->IgnoreParens();
10816 
10817     // Skip checking T a = a where T is not a record or reference type.
10818     // Doing so is a way to silence uninitialized warnings.
10819     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10820       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10821         if (ICE->getCastKind() == CK_LValueToRValue)
10822           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10823             if (DRE->getDecl() == OrigDecl)
10824               return;
10825 
10826     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10827   }
10828 } // end anonymous namespace
10829 
10830 namespace {
10831   // Simple wrapper to add the name of a variable or (if no variable is
10832   // available) a DeclarationName into a diagnostic.
10833   struct VarDeclOrName {
10834     VarDecl *VDecl;
10835     DeclarationName Name;
10836 
10837     friend const Sema::SemaDiagnosticBuilder &
10838     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10839       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10840     }
10841   };
10842 } // end anonymous namespace
10843 
10844 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10845                                             DeclarationName Name, QualType Type,
10846                                             TypeSourceInfo *TSI,
10847                                             SourceRange Range, bool DirectInit,
10848                                             Expr *&Init) {
10849   bool IsInitCapture = !VDecl;
10850   assert((!VDecl || !VDecl->isInitCapture()) &&
10851          "init captures are expected to be deduced prior to initialization");
10852 
10853   VarDeclOrName VN{VDecl, Name};
10854 
10855   DeducedType *Deduced = Type->getContainedDeducedType();
10856   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10857 
10858   // C++11 [dcl.spec.auto]p3
10859   if (!Init) {
10860     assert(VDecl && "no init for init capture deduction?");
10861 
10862     // Except for class argument deduction, and then for an initializing
10863     // declaration only, i.e. no static at class scope or extern.
10864     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
10865         VDecl->hasExternalStorage() ||
10866         VDecl->isStaticDataMember()) {
10867       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10868         << VDecl->getDeclName() << Type;
10869       return QualType();
10870     }
10871   }
10872 
10873   ArrayRef<Expr*> DeduceInits;
10874   if (Init)
10875     DeduceInits = Init;
10876 
10877   if (DirectInit) {
10878     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10879       DeduceInits = PL->exprs();
10880   }
10881 
10882   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10883     assert(VDecl && "non-auto type for init capture deduction?");
10884     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10885     InitializationKind Kind = InitializationKind::CreateForInit(
10886         VDecl->getLocation(), DirectInit, Init);
10887     // FIXME: Initialization should not be taking a mutable list of inits.
10888     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10889     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10890                                                        InitsCopy);
10891   }
10892 
10893   if (DirectInit) {
10894     if (auto *IL = dyn_cast<InitListExpr>(Init))
10895       DeduceInits = IL->inits();
10896   }
10897 
10898   // Deduction only works if we have exactly one source expression.
10899   if (DeduceInits.empty()) {
10900     // It isn't possible to write this directly, but it is possible to
10901     // end up in this situation with "auto x(some_pack...);"
10902     Diag(Init->getBeginLoc(), IsInitCapture
10903                                   ? diag::err_init_capture_no_expression
10904                                   : diag::err_auto_var_init_no_expression)
10905         << VN << Type << Range;
10906     return QualType();
10907   }
10908 
10909   if (DeduceInits.size() > 1) {
10910     Diag(DeduceInits[1]->getBeginLoc(),
10911          IsInitCapture ? diag::err_init_capture_multiple_expressions
10912                        : diag::err_auto_var_init_multiple_expressions)
10913         << VN << Type << Range;
10914     return QualType();
10915   }
10916 
10917   Expr *DeduceInit = DeduceInits[0];
10918   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10919     Diag(Init->getBeginLoc(), IsInitCapture
10920                                   ? diag::err_init_capture_paren_braces
10921                                   : diag::err_auto_var_init_paren_braces)
10922         << isa<InitListExpr>(Init) << VN << Type << Range;
10923     return QualType();
10924   }
10925 
10926   // Expressions default to 'id' when we're in a debugger.
10927   bool DefaultedAnyToId = false;
10928   if (getLangOpts().DebuggerCastResultToId &&
10929       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10930     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10931     if (Result.isInvalid()) {
10932       return QualType();
10933     }
10934     Init = Result.get();
10935     DefaultedAnyToId = true;
10936   }
10937 
10938   // C++ [dcl.decomp]p1:
10939   //   If the assignment-expression [...] has array type A and no ref-qualifier
10940   //   is present, e has type cv A
10941   if (VDecl && isa<DecompositionDecl>(VDecl) &&
10942       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10943       DeduceInit->getType()->isConstantArrayType())
10944     return Context.getQualifiedType(DeduceInit->getType(),
10945                                     Type.getQualifiers());
10946 
10947   QualType DeducedType;
10948   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
10949     if (!IsInitCapture)
10950       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
10951     else if (isa<InitListExpr>(Init))
10952       Diag(Range.getBegin(),
10953            diag::err_init_capture_deduction_failure_from_init_list)
10954           << VN
10955           << (DeduceInit->getType().isNull() ? TSI->getType()
10956                                              : DeduceInit->getType())
10957           << DeduceInit->getSourceRange();
10958     else
10959       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10960           << VN << TSI->getType()
10961           << (DeduceInit->getType().isNull() ? TSI->getType()
10962                                              : DeduceInit->getType())
10963           << DeduceInit->getSourceRange();
10964   } else
10965     Init = DeduceInit;
10966 
10967   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10968   // 'id' instead of a specific object type prevents most of our usual
10969   // checks.
10970   // We only want to warn outside of template instantiations, though:
10971   // inside a template, the 'id' could have come from a parameter.
10972   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10973       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10974     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10975     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10976   }
10977 
10978   return DeducedType;
10979 }
10980 
10981 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
10982                                          Expr *&Init) {
10983   QualType DeducedType = deduceVarTypeFromInitializer(
10984       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10985       VDecl->getSourceRange(), DirectInit, Init);
10986   if (DeducedType.isNull()) {
10987     VDecl->setInvalidDecl();
10988     return true;
10989   }
10990 
10991   VDecl->setType(DeducedType);
10992   assert(VDecl->isLinkageValid());
10993 
10994   // In ARC, infer lifetime.
10995   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10996     VDecl->setInvalidDecl();
10997 
10998   // If this is a redeclaration, check that the type we just deduced matches
10999   // the previously declared type.
11000   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11001     // We never need to merge the type, because we cannot form an incomplete
11002     // array of auto, nor deduce such a type.
11003     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11004   }
11005 
11006   // Check the deduced type is valid for a variable declaration.
11007   CheckVariableDeclarationType(VDecl);
11008   return VDecl->isInvalidDecl();
11009 }
11010 
11011 /// AddInitializerToDecl - Adds the initializer Init to the
11012 /// declaration dcl. If DirectInit is true, this is C++ direct
11013 /// initialization rather than copy initialization.
11014 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11015   // If there is no declaration, there was an error parsing it.  Just ignore
11016   // the initializer.
11017   if (!RealDecl || RealDecl->isInvalidDecl()) {
11018     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11019     return;
11020   }
11021 
11022   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11023     // Pure-specifiers are handled in ActOnPureSpecifier.
11024     Diag(Method->getLocation(), diag::err_member_function_initialization)
11025       << Method->getDeclName() << Init->getSourceRange();
11026     Method->setInvalidDecl();
11027     return;
11028   }
11029 
11030   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11031   if (!VDecl) {
11032     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11033     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11034     RealDecl->setInvalidDecl();
11035     return;
11036   }
11037 
11038   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11039   if (VDecl->getType()->isUndeducedType()) {
11040     // Attempt typo correction early so that the type of the init expression can
11041     // be deduced based on the chosen correction if the original init contains a
11042     // TypoExpr.
11043     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11044     if (!Res.isUsable()) {
11045       RealDecl->setInvalidDecl();
11046       return;
11047     }
11048     Init = Res.get();
11049 
11050     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11051       return;
11052   }
11053 
11054   // dllimport cannot be used on variable definitions.
11055   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11056     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11057     VDecl->setInvalidDecl();
11058     return;
11059   }
11060 
11061   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11062     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11063     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11064     VDecl->setInvalidDecl();
11065     return;
11066   }
11067 
11068   if (!VDecl->getType()->isDependentType()) {
11069     // A definition must end up with a complete type, which means it must be
11070     // complete with the restriction that an array type might be completed by
11071     // the initializer; note that later code assumes this restriction.
11072     QualType BaseDeclType = VDecl->getType();
11073     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11074       BaseDeclType = Array->getElementType();
11075     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11076                             diag::err_typecheck_decl_incomplete_type)) {
11077       RealDecl->setInvalidDecl();
11078       return;
11079     }
11080 
11081     // The variable can not have an abstract class type.
11082     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11083                                diag::err_abstract_type_in_decl,
11084                                AbstractVariableType))
11085       VDecl->setInvalidDecl();
11086   }
11087 
11088   // If adding the initializer will turn this declaration into a definition,
11089   // and we already have a definition for this variable, diagnose or otherwise
11090   // handle the situation.
11091   VarDecl *Def;
11092   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11093       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11094       !VDecl->isThisDeclarationADemotedDefinition() &&
11095       checkVarDeclRedefinition(Def, VDecl))
11096     return;
11097 
11098   if (getLangOpts().CPlusPlus) {
11099     // C++ [class.static.data]p4
11100     //   If a static data member is of const integral or const
11101     //   enumeration type, its declaration in the class definition can
11102     //   specify a constant-initializer which shall be an integral
11103     //   constant expression (5.19). In that case, the member can appear
11104     //   in integral constant expressions. The member shall still be
11105     //   defined in a namespace scope if it is used in the program and the
11106     //   namespace scope definition shall not contain an initializer.
11107     //
11108     // We already performed a redefinition check above, but for static
11109     // data members we also need to check whether there was an in-class
11110     // declaration with an initializer.
11111     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11112       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11113           << VDecl->getDeclName();
11114       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11115            diag::note_previous_initializer)
11116           << 0;
11117       return;
11118     }
11119 
11120     if (VDecl->hasLocalStorage())
11121       setFunctionHasBranchProtectedScope();
11122 
11123     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11124       VDecl->setInvalidDecl();
11125       return;
11126     }
11127   }
11128 
11129   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11130   // a kernel function cannot be initialized."
11131   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11132     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11133     VDecl->setInvalidDecl();
11134     return;
11135   }
11136 
11137   // Get the decls type and save a reference for later, since
11138   // CheckInitializerTypes may change it.
11139   QualType DclT = VDecl->getType(), SavT = DclT;
11140 
11141   // Expressions default to 'id' when we're in a debugger
11142   // and we are assigning it to a variable of Objective-C pointer type.
11143   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11144       Init->getType() == Context.UnknownAnyTy) {
11145     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11146     if (Result.isInvalid()) {
11147       VDecl->setInvalidDecl();
11148       return;
11149     }
11150     Init = Result.get();
11151   }
11152 
11153   // Perform the initialization.
11154   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11155   if (!VDecl->isInvalidDecl()) {
11156     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11157     InitializationKind Kind = InitializationKind::CreateForInit(
11158         VDecl->getLocation(), DirectInit, Init);
11159 
11160     MultiExprArg Args = Init;
11161     if (CXXDirectInit)
11162       Args = MultiExprArg(CXXDirectInit->getExprs(),
11163                           CXXDirectInit->getNumExprs());
11164 
11165     // Try to correct any TypoExprs in the initialization arguments.
11166     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11167       ExprResult Res = CorrectDelayedTyposInExpr(
11168           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11169             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11170             return Init.Failed() ? ExprError() : E;
11171           });
11172       if (Res.isInvalid()) {
11173         VDecl->setInvalidDecl();
11174       } else if (Res.get() != Args[Idx]) {
11175         Args[Idx] = Res.get();
11176       }
11177     }
11178     if (VDecl->isInvalidDecl())
11179       return;
11180 
11181     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11182                                    /*TopLevelOfInitList=*/false,
11183                                    /*TreatUnavailableAsInvalid=*/false);
11184     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11185     if (Result.isInvalid()) {
11186       VDecl->setInvalidDecl();
11187       return;
11188     }
11189 
11190     Init = Result.getAs<Expr>();
11191   }
11192 
11193   // Check for self-references within variable initializers.
11194   // Variables declared within a function/method body (except for references)
11195   // are handled by a dataflow analysis.
11196   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11197       VDecl->getType()->isReferenceType()) {
11198     CheckSelfReference(*this, RealDecl, Init, DirectInit);
11199   }
11200 
11201   // If the type changed, it means we had an incomplete type that was
11202   // completed by the initializer. For example:
11203   //   int ary[] = { 1, 3, 5 };
11204   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11205   if (!VDecl->isInvalidDecl() && (DclT != SavT))
11206     VDecl->setType(DclT);
11207 
11208   if (!VDecl->isInvalidDecl()) {
11209     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11210 
11211     if (VDecl->hasAttr<BlocksAttr>())
11212       checkRetainCycles(VDecl, Init);
11213 
11214     // It is safe to assign a weak reference into a strong variable.
11215     // Although this code can still have problems:
11216     //   id x = self.weakProp;
11217     //   id y = self.weakProp;
11218     // we do not warn to warn spuriously when 'x' and 'y' are on separate
11219     // paths through the function. This should be revisited if
11220     // -Wrepeated-use-of-weak is made flow-sensitive.
11221     if (FunctionScopeInfo *FSI = getCurFunction())
11222       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11223            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11224           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11225                            Init->getBeginLoc()))
11226         FSI->markSafeWeakUse(Init);
11227   }
11228 
11229   // The initialization is usually a full-expression.
11230   //
11231   // FIXME: If this is a braced initialization of an aggregate, it is not
11232   // an expression, and each individual field initializer is a separate
11233   // full-expression. For instance, in:
11234   //
11235   //   struct Temp { ~Temp(); };
11236   //   struct S { S(Temp); };
11237   //   struct T { S a, b; } t = { Temp(), Temp() }
11238   //
11239   // we should destroy the first Temp before constructing the second.
11240   ExprResult Result =
11241       ActOnFinishFullExpr(Init, VDecl->getLocation(),
11242                           /*DiscardedValue*/ false, VDecl->isConstexpr());
11243   if (Result.isInvalid()) {
11244     VDecl->setInvalidDecl();
11245     return;
11246   }
11247   Init = Result.get();
11248 
11249   // Attach the initializer to the decl.
11250   VDecl->setInit(Init);
11251 
11252   if (VDecl->isLocalVarDecl()) {
11253     // Don't check the initializer if the declaration is malformed.
11254     if (VDecl->isInvalidDecl()) {
11255       // do nothing
11256 
11257     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11258     // This is true even in OpenCL C++.
11259     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11260       CheckForConstantInitializer(Init, DclT);
11261 
11262     // Otherwise, C++ does not restrict the initializer.
11263     } else if (getLangOpts().CPlusPlus) {
11264       // do nothing
11265 
11266     // C99 6.7.8p4: All the expressions in an initializer for an object that has
11267     // static storage duration shall be constant expressions or string literals.
11268     } else if (VDecl->getStorageClass() == SC_Static) {
11269       CheckForConstantInitializer(Init, DclT);
11270 
11271     // C89 is stricter than C99 for aggregate initializers.
11272     // C89 6.5.7p3: All the expressions [...] in an initializer list
11273     // for an object that has aggregate or union type shall be
11274     // constant expressions.
11275     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11276                isa<InitListExpr>(Init)) {
11277       const Expr *Culprit;
11278       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11279         Diag(Culprit->getExprLoc(),
11280              diag::ext_aggregate_init_not_constant)
11281           << Culprit->getSourceRange();
11282       }
11283     }
11284 
11285     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
11286       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
11287         if (VDecl->hasLocalStorage())
11288           BE->getBlockDecl()->setCanAvoidCopyToHeap();
11289   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11290              VDecl->getLexicalDeclContext()->isRecord()) {
11291     // This is an in-class initialization for a static data member, e.g.,
11292     //
11293     // struct S {
11294     //   static const int value = 17;
11295     // };
11296 
11297     // C++ [class.mem]p4:
11298     //   A member-declarator can contain a constant-initializer only
11299     //   if it declares a static member (9.4) of const integral or
11300     //   const enumeration type, see 9.4.2.
11301     //
11302     // C++11 [class.static.data]p3:
11303     //   If a non-volatile non-inline const static data member is of integral
11304     //   or enumeration type, its declaration in the class definition can
11305     //   specify a brace-or-equal-initializer in which every initializer-clause
11306     //   that is an assignment-expression is a constant expression. A static
11307     //   data member of literal type can be declared in the class definition
11308     //   with the constexpr specifier; if so, its declaration shall specify a
11309     //   brace-or-equal-initializer in which every initializer-clause that is
11310     //   an assignment-expression is a constant expression.
11311 
11312     // Do nothing on dependent types.
11313     if (DclT->isDependentType()) {
11314 
11315     // Allow any 'static constexpr' members, whether or not they are of literal
11316     // type. We separately check that every constexpr variable is of literal
11317     // type.
11318     } else if (VDecl->isConstexpr()) {
11319 
11320     // Require constness.
11321     } else if (!DclT.isConstQualified()) {
11322       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11323         << Init->getSourceRange();
11324       VDecl->setInvalidDecl();
11325 
11326     // We allow integer constant expressions in all cases.
11327     } else if (DclT->isIntegralOrEnumerationType()) {
11328       // Check whether the expression is a constant expression.
11329       SourceLocation Loc;
11330       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11331         // In C++11, a non-constexpr const static data member with an
11332         // in-class initializer cannot be volatile.
11333         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11334       else if (Init->isValueDependent())
11335         ; // Nothing to check.
11336       else if (Init->isIntegerConstantExpr(Context, &Loc))
11337         ; // Ok, it's an ICE!
11338       else if (Init->getType()->isScopedEnumeralType() &&
11339                Init->isCXX11ConstantExpr(Context))
11340         ; // Ok, it is a scoped-enum constant expression.
11341       else if (Init->isEvaluatable(Context)) {
11342         // If we can constant fold the initializer through heroics, accept it,
11343         // but report this as a use of an extension for -pedantic.
11344         Diag(Loc, diag::ext_in_class_initializer_non_constant)
11345           << Init->getSourceRange();
11346       } else {
11347         // Otherwise, this is some crazy unknown case.  Report the issue at the
11348         // location provided by the isIntegerConstantExpr failed check.
11349         Diag(Loc, diag::err_in_class_initializer_non_constant)
11350           << Init->getSourceRange();
11351         VDecl->setInvalidDecl();
11352       }
11353 
11354     // We allow foldable floating-point constants as an extension.
11355     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
11356       // In C++98, this is a GNU extension. In C++11, it is not, but we support
11357       // it anyway and provide a fixit to add the 'constexpr'.
11358       if (getLangOpts().CPlusPlus11) {
11359         Diag(VDecl->getLocation(),
11360              diag::ext_in_class_initializer_float_type_cxx11)
11361             << DclT << Init->getSourceRange();
11362         Diag(VDecl->getBeginLoc(),
11363              diag::note_in_class_initializer_float_type_cxx11)
11364             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11365       } else {
11366         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
11367           << DclT << Init->getSourceRange();
11368 
11369         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
11370           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
11371             << Init->getSourceRange();
11372           VDecl->setInvalidDecl();
11373         }
11374       }
11375 
11376     // Suggest adding 'constexpr' in C++11 for literal types.
11377     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
11378       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
11379           << DclT << Init->getSourceRange()
11380           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11381       VDecl->setConstexpr(true);
11382 
11383     } else {
11384       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
11385         << DclT << Init->getSourceRange();
11386       VDecl->setInvalidDecl();
11387     }
11388   } else if (VDecl->isFileVarDecl()) {
11389     // In C, extern is typically used to avoid tentative definitions when
11390     // declaring variables in headers, but adding an intializer makes it a
11391     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
11392     // In C++, extern is often used to give implictly static const variables
11393     // external linkage, so don't warn in that case. If selectany is present,
11394     // this might be header code intended for C and C++ inclusion, so apply the
11395     // C++ rules.
11396     if (VDecl->getStorageClass() == SC_Extern &&
11397         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
11398          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
11399         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
11400         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
11401       Diag(VDecl->getLocation(), diag::warn_extern_init);
11402 
11403     // In Microsoft C++ mode, a const variable defined in namespace scope has
11404     // external linkage by default if the variable is declared with
11405     // __declspec(dllexport).
11406     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11407         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
11408         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
11409       VDecl->setStorageClass(SC_Extern);
11410 
11411     // C99 6.7.8p4. All file scoped initializers need to be constant.
11412     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
11413       CheckForConstantInitializer(Init, DclT);
11414   }
11415 
11416   // We will represent direct-initialization similarly to copy-initialization:
11417   //    int x(1);  -as-> int x = 1;
11418   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
11419   //
11420   // Clients that want to distinguish between the two forms, can check for
11421   // direct initializer using VarDecl::getInitStyle().
11422   // A major benefit is that clients that don't particularly care about which
11423   // exactly form was it (like the CodeGen) can handle both cases without
11424   // special case code.
11425 
11426   // C++ 8.5p11:
11427   // The form of initialization (using parentheses or '=') is generally
11428   // insignificant, but does matter when the entity being initialized has a
11429   // class type.
11430   if (CXXDirectInit) {
11431     assert(DirectInit && "Call-style initializer must be direct init.");
11432     VDecl->setInitStyle(VarDecl::CallInit);
11433   } else if (DirectInit) {
11434     // This must be list-initialization. No other way is direct-initialization.
11435     VDecl->setInitStyle(VarDecl::ListInit);
11436   }
11437 
11438   CheckCompleteVariableDeclaration(VDecl);
11439 }
11440 
11441 /// ActOnInitializerError - Given that there was an error parsing an
11442 /// initializer for the given declaration, try to return to some form
11443 /// of sanity.
11444 void Sema::ActOnInitializerError(Decl *D) {
11445   // Our main concern here is re-establishing invariants like "a
11446   // variable's type is either dependent or complete".
11447   if (!D || D->isInvalidDecl()) return;
11448 
11449   VarDecl *VD = dyn_cast<VarDecl>(D);
11450   if (!VD) return;
11451 
11452   // Bindings are not usable if we can't make sense of the initializer.
11453   if (auto *DD = dyn_cast<DecompositionDecl>(D))
11454     for (auto *BD : DD->bindings())
11455       BD->setInvalidDecl();
11456 
11457   // Auto types are meaningless if we can't make sense of the initializer.
11458   if (ParsingInitForAutoVars.count(D)) {
11459     D->setInvalidDecl();
11460     return;
11461   }
11462 
11463   QualType Ty = VD->getType();
11464   if (Ty->isDependentType()) return;
11465 
11466   // Require a complete type.
11467   if (RequireCompleteType(VD->getLocation(),
11468                           Context.getBaseElementType(Ty),
11469                           diag::err_typecheck_decl_incomplete_type)) {
11470     VD->setInvalidDecl();
11471     return;
11472   }
11473 
11474   // Require a non-abstract type.
11475   if (RequireNonAbstractType(VD->getLocation(), Ty,
11476                              diag::err_abstract_type_in_decl,
11477                              AbstractVariableType)) {
11478     VD->setInvalidDecl();
11479     return;
11480   }
11481 
11482   // Don't bother complaining about constructors or destructors,
11483   // though.
11484 }
11485 
11486 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
11487   // If there is no declaration, there was an error parsing it. Just ignore it.
11488   if (!RealDecl)
11489     return;
11490 
11491   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
11492     QualType Type = Var->getType();
11493 
11494     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
11495     if (isa<DecompositionDecl>(RealDecl)) {
11496       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
11497       Var->setInvalidDecl();
11498       return;
11499     }
11500 
11501     Expr *TmpInit = nullptr;
11502     if (Type->isUndeducedType() &&
11503         DeduceVariableDeclarationType(Var, false, TmpInit))
11504       return;
11505 
11506     // C++11 [class.static.data]p3: A static data member can be declared with
11507     // the constexpr specifier; if so, its declaration shall specify
11508     // a brace-or-equal-initializer.
11509     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
11510     // the definition of a variable [...] or the declaration of a static data
11511     // member.
11512     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
11513         !Var->isThisDeclarationADemotedDefinition()) {
11514       if (Var->isStaticDataMember()) {
11515         // C++1z removes the relevant rule; the in-class declaration is always
11516         // a definition there.
11517         if (!getLangOpts().CPlusPlus17) {
11518           Diag(Var->getLocation(),
11519                diag::err_constexpr_static_mem_var_requires_init)
11520             << Var->getDeclName();
11521           Var->setInvalidDecl();
11522           return;
11523         }
11524       } else {
11525         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
11526         Var->setInvalidDecl();
11527         return;
11528       }
11529     }
11530 
11531     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
11532     // be initialized.
11533     if (!Var->isInvalidDecl() &&
11534         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
11535         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
11536       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
11537       Var->setInvalidDecl();
11538       return;
11539     }
11540 
11541     switch (Var->isThisDeclarationADefinition()) {
11542     case VarDecl::Definition:
11543       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
11544         break;
11545 
11546       // We have an out-of-line definition of a static data member
11547       // that has an in-class initializer, so we type-check this like
11548       // a declaration.
11549       //
11550       LLVM_FALLTHROUGH;
11551 
11552     case VarDecl::DeclarationOnly:
11553       // It's only a declaration.
11554 
11555       // Block scope. C99 6.7p7: If an identifier for an object is
11556       // declared with no linkage (C99 6.2.2p6), the type for the
11557       // object shall be complete.
11558       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
11559           !Var->hasLinkage() && !Var->isInvalidDecl() &&
11560           RequireCompleteType(Var->getLocation(), Type,
11561                               diag::err_typecheck_decl_incomplete_type))
11562         Var->setInvalidDecl();
11563 
11564       // Make sure that the type is not abstract.
11565       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11566           RequireNonAbstractType(Var->getLocation(), Type,
11567                                  diag::err_abstract_type_in_decl,
11568                                  AbstractVariableType))
11569         Var->setInvalidDecl();
11570       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11571           Var->getStorageClass() == SC_PrivateExtern) {
11572         Diag(Var->getLocation(), diag::warn_private_extern);
11573         Diag(Var->getLocation(), diag::note_private_extern);
11574       }
11575 
11576       return;
11577 
11578     case VarDecl::TentativeDefinition:
11579       // File scope. C99 6.9.2p2: A declaration of an identifier for an
11580       // object that has file scope without an initializer, and without a
11581       // storage-class specifier or with the storage-class specifier "static",
11582       // constitutes a tentative definition. Note: A tentative definition with
11583       // external linkage is valid (C99 6.2.2p5).
11584       if (!Var->isInvalidDecl()) {
11585         if (const IncompleteArrayType *ArrayT
11586                                     = Context.getAsIncompleteArrayType(Type)) {
11587           if (RequireCompleteType(Var->getLocation(),
11588                                   ArrayT->getElementType(),
11589                                   diag::err_illegal_decl_array_incomplete_type))
11590             Var->setInvalidDecl();
11591         } else if (Var->getStorageClass() == SC_Static) {
11592           // C99 6.9.2p3: If the declaration of an identifier for an object is
11593           // a tentative definition and has internal linkage (C99 6.2.2p3), the
11594           // declared type shall not be an incomplete type.
11595           // NOTE: code such as the following
11596           //     static struct s;
11597           //     struct s { int a; };
11598           // is accepted by gcc. Hence here we issue a warning instead of
11599           // an error and we do not invalidate the static declaration.
11600           // NOTE: to avoid multiple warnings, only check the first declaration.
11601           if (Var->isFirstDecl())
11602             RequireCompleteType(Var->getLocation(), Type,
11603                                 diag::ext_typecheck_decl_incomplete_type);
11604         }
11605       }
11606 
11607       // Record the tentative definition; we're done.
11608       if (!Var->isInvalidDecl())
11609         TentativeDefinitions.push_back(Var);
11610       return;
11611     }
11612 
11613     // Provide a specific diagnostic for uninitialized variable
11614     // definitions with incomplete array type.
11615     if (Type->isIncompleteArrayType()) {
11616       Diag(Var->getLocation(),
11617            diag::err_typecheck_incomplete_array_needs_initializer);
11618       Var->setInvalidDecl();
11619       return;
11620     }
11621 
11622     // Provide a specific diagnostic for uninitialized variable
11623     // definitions with reference type.
11624     if (Type->isReferenceType()) {
11625       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
11626         << Var->getDeclName()
11627         << SourceRange(Var->getLocation(), Var->getLocation());
11628       Var->setInvalidDecl();
11629       return;
11630     }
11631 
11632     // Do not attempt to type-check the default initializer for a
11633     // variable with dependent type.
11634     if (Type->isDependentType())
11635       return;
11636 
11637     if (Var->isInvalidDecl())
11638       return;
11639 
11640     if (!Var->hasAttr<AliasAttr>()) {
11641       if (RequireCompleteType(Var->getLocation(),
11642                               Context.getBaseElementType(Type),
11643                               diag::err_typecheck_decl_incomplete_type)) {
11644         Var->setInvalidDecl();
11645         return;
11646       }
11647     } else {
11648       return;
11649     }
11650 
11651     // The variable can not have an abstract class type.
11652     if (RequireNonAbstractType(Var->getLocation(), Type,
11653                                diag::err_abstract_type_in_decl,
11654                                AbstractVariableType)) {
11655       Var->setInvalidDecl();
11656       return;
11657     }
11658 
11659     // Check for jumps past the implicit initializer.  C++0x
11660     // clarifies that this applies to a "variable with automatic
11661     // storage duration", not a "local variable".
11662     // C++11 [stmt.dcl]p3
11663     //   A program that jumps from a point where a variable with automatic
11664     //   storage duration is not in scope to a point where it is in scope is
11665     //   ill-formed unless the variable has scalar type, class type with a
11666     //   trivial default constructor and a trivial destructor, a cv-qualified
11667     //   version of one of these types, or an array of one of the preceding
11668     //   types and is declared without an initializer.
11669     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
11670       if (const RecordType *Record
11671             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
11672         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
11673         // Mark the function (if we're in one) for further checking even if the
11674         // looser rules of C++11 do not require such checks, so that we can
11675         // diagnose incompatibilities with C++98.
11676         if (!CXXRecord->isPOD())
11677           setFunctionHasBranchProtectedScope();
11678       }
11679     }
11680 
11681     // C++03 [dcl.init]p9:
11682     //   If no initializer is specified for an object, and the
11683     //   object is of (possibly cv-qualified) non-POD class type (or
11684     //   array thereof), the object shall be default-initialized; if
11685     //   the object is of const-qualified type, the underlying class
11686     //   type shall have a user-declared default
11687     //   constructor. Otherwise, if no initializer is specified for
11688     //   a non- static object, the object and its subobjects, if
11689     //   any, have an indeterminate initial value); if the object
11690     //   or any of its subobjects are of const-qualified type, the
11691     //   program is ill-formed.
11692     // C++0x [dcl.init]p11:
11693     //   If no initializer is specified for an object, the object is
11694     //   default-initialized; [...].
11695     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
11696     InitializationKind Kind
11697       = InitializationKind::CreateDefault(Var->getLocation());
11698 
11699     InitializationSequence InitSeq(*this, Entity, Kind, None);
11700     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
11701     if (Init.isInvalid())
11702       Var->setInvalidDecl();
11703     else if (Init.get()) {
11704       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
11705       // This is important for template substitution.
11706       Var->setInitStyle(VarDecl::CallInit);
11707     }
11708 
11709     CheckCompleteVariableDeclaration(Var);
11710   }
11711 }
11712 
11713 void Sema::ActOnCXXForRangeDecl(Decl *D) {
11714   // If there is no declaration, there was an error parsing it. Ignore it.
11715   if (!D)
11716     return;
11717 
11718   VarDecl *VD = dyn_cast<VarDecl>(D);
11719   if (!VD) {
11720     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
11721     D->setInvalidDecl();
11722     return;
11723   }
11724 
11725   VD->setCXXForRangeDecl(true);
11726 
11727   // for-range-declaration cannot be given a storage class specifier.
11728   int Error = -1;
11729   switch (VD->getStorageClass()) {
11730   case SC_None:
11731     break;
11732   case SC_Extern:
11733     Error = 0;
11734     break;
11735   case SC_Static:
11736     Error = 1;
11737     break;
11738   case SC_PrivateExtern:
11739     Error = 2;
11740     break;
11741   case SC_Auto:
11742     Error = 3;
11743     break;
11744   case SC_Register:
11745     Error = 4;
11746     break;
11747   }
11748   if (Error != -1) {
11749     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
11750       << VD->getDeclName() << Error;
11751     D->setInvalidDecl();
11752   }
11753 }
11754 
11755 StmtResult
11756 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
11757                                  IdentifierInfo *Ident,
11758                                  ParsedAttributes &Attrs,
11759                                  SourceLocation AttrEnd) {
11760   // C++1y [stmt.iter]p1:
11761   //   A range-based for statement of the form
11762   //      for ( for-range-identifier : for-range-initializer ) statement
11763   //   is equivalent to
11764   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
11765   DeclSpec DS(Attrs.getPool().getFactory());
11766 
11767   const char *PrevSpec;
11768   unsigned DiagID;
11769   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
11770                      getPrintingPolicy());
11771 
11772   Declarator D(DS, DeclaratorContext::ForContext);
11773   D.SetIdentifier(Ident, IdentLoc);
11774   D.takeAttributes(Attrs, AttrEnd);
11775 
11776   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
11777   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
11778                 IdentLoc);
11779   Decl *Var = ActOnDeclarator(S, D);
11780   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
11781   FinalizeDeclaration(Var);
11782   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
11783                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
11784 }
11785 
11786 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
11787   if (var->isInvalidDecl()) return;
11788 
11789   if (getLangOpts().OpenCL) {
11790     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
11791     // initialiser
11792     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
11793         !var->hasInit()) {
11794       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
11795           << 1 /*Init*/;
11796       var->setInvalidDecl();
11797       return;
11798     }
11799   }
11800 
11801   // In Objective-C, don't allow jumps past the implicit initialization of a
11802   // local retaining variable.
11803   if (getLangOpts().ObjC &&
11804       var->hasLocalStorage()) {
11805     switch (var->getType().getObjCLifetime()) {
11806     case Qualifiers::OCL_None:
11807     case Qualifiers::OCL_ExplicitNone:
11808     case Qualifiers::OCL_Autoreleasing:
11809       break;
11810 
11811     case Qualifiers::OCL_Weak:
11812     case Qualifiers::OCL_Strong:
11813       setFunctionHasBranchProtectedScope();
11814       break;
11815     }
11816   }
11817 
11818   if (var->hasLocalStorage() &&
11819       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
11820     setFunctionHasBranchProtectedScope();
11821 
11822   // Warn about externally-visible variables being defined without a
11823   // prior declaration.  We only want to do this for global
11824   // declarations, but we also specifically need to avoid doing it for
11825   // class members because the linkage of an anonymous class can
11826   // change if it's later given a typedef name.
11827   if (var->isThisDeclarationADefinition() &&
11828       var->getDeclContext()->getRedeclContext()->isFileContext() &&
11829       var->isExternallyVisible() && var->hasLinkage() &&
11830       !var->isInline() && !var->getDescribedVarTemplate() &&
11831       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
11832       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11833                                   var->getLocation())) {
11834     // Find a previous declaration that's not a definition.
11835     VarDecl *prev = var->getPreviousDecl();
11836     while (prev && prev->isThisDeclarationADefinition())
11837       prev = prev->getPreviousDecl();
11838 
11839     if (!prev)
11840       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11841   }
11842 
11843   // Cache the result of checking for constant initialization.
11844   Optional<bool> CacheHasConstInit;
11845   const Expr *CacheCulprit;
11846   auto checkConstInit = [&]() mutable {
11847     if (!CacheHasConstInit)
11848       CacheHasConstInit = var->getInit()->isConstantInitializer(
11849             Context, var->getType()->isReferenceType(), &CacheCulprit);
11850     return *CacheHasConstInit;
11851   };
11852 
11853   if (var->getTLSKind() == VarDecl::TLS_Static) {
11854     if (var->getType().isDestructedType()) {
11855       // GNU C++98 edits for __thread, [basic.start.term]p3:
11856       //   The type of an object with thread storage duration shall not
11857       //   have a non-trivial destructor.
11858       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11859       if (getLangOpts().CPlusPlus11)
11860         Diag(var->getLocation(), diag::note_use_thread_local);
11861     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11862       if (!checkConstInit()) {
11863         // GNU C++98 edits for __thread, [basic.start.init]p4:
11864         //   An object of thread storage duration shall not require dynamic
11865         //   initialization.
11866         // FIXME: Need strict checking here.
11867         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11868           << CacheCulprit->getSourceRange();
11869         if (getLangOpts().CPlusPlus11)
11870           Diag(var->getLocation(), diag::note_use_thread_local);
11871       }
11872     }
11873   }
11874 
11875   // Apply section attributes and pragmas to global variables.
11876   bool GlobalStorage = var->hasGlobalStorage();
11877   if (GlobalStorage && var->isThisDeclarationADefinition() &&
11878       !inTemplateInstantiation()) {
11879     PragmaStack<StringLiteral *> *Stack = nullptr;
11880     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11881     if (var->getType().isConstQualified())
11882       Stack = &ConstSegStack;
11883     else if (!var->getInit()) {
11884       Stack = &BSSSegStack;
11885       SectionFlags |= ASTContext::PSF_Write;
11886     } else {
11887       Stack = &DataSegStack;
11888       SectionFlags |= ASTContext::PSF_Write;
11889     }
11890     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11891       var->addAttr(SectionAttr::CreateImplicit(
11892           Context, SectionAttr::Declspec_allocate,
11893           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11894     }
11895     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11896       if (UnifySection(SA->getName(), SectionFlags, var))
11897         var->dropAttr<SectionAttr>();
11898 
11899     // Apply the init_seg attribute if this has an initializer.  If the
11900     // initializer turns out to not be dynamic, we'll end up ignoring this
11901     // attribute.
11902     if (CurInitSeg && var->getInit())
11903       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11904                                                CurInitSegLoc));
11905   }
11906 
11907   // All the following checks are C++ only.
11908   if (!getLangOpts().CPlusPlus) {
11909       // If this variable must be emitted, add it as an initializer for the
11910       // current module.
11911      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11912        Context.addModuleInitializer(ModuleScopes.back().Module, var);
11913      return;
11914   }
11915 
11916   if (auto *DD = dyn_cast<DecompositionDecl>(var))
11917     CheckCompleteDecompositionDeclaration(DD);
11918 
11919   QualType type = var->getType();
11920   if (type->isDependentType()) return;
11921 
11922   if (var->hasAttr<BlocksAttr>())
11923     getCurFunction()->addByrefBlockVar(var);
11924 
11925   Expr *Init = var->getInit();
11926   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11927   QualType baseType = Context.getBaseElementType(type);
11928 
11929   if (Init && !Init->isValueDependent()) {
11930     if (var->isConstexpr()) {
11931       SmallVector<PartialDiagnosticAt, 8> Notes;
11932       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11933         SourceLocation DiagLoc = var->getLocation();
11934         // If the note doesn't add any useful information other than a source
11935         // location, fold it into the primary diagnostic.
11936         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11937               diag::note_invalid_subexpr_in_const_expr) {
11938           DiagLoc = Notes[0].first;
11939           Notes.clear();
11940         }
11941         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11942           << var << Init->getSourceRange();
11943         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11944           Diag(Notes[I].first, Notes[I].second);
11945       }
11946     } else if (var->isUsableInConstantExpressions(Context)) {
11947       // Check whether the initializer of a const variable of integral or
11948       // enumeration type is an ICE now, since we can't tell whether it was
11949       // initialized by a constant expression if we check later.
11950       var->checkInitIsICE();
11951     }
11952 
11953     // Don't emit further diagnostics about constexpr globals since they
11954     // were just diagnosed.
11955     if (!var->isConstexpr() && GlobalStorage &&
11956             var->hasAttr<RequireConstantInitAttr>()) {
11957       // FIXME: Need strict checking in C++03 here.
11958       bool DiagErr = getLangOpts().CPlusPlus11
11959           ? !var->checkInitIsICE() : !checkConstInit();
11960       if (DiagErr) {
11961         auto attr = var->getAttr<RequireConstantInitAttr>();
11962         Diag(var->getLocation(), diag::err_require_constant_init_failed)
11963           << Init->getSourceRange();
11964         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11965           << attr->getRange();
11966         if (getLangOpts().CPlusPlus11) {
11967           APValue Value;
11968           SmallVector<PartialDiagnosticAt, 8> Notes;
11969           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11970           for (auto &it : Notes)
11971             Diag(it.first, it.second);
11972         } else {
11973           Diag(CacheCulprit->getExprLoc(),
11974                diag::note_invalid_subexpr_in_const_expr)
11975               << CacheCulprit->getSourceRange();
11976         }
11977       }
11978     }
11979     else if (!var->isConstexpr() && IsGlobal &&
11980              !getDiagnostics().isIgnored(diag::warn_global_constructor,
11981                                     var->getLocation())) {
11982       // Warn about globals which don't have a constant initializer.  Don't
11983       // warn about globals with a non-trivial destructor because we already
11984       // warned about them.
11985       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11986       if (!(RD && !RD->hasTrivialDestructor())) {
11987         if (!checkConstInit())
11988           Diag(var->getLocation(), diag::warn_global_constructor)
11989             << Init->getSourceRange();
11990       }
11991     }
11992   }
11993 
11994   // Require the destructor.
11995   if (const RecordType *recordType = baseType->getAs<RecordType>())
11996     FinalizeVarWithDestructor(var, recordType);
11997 
11998   // If this variable must be emitted, add it as an initializer for the current
11999   // module.
12000   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12001     Context.addModuleInitializer(ModuleScopes.back().Module, var);
12002 }
12003 
12004 /// Determines if a variable's alignment is dependent.
12005 static bool hasDependentAlignment(VarDecl *VD) {
12006   if (VD->getType()->isDependentType())
12007     return true;
12008   for (auto *I : VD->specific_attrs<AlignedAttr>())
12009     if (I->isAlignmentDependent())
12010       return true;
12011   return false;
12012 }
12013 
12014 /// Check if VD needs to be dllexport/dllimport due to being in a
12015 /// dllexport/import function.
12016 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12017   assert(VD->isStaticLocal());
12018 
12019   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12020 
12021   // Find outermost function when VD is in lambda function.
12022   while (FD && !getDLLAttr(FD) &&
12023          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12024          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12025     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12026   }
12027 
12028   if (!FD)
12029     return;
12030 
12031   // Static locals inherit dll attributes from their function.
12032   if (Attr *A = getDLLAttr(FD)) {
12033     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12034     NewAttr->setInherited(true);
12035     VD->addAttr(NewAttr);
12036   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12037     auto *NewAttr = ::new (getASTContext()) DLLExportAttr(A->getRange(),
12038                                                           getASTContext(),
12039                                                           A->getSpellingListIndex());
12040     NewAttr->setInherited(true);
12041     VD->addAttr(NewAttr);
12042 
12043     // Export this function to enforce exporting this static variable even
12044     // if it is not used in this compilation unit.
12045     if (!FD->hasAttr<DLLExportAttr>())
12046       FD->addAttr(NewAttr);
12047 
12048   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12049     auto *NewAttr = ::new (getASTContext()) DLLImportAttr(A->getRange(),
12050                                                           getASTContext(),
12051                                                           A->getSpellingListIndex());
12052     NewAttr->setInherited(true);
12053     VD->addAttr(NewAttr);
12054   }
12055 }
12056 
12057 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12058 /// any semantic actions necessary after any initializer has been attached.
12059 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12060   // Note that we are no longer parsing the initializer for this declaration.
12061   ParsingInitForAutoVars.erase(ThisDecl);
12062 
12063   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12064   if (!VD)
12065     return;
12066 
12067   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12068   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12069       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12070     if (PragmaClangBSSSection.Valid)
12071       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
12072                                                             PragmaClangBSSSection.SectionName,
12073                                                             PragmaClangBSSSection.PragmaLocation));
12074     if (PragmaClangDataSection.Valid)
12075       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
12076                                                              PragmaClangDataSection.SectionName,
12077                                                              PragmaClangDataSection.PragmaLocation));
12078     if (PragmaClangRodataSection.Valid)
12079       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
12080                                                                PragmaClangRodataSection.SectionName,
12081                                                                PragmaClangRodataSection.PragmaLocation));
12082   }
12083 
12084   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12085     for (auto *BD : DD->bindings()) {
12086       FinalizeDeclaration(BD);
12087     }
12088   }
12089 
12090   checkAttributesAfterMerging(*this, *VD);
12091 
12092   // Perform TLS alignment check here after attributes attached to the variable
12093   // which may affect the alignment have been processed. Only perform the check
12094   // if the target has a maximum TLS alignment (zero means no constraints).
12095   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12096     // Protect the check so that it's not performed on dependent types and
12097     // dependent alignments (we can't determine the alignment in that case).
12098     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12099         !VD->isInvalidDecl()) {
12100       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12101       if (Context.getDeclAlign(VD) > MaxAlignChars) {
12102         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12103           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12104           << (unsigned)MaxAlignChars.getQuantity();
12105       }
12106     }
12107   }
12108 
12109   if (VD->isStaticLocal()) {
12110     CheckStaticLocalForDllExport(VD);
12111 
12112     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12113       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12114       // function, only __shared__ variables or variables without any device
12115       // memory qualifiers may be declared with static storage class.
12116       // Note: It is unclear how a function-scope non-const static variable
12117       // without device memory qualifier is implemented, therefore only static
12118       // const variable without device memory qualifier is allowed.
12119       [&]() {
12120         if (!getLangOpts().CUDA)
12121           return;
12122         if (VD->hasAttr<CUDASharedAttr>())
12123           return;
12124         if (VD->getType().isConstQualified() &&
12125             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12126           return;
12127         if (CUDADiagIfDeviceCode(VD->getLocation(),
12128                                  diag::err_device_static_local_var)
12129             << CurrentCUDATarget())
12130           VD->setInvalidDecl();
12131       }();
12132     }
12133   }
12134 
12135   // Perform check for initializers of device-side global variables.
12136   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12137   // 7.5). We must also apply the same checks to all __shared__
12138   // variables whether they are local or not. CUDA also allows
12139   // constant initializers for __constant__ and __device__ variables.
12140   if (getLangOpts().CUDA)
12141     checkAllowedCUDAInitializer(VD);
12142 
12143   // Grab the dllimport or dllexport attribute off of the VarDecl.
12144   const InheritableAttr *DLLAttr = getDLLAttr(VD);
12145 
12146   // Imported static data members cannot be defined out-of-line.
12147   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12148     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12149         VD->isThisDeclarationADefinition()) {
12150       // We allow definitions of dllimport class template static data members
12151       // with a warning.
12152       CXXRecordDecl *Context =
12153         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12154       bool IsClassTemplateMember =
12155           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12156           Context->getDescribedClassTemplate();
12157 
12158       Diag(VD->getLocation(),
12159            IsClassTemplateMember
12160                ? diag::warn_attribute_dllimport_static_field_definition
12161                : diag::err_attribute_dllimport_static_field_definition);
12162       Diag(IA->getLocation(), diag::note_attribute);
12163       if (!IsClassTemplateMember)
12164         VD->setInvalidDecl();
12165     }
12166   }
12167 
12168   // dllimport/dllexport variables cannot be thread local, their TLS index
12169   // isn't exported with the variable.
12170   if (DLLAttr && VD->getTLSKind()) {
12171     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12172     if (F && getDLLAttr(F)) {
12173       assert(VD->isStaticLocal());
12174       // But if this is a static local in a dlimport/dllexport function, the
12175       // function will never be inlined, which means the var would never be
12176       // imported, so having it marked import/export is safe.
12177     } else {
12178       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12179                                                                     << DLLAttr;
12180       VD->setInvalidDecl();
12181     }
12182   }
12183 
12184   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12185     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12186       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12187       VD->dropAttr<UsedAttr>();
12188     }
12189   }
12190 
12191   const DeclContext *DC = VD->getDeclContext();
12192   // If there's a #pragma GCC visibility in scope, and this isn't a class
12193   // member, set the visibility of this variable.
12194   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12195     AddPushedVisibilityAttribute(VD);
12196 
12197   // FIXME: Warn on unused var template partial specializations.
12198   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12199     MarkUnusedFileScopedDecl(VD);
12200 
12201   // Now we have parsed the initializer and can update the table of magic
12202   // tag values.
12203   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12204       !VD->getType()->isIntegralOrEnumerationType())
12205     return;
12206 
12207   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12208     const Expr *MagicValueExpr = VD->getInit();
12209     if (!MagicValueExpr) {
12210       continue;
12211     }
12212     llvm::APSInt MagicValueInt;
12213     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12214       Diag(I->getRange().getBegin(),
12215            diag::err_type_tag_for_datatype_not_ice)
12216         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12217       continue;
12218     }
12219     if (MagicValueInt.getActiveBits() > 64) {
12220       Diag(I->getRange().getBegin(),
12221            diag::err_type_tag_for_datatype_too_large)
12222         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12223       continue;
12224     }
12225     uint64_t MagicValue = MagicValueInt.getZExtValue();
12226     RegisterTypeTagForDatatype(I->getArgumentKind(),
12227                                MagicValue,
12228                                I->getMatchingCType(),
12229                                I->getLayoutCompatible(),
12230                                I->getMustBeNull());
12231   }
12232 }
12233 
12234 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12235   auto *VD = dyn_cast<VarDecl>(DD);
12236   return VD && !VD->getType()->hasAutoForTrailingReturnType();
12237 }
12238 
12239 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12240                                                    ArrayRef<Decl *> Group) {
12241   SmallVector<Decl*, 8> Decls;
12242 
12243   if (DS.isTypeSpecOwned())
12244     Decls.push_back(DS.getRepAsDecl());
12245 
12246   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12247   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12248   bool DiagnosedMultipleDecomps = false;
12249   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12250   bool DiagnosedNonDeducedAuto = false;
12251 
12252   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12253     if (Decl *D = Group[i]) {
12254       // For declarators, there are some additional syntactic-ish checks we need
12255       // to perform.
12256       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12257         if (!FirstDeclaratorInGroup)
12258           FirstDeclaratorInGroup = DD;
12259         if (!FirstDecompDeclaratorInGroup)
12260           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12261         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12262             !hasDeducedAuto(DD))
12263           FirstNonDeducedAutoInGroup = DD;
12264 
12265         if (FirstDeclaratorInGroup != DD) {
12266           // A decomposition declaration cannot be combined with any other
12267           // declaration in the same group.
12268           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12269             Diag(FirstDecompDeclaratorInGroup->getLocation(),
12270                  diag::err_decomp_decl_not_alone)
12271                 << FirstDeclaratorInGroup->getSourceRange()
12272                 << DD->getSourceRange();
12273             DiagnosedMultipleDecomps = true;
12274           }
12275 
12276           // A declarator that uses 'auto' in any way other than to declare a
12277           // variable with a deduced type cannot be combined with any other
12278           // declarator in the same group.
12279           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12280             Diag(FirstNonDeducedAutoInGroup->getLocation(),
12281                  diag::err_auto_non_deduced_not_alone)
12282                 << FirstNonDeducedAutoInGroup->getType()
12283                        ->hasAutoForTrailingReturnType()
12284                 << FirstDeclaratorInGroup->getSourceRange()
12285                 << DD->getSourceRange();
12286             DiagnosedNonDeducedAuto = true;
12287           }
12288         }
12289       }
12290 
12291       Decls.push_back(D);
12292     }
12293   }
12294 
12295   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12296     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12297       handleTagNumbering(Tag, S);
12298       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12299           getLangOpts().CPlusPlus)
12300         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
12301     }
12302   }
12303 
12304   return BuildDeclaratorGroup(Decls);
12305 }
12306 
12307 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
12308 /// group, performing any necessary semantic checking.
12309 Sema::DeclGroupPtrTy
12310 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
12311   // C++14 [dcl.spec.auto]p7: (DR1347)
12312   //   If the type that replaces the placeholder type is not the same in each
12313   //   deduction, the program is ill-formed.
12314   if (Group.size() > 1) {
12315     QualType Deduced;
12316     VarDecl *DeducedDecl = nullptr;
12317     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12318       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
12319       if (!D || D->isInvalidDecl())
12320         break;
12321       DeducedType *DT = D->getType()->getContainedDeducedType();
12322       if (!DT || DT->getDeducedType().isNull())
12323         continue;
12324       if (Deduced.isNull()) {
12325         Deduced = DT->getDeducedType();
12326         DeducedDecl = D;
12327       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
12328         auto *AT = dyn_cast<AutoType>(DT);
12329         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
12330              diag::err_auto_different_deductions)
12331           << (AT ? (unsigned)AT->getKeyword() : 3)
12332           << Deduced << DeducedDecl->getDeclName()
12333           << DT->getDeducedType() << D->getDeclName()
12334           << DeducedDecl->getInit()->getSourceRange()
12335           << D->getInit()->getSourceRange();
12336         D->setInvalidDecl();
12337         break;
12338       }
12339     }
12340   }
12341 
12342   ActOnDocumentableDecls(Group);
12343 
12344   return DeclGroupPtrTy::make(
12345       DeclGroupRef::Create(Context, Group.data(), Group.size()));
12346 }
12347 
12348 void Sema::ActOnDocumentableDecl(Decl *D) {
12349   ActOnDocumentableDecls(D);
12350 }
12351 
12352 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
12353   // Don't parse the comment if Doxygen diagnostics are ignored.
12354   if (Group.empty() || !Group[0])
12355     return;
12356 
12357   if (Diags.isIgnored(diag::warn_doc_param_not_found,
12358                       Group[0]->getLocation()) &&
12359       Diags.isIgnored(diag::warn_unknown_comment_command_name,
12360                       Group[0]->getLocation()))
12361     return;
12362 
12363   if (Group.size() >= 2) {
12364     // This is a decl group.  Normally it will contain only declarations
12365     // produced from declarator list.  But in case we have any definitions or
12366     // additional declaration references:
12367     //   'typedef struct S {} S;'
12368     //   'typedef struct S *S;'
12369     //   'struct S *pS;'
12370     // FinalizeDeclaratorGroup adds these as separate declarations.
12371     Decl *MaybeTagDecl = Group[0];
12372     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
12373       Group = Group.slice(1);
12374     }
12375   }
12376 
12377   // See if there are any new comments that are not attached to a decl.
12378   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
12379   if (!Comments.empty() &&
12380       !Comments.back()->isAttached()) {
12381     // There is at least one comment that not attached to a decl.
12382     // Maybe it should be attached to one of these decls?
12383     //
12384     // Note that this way we pick up not only comments that precede the
12385     // declaration, but also comments that *follow* the declaration -- thanks to
12386     // the lookahead in the lexer: we've consumed the semicolon and looked
12387     // ahead through comments.
12388     for (unsigned i = 0, e = Group.size(); i != e; ++i)
12389       Context.getCommentForDecl(Group[i], &PP);
12390   }
12391 }
12392 
12393 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
12394 /// to introduce parameters into function prototype scope.
12395 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
12396   const DeclSpec &DS = D.getDeclSpec();
12397 
12398   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
12399 
12400   // C++03 [dcl.stc]p2 also permits 'auto'.
12401   StorageClass SC = SC_None;
12402   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
12403     SC = SC_Register;
12404     // In C++11, the 'register' storage class specifier is deprecated.
12405     // In C++17, it is not allowed, but we tolerate it as an extension.
12406     if (getLangOpts().CPlusPlus11) {
12407       Diag(DS.getStorageClassSpecLoc(),
12408            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
12409                                      : diag::warn_deprecated_register)
12410         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12411     }
12412   } else if (getLangOpts().CPlusPlus &&
12413              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
12414     SC = SC_Auto;
12415   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
12416     Diag(DS.getStorageClassSpecLoc(),
12417          diag::err_invalid_storage_class_in_func_decl);
12418     D.getMutableDeclSpec().ClearStorageClassSpecs();
12419   }
12420 
12421   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
12422     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
12423       << DeclSpec::getSpecifierName(TSCS);
12424   if (DS.isInlineSpecified())
12425     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
12426         << getLangOpts().CPlusPlus17;
12427   if (DS.isConstexprSpecified())
12428     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
12429       << 0;
12430 
12431   DiagnoseFunctionSpecifiers(DS);
12432 
12433   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12434   QualType parmDeclType = TInfo->getType();
12435 
12436   if (getLangOpts().CPlusPlus) {
12437     // Check that there are no default arguments inside the type of this
12438     // parameter.
12439     CheckExtraCXXDefaultArguments(D);
12440 
12441     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
12442     if (D.getCXXScopeSpec().isSet()) {
12443       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
12444         << D.getCXXScopeSpec().getRange();
12445       D.getCXXScopeSpec().clear();
12446     }
12447   }
12448 
12449   // Ensure we have a valid name
12450   IdentifierInfo *II = nullptr;
12451   if (D.hasName()) {
12452     II = D.getIdentifier();
12453     if (!II) {
12454       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
12455         << GetNameForDeclarator(D).getName();
12456       D.setInvalidType(true);
12457     }
12458   }
12459 
12460   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
12461   if (II) {
12462     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
12463                    ForVisibleRedeclaration);
12464     LookupName(R, S);
12465     if (R.isSingleResult()) {
12466       NamedDecl *PrevDecl = R.getFoundDecl();
12467       if (PrevDecl->isTemplateParameter()) {
12468         // Maybe we will complain about the shadowed template parameter.
12469         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12470         // Just pretend that we didn't see the previous declaration.
12471         PrevDecl = nullptr;
12472       } else if (S->isDeclScope(PrevDecl)) {
12473         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
12474         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12475 
12476         // Recover by removing the name
12477         II = nullptr;
12478         D.SetIdentifier(nullptr, D.getIdentifierLoc());
12479         D.setInvalidType(true);
12480       }
12481     }
12482   }
12483 
12484   // Temporarily put parameter variables in the translation unit, not
12485   // the enclosing context.  This prevents them from accidentally
12486   // looking like class members in C++.
12487   ParmVarDecl *New =
12488       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
12489                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
12490 
12491   if (D.isInvalidType())
12492     New->setInvalidDecl();
12493 
12494   assert(S->isFunctionPrototypeScope());
12495   assert(S->getFunctionPrototypeDepth() >= 1);
12496   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
12497                     S->getNextFunctionPrototypeIndex());
12498 
12499   // Add the parameter declaration into this scope.
12500   S->AddDecl(New);
12501   if (II)
12502     IdResolver.AddDecl(New);
12503 
12504   ProcessDeclAttributes(S, New, D);
12505 
12506   if (D.getDeclSpec().isModulePrivateSpecified())
12507     Diag(New->getLocation(), diag::err_module_private_local)
12508       << 1 << New->getDeclName()
12509       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12510       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12511 
12512   if (New->hasAttr<BlocksAttr>()) {
12513     Diag(New->getLocation(), diag::err_block_on_nonlocal);
12514   }
12515   return New;
12516 }
12517 
12518 /// Synthesizes a variable for a parameter arising from a
12519 /// typedef.
12520 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
12521                                               SourceLocation Loc,
12522                                               QualType T) {
12523   /* FIXME: setting StartLoc == Loc.
12524      Would it be worth to modify callers so as to provide proper source
12525      location for the unnamed parameters, embedding the parameter's type? */
12526   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
12527                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
12528                                            SC_None, nullptr);
12529   Param->setImplicit();
12530   return Param;
12531 }
12532 
12533 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
12534   // Don't diagnose unused-parameter errors in template instantiations; we
12535   // will already have done so in the template itself.
12536   if (inTemplateInstantiation())
12537     return;
12538 
12539   for (const ParmVarDecl *Parameter : Parameters) {
12540     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
12541         !Parameter->hasAttr<UnusedAttr>()) {
12542       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
12543         << Parameter->getDeclName();
12544     }
12545   }
12546 }
12547 
12548 void Sema::DiagnoseSizeOfParametersAndReturnValue(
12549     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
12550   if (LangOpts.NumLargeByValueCopy == 0) // No check.
12551     return;
12552 
12553   // Warn if the return value is pass-by-value and larger than the specified
12554   // threshold.
12555   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
12556     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
12557     if (Size > LangOpts.NumLargeByValueCopy)
12558       Diag(D->getLocation(), diag::warn_return_value_size)
12559           << D->getDeclName() << Size;
12560   }
12561 
12562   // Warn if any parameter is pass-by-value and larger than the specified
12563   // threshold.
12564   for (const ParmVarDecl *Parameter : Parameters) {
12565     QualType T = Parameter->getType();
12566     if (T->isDependentType() || !T.isPODType(Context))
12567       continue;
12568     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
12569     if (Size > LangOpts.NumLargeByValueCopy)
12570       Diag(Parameter->getLocation(), diag::warn_parameter_size)
12571           << Parameter->getDeclName() << Size;
12572   }
12573 }
12574 
12575 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
12576                                   SourceLocation NameLoc, IdentifierInfo *Name,
12577                                   QualType T, TypeSourceInfo *TSInfo,
12578                                   StorageClass SC) {
12579   // In ARC, infer a lifetime qualifier for appropriate parameter types.
12580   if (getLangOpts().ObjCAutoRefCount &&
12581       T.getObjCLifetime() == Qualifiers::OCL_None &&
12582       T->isObjCLifetimeType()) {
12583 
12584     Qualifiers::ObjCLifetime lifetime;
12585 
12586     // Special cases for arrays:
12587     //   - if it's const, use __unsafe_unretained
12588     //   - otherwise, it's an error
12589     if (T->isArrayType()) {
12590       if (!T.isConstQualified()) {
12591         if (DelayedDiagnostics.shouldDelayDiagnostics())
12592           DelayedDiagnostics.add(
12593               sema::DelayedDiagnostic::makeForbiddenType(
12594               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
12595         else
12596           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
12597               << TSInfo->getTypeLoc().getSourceRange();
12598       }
12599       lifetime = Qualifiers::OCL_ExplicitNone;
12600     } else {
12601       lifetime = T->getObjCARCImplicitLifetime();
12602     }
12603     T = Context.getLifetimeQualifiedType(T, lifetime);
12604   }
12605 
12606   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
12607                                          Context.getAdjustedParameterType(T),
12608                                          TSInfo, SC, nullptr);
12609 
12610   // Parameters can not be abstract class types.
12611   // For record types, this is done by the AbstractClassUsageDiagnoser once
12612   // the class has been completely parsed.
12613   if (!CurContext->isRecord() &&
12614       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
12615                              AbstractParamType))
12616     New->setInvalidDecl();
12617 
12618   // Parameter declarators cannot be interface types. All ObjC objects are
12619   // passed by reference.
12620   if (T->isObjCObjectType()) {
12621     SourceLocation TypeEndLoc =
12622         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
12623     Diag(NameLoc,
12624          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
12625       << FixItHint::CreateInsertion(TypeEndLoc, "*");
12626     T = Context.getObjCObjectPointerType(T);
12627     New->setType(T);
12628   }
12629 
12630   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
12631   // duration shall not be qualified by an address-space qualifier."
12632   // Since all parameters have automatic store duration, they can not have
12633   // an address space.
12634   if (T.getAddressSpace() != LangAS::Default &&
12635       // OpenCL allows function arguments declared to be an array of a type
12636       // to be qualified with an address space.
12637       !(getLangOpts().OpenCL &&
12638         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
12639     Diag(NameLoc, diag::err_arg_with_address_space);
12640     New->setInvalidDecl();
12641   }
12642 
12643   return New;
12644 }
12645 
12646 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
12647                                            SourceLocation LocAfterDecls) {
12648   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
12649 
12650   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
12651   // for a K&R function.
12652   if (!FTI.hasPrototype) {
12653     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
12654       --i;
12655       if (FTI.Params[i].Param == nullptr) {
12656         SmallString<256> Code;
12657         llvm::raw_svector_ostream(Code)
12658             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
12659         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
12660             << FTI.Params[i].Ident
12661             << FixItHint::CreateInsertion(LocAfterDecls, Code);
12662 
12663         // Implicitly declare the argument as type 'int' for lack of a better
12664         // type.
12665         AttributeFactory attrs;
12666         DeclSpec DS(attrs);
12667         const char* PrevSpec; // unused
12668         unsigned DiagID; // unused
12669         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
12670                            DiagID, Context.getPrintingPolicy());
12671         // Use the identifier location for the type source range.
12672         DS.SetRangeStart(FTI.Params[i].IdentLoc);
12673         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
12674         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
12675         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
12676         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
12677       }
12678     }
12679   }
12680 }
12681 
12682 Decl *
12683 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
12684                               MultiTemplateParamsArg TemplateParameterLists,
12685                               SkipBodyInfo *SkipBody) {
12686   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
12687   assert(D.isFunctionDeclarator() && "Not a function declarator!");
12688   Scope *ParentScope = FnBodyScope->getParent();
12689 
12690   D.setFunctionDefinitionKind(FDK_Definition);
12691   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
12692   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
12693 }
12694 
12695 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
12696   Consumer.HandleInlineFunctionDefinition(D);
12697 }
12698 
12699 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
12700                              const FunctionDecl*& PossibleZeroParamPrototype) {
12701   // Don't warn about invalid declarations.
12702   if (FD->isInvalidDecl())
12703     return false;
12704 
12705   // Or declarations that aren't global.
12706   if (!FD->isGlobal())
12707     return false;
12708 
12709   // Don't warn about C++ member functions.
12710   if (isa<CXXMethodDecl>(FD))
12711     return false;
12712 
12713   // Don't warn about 'main'.
12714   if (FD->isMain())
12715     return false;
12716 
12717   // Don't warn about inline functions.
12718   if (FD->isInlined())
12719     return false;
12720 
12721   // Don't warn about function templates.
12722   if (FD->getDescribedFunctionTemplate())
12723     return false;
12724 
12725   // Don't warn about function template specializations.
12726   if (FD->isFunctionTemplateSpecialization())
12727     return false;
12728 
12729   // Don't warn for OpenCL kernels.
12730   if (FD->hasAttr<OpenCLKernelAttr>())
12731     return false;
12732 
12733   // Don't warn on explicitly deleted functions.
12734   if (FD->isDeleted())
12735     return false;
12736 
12737   bool MissingPrototype = true;
12738   for (const FunctionDecl *Prev = FD->getPreviousDecl();
12739        Prev; Prev = Prev->getPreviousDecl()) {
12740     // Ignore any declarations that occur in function or method
12741     // scope, because they aren't visible from the header.
12742     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
12743       continue;
12744 
12745     MissingPrototype = !Prev->getType()->isFunctionProtoType();
12746     if (FD->getNumParams() == 0)
12747       PossibleZeroParamPrototype = Prev;
12748     break;
12749   }
12750 
12751   return MissingPrototype;
12752 }
12753 
12754 void
12755 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
12756                                    const FunctionDecl *EffectiveDefinition,
12757                                    SkipBodyInfo *SkipBody) {
12758   const FunctionDecl *Definition = EffectiveDefinition;
12759   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
12760     // If this is a friend function defined in a class template, it does not
12761     // have a body until it is used, nevertheless it is a definition, see
12762     // [temp.inst]p2:
12763     //
12764     // ... for the purpose of determining whether an instantiated redeclaration
12765     // is valid according to [basic.def.odr] and [class.mem], a declaration that
12766     // corresponds to a definition in the template is considered to be a
12767     // definition.
12768     //
12769     // The following code must produce redefinition error:
12770     //
12771     //     template<typename T> struct C20 { friend void func_20() {} };
12772     //     C20<int> c20i;
12773     //     void func_20() {}
12774     //
12775     for (auto I : FD->redecls()) {
12776       if (I != FD && !I->isInvalidDecl() &&
12777           I->getFriendObjectKind() != Decl::FOK_None) {
12778         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
12779           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
12780             // A merged copy of the same function, instantiated as a member of
12781             // the same class, is OK.
12782             if (declaresSameEntity(OrigFD, Original) &&
12783                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
12784                                    cast<Decl>(FD->getLexicalDeclContext())))
12785               continue;
12786           }
12787 
12788           if (Original->isThisDeclarationADefinition()) {
12789             Definition = I;
12790             break;
12791           }
12792         }
12793       }
12794     }
12795   }
12796 
12797   if (!Definition)
12798     // Similar to friend functions a friend function template may be a
12799     // definition and do not have a body if it is instantiated in a class
12800     // template.
12801     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
12802       for (auto I : FTD->redecls()) {
12803         auto D = cast<FunctionTemplateDecl>(I);
12804         if (D != FTD) {
12805           assert(!D->isThisDeclarationADefinition() &&
12806                  "More than one definition in redeclaration chain");
12807           if (D->getFriendObjectKind() != Decl::FOK_None)
12808             if (FunctionTemplateDecl *FT =
12809                                        D->getInstantiatedFromMemberTemplate()) {
12810               if (FT->isThisDeclarationADefinition()) {
12811                 Definition = D->getTemplatedDecl();
12812                 break;
12813               }
12814             }
12815         }
12816       }
12817     }
12818 
12819   if (!Definition)
12820     return;
12821 
12822   if (canRedefineFunction(Definition, getLangOpts()))
12823     return;
12824 
12825   // Don't emit an error when this is redefinition of a typo-corrected
12826   // definition.
12827   if (TypoCorrectedFunctionDefinitions.count(Definition))
12828     return;
12829 
12830   // If we don't have a visible definition of the function, and it's inline or
12831   // a template, skip the new definition.
12832   if (SkipBody && !hasVisibleDefinition(Definition) &&
12833       (Definition->getFormalLinkage() == InternalLinkage ||
12834        Definition->isInlined() ||
12835        Definition->getDescribedFunctionTemplate() ||
12836        Definition->getNumTemplateParameterLists())) {
12837     SkipBody->ShouldSkip = true;
12838     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
12839     if (auto *TD = Definition->getDescribedFunctionTemplate())
12840       makeMergedDefinitionVisible(TD);
12841     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
12842     return;
12843   }
12844 
12845   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
12846       Definition->getStorageClass() == SC_Extern)
12847     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
12848         << FD->getDeclName() << getLangOpts().CPlusPlus;
12849   else
12850     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12851 
12852   Diag(Definition->getLocation(), diag::note_previous_definition);
12853   FD->setInvalidDecl();
12854 }
12855 
12856 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12857                                    Sema &S) {
12858   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12859 
12860   LambdaScopeInfo *LSI = S.PushLambdaScope();
12861   LSI->CallOperator = CallOperator;
12862   LSI->Lambda = LambdaClass;
12863   LSI->ReturnType = CallOperator->getReturnType();
12864   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12865 
12866   if (LCD == LCD_None)
12867     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12868   else if (LCD == LCD_ByCopy)
12869     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12870   else if (LCD == LCD_ByRef)
12871     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12872   DeclarationNameInfo DNI = CallOperator->getNameInfo();
12873 
12874   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12875   LSI->Mutable = !CallOperator->isConst();
12876 
12877   // Add the captures to the LSI so they can be noted as already
12878   // captured within tryCaptureVar.
12879   auto I = LambdaClass->field_begin();
12880   for (const auto &C : LambdaClass->captures()) {
12881     if (C.capturesVariable()) {
12882       VarDecl *VD = C.getCapturedVar();
12883       if (VD->isInitCapture())
12884         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12885       QualType CaptureType = VD->getType();
12886       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12887       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12888           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12889           /*EllipsisLoc*/C.isPackExpansion()
12890                          ? C.getEllipsisLoc() : SourceLocation(),
12891           CaptureType, /*Expr*/ nullptr);
12892 
12893     } else if (C.capturesThis()) {
12894       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
12895                               /*Expr*/ nullptr,
12896                               C.getCaptureKind() == LCK_StarThis);
12897     } else {
12898       LSI->addVLATypeCapture(C.getLocation(), I->getType());
12899     }
12900     ++I;
12901   }
12902 }
12903 
12904 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12905                                     SkipBodyInfo *SkipBody) {
12906   if (!D) {
12907     // Parsing the function declaration failed in some way. Push on a fake scope
12908     // anyway so we can try to parse the function body.
12909     PushFunctionScope();
12910     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12911     return D;
12912   }
12913 
12914   FunctionDecl *FD = nullptr;
12915 
12916   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
12917     FD = FunTmpl->getTemplatedDecl();
12918   else
12919     FD = cast<FunctionDecl>(D);
12920 
12921   // Do not push if it is a lambda because one is already pushed when building
12922   // the lambda in ActOnStartOfLambdaDefinition().
12923   if (!isLambdaCallOperator(FD))
12924     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12925 
12926   // Check for defining attributes before the check for redefinition.
12927   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
12928     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
12929     FD->dropAttr<AliasAttr>();
12930     FD->setInvalidDecl();
12931   }
12932   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12933     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12934     FD->dropAttr<IFuncAttr>();
12935     FD->setInvalidDecl();
12936   }
12937 
12938   // See if this is a redefinition. If 'will have body' is already set, then
12939   // these checks were already performed when it was set.
12940   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
12941     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
12942 
12943     // If we're skipping the body, we're done. Don't enter the scope.
12944     if (SkipBody && SkipBody->ShouldSkip)
12945       return D;
12946   }
12947 
12948   // Mark this function as "will have a body eventually".  This lets users to
12949   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12950   // this function.
12951   FD->setWillHaveBody();
12952 
12953   // If we are instantiating a generic lambda call operator, push
12954   // a LambdaScopeInfo onto the function stack.  But use the information
12955   // that's already been calculated (ActOnLambdaExpr) to prime the current
12956   // LambdaScopeInfo.
12957   // When the template operator is being specialized, the LambdaScopeInfo,
12958   // has to be properly restored so that tryCaptureVariable doesn't try
12959   // and capture any new variables. In addition when calculating potential
12960   // captures during transformation of nested lambdas, it is necessary to
12961   // have the LSI properly restored.
12962   if (isGenericLambdaCallOperatorSpecialization(FD)) {
12963     assert(inTemplateInstantiation() &&
12964            "There should be an active template instantiation on the stack "
12965            "when instantiating a generic lambda!");
12966     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12967   } else {
12968     // Enter a new function scope
12969     PushFunctionScope();
12970   }
12971 
12972   // Builtin functions cannot be defined.
12973   if (unsigned BuiltinID = FD->getBuiltinID()) {
12974     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12975         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12976       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12977       FD->setInvalidDecl();
12978     }
12979   }
12980 
12981   // The return type of a function definition must be complete
12982   // (C99 6.9.1p3, C++ [dcl.fct]p6).
12983   QualType ResultType = FD->getReturnType();
12984   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12985       !FD->isInvalidDecl() &&
12986       RequireCompleteType(FD->getLocation(), ResultType,
12987                           diag::err_func_def_incomplete_result))
12988     FD->setInvalidDecl();
12989 
12990   if (FnBodyScope)
12991     PushDeclContext(FnBodyScope, FD);
12992 
12993   // Check the validity of our function parameters
12994   CheckParmsForFunctionDef(FD->parameters(),
12995                            /*CheckParameterNames=*/true);
12996 
12997   // Add non-parameter declarations already in the function to the current
12998   // scope.
12999   if (FnBodyScope) {
13000     for (Decl *NPD : FD->decls()) {
13001       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
13002       if (!NonParmDecl)
13003         continue;
13004       assert(!isa<ParmVarDecl>(NonParmDecl) &&
13005              "parameters should not be in newly created FD yet");
13006 
13007       // If the decl has a name, make it accessible in the current scope.
13008       if (NonParmDecl->getDeclName())
13009         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13010 
13011       // Similarly, dive into enums and fish their constants out, making them
13012       // accessible in this scope.
13013       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13014         for (auto *EI : ED->enumerators())
13015           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13016       }
13017     }
13018   }
13019 
13020   // Introduce our parameters into the function scope
13021   for (auto Param : FD->parameters()) {
13022     Param->setOwningFunction(FD);
13023 
13024     // If this has an identifier, add it to the scope stack.
13025     if (Param->getIdentifier() && FnBodyScope) {
13026       CheckShadow(FnBodyScope, Param);
13027 
13028       PushOnScopeChains(Param, FnBodyScope);
13029     }
13030   }
13031 
13032   // Ensure that the function's exception specification is instantiated.
13033   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13034     ResolveExceptionSpec(D->getLocation(), FPT);
13035 
13036   // dllimport cannot be applied to non-inline function definitions.
13037   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13038       !FD->isTemplateInstantiation()) {
13039     assert(!FD->hasAttr<DLLExportAttr>());
13040     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13041     FD->setInvalidDecl();
13042     return D;
13043   }
13044   // We want to attach documentation to original Decl (which might be
13045   // a function template).
13046   ActOnDocumentableDecl(D);
13047   if (getCurLexicalContext()->isObjCContainer() &&
13048       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13049       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13050     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13051 
13052   return D;
13053 }
13054 
13055 /// Given the set of return statements within a function body,
13056 /// compute the variables that are subject to the named return value
13057 /// optimization.
13058 ///
13059 /// Each of the variables that is subject to the named return value
13060 /// optimization will be marked as NRVO variables in the AST, and any
13061 /// return statement that has a marked NRVO variable as its NRVO candidate can
13062 /// use the named return value optimization.
13063 ///
13064 /// This function applies a very simplistic algorithm for NRVO: if every return
13065 /// statement in the scope of a variable has the same NRVO candidate, that
13066 /// candidate is an NRVO variable.
13067 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13068   ReturnStmt **Returns = Scope->Returns.data();
13069 
13070   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13071     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13072       if (!NRVOCandidate->isNRVOVariable())
13073         Returns[I]->setNRVOCandidate(nullptr);
13074     }
13075   }
13076 }
13077 
13078 bool Sema::canDelayFunctionBody(const Declarator &D) {
13079   // We can't delay parsing the body of a constexpr function template (yet).
13080   if (D.getDeclSpec().isConstexprSpecified())
13081     return false;
13082 
13083   // We can't delay parsing the body of a function template with a deduced
13084   // return type (yet).
13085   if (D.getDeclSpec().hasAutoTypeSpec()) {
13086     // If the placeholder introduces a non-deduced trailing return type,
13087     // we can still delay parsing it.
13088     if (D.getNumTypeObjects()) {
13089       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13090       if (Outer.Kind == DeclaratorChunk::Function &&
13091           Outer.Fun.hasTrailingReturnType()) {
13092         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13093         return Ty.isNull() || !Ty->isUndeducedType();
13094       }
13095     }
13096     return false;
13097   }
13098 
13099   return true;
13100 }
13101 
13102 bool Sema::canSkipFunctionBody(Decl *D) {
13103   // We cannot skip the body of a function (or function template) which is
13104   // constexpr, since we may need to evaluate its body in order to parse the
13105   // rest of the file.
13106   // We cannot skip the body of a function with an undeduced return type,
13107   // because any callers of that function need to know the type.
13108   if (const FunctionDecl *FD = D->getAsFunction()) {
13109     if (FD->isConstexpr())
13110       return false;
13111     // We can't simply call Type::isUndeducedType here, because inside template
13112     // auto can be deduced to a dependent type, which is not considered
13113     // "undeduced".
13114     if (FD->getReturnType()->getContainedDeducedType())
13115       return false;
13116   }
13117   return Consumer.shouldSkipFunctionBody(D);
13118 }
13119 
13120 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13121   if (!Decl)
13122     return nullptr;
13123   if (FunctionDecl *FD = Decl->getAsFunction())
13124     FD->setHasSkippedBody();
13125   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13126     MD->setHasSkippedBody();
13127   return Decl;
13128 }
13129 
13130 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13131   return ActOnFinishFunctionBody(D, BodyArg, false);
13132 }
13133 
13134 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
13135 /// body.
13136 class ExitFunctionBodyRAII {
13137 public:
13138   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
13139   ~ExitFunctionBodyRAII() {
13140     if (!IsLambda)
13141       S.PopExpressionEvaluationContext();
13142   }
13143 
13144 private:
13145   Sema &S;
13146   bool IsLambda = false;
13147 };
13148 
13149 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13150                                     bool IsInstantiation) {
13151   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13152 
13153   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13154   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13155 
13156   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
13157     CheckCompletedCoroutineBody(FD, Body);
13158 
13159   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13160   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13161   // meant to pop the context added in ActOnStartOfFunctionDef().
13162   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13163 
13164   if (FD) {
13165     FD->setBody(Body);
13166     FD->setWillHaveBody(false);
13167 
13168     if (getLangOpts().CPlusPlus14) {
13169       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13170           FD->getReturnType()->isUndeducedType()) {
13171         // If the function has a deduced result type but contains no 'return'
13172         // statements, the result type as written must be exactly 'auto', and
13173         // the deduced result type is 'void'.
13174         if (!FD->getReturnType()->getAs<AutoType>()) {
13175           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13176               << FD->getReturnType();
13177           FD->setInvalidDecl();
13178         } else {
13179           // Substitute 'void' for the 'auto' in the type.
13180           TypeLoc ResultType = getReturnTypeLoc(FD);
13181           Context.adjustDeducedFunctionResultType(
13182               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13183         }
13184       }
13185     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13186       // In C++11, we don't use 'auto' deduction rules for lambda call
13187       // operators because we don't support return type deduction.
13188       auto *LSI = getCurLambda();
13189       if (LSI->HasImplicitReturnType) {
13190         deduceClosureReturnType(*LSI);
13191 
13192         // C++11 [expr.prim.lambda]p4:
13193         //   [...] if there are no return statements in the compound-statement
13194         //   [the deduced type is] the type void
13195         QualType RetType =
13196             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13197 
13198         // Update the return type to the deduced type.
13199         const FunctionProtoType *Proto =
13200             FD->getType()->getAs<FunctionProtoType>();
13201         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13202                                             Proto->getExtProtoInfo()));
13203       }
13204     }
13205 
13206     // If the function implicitly returns zero (like 'main') or is naked,
13207     // don't complain about missing return statements.
13208     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13209       WP.disableCheckFallThrough();
13210 
13211     // MSVC permits the use of pure specifier (=0) on function definition,
13212     // defined at class scope, warn about this non-standard construct.
13213     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
13214       Diag(FD->getLocation(), diag::ext_pure_function_definition);
13215 
13216     if (!FD->isInvalidDecl()) {
13217       // Don't diagnose unused parameters of defaulted or deleted functions.
13218       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13219         DiagnoseUnusedParameters(FD->parameters());
13220       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13221                                              FD->getReturnType(), FD);
13222 
13223       // If this is a structor, we need a vtable.
13224       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13225         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13226       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13227         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13228 
13229       // Try to apply the named return value optimization. We have to check
13230       // if we can do this here because lambdas keep return statements around
13231       // to deduce an implicit return type.
13232       if (FD->getReturnType()->isRecordType() &&
13233           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13234         computeNRVO(Body, getCurFunction());
13235     }
13236 
13237     // GNU warning -Wmissing-prototypes:
13238     //   Warn if a global function is defined without a previous
13239     //   prototype declaration. This warning is issued even if the
13240     //   definition itself provides a prototype. The aim is to detect
13241     //   global functions that fail to be declared in header files.
13242     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
13243     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
13244       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
13245 
13246       if (PossibleZeroParamPrototype) {
13247         // We found a declaration that is not a prototype,
13248         // but that could be a zero-parameter prototype
13249         if (TypeSourceInfo *TI =
13250                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
13251           TypeLoc TL = TI->getTypeLoc();
13252           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
13253             Diag(PossibleZeroParamPrototype->getLocation(),
13254                  diag::note_declaration_not_a_prototype)
13255                 << PossibleZeroParamPrototype
13256                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
13257         }
13258       }
13259 
13260       // GNU warning -Wstrict-prototypes
13261       //   Warn if K&R function is defined without a previous declaration.
13262       //   This warning is issued only if the definition itself does not provide
13263       //   a prototype. Only K&R definitions do not provide a prototype.
13264       //   An empty list in a function declarator that is part of a definition
13265       //   of that function specifies that the function has no parameters
13266       //   (C99 6.7.5.3p14)
13267       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
13268           !LangOpts.CPlusPlus) {
13269         TypeSourceInfo *TI = FD->getTypeSourceInfo();
13270         TypeLoc TL = TI->getTypeLoc();
13271         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
13272         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
13273       }
13274     }
13275 
13276     // Warn on CPUDispatch with an actual body.
13277     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
13278       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
13279         if (!CmpndBody->body_empty())
13280           Diag(CmpndBody->body_front()->getBeginLoc(),
13281                diag::warn_dispatch_body_ignored);
13282 
13283     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13284       const CXXMethodDecl *KeyFunction;
13285       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
13286           MD->isVirtual() &&
13287           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
13288           MD == KeyFunction->getCanonicalDecl()) {
13289         // Update the key-function state if necessary for this ABI.
13290         if (FD->isInlined() &&
13291             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13292           Context.setNonKeyFunction(MD);
13293 
13294           // If the newly-chosen key function is already defined, then we
13295           // need to mark the vtable as used retroactively.
13296           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
13297           const FunctionDecl *Definition;
13298           if (KeyFunction && KeyFunction->isDefined(Definition))
13299             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
13300         } else {
13301           // We just defined they key function; mark the vtable as used.
13302           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
13303         }
13304       }
13305     }
13306 
13307     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
13308            "Function parsing confused");
13309   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
13310     assert(MD == getCurMethodDecl() && "Method parsing confused");
13311     MD->setBody(Body);
13312     if (!MD->isInvalidDecl()) {
13313       if (!MD->hasSkippedBody())
13314         DiagnoseUnusedParameters(MD->parameters());
13315       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
13316                                              MD->getReturnType(), MD);
13317 
13318       if (Body)
13319         computeNRVO(Body, getCurFunction());
13320     }
13321     if (getCurFunction()->ObjCShouldCallSuper) {
13322       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
13323           << MD->getSelector().getAsString();
13324       getCurFunction()->ObjCShouldCallSuper = false;
13325     }
13326     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
13327       const ObjCMethodDecl *InitMethod = nullptr;
13328       bool isDesignated =
13329           MD->isDesignatedInitializerForTheInterface(&InitMethod);
13330       assert(isDesignated && InitMethod);
13331       (void)isDesignated;
13332 
13333       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
13334         auto IFace = MD->getClassInterface();
13335         if (!IFace)
13336           return false;
13337         auto SuperD = IFace->getSuperClass();
13338         if (!SuperD)
13339           return false;
13340         return SuperD->getIdentifier() ==
13341             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
13342       };
13343       // Don't issue this warning for unavailable inits or direct subclasses
13344       // of NSObject.
13345       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
13346         Diag(MD->getLocation(),
13347              diag::warn_objc_designated_init_missing_super_call);
13348         Diag(InitMethod->getLocation(),
13349              diag::note_objc_designated_init_marked_here);
13350       }
13351       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
13352     }
13353     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
13354       // Don't issue this warning for unavaialable inits.
13355       if (!MD->isUnavailable())
13356         Diag(MD->getLocation(),
13357              diag::warn_objc_secondary_init_missing_init_call);
13358       getCurFunction()->ObjCWarnForNoInitDelegation = false;
13359     }
13360   } else {
13361     // Parsing the function declaration failed in some way. Pop the fake scope
13362     // we pushed on.
13363     PopFunctionScopeInfo(ActivePolicy, dcl);
13364     return nullptr;
13365   }
13366 
13367   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13368     DiagnoseUnguardedAvailabilityViolations(dcl);
13369 
13370   assert(!getCurFunction()->ObjCShouldCallSuper &&
13371          "This should only be set for ObjC methods, which should have been "
13372          "handled in the block above.");
13373 
13374   // Verify and clean out per-function state.
13375   if (Body && (!FD || !FD->isDefaulted())) {
13376     // C++ constructors that have function-try-blocks can't have return
13377     // statements in the handlers of that block. (C++ [except.handle]p14)
13378     // Verify this.
13379     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
13380       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
13381 
13382     // Verify that gotos and switch cases don't jump into scopes illegally.
13383     if (getCurFunction()->NeedsScopeChecking() &&
13384         !PP.isCodeCompletionEnabled())
13385       DiagnoseInvalidJumps(Body);
13386 
13387     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
13388       if (!Destructor->getParent()->isDependentType())
13389         CheckDestructor(Destructor);
13390 
13391       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13392                                              Destructor->getParent());
13393     }
13394 
13395     // If any errors have occurred, clear out any temporaries that may have
13396     // been leftover. This ensures that these temporaries won't be picked up for
13397     // deletion in some later function.
13398     if (getDiagnostics().hasErrorOccurred() ||
13399         getDiagnostics().getSuppressAllDiagnostics()) {
13400       DiscardCleanupsInEvaluationContext();
13401     }
13402     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
13403         !isa<FunctionTemplateDecl>(dcl)) {
13404       // Since the body is valid, issue any analysis-based warnings that are
13405       // enabled.
13406       ActivePolicy = &WP;
13407     }
13408 
13409     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
13410         (!CheckConstexprFunctionDecl(FD) ||
13411          !CheckConstexprFunctionBody(FD, Body)))
13412       FD->setInvalidDecl();
13413 
13414     if (FD && FD->hasAttr<NakedAttr>()) {
13415       for (const Stmt *S : Body->children()) {
13416         // Allow local register variables without initializer as they don't
13417         // require prologue.
13418         bool RegisterVariables = false;
13419         if (auto *DS = dyn_cast<DeclStmt>(S)) {
13420           for (const auto *Decl : DS->decls()) {
13421             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
13422               RegisterVariables =
13423                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
13424               if (!RegisterVariables)
13425                 break;
13426             }
13427           }
13428         }
13429         if (RegisterVariables)
13430           continue;
13431         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
13432           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
13433           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
13434           FD->setInvalidDecl();
13435           break;
13436         }
13437       }
13438     }
13439 
13440     assert(ExprCleanupObjects.size() ==
13441                ExprEvalContexts.back().NumCleanupObjects &&
13442            "Leftover temporaries in function");
13443     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
13444     assert(MaybeODRUseExprs.empty() &&
13445            "Leftover expressions for odr-use checking");
13446   }
13447 
13448   if (!IsInstantiation)
13449     PopDeclContext();
13450 
13451   PopFunctionScopeInfo(ActivePolicy, dcl);
13452   // If any errors have occurred, clear out any temporaries that may have
13453   // been leftover. This ensures that these temporaries won't be picked up for
13454   // deletion in some later function.
13455   if (getDiagnostics().hasErrorOccurred()) {
13456     DiscardCleanupsInEvaluationContext();
13457   }
13458 
13459   return dcl;
13460 }
13461 
13462 /// When we finish delayed parsing of an attribute, we must attach it to the
13463 /// relevant Decl.
13464 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
13465                                        ParsedAttributes &Attrs) {
13466   // Always attach attributes to the underlying decl.
13467   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
13468     D = TD->getTemplatedDecl();
13469   ProcessDeclAttributeList(S, D, Attrs);
13470 
13471   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
13472     if (Method->isStatic())
13473       checkThisInStaticMemberFunctionAttributes(Method);
13474 }
13475 
13476 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
13477 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
13478 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
13479                                           IdentifierInfo &II, Scope *S) {
13480   // Find the scope in which the identifier is injected and the corresponding
13481   // DeclContext.
13482   // FIXME: C89 does not say what happens if there is no enclosing block scope.
13483   // In that case, we inject the declaration into the translation unit scope
13484   // instead.
13485   Scope *BlockScope = S;
13486   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
13487     BlockScope = BlockScope->getParent();
13488 
13489   Scope *ContextScope = BlockScope;
13490   while (!ContextScope->getEntity())
13491     ContextScope = ContextScope->getParent();
13492   ContextRAII SavedContext(*this, ContextScope->getEntity());
13493 
13494   // Before we produce a declaration for an implicitly defined
13495   // function, see whether there was a locally-scoped declaration of
13496   // this name as a function or variable. If so, use that
13497   // (non-visible) declaration, and complain about it.
13498   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
13499   if (ExternCPrev) {
13500     // We still need to inject the function into the enclosing block scope so
13501     // that later (non-call) uses can see it.
13502     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
13503 
13504     // C89 footnote 38:
13505     //   If in fact it is not defined as having type "function returning int",
13506     //   the behavior is undefined.
13507     if (!isa<FunctionDecl>(ExternCPrev) ||
13508         !Context.typesAreCompatible(
13509             cast<FunctionDecl>(ExternCPrev)->getType(),
13510             Context.getFunctionNoProtoType(Context.IntTy))) {
13511       Diag(Loc, diag::ext_use_out_of_scope_declaration)
13512           << ExternCPrev << !getLangOpts().C99;
13513       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
13514       return ExternCPrev;
13515     }
13516   }
13517 
13518   // Extension in C99.  Legal in C90, but warn about it.
13519   unsigned diag_id;
13520   if (II.getName().startswith("__builtin_"))
13521     diag_id = diag::warn_builtin_unknown;
13522   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
13523   else if (getLangOpts().OpenCL)
13524     diag_id = diag::err_opencl_implicit_function_decl;
13525   else if (getLangOpts().C99)
13526     diag_id = diag::ext_implicit_function_decl;
13527   else
13528     diag_id = diag::warn_implicit_function_decl;
13529   Diag(Loc, diag_id) << &II;
13530 
13531   // If we found a prior declaration of this function, don't bother building
13532   // another one. We've already pushed that one into scope, so there's nothing
13533   // more to do.
13534   if (ExternCPrev)
13535     return ExternCPrev;
13536 
13537   // Because typo correction is expensive, only do it if the implicit
13538   // function declaration is going to be treated as an error.
13539   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
13540     TypoCorrection Corrected;
13541     if (S &&
13542         (Corrected = CorrectTypo(
13543              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
13544              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
13545       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
13546                    /*ErrorRecovery*/false);
13547   }
13548 
13549   // Set a Declarator for the implicit definition: int foo();
13550   const char *Dummy;
13551   AttributeFactory attrFactory;
13552   DeclSpec DS(attrFactory);
13553   unsigned DiagID;
13554   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
13555                                   Context.getPrintingPolicy());
13556   (void)Error; // Silence warning.
13557   assert(!Error && "Error setting up implicit decl!");
13558   SourceLocation NoLoc;
13559   Declarator D(DS, DeclaratorContext::BlockContext);
13560   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
13561                                              /*IsAmbiguous=*/false,
13562                                              /*LParenLoc=*/NoLoc,
13563                                              /*Params=*/nullptr,
13564                                              /*NumParams=*/0,
13565                                              /*EllipsisLoc=*/NoLoc,
13566                                              /*RParenLoc=*/NoLoc,
13567                                              /*RefQualifierIsLvalueRef=*/true,
13568                                              /*RefQualifierLoc=*/NoLoc,
13569                                              /*MutableLoc=*/NoLoc, EST_None,
13570                                              /*ESpecRange=*/SourceRange(),
13571                                              /*Exceptions=*/nullptr,
13572                                              /*ExceptionRanges=*/nullptr,
13573                                              /*NumExceptions=*/0,
13574                                              /*NoexceptExpr=*/nullptr,
13575                                              /*ExceptionSpecTokens=*/nullptr,
13576                                              /*DeclsInPrototype=*/None, Loc,
13577                                              Loc, D),
13578                 std::move(DS.getAttributes()), SourceLocation());
13579   D.SetIdentifier(&II, Loc);
13580 
13581   // Insert this function into the enclosing block scope.
13582   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
13583   FD->setImplicit();
13584 
13585   AddKnownFunctionAttributes(FD);
13586 
13587   return FD;
13588 }
13589 
13590 /// Adds any function attributes that we know a priori based on
13591 /// the declaration of this function.
13592 ///
13593 /// These attributes can apply both to implicitly-declared builtins
13594 /// (like __builtin___printf_chk) or to library-declared functions
13595 /// like NSLog or printf.
13596 ///
13597 /// We need to check for duplicate attributes both here and where user-written
13598 /// attributes are applied to declarations.
13599 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
13600   if (FD->isInvalidDecl())
13601     return;
13602 
13603   // If this is a built-in function, map its builtin attributes to
13604   // actual attributes.
13605   if (unsigned BuiltinID = FD->getBuiltinID()) {
13606     // Handle printf-formatting attributes.
13607     unsigned FormatIdx;
13608     bool HasVAListArg;
13609     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
13610       if (!FD->hasAttr<FormatAttr>()) {
13611         const char *fmt = "printf";
13612         unsigned int NumParams = FD->getNumParams();
13613         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
13614             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
13615           fmt = "NSString";
13616         FD->addAttr(FormatAttr::CreateImplicit(Context,
13617                                                &Context.Idents.get(fmt),
13618                                                FormatIdx+1,
13619                                                HasVAListArg ? 0 : FormatIdx+2,
13620                                                FD->getLocation()));
13621       }
13622     }
13623     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
13624                                              HasVAListArg)) {
13625      if (!FD->hasAttr<FormatAttr>())
13626        FD->addAttr(FormatAttr::CreateImplicit(Context,
13627                                               &Context.Idents.get("scanf"),
13628                                               FormatIdx+1,
13629                                               HasVAListArg ? 0 : FormatIdx+2,
13630                                               FD->getLocation()));
13631     }
13632 
13633     // Handle automatically recognized callbacks.
13634     SmallVector<int, 4> Encoding;
13635     if (!FD->hasAttr<CallbackAttr>() &&
13636         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
13637       FD->addAttr(CallbackAttr::CreateImplicit(
13638           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
13639 
13640     // Mark const if we don't care about errno and that is the only thing
13641     // preventing the function from being const. This allows IRgen to use LLVM
13642     // intrinsics for such functions.
13643     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
13644         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
13645       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13646 
13647     // We make "fma" on some platforms const because we know it does not set
13648     // errno in those environments even though it could set errno based on the
13649     // C standard.
13650     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
13651     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
13652         !FD->hasAttr<ConstAttr>()) {
13653       switch (BuiltinID) {
13654       case Builtin::BI__builtin_fma:
13655       case Builtin::BI__builtin_fmaf:
13656       case Builtin::BI__builtin_fmal:
13657       case Builtin::BIfma:
13658       case Builtin::BIfmaf:
13659       case Builtin::BIfmal:
13660         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13661         break;
13662       default:
13663         break;
13664       }
13665     }
13666 
13667     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
13668         !FD->hasAttr<ReturnsTwiceAttr>())
13669       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
13670                                          FD->getLocation()));
13671     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
13672       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13673     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
13674       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
13675     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
13676       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13677     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
13678         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
13679       // Add the appropriate attribute, depending on the CUDA compilation mode
13680       // and which target the builtin belongs to. For example, during host
13681       // compilation, aux builtins are __device__, while the rest are __host__.
13682       if (getLangOpts().CUDAIsDevice !=
13683           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
13684         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
13685       else
13686         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
13687     }
13688   }
13689 
13690   // If C++ exceptions are enabled but we are told extern "C" functions cannot
13691   // throw, add an implicit nothrow attribute to any extern "C" function we come
13692   // across.
13693   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
13694       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
13695     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
13696     if (!FPT || FPT->getExceptionSpecType() == EST_None)
13697       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13698   }
13699 
13700   IdentifierInfo *Name = FD->getIdentifier();
13701   if (!Name)
13702     return;
13703   if ((!getLangOpts().CPlusPlus &&
13704        FD->getDeclContext()->isTranslationUnit()) ||
13705       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
13706        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
13707        LinkageSpecDecl::lang_c)) {
13708     // Okay: this could be a libc/libm/Objective-C function we know
13709     // about.
13710   } else
13711     return;
13712 
13713   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
13714     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
13715     // target-specific builtins, perhaps?
13716     if (!FD->hasAttr<FormatAttr>())
13717       FD->addAttr(FormatAttr::CreateImplicit(Context,
13718                                              &Context.Idents.get("printf"), 2,
13719                                              Name->isStr("vasprintf") ? 0 : 3,
13720                                              FD->getLocation()));
13721   }
13722 
13723   if (Name->isStr("__CFStringMakeConstantString")) {
13724     // We already have a __builtin___CFStringMakeConstantString,
13725     // but builds that use -fno-constant-cfstrings don't go through that.
13726     if (!FD->hasAttr<FormatArgAttr>())
13727       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
13728                                                 FD->getLocation()));
13729   }
13730 }
13731 
13732 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
13733                                     TypeSourceInfo *TInfo) {
13734   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
13735   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
13736 
13737   if (!TInfo) {
13738     assert(D.isInvalidType() && "no declarator info for valid type");
13739     TInfo = Context.getTrivialTypeSourceInfo(T);
13740   }
13741 
13742   // Scope manipulation handled by caller.
13743   TypedefDecl *NewTD =
13744       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
13745                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
13746 
13747   // Bail out immediately if we have an invalid declaration.
13748   if (D.isInvalidType()) {
13749     NewTD->setInvalidDecl();
13750     return NewTD;
13751   }
13752 
13753   if (D.getDeclSpec().isModulePrivateSpecified()) {
13754     if (CurContext->isFunctionOrMethod())
13755       Diag(NewTD->getLocation(), diag::err_module_private_local)
13756         << 2 << NewTD->getDeclName()
13757         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13758         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13759     else
13760       NewTD->setModulePrivate();
13761   }
13762 
13763   // C++ [dcl.typedef]p8:
13764   //   If the typedef declaration defines an unnamed class (or
13765   //   enum), the first typedef-name declared by the declaration
13766   //   to be that class type (or enum type) is used to denote the
13767   //   class type (or enum type) for linkage purposes only.
13768   // We need to check whether the type was declared in the declaration.
13769   switch (D.getDeclSpec().getTypeSpecType()) {
13770   case TST_enum:
13771   case TST_struct:
13772   case TST_interface:
13773   case TST_union:
13774   case TST_class: {
13775     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
13776     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
13777     break;
13778   }
13779 
13780   default:
13781     break;
13782   }
13783 
13784   return NewTD;
13785 }
13786 
13787 /// Check that this is a valid underlying type for an enum declaration.
13788 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
13789   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
13790   QualType T = TI->getType();
13791 
13792   if (T->isDependentType())
13793     return false;
13794 
13795   if (const BuiltinType *BT = T->getAs<BuiltinType>())
13796     if (BT->isInteger())
13797       return false;
13798 
13799   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
13800   return true;
13801 }
13802 
13803 /// Check whether this is a valid redeclaration of a previous enumeration.
13804 /// \return true if the redeclaration was invalid.
13805 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
13806                                   QualType EnumUnderlyingTy, bool IsFixed,
13807                                   const EnumDecl *Prev) {
13808   if (IsScoped != Prev->isScoped()) {
13809     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
13810       << Prev->isScoped();
13811     Diag(Prev->getLocation(), diag::note_previous_declaration);
13812     return true;
13813   }
13814 
13815   if (IsFixed && Prev->isFixed()) {
13816     if (!EnumUnderlyingTy->isDependentType() &&
13817         !Prev->getIntegerType()->isDependentType() &&
13818         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
13819                                         Prev->getIntegerType())) {
13820       // TODO: Highlight the underlying type of the redeclaration.
13821       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
13822         << EnumUnderlyingTy << Prev->getIntegerType();
13823       Diag(Prev->getLocation(), diag::note_previous_declaration)
13824           << Prev->getIntegerTypeRange();
13825       return true;
13826     }
13827   } else if (IsFixed != Prev->isFixed()) {
13828     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
13829       << Prev->isFixed();
13830     Diag(Prev->getLocation(), diag::note_previous_declaration);
13831     return true;
13832   }
13833 
13834   return false;
13835 }
13836 
13837 /// Get diagnostic %select index for tag kind for
13838 /// redeclaration diagnostic message.
13839 /// WARNING: Indexes apply to particular diagnostics only!
13840 ///
13841 /// \returns diagnostic %select index.
13842 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
13843   switch (Tag) {
13844   case TTK_Struct: return 0;
13845   case TTK_Interface: return 1;
13846   case TTK_Class:  return 2;
13847   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
13848   }
13849 }
13850 
13851 /// Determine if tag kind is a class-key compatible with
13852 /// class for redeclaration (class, struct, or __interface).
13853 ///
13854 /// \returns true iff the tag kind is compatible.
13855 static bool isClassCompatTagKind(TagTypeKind Tag)
13856 {
13857   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
13858 }
13859 
13860 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
13861                                              TagTypeKind TTK) {
13862   if (isa<TypedefDecl>(PrevDecl))
13863     return NTK_Typedef;
13864   else if (isa<TypeAliasDecl>(PrevDecl))
13865     return NTK_TypeAlias;
13866   else if (isa<ClassTemplateDecl>(PrevDecl))
13867     return NTK_Template;
13868   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
13869     return NTK_TypeAliasTemplate;
13870   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
13871     return NTK_TemplateTemplateArgument;
13872   switch (TTK) {
13873   case TTK_Struct:
13874   case TTK_Interface:
13875   case TTK_Class:
13876     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
13877   case TTK_Union:
13878     return NTK_NonUnion;
13879   case TTK_Enum:
13880     return NTK_NonEnum;
13881   }
13882   llvm_unreachable("invalid TTK");
13883 }
13884 
13885 /// Determine whether a tag with a given kind is acceptable
13886 /// as a redeclaration of the given tag declaration.
13887 ///
13888 /// \returns true if the new tag kind is acceptable, false otherwise.
13889 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
13890                                         TagTypeKind NewTag, bool isDefinition,
13891                                         SourceLocation NewTagLoc,
13892                                         const IdentifierInfo *Name) {
13893   // C++ [dcl.type.elab]p3:
13894   //   The class-key or enum keyword present in the
13895   //   elaborated-type-specifier shall agree in kind with the
13896   //   declaration to which the name in the elaborated-type-specifier
13897   //   refers. This rule also applies to the form of
13898   //   elaborated-type-specifier that declares a class-name or
13899   //   friend class since it can be construed as referring to the
13900   //   definition of the class. Thus, in any
13901   //   elaborated-type-specifier, the enum keyword shall be used to
13902   //   refer to an enumeration (7.2), the union class-key shall be
13903   //   used to refer to a union (clause 9), and either the class or
13904   //   struct class-key shall be used to refer to a class (clause 9)
13905   //   declared using the class or struct class-key.
13906   TagTypeKind OldTag = Previous->getTagKind();
13907   if (OldTag != NewTag &&
13908       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
13909     return false;
13910 
13911   // Tags are compatible, but we might still want to warn on mismatched tags.
13912   // Non-class tags can't be mismatched at this point.
13913   if (!isClassCompatTagKind(NewTag))
13914     return true;
13915 
13916   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
13917   // by our warning analysis. We don't want to warn about mismatches with (eg)
13918   // declarations in system headers that are designed to be specialized, but if
13919   // a user asks us to warn, we should warn if their code contains mismatched
13920   // declarations.
13921   auto IsIgnoredLoc = [&](SourceLocation Loc) {
13922     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
13923                                       Loc);
13924   };
13925   if (IsIgnoredLoc(NewTagLoc))
13926     return true;
13927 
13928   auto IsIgnored = [&](const TagDecl *Tag) {
13929     return IsIgnoredLoc(Tag->getLocation());
13930   };
13931   while (IsIgnored(Previous)) {
13932     Previous = Previous->getPreviousDecl();
13933     if (!Previous)
13934       return true;
13935     OldTag = Previous->getTagKind();
13936   }
13937 
13938   bool isTemplate = false;
13939   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
13940     isTemplate = Record->getDescribedClassTemplate();
13941 
13942   if (inTemplateInstantiation()) {
13943     if (OldTag != NewTag) {
13944       // In a template instantiation, do not offer fix-its for tag mismatches
13945       // since they usually mess up the template instead of fixing the problem.
13946       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13947         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13948         << getRedeclDiagFromTagKind(OldTag);
13949       // FIXME: Note previous location?
13950     }
13951     return true;
13952   }
13953 
13954   if (isDefinition) {
13955     // On definitions, check all previous tags and issue a fix-it for each
13956     // one that doesn't match the current tag.
13957     if (Previous->getDefinition()) {
13958       // Don't suggest fix-its for redefinitions.
13959       return true;
13960     }
13961 
13962     bool previousMismatch = false;
13963     for (const TagDecl *I : Previous->redecls()) {
13964       if (I->getTagKind() != NewTag) {
13965         // Ignore previous declarations for which the warning was disabled.
13966         if (IsIgnored(I))
13967           continue;
13968 
13969         if (!previousMismatch) {
13970           previousMismatch = true;
13971           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
13972             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13973             << getRedeclDiagFromTagKind(I->getTagKind());
13974         }
13975         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
13976           << getRedeclDiagFromTagKind(NewTag)
13977           << FixItHint::CreateReplacement(I->getInnerLocStart(),
13978                TypeWithKeyword::getTagTypeKindName(NewTag));
13979       }
13980     }
13981     return true;
13982   }
13983 
13984   // Identify the prevailing tag kind: this is the kind of the definition (if
13985   // there is a non-ignored definition), or otherwise the kind of the prior
13986   // (non-ignored) declaration.
13987   const TagDecl *PrevDef = Previous->getDefinition();
13988   if (PrevDef && IsIgnored(PrevDef))
13989     PrevDef = nullptr;
13990   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
13991   if (Redecl->getTagKind() != NewTag) {
13992     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13993       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13994       << getRedeclDiagFromTagKind(OldTag);
13995     Diag(Redecl->getLocation(), diag::note_previous_use);
13996 
13997     // If there is a previous definition, suggest a fix-it.
13998     if (PrevDef) {
13999       Diag(NewTagLoc, diag::note_struct_class_suggestion)
14000         << getRedeclDiagFromTagKind(Redecl->getTagKind())
14001         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
14002              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
14003     }
14004   }
14005 
14006   return true;
14007 }
14008 
14009 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
14010 /// from an outer enclosing namespace or file scope inside a friend declaration.
14011 /// This should provide the commented out code in the following snippet:
14012 ///   namespace N {
14013 ///     struct X;
14014 ///     namespace M {
14015 ///       struct Y { friend struct /*N::*/ X; };
14016 ///     }
14017 ///   }
14018 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
14019                                          SourceLocation NameLoc) {
14020   // While the decl is in a namespace, do repeated lookup of that name and see
14021   // if we get the same namespace back.  If we do not, continue until
14022   // translation unit scope, at which point we have a fully qualified NNS.
14023   SmallVector<IdentifierInfo *, 4> Namespaces;
14024   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14025   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
14026     // This tag should be declared in a namespace, which can only be enclosed by
14027     // other namespaces.  Bail if there's an anonymous namespace in the chain.
14028     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
14029     if (!Namespace || Namespace->isAnonymousNamespace())
14030       return FixItHint();
14031     IdentifierInfo *II = Namespace->getIdentifier();
14032     Namespaces.push_back(II);
14033     NamedDecl *Lookup = SemaRef.LookupSingleName(
14034         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
14035     if (Lookup == Namespace)
14036       break;
14037   }
14038 
14039   // Once we have all the namespaces, reverse them to go outermost first, and
14040   // build an NNS.
14041   SmallString<64> Insertion;
14042   llvm::raw_svector_ostream OS(Insertion);
14043   if (DC->isTranslationUnit())
14044     OS << "::";
14045   std::reverse(Namespaces.begin(), Namespaces.end());
14046   for (auto *II : Namespaces)
14047     OS << II->getName() << "::";
14048   return FixItHint::CreateInsertion(NameLoc, Insertion);
14049 }
14050 
14051 /// Determine whether a tag originally declared in context \p OldDC can
14052 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14053 /// found a declaration in \p OldDC as a previous decl, perhaps through a
14054 /// using-declaration).
14055 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
14056                                          DeclContext *NewDC) {
14057   OldDC = OldDC->getRedeclContext();
14058   NewDC = NewDC->getRedeclContext();
14059 
14060   if (OldDC->Equals(NewDC))
14061     return true;
14062 
14063   // In MSVC mode, we allow a redeclaration if the contexts are related (either
14064   // encloses the other).
14065   if (S.getLangOpts().MSVCCompat &&
14066       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14067     return true;
14068 
14069   return false;
14070 }
14071 
14072 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
14073 /// former case, Name will be non-null.  In the later case, Name will be null.
14074 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14075 /// reference/declaration/definition of a tag.
14076 ///
14077 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
14078 /// trailing-type-specifier) other than one in an alias-declaration.
14079 ///
14080 /// \param SkipBody If non-null, will be set to indicate if the caller should
14081 /// skip the definition of this tag and treat it as if it were a declaration.
14082 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
14083                      SourceLocation KWLoc, CXXScopeSpec &SS,
14084                      IdentifierInfo *Name, SourceLocation NameLoc,
14085                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
14086                      SourceLocation ModulePrivateLoc,
14087                      MultiTemplateParamsArg TemplateParameterLists,
14088                      bool &OwnedDecl, bool &IsDependent,
14089                      SourceLocation ScopedEnumKWLoc,
14090                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
14091                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
14092                      SkipBodyInfo *SkipBody) {
14093   // If this is not a definition, it must have a name.
14094   IdentifierInfo *OrigName = Name;
14095   assert((Name != nullptr || TUK == TUK_Definition) &&
14096          "Nameless record must be a definition!");
14097   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14098 
14099   OwnedDecl = false;
14100   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14101   bool ScopedEnum = ScopedEnumKWLoc.isValid();
14102 
14103   // FIXME: Check member specializations more carefully.
14104   bool isMemberSpecialization = false;
14105   bool Invalid = false;
14106 
14107   // We only need to do this matching if we have template parameters
14108   // or a scope specifier, which also conveniently avoids this work
14109   // for non-C++ cases.
14110   if (TemplateParameterLists.size() > 0 ||
14111       (SS.isNotEmpty() && TUK != TUK_Reference)) {
14112     if (TemplateParameterList *TemplateParams =
14113             MatchTemplateParametersToScopeSpecifier(
14114                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14115                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14116       if (Kind == TTK_Enum) {
14117         Diag(KWLoc, diag::err_enum_template);
14118         return nullptr;
14119       }
14120 
14121       if (TemplateParams->size() > 0) {
14122         // This is a declaration or definition of a class template (which may
14123         // be a member of another template).
14124 
14125         if (Invalid)
14126           return nullptr;
14127 
14128         OwnedDecl = false;
14129         DeclResult Result = CheckClassTemplate(
14130             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14131             AS, ModulePrivateLoc,
14132             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14133             TemplateParameterLists.data(), SkipBody);
14134         return Result.get();
14135       } else {
14136         // The "template<>" header is extraneous.
14137         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14138           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14139         isMemberSpecialization = true;
14140       }
14141     }
14142   }
14143 
14144   // Figure out the underlying type if this a enum declaration. We need to do
14145   // this early, because it's needed to detect if this is an incompatible
14146   // redeclaration.
14147   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14148   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14149 
14150   if (Kind == TTK_Enum) {
14151     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14152       // No underlying type explicitly specified, or we failed to parse the
14153       // type, default to int.
14154       EnumUnderlying = Context.IntTy.getTypePtr();
14155     } else if (UnderlyingType.get()) {
14156       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14157       // integral type; any cv-qualification is ignored.
14158       TypeSourceInfo *TI = nullptr;
14159       GetTypeFromParser(UnderlyingType.get(), &TI);
14160       EnumUnderlying = TI;
14161 
14162       if (CheckEnumUnderlyingType(TI))
14163         // Recover by falling back to int.
14164         EnumUnderlying = Context.IntTy.getTypePtr();
14165 
14166       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14167                                           UPPC_FixedUnderlyingType))
14168         EnumUnderlying = Context.IntTy.getTypePtr();
14169 
14170     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14171       // For MSVC ABI compatibility, unfixed enums must use an underlying type
14172       // of 'int'. However, if this is an unfixed forward declaration, don't set
14173       // the underlying type unless the user enables -fms-compatibility. This
14174       // makes unfixed forward declared enums incomplete and is more conforming.
14175       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14176         EnumUnderlying = Context.IntTy.getTypePtr();
14177     }
14178   }
14179 
14180   DeclContext *SearchDC = CurContext;
14181   DeclContext *DC = CurContext;
14182   bool isStdBadAlloc = false;
14183   bool isStdAlignValT = false;
14184 
14185   RedeclarationKind Redecl = forRedeclarationInCurContext();
14186   if (TUK == TUK_Friend || TUK == TUK_Reference)
14187     Redecl = NotForRedeclaration;
14188 
14189   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14190   /// implemented asks for structural equivalence checking, the returned decl
14191   /// here is passed back to the parser, allowing the tag body to be parsed.
14192   auto createTagFromNewDecl = [&]() -> TagDecl * {
14193     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14194     // If there is an identifier, use the location of the identifier as the
14195     // location of the decl, otherwise use the location of the struct/union
14196     // keyword.
14197     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14198     TagDecl *New = nullptr;
14199 
14200     if (Kind == TTK_Enum) {
14201       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14202                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14203       // If this is an undefined enum, bail.
14204       if (TUK != TUK_Definition && !Invalid)
14205         return nullptr;
14206       if (EnumUnderlying) {
14207         EnumDecl *ED = cast<EnumDecl>(New);
14208         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14209           ED->setIntegerTypeSourceInfo(TI);
14210         else
14211           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14212         ED->setPromotionType(ED->getIntegerType());
14213       }
14214     } else { // struct/union
14215       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14216                                nullptr);
14217     }
14218 
14219     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14220       // Add alignment attributes if necessary; these attributes are checked
14221       // when the ASTContext lays out the structure.
14222       //
14223       // It is important for implementing the correct semantics that this
14224       // happen here (in ActOnTag). The #pragma pack stack is
14225       // maintained as a result of parser callbacks which can occur at
14226       // many points during the parsing of a struct declaration (because
14227       // the #pragma tokens are effectively skipped over during the
14228       // parsing of the struct).
14229       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14230         AddAlignmentAttributesForRecord(RD);
14231         AddMsStructLayoutForRecord(RD);
14232       }
14233     }
14234     New->setLexicalDeclContext(CurContext);
14235     return New;
14236   };
14237 
14238   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
14239   if (Name && SS.isNotEmpty()) {
14240     // We have a nested-name tag ('struct foo::bar').
14241 
14242     // Check for invalid 'foo::'.
14243     if (SS.isInvalid()) {
14244       Name = nullptr;
14245       goto CreateNewDecl;
14246     }
14247 
14248     // If this is a friend or a reference to a class in a dependent
14249     // context, don't try to make a decl for it.
14250     if (TUK == TUK_Friend || TUK == TUK_Reference) {
14251       DC = computeDeclContext(SS, false);
14252       if (!DC) {
14253         IsDependent = true;
14254         return nullptr;
14255       }
14256     } else {
14257       DC = computeDeclContext(SS, true);
14258       if (!DC) {
14259         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
14260           << SS.getRange();
14261         return nullptr;
14262       }
14263     }
14264 
14265     if (RequireCompleteDeclContext(SS, DC))
14266       return nullptr;
14267 
14268     SearchDC = DC;
14269     // Look-up name inside 'foo::'.
14270     LookupQualifiedName(Previous, DC);
14271 
14272     if (Previous.isAmbiguous())
14273       return nullptr;
14274 
14275     if (Previous.empty()) {
14276       // Name lookup did not find anything. However, if the
14277       // nested-name-specifier refers to the current instantiation,
14278       // and that current instantiation has any dependent base
14279       // classes, we might find something at instantiation time: treat
14280       // this as a dependent elaborated-type-specifier.
14281       // But this only makes any sense for reference-like lookups.
14282       if (Previous.wasNotFoundInCurrentInstantiation() &&
14283           (TUK == TUK_Reference || TUK == TUK_Friend)) {
14284         IsDependent = true;
14285         return nullptr;
14286       }
14287 
14288       // A tag 'foo::bar' must already exist.
14289       Diag(NameLoc, diag::err_not_tag_in_scope)
14290         << Kind << Name << DC << SS.getRange();
14291       Name = nullptr;
14292       Invalid = true;
14293       goto CreateNewDecl;
14294     }
14295   } else if (Name) {
14296     // C++14 [class.mem]p14:
14297     //   If T is the name of a class, then each of the following shall have a
14298     //   name different from T:
14299     //    -- every member of class T that is itself a type
14300     if (TUK != TUK_Reference && TUK != TUK_Friend &&
14301         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
14302       return nullptr;
14303 
14304     // If this is a named struct, check to see if there was a previous forward
14305     // declaration or definition.
14306     // FIXME: We're looking into outer scopes here, even when we
14307     // shouldn't be. Doing so can result in ambiguities that we
14308     // shouldn't be diagnosing.
14309     LookupName(Previous, S);
14310 
14311     // When declaring or defining a tag, ignore ambiguities introduced
14312     // by types using'ed into this scope.
14313     if (Previous.isAmbiguous() &&
14314         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
14315       LookupResult::Filter F = Previous.makeFilter();
14316       while (F.hasNext()) {
14317         NamedDecl *ND = F.next();
14318         if (!ND->getDeclContext()->getRedeclContext()->Equals(
14319                 SearchDC->getRedeclContext()))
14320           F.erase();
14321       }
14322       F.done();
14323     }
14324 
14325     // C++11 [namespace.memdef]p3:
14326     //   If the name in a friend declaration is neither qualified nor
14327     //   a template-id and the declaration is a function or an
14328     //   elaborated-type-specifier, the lookup to determine whether
14329     //   the entity has been previously declared shall not consider
14330     //   any scopes outside the innermost enclosing namespace.
14331     //
14332     // MSVC doesn't implement the above rule for types, so a friend tag
14333     // declaration may be a redeclaration of a type declared in an enclosing
14334     // scope.  They do implement this rule for friend functions.
14335     //
14336     // Does it matter that this should be by scope instead of by
14337     // semantic context?
14338     if (!Previous.empty() && TUK == TUK_Friend) {
14339       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
14340       LookupResult::Filter F = Previous.makeFilter();
14341       bool FriendSawTagOutsideEnclosingNamespace = false;
14342       while (F.hasNext()) {
14343         NamedDecl *ND = F.next();
14344         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14345         if (DC->isFileContext() &&
14346             !EnclosingNS->Encloses(ND->getDeclContext())) {
14347           if (getLangOpts().MSVCCompat)
14348             FriendSawTagOutsideEnclosingNamespace = true;
14349           else
14350             F.erase();
14351         }
14352       }
14353       F.done();
14354 
14355       // Diagnose this MSVC extension in the easy case where lookup would have
14356       // unambiguously found something outside the enclosing namespace.
14357       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
14358         NamedDecl *ND = Previous.getFoundDecl();
14359         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
14360             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
14361       }
14362     }
14363 
14364     // Note:  there used to be some attempt at recovery here.
14365     if (Previous.isAmbiguous())
14366       return nullptr;
14367 
14368     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
14369       // FIXME: This makes sure that we ignore the contexts associated
14370       // with C structs, unions, and enums when looking for a matching
14371       // tag declaration or definition. See the similar lookup tweak
14372       // in Sema::LookupName; is there a better way to deal with this?
14373       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
14374         SearchDC = SearchDC->getParent();
14375     }
14376   }
14377 
14378   if (Previous.isSingleResult() &&
14379       Previous.getFoundDecl()->isTemplateParameter()) {
14380     // Maybe we will complain about the shadowed template parameter.
14381     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
14382     // Just pretend that we didn't see the previous declaration.
14383     Previous.clear();
14384   }
14385 
14386   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
14387       DC->Equals(getStdNamespace())) {
14388     if (Name->isStr("bad_alloc")) {
14389       // This is a declaration of or a reference to "std::bad_alloc".
14390       isStdBadAlloc = true;
14391 
14392       // If std::bad_alloc has been implicitly declared (but made invisible to
14393       // name lookup), fill in this implicit declaration as the previous
14394       // declaration, so that the declarations get chained appropriately.
14395       if (Previous.empty() && StdBadAlloc)
14396         Previous.addDecl(getStdBadAlloc());
14397     } else if (Name->isStr("align_val_t")) {
14398       isStdAlignValT = true;
14399       if (Previous.empty() && StdAlignValT)
14400         Previous.addDecl(getStdAlignValT());
14401     }
14402   }
14403 
14404   // If we didn't find a previous declaration, and this is a reference
14405   // (or friend reference), move to the correct scope.  In C++, we
14406   // also need to do a redeclaration lookup there, just in case
14407   // there's a shadow friend decl.
14408   if (Name && Previous.empty() &&
14409       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
14410     if (Invalid) goto CreateNewDecl;
14411     assert(SS.isEmpty());
14412 
14413     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
14414       // C++ [basic.scope.pdecl]p5:
14415       //   -- for an elaborated-type-specifier of the form
14416       //
14417       //          class-key identifier
14418       //
14419       //      if the elaborated-type-specifier is used in the
14420       //      decl-specifier-seq or parameter-declaration-clause of a
14421       //      function defined in namespace scope, the identifier is
14422       //      declared as a class-name in the namespace that contains
14423       //      the declaration; otherwise, except as a friend
14424       //      declaration, the identifier is declared in the smallest
14425       //      non-class, non-function-prototype scope that contains the
14426       //      declaration.
14427       //
14428       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
14429       // C structs and unions.
14430       //
14431       // It is an error in C++ to declare (rather than define) an enum
14432       // type, including via an elaborated type specifier.  We'll
14433       // diagnose that later; for now, declare the enum in the same
14434       // scope as we would have picked for any other tag type.
14435       //
14436       // GNU C also supports this behavior as part of its incomplete
14437       // enum types extension, while GNU C++ does not.
14438       //
14439       // Find the context where we'll be declaring the tag.
14440       // FIXME: We would like to maintain the current DeclContext as the
14441       // lexical context,
14442       SearchDC = getTagInjectionContext(SearchDC);
14443 
14444       // Find the scope where we'll be declaring the tag.
14445       S = getTagInjectionScope(S, getLangOpts());
14446     } else {
14447       assert(TUK == TUK_Friend);
14448       // C++ [namespace.memdef]p3:
14449       //   If a friend declaration in a non-local class first declares a
14450       //   class or function, the friend class or function is a member of
14451       //   the innermost enclosing namespace.
14452       SearchDC = SearchDC->getEnclosingNamespaceContext();
14453     }
14454 
14455     // In C++, we need to do a redeclaration lookup to properly
14456     // diagnose some problems.
14457     // FIXME: redeclaration lookup is also used (with and without C++) to find a
14458     // hidden declaration so that we don't get ambiguity errors when using a
14459     // type declared by an elaborated-type-specifier.  In C that is not correct
14460     // and we should instead merge compatible types found by lookup.
14461     if (getLangOpts().CPlusPlus) {
14462       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14463       LookupQualifiedName(Previous, SearchDC);
14464     } else {
14465       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14466       LookupName(Previous, S);
14467     }
14468   }
14469 
14470   // If we have a known previous declaration to use, then use it.
14471   if (Previous.empty() && SkipBody && SkipBody->Previous)
14472     Previous.addDecl(SkipBody->Previous);
14473 
14474   if (!Previous.empty()) {
14475     NamedDecl *PrevDecl = Previous.getFoundDecl();
14476     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
14477 
14478     // It's okay to have a tag decl in the same scope as a typedef
14479     // which hides a tag decl in the same scope.  Finding this
14480     // insanity with a redeclaration lookup can only actually happen
14481     // in C++.
14482     //
14483     // This is also okay for elaborated-type-specifiers, which is
14484     // technically forbidden by the current standard but which is
14485     // okay according to the likely resolution of an open issue;
14486     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
14487     if (getLangOpts().CPlusPlus) {
14488       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14489         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
14490           TagDecl *Tag = TT->getDecl();
14491           if (Tag->getDeclName() == Name &&
14492               Tag->getDeclContext()->getRedeclContext()
14493                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
14494             PrevDecl = Tag;
14495             Previous.clear();
14496             Previous.addDecl(Tag);
14497             Previous.resolveKind();
14498           }
14499         }
14500       }
14501     }
14502 
14503     // If this is a redeclaration of a using shadow declaration, it must
14504     // declare a tag in the same context. In MSVC mode, we allow a
14505     // redefinition if either context is within the other.
14506     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
14507       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
14508       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
14509           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
14510           !(OldTag && isAcceptableTagRedeclContext(
14511                           *this, OldTag->getDeclContext(), SearchDC))) {
14512         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
14513         Diag(Shadow->getTargetDecl()->getLocation(),
14514              diag::note_using_decl_target);
14515         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
14516             << 0;
14517         // Recover by ignoring the old declaration.
14518         Previous.clear();
14519         goto CreateNewDecl;
14520       }
14521     }
14522 
14523     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
14524       // If this is a use of a previous tag, or if the tag is already declared
14525       // in the same scope (so that the definition/declaration completes or
14526       // rementions the tag), reuse the decl.
14527       if (TUK == TUK_Reference || TUK == TUK_Friend ||
14528           isDeclInScope(DirectPrevDecl, SearchDC, S,
14529                         SS.isNotEmpty() || isMemberSpecialization)) {
14530         // Make sure that this wasn't declared as an enum and now used as a
14531         // struct or something similar.
14532         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
14533                                           TUK == TUK_Definition, KWLoc,
14534                                           Name)) {
14535           bool SafeToContinue
14536             = (PrevTagDecl->getTagKind() != TTK_Enum &&
14537                Kind != TTK_Enum);
14538           if (SafeToContinue)
14539             Diag(KWLoc, diag::err_use_with_wrong_tag)
14540               << Name
14541               << FixItHint::CreateReplacement(SourceRange(KWLoc),
14542                                               PrevTagDecl->getKindName());
14543           else
14544             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
14545           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
14546 
14547           if (SafeToContinue)
14548             Kind = PrevTagDecl->getTagKind();
14549           else {
14550             // Recover by making this an anonymous redefinition.
14551             Name = nullptr;
14552             Previous.clear();
14553             Invalid = true;
14554           }
14555         }
14556 
14557         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
14558           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
14559 
14560           // If this is an elaborated-type-specifier for a scoped enumeration,
14561           // the 'class' keyword is not necessary and not permitted.
14562           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14563             if (ScopedEnum)
14564               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
14565                 << PrevEnum->isScoped()
14566                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
14567             return PrevTagDecl;
14568           }
14569 
14570           QualType EnumUnderlyingTy;
14571           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14572             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
14573           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
14574             EnumUnderlyingTy = QualType(T, 0);
14575 
14576           // All conflicts with previous declarations are recovered by
14577           // returning the previous declaration, unless this is a definition,
14578           // in which case we want the caller to bail out.
14579           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
14580                                      ScopedEnum, EnumUnderlyingTy,
14581                                      IsFixed, PrevEnum))
14582             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
14583         }
14584 
14585         // C++11 [class.mem]p1:
14586         //   A member shall not be declared twice in the member-specification,
14587         //   except that a nested class or member class template can be declared
14588         //   and then later defined.
14589         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
14590             S->isDeclScope(PrevDecl)) {
14591           Diag(NameLoc, diag::ext_member_redeclared);
14592           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
14593         }
14594 
14595         if (!Invalid) {
14596           // If this is a use, just return the declaration we found, unless
14597           // we have attributes.
14598           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14599             if (!Attrs.empty()) {
14600               // FIXME: Diagnose these attributes. For now, we create a new
14601               // declaration to hold them.
14602             } else if (TUK == TUK_Reference &&
14603                        (PrevTagDecl->getFriendObjectKind() ==
14604                             Decl::FOK_Undeclared ||
14605                         PrevDecl->getOwningModule() != getCurrentModule()) &&
14606                        SS.isEmpty()) {
14607               // This declaration is a reference to an existing entity, but
14608               // has different visibility from that entity: it either makes
14609               // a friend visible or it makes a type visible in a new module.
14610               // In either case, create a new declaration. We only do this if
14611               // the declaration would have meant the same thing if no prior
14612               // declaration were found, that is, if it was found in the same
14613               // scope where we would have injected a declaration.
14614               if (!getTagInjectionContext(CurContext)->getRedeclContext()
14615                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
14616                 return PrevTagDecl;
14617               // This is in the injected scope, create a new declaration in
14618               // that scope.
14619               S = getTagInjectionScope(S, getLangOpts());
14620             } else {
14621               return PrevTagDecl;
14622             }
14623           }
14624 
14625           // Diagnose attempts to redefine a tag.
14626           if (TUK == TUK_Definition) {
14627             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
14628               // If we're defining a specialization and the previous definition
14629               // is from an implicit instantiation, don't emit an error
14630               // here; we'll catch this in the general case below.
14631               bool IsExplicitSpecializationAfterInstantiation = false;
14632               if (isMemberSpecialization) {
14633                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
14634                   IsExplicitSpecializationAfterInstantiation =
14635                     RD->getTemplateSpecializationKind() !=
14636                     TSK_ExplicitSpecialization;
14637                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
14638                   IsExplicitSpecializationAfterInstantiation =
14639                     ED->getTemplateSpecializationKind() !=
14640                     TSK_ExplicitSpecialization;
14641               }
14642 
14643               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
14644               // not keep more that one definition around (merge them). However,
14645               // ensure the decl passes the structural compatibility check in
14646               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
14647               NamedDecl *Hidden = nullptr;
14648               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
14649                 // There is a definition of this tag, but it is not visible. We
14650                 // explicitly make use of C++'s one definition rule here, and
14651                 // assume that this definition is identical to the hidden one
14652                 // we already have. Make the existing definition visible and
14653                 // use it in place of this one.
14654                 if (!getLangOpts().CPlusPlus) {
14655                   // Postpone making the old definition visible until after we
14656                   // complete parsing the new one and do the structural
14657                   // comparison.
14658                   SkipBody->CheckSameAsPrevious = true;
14659                   SkipBody->New = createTagFromNewDecl();
14660                   SkipBody->Previous = Def;
14661                   return Def;
14662                 } else {
14663                   SkipBody->ShouldSkip = true;
14664                   SkipBody->Previous = Def;
14665                   makeMergedDefinitionVisible(Hidden);
14666                   // Carry on and handle it like a normal definition. We'll
14667                   // skip starting the definitiion later.
14668                 }
14669               } else if (!IsExplicitSpecializationAfterInstantiation) {
14670                 // A redeclaration in function prototype scope in C isn't
14671                 // visible elsewhere, so merely issue a warning.
14672                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
14673                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
14674                 else
14675                   Diag(NameLoc, diag::err_redefinition) << Name;
14676                 notePreviousDefinition(Def,
14677                                        NameLoc.isValid() ? NameLoc : KWLoc);
14678                 // If this is a redefinition, recover by making this
14679                 // struct be anonymous, which will make any later
14680                 // references get the previous definition.
14681                 Name = nullptr;
14682                 Previous.clear();
14683                 Invalid = true;
14684               }
14685             } else {
14686               // If the type is currently being defined, complain
14687               // about a nested redefinition.
14688               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
14689               if (TD->isBeingDefined()) {
14690                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
14691                 Diag(PrevTagDecl->getLocation(),
14692                      diag::note_previous_definition);
14693                 Name = nullptr;
14694                 Previous.clear();
14695                 Invalid = true;
14696               }
14697             }
14698 
14699             // Okay, this is definition of a previously declared or referenced
14700             // tag. We're going to create a new Decl for it.
14701           }
14702 
14703           // Okay, we're going to make a redeclaration.  If this is some kind
14704           // of reference, make sure we build the redeclaration in the same DC
14705           // as the original, and ignore the current access specifier.
14706           if (TUK == TUK_Friend || TUK == TUK_Reference) {
14707             SearchDC = PrevTagDecl->getDeclContext();
14708             AS = AS_none;
14709           }
14710         }
14711         // If we get here we have (another) forward declaration or we
14712         // have a definition.  Just create a new decl.
14713 
14714       } else {
14715         // If we get here, this is a definition of a new tag type in a nested
14716         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
14717         // new decl/type.  We set PrevDecl to NULL so that the entities
14718         // have distinct types.
14719         Previous.clear();
14720       }
14721       // If we get here, we're going to create a new Decl. If PrevDecl
14722       // is non-NULL, it's a definition of the tag declared by
14723       // PrevDecl. If it's NULL, we have a new definition.
14724 
14725     // Otherwise, PrevDecl is not a tag, but was found with tag
14726     // lookup.  This is only actually possible in C++, where a few
14727     // things like templates still live in the tag namespace.
14728     } else {
14729       // Use a better diagnostic if an elaborated-type-specifier
14730       // found the wrong kind of type on the first
14731       // (non-redeclaration) lookup.
14732       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
14733           !Previous.isForRedeclaration()) {
14734         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14735         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
14736                                                        << Kind;
14737         Diag(PrevDecl->getLocation(), diag::note_declared_at);
14738         Invalid = true;
14739 
14740       // Otherwise, only diagnose if the declaration is in scope.
14741       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
14742                                 SS.isNotEmpty() || isMemberSpecialization)) {
14743         // do nothing
14744 
14745       // Diagnose implicit declarations introduced by elaborated types.
14746       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
14747         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14748         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
14749         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14750         Invalid = true;
14751 
14752       // Otherwise it's a declaration.  Call out a particularly common
14753       // case here.
14754       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14755         unsigned Kind = 0;
14756         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
14757         Diag(NameLoc, diag::err_tag_definition_of_typedef)
14758           << Name << Kind << TND->getUnderlyingType();
14759         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14760         Invalid = true;
14761 
14762       // Otherwise, diagnose.
14763       } else {
14764         // The tag name clashes with something else in the target scope,
14765         // issue an error and recover by making this tag be anonymous.
14766         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
14767         notePreviousDefinition(PrevDecl, NameLoc);
14768         Name = nullptr;
14769         Invalid = true;
14770       }
14771 
14772       // The existing declaration isn't relevant to us; we're in a
14773       // new scope, so clear out the previous declaration.
14774       Previous.clear();
14775     }
14776   }
14777 
14778 CreateNewDecl:
14779 
14780   TagDecl *PrevDecl = nullptr;
14781   if (Previous.isSingleResult())
14782     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
14783 
14784   // If there is an identifier, use the location of the identifier as the
14785   // location of the decl, otherwise use the location of the struct/union
14786   // keyword.
14787   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14788 
14789   // Otherwise, create a new declaration. If there is a previous
14790   // declaration of the same entity, the two will be linked via
14791   // PrevDecl.
14792   TagDecl *New;
14793 
14794   if (Kind == TTK_Enum) {
14795     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14796     // enum X { A, B, C } D;    D should chain to X.
14797     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
14798                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
14799                            ScopedEnumUsesClassTag, IsFixed);
14800 
14801     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
14802       StdAlignValT = cast<EnumDecl>(New);
14803 
14804     // If this is an undefined enum, warn.
14805     if (TUK != TUK_Definition && !Invalid) {
14806       TagDecl *Def;
14807       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
14808         // C++0x: 7.2p2: opaque-enum-declaration.
14809         // Conflicts are diagnosed above. Do nothing.
14810       }
14811       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
14812         Diag(Loc, diag::ext_forward_ref_enum_def)
14813           << New;
14814         Diag(Def->getLocation(), diag::note_previous_definition);
14815       } else {
14816         unsigned DiagID = diag::ext_forward_ref_enum;
14817         if (getLangOpts().MSVCCompat)
14818           DiagID = diag::ext_ms_forward_ref_enum;
14819         else if (getLangOpts().CPlusPlus)
14820           DiagID = diag::err_forward_ref_enum;
14821         Diag(Loc, DiagID);
14822       }
14823     }
14824 
14825     if (EnumUnderlying) {
14826       EnumDecl *ED = cast<EnumDecl>(New);
14827       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14828         ED->setIntegerTypeSourceInfo(TI);
14829       else
14830         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
14831       ED->setPromotionType(ED->getIntegerType());
14832       assert(ED->isComplete() && "enum with type should be complete");
14833     }
14834   } else {
14835     // struct/union/class
14836 
14837     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14838     // struct X { int A; } D;    D should chain to X.
14839     if (getLangOpts().CPlusPlus) {
14840       // FIXME: Look for a way to use RecordDecl for simple structs.
14841       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14842                                   cast_or_null<CXXRecordDecl>(PrevDecl));
14843 
14844       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
14845         StdBadAlloc = cast<CXXRecordDecl>(New);
14846     } else
14847       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14848                                cast_or_null<RecordDecl>(PrevDecl));
14849   }
14850 
14851   // C++11 [dcl.type]p3:
14852   //   A type-specifier-seq shall not define a class or enumeration [...].
14853   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
14854       TUK == TUK_Definition) {
14855     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
14856       << Context.getTagDeclType(New);
14857     Invalid = true;
14858   }
14859 
14860   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
14861       DC->getDeclKind() == Decl::Enum) {
14862     Diag(New->getLocation(), diag::err_type_defined_in_enum)
14863       << Context.getTagDeclType(New);
14864     Invalid = true;
14865   }
14866 
14867   // Maybe add qualifier info.
14868   if (SS.isNotEmpty()) {
14869     if (SS.isSet()) {
14870       // If this is either a declaration or a definition, check the
14871       // nested-name-specifier against the current context.
14872       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
14873           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
14874                                        isMemberSpecialization))
14875         Invalid = true;
14876 
14877       New->setQualifierInfo(SS.getWithLocInContext(Context));
14878       if (TemplateParameterLists.size() > 0) {
14879         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
14880       }
14881     }
14882     else
14883       Invalid = true;
14884   }
14885 
14886   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14887     // Add alignment attributes if necessary; these attributes are checked when
14888     // the ASTContext lays out the structure.
14889     //
14890     // It is important for implementing the correct semantics that this
14891     // happen here (in ActOnTag). The #pragma pack stack is
14892     // maintained as a result of parser callbacks which can occur at
14893     // many points during the parsing of a struct declaration (because
14894     // the #pragma tokens are effectively skipped over during the
14895     // parsing of the struct).
14896     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14897       AddAlignmentAttributesForRecord(RD);
14898       AddMsStructLayoutForRecord(RD);
14899     }
14900   }
14901 
14902   if (ModulePrivateLoc.isValid()) {
14903     if (isMemberSpecialization)
14904       Diag(New->getLocation(), diag::err_module_private_specialization)
14905         << 2
14906         << FixItHint::CreateRemoval(ModulePrivateLoc);
14907     // __module_private__ does not apply to local classes. However, we only
14908     // diagnose this as an error when the declaration specifiers are
14909     // freestanding. Here, we just ignore the __module_private__.
14910     else if (!SearchDC->isFunctionOrMethod())
14911       New->setModulePrivate();
14912   }
14913 
14914   // If this is a specialization of a member class (of a class template),
14915   // check the specialization.
14916   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
14917     Invalid = true;
14918 
14919   // If we're declaring or defining a tag in function prototype scope in C,
14920   // note that this type can only be used within the function and add it to
14921   // the list of decls to inject into the function definition scope.
14922   if ((Name || Kind == TTK_Enum) &&
14923       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
14924     if (getLangOpts().CPlusPlus) {
14925       // C++ [dcl.fct]p6:
14926       //   Types shall not be defined in return or parameter types.
14927       if (TUK == TUK_Definition && !IsTypeSpecifier) {
14928         Diag(Loc, diag::err_type_defined_in_param_type)
14929             << Name;
14930         Invalid = true;
14931       }
14932     } else if (!PrevDecl) {
14933       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
14934     }
14935   }
14936 
14937   if (Invalid)
14938     New->setInvalidDecl();
14939 
14940   // Set the lexical context. If the tag has a C++ scope specifier, the
14941   // lexical context will be different from the semantic context.
14942   New->setLexicalDeclContext(CurContext);
14943 
14944   // Mark this as a friend decl if applicable.
14945   // In Microsoft mode, a friend declaration also acts as a forward
14946   // declaration so we always pass true to setObjectOfFriendDecl to make
14947   // the tag name visible.
14948   if (TUK == TUK_Friend)
14949     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
14950 
14951   // Set the access specifier.
14952   if (!Invalid && SearchDC->isRecord())
14953     SetMemberAccessSpecifier(New, PrevDecl, AS);
14954 
14955   if (PrevDecl)
14956     CheckRedeclarationModuleOwnership(New, PrevDecl);
14957 
14958   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
14959     New->startDefinition();
14960 
14961   ProcessDeclAttributeList(S, New, Attrs);
14962   AddPragmaAttributes(S, New);
14963 
14964   // If this has an identifier, add it to the scope stack.
14965   if (TUK == TUK_Friend) {
14966     // We might be replacing an existing declaration in the lookup tables;
14967     // if so, borrow its access specifier.
14968     if (PrevDecl)
14969       New->setAccess(PrevDecl->getAccess());
14970 
14971     DeclContext *DC = New->getDeclContext()->getRedeclContext();
14972     DC->makeDeclVisibleInContext(New);
14973     if (Name) // can be null along some error paths
14974       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14975         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
14976   } else if (Name) {
14977     S = getNonFieldDeclScope(S);
14978     PushOnScopeChains(New, S, true);
14979   } else {
14980     CurContext->addDecl(New);
14981   }
14982 
14983   // If this is the C FILE type, notify the AST context.
14984   if (IdentifierInfo *II = New->getIdentifier())
14985     if (!New->isInvalidDecl() &&
14986         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
14987         II->isStr("FILE"))
14988       Context.setFILEDecl(New);
14989 
14990   if (PrevDecl)
14991     mergeDeclAttributes(New, PrevDecl);
14992 
14993   // If there's a #pragma GCC visibility in scope, set the visibility of this
14994   // record.
14995   AddPushedVisibilityAttribute(New);
14996 
14997   if (isMemberSpecialization && !New->isInvalidDecl())
14998     CompleteMemberSpecialization(New, Previous);
14999 
15000   OwnedDecl = true;
15001   // In C++, don't return an invalid declaration. We can't recover well from
15002   // the cases where we make the type anonymous.
15003   if (Invalid && getLangOpts().CPlusPlus) {
15004     if (New->isBeingDefined())
15005       if (auto RD = dyn_cast<RecordDecl>(New))
15006         RD->completeDefinition();
15007     return nullptr;
15008   } else if (SkipBody && SkipBody->ShouldSkip) {
15009     return SkipBody->Previous;
15010   } else {
15011     return New;
15012   }
15013 }
15014 
15015 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
15016   AdjustDeclIfTemplate(TagD);
15017   TagDecl *Tag = cast<TagDecl>(TagD);
15018 
15019   // Enter the tag context.
15020   PushDeclContext(S, Tag);
15021 
15022   ActOnDocumentableDecl(TagD);
15023 
15024   // If there's a #pragma GCC visibility in scope, set the visibility of this
15025   // record.
15026   AddPushedVisibilityAttribute(Tag);
15027 }
15028 
15029 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
15030                                     SkipBodyInfo &SkipBody) {
15031   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
15032     return false;
15033 
15034   // Make the previous decl visible.
15035   makeMergedDefinitionVisible(SkipBody.Previous);
15036   return true;
15037 }
15038 
15039 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
15040   assert(isa<ObjCContainerDecl>(IDecl) &&
15041          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15042   DeclContext *OCD = cast<DeclContext>(IDecl);
15043   assert(getContainingDC(OCD) == CurContext &&
15044       "The next DeclContext should be lexically contained in the current one.");
15045   CurContext = OCD;
15046   return IDecl;
15047 }
15048 
15049 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
15050                                            SourceLocation FinalLoc,
15051                                            bool IsFinalSpelledSealed,
15052                                            SourceLocation LBraceLoc) {
15053   AdjustDeclIfTemplate(TagD);
15054   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15055 
15056   FieldCollector->StartClass();
15057 
15058   if (!Record->getIdentifier())
15059     return;
15060 
15061   if (FinalLoc.isValid())
15062     Record->addAttr(new (Context)
15063                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
15064 
15065   // C++ [class]p2:
15066   //   [...] The class-name is also inserted into the scope of the
15067   //   class itself; this is known as the injected-class-name. For
15068   //   purposes of access checking, the injected-class-name is treated
15069   //   as if it were a public member name.
15070   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15071       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
15072       Record->getLocation(), Record->getIdentifier(),
15073       /*PrevDecl=*/nullptr,
15074       /*DelayTypeCreation=*/true);
15075   Context.getTypeDeclType(InjectedClassName, Record);
15076   InjectedClassName->setImplicit();
15077   InjectedClassName->setAccess(AS_public);
15078   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15079       InjectedClassName->setDescribedClassTemplate(Template);
15080   PushOnScopeChains(InjectedClassName, S);
15081   assert(InjectedClassName->isInjectedClassName() &&
15082          "Broken injected-class-name");
15083 }
15084 
15085 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
15086                                     SourceRange BraceRange) {
15087   AdjustDeclIfTemplate(TagD);
15088   TagDecl *Tag = cast<TagDecl>(TagD);
15089   Tag->setBraceRange(BraceRange);
15090 
15091   // Make sure we "complete" the definition even it is invalid.
15092   if (Tag->isBeingDefined()) {
15093     assert(Tag->isInvalidDecl() && "We should already have completed it");
15094     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15095       RD->completeDefinition();
15096   }
15097 
15098   if (isa<CXXRecordDecl>(Tag)) {
15099     FieldCollector->FinishClass();
15100   }
15101 
15102   // Exit this scope of this tag's definition.
15103   PopDeclContext();
15104 
15105   if (getCurLexicalContext()->isObjCContainer() &&
15106       Tag->getDeclContext()->isFileContext())
15107     Tag->setTopLevelDeclInObjCContainer();
15108 
15109   // Notify the consumer that we've defined a tag.
15110   if (!Tag->isInvalidDecl())
15111     Consumer.HandleTagDeclDefinition(Tag);
15112 }
15113 
15114 void Sema::ActOnObjCContainerFinishDefinition() {
15115   // Exit this scope of this interface definition.
15116   PopDeclContext();
15117 }
15118 
15119 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15120   assert(DC == CurContext && "Mismatch of container contexts");
15121   OriginalLexicalContext = DC;
15122   ActOnObjCContainerFinishDefinition();
15123 }
15124 
15125 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15126   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15127   OriginalLexicalContext = nullptr;
15128 }
15129 
15130 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
15131   AdjustDeclIfTemplate(TagD);
15132   TagDecl *Tag = cast<TagDecl>(TagD);
15133   Tag->setInvalidDecl();
15134 
15135   // Make sure we "complete" the definition even it is invalid.
15136   if (Tag->isBeingDefined()) {
15137     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15138       RD->completeDefinition();
15139   }
15140 
15141   // We're undoing ActOnTagStartDefinition here, not
15142   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15143   // the FieldCollector.
15144 
15145   PopDeclContext();
15146 }
15147 
15148 // Note that FieldName may be null for anonymous bitfields.
15149 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15150                                 IdentifierInfo *FieldName,
15151                                 QualType FieldTy, bool IsMsStruct,
15152                                 Expr *BitWidth, bool *ZeroWidth) {
15153   // Default to true; that shouldn't confuse checks for emptiness
15154   if (ZeroWidth)
15155     *ZeroWidth = true;
15156 
15157   // C99 6.7.2.1p4 - verify the field type.
15158   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15159   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15160     // Handle incomplete types with specific error.
15161     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15162       return ExprError();
15163     if (FieldName)
15164       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15165         << FieldName << FieldTy << BitWidth->getSourceRange();
15166     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15167       << FieldTy << BitWidth->getSourceRange();
15168   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15169                                              UPPC_BitFieldWidth))
15170     return ExprError();
15171 
15172   // If the bit-width is type- or value-dependent, don't try to check
15173   // it now.
15174   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15175     return BitWidth;
15176 
15177   llvm::APSInt Value;
15178   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15179   if (ICE.isInvalid())
15180     return ICE;
15181   BitWidth = ICE.get();
15182 
15183   if (Value != 0 && ZeroWidth)
15184     *ZeroWidth = false;
15185 
15186   // Zero-width bitfield is ok for anonymous field.
15187   if (Value == 0 && FieldName)
15188     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15189 
15190   if (Value.isSigned() && Value.isNegative()) {
15191     if (FieldName)
15192       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15193                << FieldName << Value.toString(10);
15194     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15195       << Value.toString(10);
15196   }
15197 
15198   if (!FieldTy->isDependentType()) {
15199     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15200     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15201     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15202 
15203     // Over-wide bitfields are an error in C or when using the MSVC bitfield
15204     // ABI.
15205     bool CStdConstraintViolation =
15206         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15207     bool MSBitfieldViolation =
15208         Value.ugt(TypeStorageSize) &&
15209         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15210     if (CStdConstraintViolation || MSBitfieldViolation) {
15211       unsigned DiagWidth =
15212           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15213       if (FieldName)
15214         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15215                << FieldName << (unsigned)Value.getZExtValue()
15216                << !CStdConstraintViolation << DiagWidth;
15217 
15218       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15219              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15220              << DiagWidth;
15221     }
15222 
15223     // Warn on types where the user might conceivably expect to get all
15224     // specified bits as value bits: that's all integral types other than
15225     // 'bool'.
15226     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15227       if (FieldName)
15228         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15229             << FieldName << (unsigned)Value.getZExtValue()
15230             << (unsigned)TypeWidth;
15231       else
15232         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15233             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
15234     }
15235   }
15236 
15237   return BitWidth;
15238 }
15239 
15240 /// ActOnField - Each field of a C struct/union is passed into this in order
15241 /// to create a FieldDecl object for it.
15242 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
15243                        Declarator &D, Expr *BitfieldWidth) {
15244   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
15245                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
15246                                /*InitStyle=*/ICIS_NoInit, AS_public);
15247   return Res;
15248 }
15249 
15250 /// HandleField - Analyze a field of a C struct or a C++ data member.
15251 ///
15252 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
15253                              SourceLocation DeclStart,
15254                              Declarator &D, Expr *BitWidth,
15255                              InClassInitStyle InitStyle,
15256                              AccessSpecifier AS) {
15257   if (D.isDecompositionDeclarator()) {
15258     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
15259     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
15260       << Decomp.getSourceRange();
15261     return nullptr;
15262   }
15263 
15264   IdentifierInfo *II = D.getIdentifier();
15265   SourceLocation Loc = DeclStart;
15266   if (II) Loc = D.getIdentifierLoc();
15267 
15268   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15269   QualType T = TInfo->getType();
15270   if (getLangOpts().CPlusPlus) {
15271     CheckExtraCXXDefaultArguments(D);
15272 
15273     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15274                                         UPPC_DataMemberType)) {
15275       D.setInvalidType();
15276       T = Context.IntTy;
15277       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15278     }
15279   }
15280 
15281   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15282 
15283   if (D.getDeclSpec().isInlineSpecified())
15284     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15285         << getLangOpts().CPlusPlus17;
15286   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15287     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15288          diag::err_invalid_thread)
15289       << DeclSpec::getSpecifierName(TSCS);
15290 
15291   // Check to see if this name was declared as a member previously
15292   NamedDecl *PrevDecl = nullptr;
15293   LookupResult Previous(*this, II, Loc, LookupMemberName,
15294                         ForVisibleRedeclaration);
15295   LookupName(Previous, S);
15296   switch (Previous.getResultKind()) {
15297     case LookupResult::Found:
15298     case LookupResult::FoundUnresolvedValue:
15299       PrevDecl = Previous.getAsSingle<NamedDecl>();
15300       break;
15301 
15302     case LookupResult::FoundOverloaded:
15303       PrevDecl = Previous.getRepresentativeDecl();
15304       break;
15305 
15306     case LookupResult::NotFound:
15307     case LookupResult::NotFoundInCurrentInstantiation:
15308     case LookupResult::Ambiguous:
15309       break;
15310   }
15311   Previous.suppressDiagnostics();
15312 
15313   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15314     // Maybe we will complain about the shadowed template parameter.
15315     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15316     // Just pretend that we didn't see the previous declaration.
15317     PrevDecl = nullptr;
15318   }
15319 
15320   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15321     PrevDecl = nullptr;
15322 
15323   bool Mutable
15324     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
15325   SourceLocation TSSL = D.getBeginLoc();
15326   FieldDecl *NewFD
15327     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
15328                      TSSL, AS, PrevDecl, &D);
15329 
15330   if (NewFD->isInvalidDecl())
15331     Record->setInvalidDecl();
15332 
15333   if (D.getDeclSpec().isModulePrivateSpecified())
15334     NewFD->setModulePrivate();
15335 
15336   if (NewFD->isInvalidDecl() && PrevDecl) {
15337     // Don't introduce NewFD into scope; there's already something
15338     // with the same name in the same scope.
15339   } else if (II) {
15340     PushOnScopeChains(NewFD, S);
15341   } else
15342     Record->addDecl(NewFD);
15343 
15344   return NewFD;
15345 }
15346 
15347 /// Build a new FieldDecl and check its well-formedness.
15348 ///
15349 /// This routine builds a new FieldDecl given the fields name, type,
15350 /// record, etc. \p PrevDecl should refer to any previous declaration
15351 /// with the same name and in the same scope as the field to be
15352 /// created.
15353 ///
15354 /// \returns a new FieldDecl.
15355 ///
15356 /// \todo The Declarator argument is a hack. It will be removed once
15357 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
15358                                 TypeSourceInfo *TInfo,
15359                                 RecordDecl *Record, SourceLocation Loc,
15360                                 bool Mutable, Expr *BitWidth,
15361                                 InClassInitStyle InitStyle,
15362                                 SourceLocation TSSL,
15363                                 AccessSpecifier AS, NamedDecl *PrevDecl,
15364                                 Declarator *D) {
15365   IdentifierInfo *II = Name.getAsIdentifierInfo();
15366   bool InvalidDecl = false;
15367   if (D) InvalidDecl = D->isInvalidType();
15368 
15369   // If we receive a broken type, recover by assuming 'int' and
15370   // marking this declaration as invalid.
15371   if (T.isNull()) {
15372     InvalidDecl = true;
15373     T = Context.IntTy;
15374   }
15375 
15376   QualType EltTy = Context.getBaseElementType(T);
15377   if (!EltTy->isDependentType()) {
15378     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
15379       // Fields of incomplete type force their record to be invalid.
15380       Record->setInvalidDecl();
15381       InvalidDecl = true;
15382     } else {
15383       NamedDecl *Def;
15384       EltTy->isIncompleteType(&Def);
15385       if (Def && Def->isInvalidDecl()) {
15386         Record->setInvalidDecl();
15387         InvalidDecl = true;
15388       }
15389     }
15390   }
15391 
15392   // TR 18037 does not allow fields to be declared with address space
15393   if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() ||
15394       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
15395     Diag(Loc, diag::err_field_with_address_space);
15396     Record->setInvalidDecl();
15397     InvalidDecl = true;
15398   }
15399 
15400   if (LangOpts.OpenCL) {
15401     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
15402     // used as structure or union field: image, sampler, event or block types.
15403     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
15404         T->isBlockPointerType()) {
15405       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
15406       Record->setInvalidDecl();
15407       InvalidDecl = true;
15408     }
15409     // OpenCL v1.2 s6.9.c: bitfields are not supported.
15410     if (BitWidth) {
15411       Diag(Loc, diag::err_opencl_bitfields);
15412       InvalidDecl = true;
15413     }
15414   }
15415 
15416   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
15417   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
15418       T.hasQualifiers()) {
15419     InvalidDecl = true;
15420     Diag(Loc, diag::err_anon_bitfield_qualifiers);
15421   }
15422 
15423   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15424   // than a variably modified type.
15425   if (!InvalidDecl && T->isVariablyModifiedType()) {
15426     bool SizeIsNegative;
15427     llvm::APSInt Oversized;
15428 
15429     TypeSourceInfo *FixedTInfo =
15430       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
15431                                                     SizeIsNegative,
15432                                                     Oversized);
15433     if (FixedTInfo) {
15434       Diag(Loc, diag::warn_illegal_constant_array_size);
15435       TInfo = FixedTInfo;
15436       T = FixedTInfo->getType();
15437     } else {
15438       if (SizeIsNegative)
15439         Diag(Loc, diag::err_typecheck_negative_array_size);
15440       else if (Oversized.getBoolValue())
15441         Diag(Loc, diag::err_array_too_large)
15442           << Oversized.toString(10);
15443       else
15444         Diag(Loc, diag::err_typecheck_field_variable_size);
15445       InvalidDecl = true;
15446     }
15447   }
15448 
15449   // Fields can not have abstract class types
15450   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
15451                                              diag::err_abstract_type_in_decl,
15452                                              AbstractFieldType))
15453     InvalidDecl = true;
15454 
15455   bool ZeroWidth = false;
15456   if (InvalidDecl)
15457     BitWidth = nullptr;
15458   // If this is declared as a bit-field, check the bit-field.
15459   if (BitWidth) {
15460     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
15461                               &ZeroWidth).get();
15462     if (!BitWidth) {
15463       InvalidDecl = true;
15464       BitWidth = nullptr;
15465       ZeroWidth = false;
15466     }
15467   }
15468 
15469   // Check that 'mutable' is consistent with the type of the declaration.
15470   if (!InvalidDecl && Mutable) {
15471     unsigned DiagID = 0;
15472     if (T->isReferenceType())
15473       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
15474                                         : diag::err_mutable_reference;
15475     else if (T.isConstQualified())
15476       DiagID = diag::err_mutable_const;
15477 
15478     if (DiagID) {
15479       SourceLocation ErrLoc = Loc;
15480       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
15481         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
15482       Diag(ErrLoc, DiagID);
15483       if (DiagID != diag::ext_mutable_reference) {
15484         Mutable = false;
15485         InvalidDecl = true;
15486       }
15487     }
15488   }
15489 
15490   // C++11 [class.union]p8 (DR1460):
15491   //   At most one variant member of a union may have a
15492   //   brace-or-equal-initializer.
15493   if (InitStyle != ICIS_NoInit)
15494     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
15495 
15496   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
15497                                        BitWidth, Mutable, InitStyle);
15498   if (InvalidDecl)
15499     NewFD->setInvalidDecl();
15500 
15501   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
15502     Diag(Loc, diag::err_duplicate_member) << II;
15503     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15504     NewFD->setInvalidDecl();
15505   }
15506 
15507   if (!InvalidDecl && getLangOpts().CPlusPlus) {
15508     if (Record->isUnion()) {
15509       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15510         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
15511         if (RDecl->getDefinition()) {
15512           // C++ [class.union]p1: An object of a class with a non-trivial
15513           // constructor, a non-trivial copy constructor, a non-trivial
15514           // destructor, or a non-trivial copy assignment operator
15515           // cannot be a member of a union, nor can an array of such
15516           // objects.
15517           if (CheckNontrivialField(NewFD))
15518             NewFD->setInvalidDecl();
15519         }
15520       }
15521 
15522       // C++ [class.union]p1: If a union contains a member of reference type,
15523       // the program is ill-formed, except when compiling with MSVC extensions
15524       // enabled.
15525       if (EltTy->isReferenceType()) {
15526         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
15527                                     diag::ext_union_member_of_reference_type :
15528                                     diag::err_union_member_of_reference_type)
15529           << NewFD->getDeclName() << EltTy;
15530         if (!getLangOpts().MicrosoftExt)
15531           NewFD->setInvalidDecl();
15532       }
15533     }
15534   }
15535 
15536   // FIXME: We need to pass in the attributes given an AST
15537   // representation, not a parser representation.
15538   if (D) {
15539     // FIXME: The current scope is almost... but not entirely... correct here.
15540     ProcessDeclAttributes(getCurScope(), NewFD, *D);
15541 
15542     if (NewFD->hasAttrs())
15543       CheckAlignasUnderalignment(NewFD);
15544   }
15545 
15546   // In auto-retain/release, infer strong retension for fields of
15547   // retainable type.
15548   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
15549     NewFD->setInvalidDecl();
15550 
15551   if (T.isObjCGCWeak())
15552     Diag(Loc, diag::warn_attribute_weak_on_field);
15553 
15554   NewFD->setAccess(AS);
15555   return NewFD;
15556 }
15557 
15558 bool Sema::CheckNontrivialField(FieldDecl *FD) {
15559   assert(FD);
15560   assert(getLangOpts().CPlusPlus && "valid check only for C++");
15561 
15562   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
15563     return false;
15564 
15565   QualType EltTy = Context.getBaseElementType(FD->getType());
15566   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15567     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
15568     if (RDecl->getDefinition()) {
15569       // We check for copy constructors before constructors
15570       // because otherwise we'll never get complaints about
15571       // copy constructors.
15572 
15573       CXXSpecialMember member = CXXInvalid;
15574       // We're required to check for any non-trivial constructors. Since the
15575       // implicit default constructor is suppressed if there are any
15576       // user-declared constructors, we just need to check that there is a
15577       // trivial default constructor and a trivial copy constructor. (We don't
15578       // worry about move constructors here, since this is a C++98 check.)
15579       if (RDecl->hasNonTrivialCopyConstructor())
15580         member = CXXCopyConstructor;
15581       else if (!RDecl->hasTrivialDefaultConstructor())
15582         member = CXXDefaultConstructor;
15583       else if (RDecl->hasNonTrivialCopyAssignment())
15584         member = CXXCopyAssignment;
15585       else if (RDecl->hasNonTrivialDestructor())
15586         member = CXXDestructor;
15587 
15588       if (member != CXXInvalid) {
15589         if (!getLangOpts().CPlusPlus11 &&
15590             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
15591           // Objective-C++ ARC: it is an error to have a non-trivial field of
15592           // a union. However, system headers in Objective-C programs
15593           // occasionally have Objective-C lifetime objects within unions,
15594           // and rather than cause the program to fail, we make those
15595           // members unavailable.
15596           SourceLocation Loc = FD->getLocation();
15597           if (getSourceManager().isInSystemHeader(Loc)) {
15598             if (!FD->hasAttr<UnavailableAttr>())
15599               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15600                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
15601             return false;
15602           }
15603         }
15604 
15605         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
15606                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
15607                diag::err_illegal_union_or_anon_struct_member)
15608           << FD->getParent()->isUnion() << FD->getDeclName() << member;
15609         DiagnoseNontrivial(RDecl, member);
15610         return !getLangOpts().CPlusPlus11;
15611       }
15612     }
15613   }
15614 
15615   return false;
15616 }
15617 
15618 /// TranslateIvarVisibility - Translate visibility from a token ID to an
15619 ///  AST enum value.
15620 static ObjCIvarDecl::AccessControl
15621 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
15622   switch (ivarVisibility) {
15623   default: llvm_unreachable("Unknown visitibility kind");
15624   case tok::objc_private: return ObjCIvarDecl::Private;
15625   case tok::objc_public: return ObjCIvarDecl::Public;
15626   case tok::objc_protected: return ObjCIvarDecl::Protected;
15627   case tok::objc_package: return ObjCIvarDecl::Package;
15628   }
15629 }
15630 
15631 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
15632 /// in order to create an IvarDecl object for it.
15633 Decl *Sema::ActOnIvar(Scope *S,
15634                                 SourceLocation DeclStart,
15635                                 Declarator &D, Expr *BitfieldWidth,
15636                                 tok::ObjCKeywordKind Visibility) {
15637 
15638   IdentifierInfo *II = D.getIdentifier();
15639   Expr *BitWidth = (Expr*)BitfieldWidth;
15640   SourceLocation Loc = DeclStart;
15641   if (II) Loc = D.getIdentifierLoc();
15642 
15643   // FIXME: Unnamed fields can be handled in various different ways, for
15644   // example, unnamed unions inject all members into the struct namespace!
15645 
15646   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15647   QualType T = TInfo->getType();
15648 
15649   if (BitWidth) {
15650     // 6.7.2.1p3, 6.7.2.1p4
15651     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
15652     if (!BitWidth)
15653       D.setInvalidType();
15654   } else {
15655     // Not a bitfield.
15656 
15657     // validate II.
15658 
15659   }
15660   if (T->isReferenceType()) {
15661     Diag(Loc, diag::err_ivar_reference_type);
15662     D.setInvalidType();
15663   }
15664   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15665   // than a variably modified type.
15666   else if (T->isVariablyModifiedType()) {
15667     Diag(Loc, diag::err_typecheck_ivar_variable_size);
15668     D.setInvalidType();
15669   }
15670 
15671   // Get the visibility (access control) for this ivar.
15672   ObjCIvarDecl::AccessControl ac =
15673     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
15674                                         : ObjCIvarDecl::None;
15675   // Must set ivar's DeclContext to its enclosing interface.
15676   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
15677   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
15678     return nullptr;
15679   ObjCContainerDecl *EnclosingContext;
15680   if (ObjCImplementationDecl *IMPDecl =
15681       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15682     if (LangOpts.ObjCRuntime.isFragile()) {
15683     // Case of ivar declared in an implementation. Context is that of its class.
15684       EnclosingContext = IMPDecl->getClassInterface();
15685       assert(EnclosingContext && "Implementation has no class interface!");
15686     }
15687     else
15688       EnclosingContext = EnclosingDecl;
15689   } else {
15690     if (ObjCCategoryDecl *CDecl =
15691         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15692       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
15693         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
15694         return nullptr;
15695       }
15696     }
15697     EnclosingContext = EnclosingDecl;
15698   }
15699 
15700   // Construct the decl.
15701   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
15702                                              DeclStart, Loc, II, T,
15703                                              TInfo, ac, (Expr *)BitfieldWidth);
15704 
15705   if (II) {
15706     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
15707                                            ForVisibleRedeclaration);
15708     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
15709         && !isa<TagDecl>(PrevDecl)) {
15710       Diag(Loc, diag::err_duplicate_member) << II;
15711       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15712       NewID->setInvalidDecl();
15713     }
15714   }
15715 
15716   // Process attributes attached to the ivar.
15717   ProcessDeclAttributes(S, NewID, D);
15718 
15719   if (D.isInvalidType())
15720     NewID->setInvalidDecl();
15721 
15722   // In ARC, infer 'retaining' for ivars of retainable type.
15723   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
15724     NewID->setInvalidDecl();
15725 
15726   if (D.getDeclSpec().isModulePrivateSpecified())
15727     NewID->setModulePrivate();
15728 
15729   if (II) {
15730     // FIXME: When interfaces are DeclContexts, we'll need to add
15731     // these to the interface.
15732     S->AddDecl(NewID);
15733     IdResolver.AddDecl(NewID);
15734   }
15735 
15736   if (LangOpts.ObjCRuntime.isNonFragile() &&
15737       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
15738     Diag(Loc, diag::warn_ivars_in_interface);
15739 
15740   return NewID;
15741 }
15742 
15743 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
15744 /// class and class extensions. For every class \@interface and class
15745 /// extension \@interface, if the last ivar is a bitfield of any type,
15746 /// then add an implicit `char :0` ivar to the end of that interface.
15747 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
15748                              SmallVectorImpl<Decl *> &AllIvarDecls) {
15749   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
15750     return;
15751 
15752   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
15753   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
15754 
15755   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
15756     return;
15757   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
15758   if (!ID) {
15759     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
15760       if (!CD->IsClassExtension())
15761         return;
15762     }
15763     // No need to add this to end of @implementation.
15764     else
15765       return;
15766   }
15767   // All conditions are met. Add a new bitfield to the tail end of ivars.
15768   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
15769   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
15770 
15771   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
15772                               DeclLoc, DeclLoc, nullptr,
15773                               Context.CharTy,
15774                               Context.getTrivialTypeSourceInfo(Context.CharTy,
15775                                                                DeclLoc),
15776                               ObjCIvarDecl::Private, BW,
15777                               true);
15778   AllIvarDecls.push_back(Ivar);
15779 }
15780 
15781 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
15782                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
15783                        SourceLocation RBrac,
15784                        const ParsedAttributesView &Attrs) {
15785   assert(EnclosingDecl && "missing record or interface decl");
15786 
15787   // If this is an Objective-C @implementation or category and we have
15788   // new fields here we should reset the layout of the interface since
15789   // it will now change.
15790   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
15791     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
15792     switch (DC->getKind()) {
15793     default: break;
15794     case Decl::ObjCCategory:
15795       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
15796       break;
15797     case Decl::ObjCImplementation:
15798       Context.
15799         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
15800       break;
15801     }
15802   }
15803 
15804   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
15805   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
15806 
15807   // Start counting up the number of named members; make sure to include
15808   // members of anonymous structs and unions in the total.
15809   unsigned NumNamedMembers = 0;
15810   if (Record) {
15811     for (const auto *I : Record->decls()) {
15812       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
15813         if (IFD->getDeclName())
15814           ++NumNamedMembers;
15815     }
15816   }
15817 
15818   // Verify that all the fields are okay.
15819   SmallVector<FieldDecl*, 32> RecFields;
15820 
15821   bool ObjCFieldLifetimeErrReported = false;
15822   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
15823        i != end; ++i) {
15824     FieldDecl *FD = cast<FieldDecl>(*i);
15825 
15826     // Get the type for the field.
15827     const Type *FDTy = FD->getType().getTypePtr();
15828 
15829     if (!FD->isAnonymousStructOrUnion()) {
15830       // Remember all fields written by the user.
15831       RecFields.push_back(FD);
15832     }
15833 
15834     // If the field is already invalid for some reason, don't emit more
15835     // diagnostics about it.
15836     if (FD->isInvalidDecl()) {
15837       EnclosingDecl->setInvalidDecl();
15838       continue;
15839     }
15840 
15841     // C99 6.7.2.1p2:
15842     //   A structure or union shall not contain a member with
15843     //   incomplete or function type (hence, a structure shall not
15844     //   contain an instance of itself, but may contain a pointer to
15845     //   an instance of itself), except that the last member of a
15846     //   structure with more than one named member may have incomplete
15847     //   array type; such a structure (and any union containing,
15848     //   possibly recursively, a member that is such a structure)
15849     //   shall not be a member of a structure or an element of an
15850     //   array.
15851     bool IsLastField = (i + 1 == Fields.end());
15852     if (FDTy->isFunctionType()) {
15853       // Field declared as a function.
15854       Diag(FD->getLocation(), diag::err_field_declared_as_function)
15855         << FD->getDeclName();
15856       FD->setInvalidDecl();
15857       EnclosingDecl->setInvalidDecl();
15858       continue;
15859     } else if (FDTy->isIncompleteArrayType() &&
15860                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
15861       if (Record) {
15862         // Flexible array member.
15863         // Microsoft and g++ is more permissive regarding flexible array.
15864         // It will accept flexible array in union and also
15865         // as the sole element of a struct/class.
15866         unsigned DiagID = 0;
15867         if (!Record->isUnion() && !IsLastField) {
15868           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
15869             << FD->getDeclName() << FD->getType() << Record->getTagKind();
15870           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
15871           FD->setInvalidDecl();
15872           EnclosingDecl->setInvalidDecl();
15873           continue;
15874         } else if (Record->isUnion())
15875           DiagID = getLangOpts().MicrosoftExt
15876                        ? diag::ext_flexible_array_union_ms
15877                        : getLangOpts().CPlusPlus
15878                              ? diag::ext_flexible_array_union_gnu
15879                              : diag::err_flexible_array_union;
15880         else if (NumNamedMembers < 1)
15881           DiagID = getLangOpts().MicrosoftExt
15882                        ? diag::ext_flexible_array_empty_aggregate_ms
15883                        : getLangOpts().CPlusPlus
15884                              ? diag::ext_flexible_array_empty_aggregate_gnu
15885                              : diag::err_flexible_array_empty_aggregate;
15886 
15887         if (DiagID)
15888           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
15889                                           << Record->getTagKind();
15890         // While the layout of types that contain virtual bases is not specified
15891         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
15892         // virtual bases after the derived members.  This would make a flexible
15893         // array member declared at the end of an object not adjacent to the end
15894         // of the type.
15895         if (CXXRecord && CXXRecord->getNumVBases() != 0)
15896           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
15897               << FD->getDeclName() << Record->getTagKind();
15898         if (!getLangOpts().C99)
15899           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
15900             << FD->getDeclName() << Record->getTagKind();
15901 
15902         // If the element type has a non-trivial destructor, we would not
15903         // implicitly destroy the elements, so disallow it for now.
15904         //
15905         // FIXME: GCC allows this. We should probably either implicitly delete
15906         // the destructor of the containing class, or just allow this.
15907         QualType BaseElem = Context.getBaseElementType(FD->getType());
15908         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
15909           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
15910             << FD->getDeclName() << FD->getType();
15911           FD->setInvalidDecl();
15912           EnclosingDecl->setInvalidDecl();
15913           continue;
15914         }
15915         // Okay, we have a legal flexible array member at the end of the struct.
15916         Record->setHasFlexibleArrayMember(true);
15917       } else {
15918         // In ObjCContainerDecl ivars with incomplete array type are accepted,
15919         // unless they are followed by another ivar. That check is done
15920         // elsewhere, after synthesized ivars are known.
15921       }
15922     } else if (!FDTy->isDependentType() &&
15923                RequireCompleteType(FD->getLocation(), FD->getType(),
15924                                    diag::err_field_incomplete)) {
15925       // Incomplete type
15926       FD->setInvalidDecl();
15927       EnclosingDecl->setInvalidDecl();
15928       continue;
15929     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
15930       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
15931         // A type which contains a flexible array member is considered to be a
15932         // flexible array member.
15933         Record->setHasFlexibleArrayMember(true);
15934         if (!Record->isUnion()) {
15935           // If this is a struct/class and this is not the last element, reject
15936           // it.  Note that GCC supports variable sized arrays in the middle of
15937           // structures.
15938           if (!IsLastField)
15939             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
15940               << FD->getDeclName() << FD->getType();
15941           else {
15942             // We support flexible arrays at the end of structs in
15943             // other structs as an extension.
15944             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
15945               << FD->getDeclName();
15946           }
15947         }
15948       }
15949       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
15950           RequireNonAbstractType(FD->getLocation(), FD->getType(),
15951                                  diag::err_abstract_type_in_decl,
15952                                  AbstractIvarType)) {
15953         // Ivars can not have abstract class types
15954         FD->setInvalidDecl();
15955       }
15956       if (Record && FDTTy->getDecl()->hasObjectMember())
15957         Record->setHasObjectMember(true);
15958       if (Record && FDTTy->getDecl()->hasVolatileMember())
15959         Record->setHasVolatileMember(true);
15960       if (Record && Record->isUnion() &&
15961           FD->getType().isNonTrivialPrimitiveCType(Context))
15962         Diag(FD->getLocation(),
15963              diag::err_nontrivial_primitive_type_in_union);
15964     } else if (FDTy->isObjCObjectType()) {
15965       /// A field cannot be an Objective-c object
15966       Diag(FD->getLocation(), diag::err_statically_allocated_object)
15967         << FixItHint::CreateInsertion(FD->getLocation(), "*");
15968       QualType T = Context.getObjCObjectPointerType(FD->getType());
15969       FD->setType(T);
15970     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
15971                Record && !ObjCFieldLifetimeErrReported && Record->isUnion() &&
15972                !getLangOpts().CPlusPlus) {
15973       // It's an error in ARC or Weak if a field has lifetime.
15974       // We don't want to report this in a system header, though,
15975       // so we just make the field unavailable.
15976       // FIXME: that's really not sufficient; we need to make the type
15977       // itself invalid to, say, initialize or copy.
15978       QualType T = FD->getType();
15979       if (T.hasNonTrivialObjCLifetime()) {
15980         SourceLocation loc = FD->getLocation();
15981         if (getSourceManager().isInSystemHeader(loc)) {
15982           if (!FD->hasAttr<UnavailableAttr>()) {
15983             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15984                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
15985           }
15986         } else {
15987           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
15988             << T->isBlockPointerType() << Record->getTagKind();
15989         }
15990         ObjCFieldLifetimeErrReported = true;
15991       }
15992     } else if (getLangOpts().ObjC &&
15993                getLangOpts().getGC() != LangOptions::NonGC &&
15994                Record && !Record->hasObjectMember()) {
15995       if (FD->getType()->isObjCObjectPointerType() ||
15996           FD->getType().isObjCGCStrong())
15997         Record->setHasObjectMember(true);
15998       else if (Context.getAsArrayType(FD->getType())) {
15999         QualType BaseType = Context.getBaseElementType(FD->getType());
16000         if (BaseType->isRecordType() &&
16001             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
16002           Record->setHasObjectMember(true);
16003         else if (BaseType->isObjCObjectPointerType() ||
16004                  BaseType.isObjCGCStrong())
16005                Record->setHasObjectMember(true);
16006       }
16007     }
16008 
16009     if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
16010       QualType FT = FD->getType();
16011       if (FT.isNonTrivialToPrimitiveDefaultInitialize())
16012         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
16013       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
16014       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial)
16015         Record->setNonTrivialToPrimitiveCopy(true);
16016       if (FT.isDestructedType()) {
16017         Record->setNonTrivialToPrimitiveDestroy(true);
16018         Record->setParamDestroyedInCallee(true);
16019       }
16020 
16021       if (const auto *RT = FT->getAs<RecordType>()) {
16022         if (RT->getDecl()->getArgPassingRestrictions() ==
16023             RecordDecl::APK_CanNeverPassInRegs)
16024           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16025       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
16026         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16027     }
16028 
16029     if (Record && FD->getType().isVolatileQualified())
16030       Record->setHasVolatileMember(true);
16031     // Keep track of the number of named members.
16032     if (FD->getIdentifier())
16033       ++NumNamedMembers;
16034   }
16035 
16036   // Okay, we successfully defined 'Record'.
16037   if (Record) {
16038     bool Completed = false;
16039     if (CXXRecord) {
16040       if (!CXXRecord->isInvalidDecl()) {
16041         // Set access bits correctly on the directly-declared conversions.
16042         for (CXXRecordDecl::conversion_iterator
16043                I = CXXRecord->conversion_begin(),
16044                E = CXXRecord->conversion_end(); I != E; ++I)
16045           I.setAccess((*I)->getAccess());
16046       }
16047 
16048       if (!CXXRecord->isDependentType()) {
16049         // Add any implicitly-declared members to this class.
16050         AddImplicitlyDeclaredMembersToClass(CXXRecord);
16051 
16052         if (!CXXRecord->isInvalidDecl()) {
16053           // If we have virtual base classes, we may end up finding multiple
16054           // final overriders for a given virtual function. Check for this
16055           // problem now.
16056           if (CXXRecord->getNumVBases()) {
16057             CXXFinalOverriderMap FinalOverriders;
16058             CXXRecord->getFinalOverriders(FinalOverriders);
16059 
16060             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16061                                              MEnd = FinalOverriders.end();
16062                  M != MEnd; ++M) {
16063               for (OverridingMethods::iterator SO = M->second.begin(),
16064                                             SOEnd = M->second.end();
16065                    SO != SOEnd; ++SO) {
16066                 assert(SO->second.size() > 0 &&
16067                        "Virtual function without overriding functions?");
16068                 if (SO->second.size() == 1)
16069                   continue;
16070 
16071                 // C++ [class.virtual]p2:
16072                 //   In a derived class, if a virtual member function of a base
16073                 //   class subobject has more than one final overrider the
16074                 //   program is ill-formed.
16075                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16076                   << (const NamedDecl *)M->first << Record;
16077                 Diag(M->first->getLocation(),
16078                      diag::note_overridden_virtual_function);
16079                 for (OverridingMethods::overriding_iterator
16080                           OM = SO->second.begin(),
16081                        OMEnd = SO->second.end();
16082                      OM != OMEnd; ++OM)
16083                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
16084                     << (const NamedDecl *)M->first << OM->Method->getParent();
16085 
16086                 Record->setInvalidDecl();
16087               }
16088             }
16089             CXXRecord->completeDefinition(&FinalOverriders);
16090             Completed = true;
16091           }
16092         }
16093       }
16094     }
16095 
16096     if (!Completed)
16097       Record->completeDefinition();
16098 
16099     // Handle attributes before checking the layout.
16100     ProcessDeclAttributeList(S, Record, Attrs);
16101 
16102     // We may have deferred checking for a deleted destructor. Check now.
16103     if (CXXRecord) {
16104       auto *Dtor = CXXRecord->getDestructor();
16105       if (Dtor && Dtor->isImplicit() &&
16106           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16107         CXXRecord->setImplicitDestructorIsDeleted();
16108         SetDeclDeleted(Dtor, CXXRecord->getLocation());
16109       }
16110     }
16111 
16112     if (Record->hasAttrs()) {
16113       CheckAlignasUnderalignment(Record);
16114 
16115       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16116         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16117                                            IA->getRange(), IA->getBestCase(),
16118                                            IA->getSemanticSpelling());
16119     }
16120 
16121     // Check if the structure/union declaration is a type that can have zero
16122     // size in C. For C this is a language extension, for C++ it may cause
16123     // compatibility problems.
16124     bool CheckForZeroSize;
16125     if (!getLangOpts().CPlusPlus) {
16126       CheckForZeroSize = true;
16127     } else {
16128       // For C++ filter out types that cannot be referenced in C code.
16129       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16130       CheckForZeroSize =
16131           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16132           !CXXRecord->isDependentType() &&
16133           CXXRecord->isCLike();
16134     }
16135     if (CheckForZeroSize) {
16136       bool ZeroSize = true;
16137       bool IsEmpty = true;
16138       unsigned NonBitFields = 0;
16139       for (RecordDecl::field_iterator I = Record->field_begin(),
16140                                       E = Record->field_end();
16141            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16142         IsEmpty = false;
16143         if (I->isUnnamedBitfield()) {
16144           if (!I->isZeroLengthBitField(Context))
16145             ZeroSize = false;
16146         } else {
16147           ++NonBitFields;
16148           QualType FieldType = I->getType();
16149           if (FieldType->isIncompleteType() ||
16150               !Context.getTypeSizeInChars(FieldType).isZero())
16151             ZeroSize = false;
16152         }
16153       }
16154 
16155       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16156       // allowed in C++, but warn if its declaration is inside
16157       // extern "C" block.
16158       if (ZeroSize) {
16159         Diag(RecLoc, getLangOpts().CPlusPlus ?
16160                          diag::warn_zero_size_struct_union_in_extern_c :
16161                          diag::warn_zero_size_struct_union_compat)
16162           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16163       }
16164 
16165       // Structs without named members are extension in C (C99 6.7.2.1p7),
16166       // but are accepted by GCC.
16167       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16168         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16169                                diag::ext_no_named_members_in_struct_union)
16170           << Record->isUnion();
16171       }
16172     }
16173   } else {
16174     ObjCIvarDecl **ClsFields =
16175       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16176     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16177       ID->setEndOfDefinitionLoc(RBrac);
16178       // Add ivar's to class's DeclContext.
16179       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16180         ClsFields[i]->setLexicalDeclContext(ID);
16181         ID->addDecl(ClsFields[i]);
16182       }
16183       // Must enforce the rule that ivars in the base classes may not be
16184       // duplicates.
16185       if (ID->getSuperClass())
16186         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16187     } else if (ObjCImplementationDecl *IMPDecl =
16188                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16189       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16190       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16191         // Ivar declared in @implementation never belongs to the implementation.
16192         // Only it is in implementation's lexical context.
16193         ClsFields[I]->setLexicalDeclContext(IMPDecl);
16194       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16195       IMPDecl->setIvarLBraceLoc(LBrac);
16196       IMPDecl->setIvarRBraceLoc(RBrac);
16197     } else if (ObjCCategoryDecl *CDecl =
16198                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16199       // case of ivars in class extension; all other cases have been
16200       // reported as errors elsewhere.
16201       // FIXME. Class extension does not have a LocEnd field.
16202       // CDecl->setLocEnd(RBrac);
16203       // Add ivar's to class extension's DeclContext.
16204       // Diagnose redeclaration of private ivars.
16205       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16206       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16207         if (IDecl) {
16208           if (const ObjCIvarDecl *ClsIvar =
16209               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16210             Diag(ClsFields[i]->getLocation(),
16211                  diag::err_duplicate_ivar_declaration);
16212             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16213             continue;
16214           }
16215           for (const auto *Ext : IDecl->known_extensions()) {
16216             if (const ObjCIvarDecl *ClsExtIvar
16217                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16218               Diag(ClsFields[i]->getLocation(),
16219                    diag::err_duplicate_ivar_declaration);
16220               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16221               continue;
16222             }
16223           }
16224         }
16225         ClsFields[i]->setLexicalDeclContext(CDecl);
16226         CDecl->addDecl(ClsFields[i]);
16227       }
16228       CDecl->setIvarLBraceLoc(LBrac);
16229       CDecl->setIvarRBraceLoc(RBrac);
16230     }
16231   }
16232 }
16233 
16234 /// Determine whether the given integral value is representable within
16235 /// the given type T.
16236 static bool isRepresentableIntegerValue(ASTContext &Context,
16237                                         llvm::APSInt &Value,
16238                                         QualType T) {
16239   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
16240          "Integral type required!");
16241   unsigned BitWidth = Context.getIntWidth(T);
16242 
16243   if (Value.isUnsigned() || Value.isNonNegative()) {
16244     if (T->isSignedIntegerOrEnumerationType())
16245       --BitWidth;
16246     return Value.getActiveBits() <= BitWidth;
16247   }
16248   return Value.getMinSignedBits() <= BitWidth;
16249 }
16250 
16251 // Given an integral type, return the next larger integral type
16252 // (or a NULL type of no such type exists).
16253 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
16254   // FIXME: Int128/UInt128 support, which also needs to be introduced into
16255   // enum checking below.
16256   assert((T->isIntegralType(Context) ||
16257          T->isEnumeralType()) && "Integral type required!");
16258   const unsigned NumTypes = 4;
16259   QualType SignedIntegralTypes[NumTypes] = {
16260     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
16261   };
16262   QualType UnsignedIntegralTypes[NumTypes] = {
16263     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
16264     Context.UnsignedLongLongTy
16265   };
16266 
16267   unsigned BitWidth = Context.getTypeSize(T);
16268   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
16269                                                         : UnsignedIntegralTypes;
16270   for (unsigned I = 0; I != NumTypes; ++I)
16271     if (Context.getTypeSize(Types[I]) > BitWidth)
16272       return Types[I];
16273 
16274   return QualType();
16275 }
16276 
16277 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
16278                                           EnumConstantDecl *LastEnumConst,
16279                                           SourceLocation IdLoc,
16280                                           IdentifierInfo *Id,
16281                                           Expr *Val) {
16282   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16283   llvm::APSInt EnumVal(IntWidth);
16284   QualType EltTy;
16285 
16286   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
16287     Val = nullptr;
16288 
16289   if (Val)
16290     Val = DefaultLvalueConversion(Val).get();
16291 
16292   if (Val) {
16293     if (Enum->isDependentType() || Val->isTypeDependent())
16294       EltTy = Context.DependentTy;
16295     else {
16296       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
16297           !getLangOpts().MSVCCompat) {
16298         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
16299         // constant-expression in the enumerator-definition shall be a converted
16300         // constant expression of the underlying type.
16301         EltTy = Enum->getIntegerType();
16302         ExprResult Converted =
16303           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
16304                                            CCEK_Enumerator);
16305         if (Converted.isInvalid())
16306           Val = nullptr;
16307         else
16308           Val = Converted.get();
16309       } else if (!Val->isValueDependent() &&
16310                  !(Val = VerifyIntegerConstantExpression(Val,
16311                                                          &EnumVal).get())) {
16312         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
16313       } else {
16314         if (Enum->isComplete()) {
16315           EltTy = Enum->getIntegerType();
16316 
16317           // In Obj-C and Microsoft mode, require the enumeration value to be
16318           // representable in the underlying type of the enumeration. In C++11,
16319           // we perform a non-narrowing conversion as part of converted constant
16320           // expression checking.
16321           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16322             if (getLangOpts().MSVCCompat) {
16323               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
16324               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
16325             } else
16326               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
16327           } else
16328             Val = ImpCastExprToType(Val, EltTy,
16329                                     EltTy->isBooleanType() ?
16330                                     CK_IntegralToBoolean : CK_IntegralCast)
16331                     .get();
16332         } else if (getLangOpts().CPlusPlus) {
16333           // C++11 [dcl.enum]p5:
16334           //   If the underlying type is not fixed, the type of each enumerator
16335           //   is the type of its initializing value:
16336           //     - If an initializer is specified for an enumerator, the
16337           //       initializing value has the same type as the expression.
16338           EltTy = Val->getType();
16339         } else {
16340           // C99 6.7.2.2p2:
16341           //   The expression that defines the value of an enumeration constant
16342           //   shall be an integer constant expression that has a value
16343           //   representable as an int.
16344 
16345           // Complain if the value is not representable in an int.
16346           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
16347             Diag(IdLoc, diag::ext_enum_value_not_int)
16348               << EnumVal.toString(10) << Val->getSourceRange()
16349               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
16350           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
16351             // Force the type of the expression to 'int'.
16352             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
16353           }
16354           EltTy = Val->getType();
16355         }
16356       }
16357     }
16358   }
16359 
16360   if (!Val) {
16361     if (Enum->isDependentType())
16362       EltTy = Context.DependentTy;
16363     else if (!LastEnumConst) {
16364       // C++0x [dcl.enum]p5:
16365       //   If the underlying type is not fixed, the type of each enumerator
16366       //   is the type of its initializing value:
16367       //     - If no initializer is specified for the first enumerator, the
16368       //       initializing value has an unspecified integral type.
16369       //
16370       // GCC uses 'int' for its unspecified integral type, as does
16371       // C99 6.7.2.2p3.
16372       if (Enum->isFixed()) {
16373         EltTy = Enum->getIntegerType();
16374       }
16375       else {
16376         EltTy = Context.IntTy;
16377       }
16378     } else {
16379       // Assign the last value + 1.
16380       EnumVal = LastEnumConst->getInitVal();
16381       ++EnumVal;
16382       EltTy = LastEnumConst->getType();
16383 
16384       // Check for overflow on increment.
16385       if (EnumVal < LastEnumConst->getInitVal()) {
16386         // C++0x [dcl.enum]p5:
16387         //   If the underlying type is not fixed, the type of each enumerator
16388         //   is the type of its initializing value:
16389         //
16390         //     - Otherwise the type of the initializing value is the same as
16391         //       the type of the initializing value of the preceding enumerator
16392         //       unless the incremented value is not representable in that type,
16393         //       in which case the type is an unspecified integral type
16394         //       sufficient to contain the incremented value. If no such type
16395         //       exists, the program is ill-formed.
16396         QualType T = getNextLargerIntegralType(Context, EltTy);
16397         if (T.isNull() || Enum->isFixed()) {
16398           // There is no integral type larger enough to represent this
16399           // value. Complain, then allow the value to wrap around.
16400           EnumVal = LastEnumConst->getInitVal();
16401           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
16402           ++EnumVal;
16403           if (Enum->isFixed())
16404             // When the underlying type is fixed, this is ill-formed.
16405             Diag(IdLoc, diag::err_enumerator_wrapped)
16406               << EnumVal.toString(10)
16407               << EltTy;
16408           else
16409             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
16410               << EnumVal.toString(10);
16411         } else {
16412           EltTy = T;
16413         }
16414 
16415         // Retrieve the last enumerator's value, extent that type to the
16416         // type that is supposed to be large enough to represent the incremented
16417         // value, then increment.
16418         EnumVal = LastEnumConst->getInitVal();
16419         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16420         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
16421         ++EnumVal;
16422 
16423         // If we're not in C++, diagnose the overflow of enumerator values,
16424         // which in C99 means that the enumerator value is not representable in
16425         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
16426         // permits enumerator values that are representable in some larger
16427         // integral type.
16428         if (!getLangOpts().CPlusPlus && !T.isNull())
16429           Diag(IdLoc, diag::warn_enum_value_overflow);
16430       } else if (!getLangOpts().CPlusPlus &&
16431                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16432         // Enforce C99 6.7.2.2p2 even when we compute the next value.
16433         Diag(IdLoc, diag::ext_enum_value_not_int)
16434           << EnumVal.toString(10) << 1;
16435       }
16436     }
16437   }
16438 
16439   if (!EltTy->isDependentType()) {
16440     // Make the enumerator value match the signedness and size of the
16441     // enumerator's type.
16442     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
16443     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16444   }
16445 
16446   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
16447                                   Val, EnumVal);
16448 }
16449 
16450 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
16451                                                 SourceLocation IILoc) {
16452   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
16453       !getLangOpts().CPlusPlus)
16454     return SkipBodyInfo();
16455 
16456   // We have an anonymous enum definition. Look up the first enumerator to
16457   // determine if we should merge the definition with an existing one and
16458   // skip the body.
16459   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
16460                                          forRedeclarationInCurContext());
16461   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
16462   if (!PrevECD)
16463     return SkipBodyInfo();
16464 
16465   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
16466   NamedDecl *Hidden;
16467   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
16468     SkipBodyInfo Skip;
16469     Skip.Previous = Hidden;
16470     return Skip;
16471   }
16472 
16473   return SkipBodyInfo();
16474 }
16475 
16476 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
16477                               SourceLocation IdLoc, IdentifierInfo *Id,
16478                               const ParsedAttributesView &Attrs,
16479                               SourceLocation EqualLoc, Expr *Val) {
16480   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
16481   EnumConstantDecl *LastEnumConst =
16482     cast_or_null<EnumConstantDecl>(lastEnumConst);
16483 
16484   // The scope passed in may not be a decl scope.  Zip up the scope tree until
16485   // we find one that is.
16486   S = getNonFieldDeclScope(S);
16487 
16488   // Verify that there isn't already something declared with this name in this
16489   // scope.
16490   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
16491   LookupName(R, S);
16492   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
16493 
16494   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16495     // Maybe we will complain about the shadowed template parameter.
16496     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
16497     // Just pretend that we didn't see the previous declaration.
16498     PrevDecl = nullptr;
16499   }
16500 
16501   // C++ [class.mem]p15:
16502   // If T is the name of a class, then each of the following shall have a name
16503   // different from T:
16504   // - every enumerator of every member of class T that is an unscoped
16505   // enumerated type
16506   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
16507     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
16508                             DeclarationNameInfo(Id, IdLoc));
16509 
16510   EnumConstantDecl *New =
16511     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
16512   if (!New)
16513     return nullptr;
16514 
16515   if (PrevDecl) {
16516     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
16517       // Check for other kinds of shadowing not already handled.
16518       CheckShadow(New, PrevDecl, R);
16519     }
16520 
16521     // When in C++, we may get a TagDecl with the same name; in this case the
16522     // enum constant will 'hide' the tag.
16523     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
16524            "Received TagDecl when not in C++!");
16525     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
16526       if (isa<EnumConstantDecl>(PrevDecl))
16527         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
16528       else
16529         Diag(IdLoc, diag::err_redefinition) << Id;
16530       notePreviousDefinition(PrevDecl, IdLoc);
16531       return nullptr;
16532     }
16533   }
16534 
16535   // Process attributes.
16536   ProcessDeclAttributeList(S, New, Attrs);
16537   AddPragmaAttributes(S, New);
16538 
16539   // Register this decl in the current scope stack.
16540   New->setAccess(TheEnumDecl->getAccess());
16541   PushOnScopeChains(New, S);
16542 
16543   ActOnDocumentableDecl(New);
16544 
16545   return New;
16546 }
16547 
16548 // Returns true when the enum initial expression does not trigger the
16549 // duplicate enum warning.  A few common cases are exempted as follows:
16550 // Element2 = Element1
16551 // Element2 = Element1 + 1
16552 // Element2 = Element1 - 1
16553 // Where Element2 and Element1 are from the same enum.
16554 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
16555   Expr *InitExpr = ECD->getInitExpr();
16556   if (!InitExpr)
16557     return true;
16558   InitExpr = InitExpr->IgnoreImpCasts();
16559 
16560   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
16561     if (!BO->isAdditiveOp())
16562       return true;
16563     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
16564     if (!IL)
16565       return true;
16566     if (IL->getValue() != 1)
16567       return true;
16568 
16569     InitExpr = BO->getLHS();
16570   }
16571 
16572   // This checks if the elements are from the same enum.
16573   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
16574   if (!DRE)
16575     return true;
16576 
16577   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
16578   if (!EnumConstant)
16579     return true;
16580 
16581   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
16582       Enum)
16583     return true;
16584 
16585   return false;
16586 }
16587 
16588 // Emits a warning when an element is implicitly set a value that
16589 // a previous element has already been set to.
16590 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
16591                                         EnumDecl *Enum, QualType EnumType) {
16592   // Avoid anonymous enums
16593   if (!Enum->getIdentifier())
16594     return;
16595 
16596   // Only check for small enums.
16597   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
16598     return;
16599 
16600   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
16601     return;
16602 
16603   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
16604   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
16605 
16606   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
16607   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
16608 
16609   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
16610   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
16611     llvm::APSInt Val = D->getInitVal();
16612     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
16613   };
16614 
16615   DuplicatesVector DupVector;
16616   ValueToVectorMap EnumMap;
16617 
16618   // Populate the EnumMap with all values represented by enum constants without
16619   // an initializer.
16620   for (auto *Element : Elements) {
16621     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
16622 
16623     // Null EnumConstantDecl means a previous diagnostic has been emitted for
16624     // this constant.  Skip this enum since it may be ill-formed.
16625     if (!ECD) {
16626       return;
16627     }
16628 
16629     // Constants with initalizers are handled in the next loop.
16630     if (ECD->getInitExpr())
16631       continue;
16632 
16633     // Duplicate values are handled in the next loop.
16634     EnumMap.insert({EnumConstantToKey(ECD), ECD});
16635   }
16636 
16637   if (EnumMap.size() == 0)
16638     return;
16639 
16640   // Create vectors for any values that has duplicates.
16641   for (auto *Element : Elements) {
16642     // The last loop returned if any constant was null.
16643     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
16644     if (!ValidDuplicateEnum(ECD, Enum))
16645       continue;
16646 
16647     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
16648     if (Iter == EnumMap.end())
16649       continue;
16650 
16651     DeclOrVector& Entry = Iter->second;
16652     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
16653       // Ensure constants are different.
16654       if (D == ECD)
16655         continue;
16656 
16657       // Create new vector and push values onto it.
16658       auto Vec = llvm::make_unique<ECDVector>();
16659       Vec->push_back(D);
16660       Vec->push_back(ECD);
16661 
16662       // Update entry to point to the duplicates vector.
16663       Entry = Vec.get();
16664 
16665       // Store the vector somewhere we can consult later for quick emission of
16666       // diagnostics.
16667       DupVector.emplace_back(std::move(Vec));
16668       continue;
16669     }
16670 
16671     ECDVector *Vec = Entry.get<ECDVector*>();
16672     // Make sure constants are not added more than once.
16673     if (*Vec->begin() == ECD)
16674       continue;
16675 
16676     Vec->push_back(ECD);
16677   }
16678 
16679   // Emit diagnostics.
16680   for (const auto &Vec : DupVector) {
16681     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
16682 
16683     // Emit warning for one enum constant.
16684     auto *FirstECD = Vec->front();
16685     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
16686       << FirstECD << FirstECD->getInitVal().toString(10)
16687       << FirstECD->getSourceRange();
16688 
16689     // Emit one note for each of the remaining enum constants with
16690     // the same value.
16691     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
16692       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
16693         << ECD << ECD->getInitVal().toString(10)
16694         << ECD->getSourceRange();
16695   }
16696 }
16697 
16698 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
16699                              bool AllowMask) const {
16700   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
16701   assert(ED->isCompleteDefinition() && "expected enum definition");
16702 
16703   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
16704   llvm::APInt &FlagBits = R.first->second;
16705 
16706   if (R.second) {
16707     for (auto *E : ED->enumerators()) {
16708       const auto &EVal = E->getInitVal();
16709       // Only single-bit enumerators introduce new flag values.
16710       if (EVal.isPowerOf2())
16711         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
16712     }
16713   }
16714 
16715   // A value is in a flag enum if either its bits are a subset of the enum's
16716   // flag bits (the first condition) or we are allowing masks and the same is
16717   // true of its complement (the second condition). When masks are allowed, we
16718   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
16719   //
16720   // While it's true that any value could be used as a mask, the assumption is
16721   // that a mask will have all of the insignificant bits set. Anything else is
16722   // likely a logic error.
16723   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
16724   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
16725 }
16726 
16727 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
16728                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
16729                          const ParsedAttributesView &Attrs) {
16730   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
16731   QualType EnumType = Context.getTypeDeclType(Enum);
16732 
16733   ProcessDeclAttributeList(S, Enum, Attrs);
16734 
16735   if (Enum->isDependentType()) {
16736     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16737       EnumConstantDecl *ECD =
16738         cast_or_null<EnumConstantDecl>(Elements[i]);
16739       if (!ECD) continue;
16740 
16741       ECD->setType(EnumType);
16742     }
16743 
16744     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
16745     return;
16746   }
16747 
16748   // TODO: If the result value doesn't fit in an int, it must be a long or long
16749   // long value.  ISO C does not support this, but GCC does as an extension,
16750   // emit a warning.
16751   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16752   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
16753   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
16754 
16755   // Verify that all the values are okay, compute the size of the values, and
16756   // reverse the list.
16757   unsigned NumNegativeBits = 0;
16758   unsigned NumPositiveBits = 0;
16759 
16760   // Keep track of whether all elements have type int.
16761   bool AllElementsInt = true;
16762 
16763   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16764     EnumConstantDecl *ECD =
16765       cast_or_null<EnumConstantDecl>(Elements[i]);
16766     if (!ECD) continue;  // Already issued a diagnostic.
16767 
16768     const llvm::APSInt &InitVal = ECD->getInitVal();
16769 
16770     // Keep track of the size of positive and negative values.
16771     if (InitVal.isUnsigned() || InitVal.isNonNegative())
16772       NumPositiveBits = std::max(NumPositiveBits,
16773                                  (unsigned)InitVal.getActiveBits());
16774     else
16775       NumNegativeBits = std::max(NumNegativeBits,
16776                                  (unsigned)InitVal.getMinSignedBits());
16777 
16778     // Keep track of whether every enum element has type int (very common).
16779     if (AllElementsInt)
16780       AllElementsInt = ECD->getType() == Context.IntTy;
16781   }
16782 
16783   // Figure out the type that should be used for this enum.
16784   QualType BestType;
16785   unsigned BestWidth;
16786 
16787   // C++0x N3000 [conv.prom]p3:
16788   //   An rvalue of an unscoped enumeration type whose underlying
16789   //   type is not fixed can be converted to an rvalue of the first
16790   //   of the following types that can represent all the values of
16791   //   the enumeration: int, unsigned int, long int, unsigned long
16792   //   int, long long int, or unsigned long long int.
16793   // C99 6.4.4.3p2:
16794   //   An identifier declared as an enumeration constant has type int.
16795   // The C99 rule is modified by a gcc extension
16796   QualType BestPromotionType;
16797 
16798   bool Packed = Enum->hasAttr<PackedAttr>();
16799   // -fshort-enums is the equivalent to specifying the packed attribute on all
16800   // enum definitions.
16801   if (LangOpts.ShortEnums)
16802     Packed = true;
16803 
16804   // If the enum already has a type because it is fixed or dictated by the
16805   // target, promote that type instead of analyzing the enumerators.
16806   if (Enum->isComplete()) {
16807     BestType = Enum->getIntegerType();
16808     if (BestType->isPromotableIntegerType())
16809       BestPromotionType = Context.getPromotedIntegerType(BestType);
16810     else
16811       BestPromotionType = BestType;
16812 
16813     BestWidth = Context.getIntWidth(BestType);
16814   }
16815   else if (NumNegativeBits) {
16816     // If there is a negative value, figure out the smallest integer type (of
16817     // int/long/longlong) that fits.
16818     // If it's packed, check also if it fits a char or a short.
16819     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
16820       BestType = Context.SignedCharTy;
16821       BestWidth = CharWidth;
16822     } else if (Packed && NumNegativeBits <= ShortWidth &&
16823                NumPositiveBits < ShortWidth) {
16824       BestType = Context.ShortTy;
16825       BestWidth = ShortWidth;
16826     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
16827       BestType = Context.IntTy;
16828       BestWidth = IntWidth;
16829     } else {
16830       BestWidth = Context.getTargetInfo().getLongWidth();
16831 
16832       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
16833         BestType = Context.LongTy;
16834       } else {
16835         BestWidth = Context.getTargetInfo().getLongLongWidth();
16836 
16837         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
16838           Diag(Enum->getLocation(), diag::ext_enum_too_large);
16839         BestType = Context.LongLongTy;
16840       }
16841     }
16842     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
16843   } else {
16844     // If there is no negative value, figure out the smallest type that fits
16845     // all of the enumerator values.
16846     // If it's packed, check also if it fits a char or a short.
16847     if (Packed && NumPositiveBits <= CharWidth) {
16848       BestType = Context.UnsignedCharTy;
16849       BestPromotionType = Context.IntTy;
16850       BestWidth = CharWidth;
16851     } else if (Packed && NumPositiveBits <= ShortWidth) {
16852       BestType = Context.UnsignedShortTy;
16853       BestPromotionType = Context.IntTy;
16854       BestWidth = ShortWidth;
16855     } else if (NumPositiveBits <= IntWidth) {
16856       BestType = Context.UnsignedIntTy;
16857       BestWidth = IntWidth;
16858       BestPromotionType
16859         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16860                            ? Context.UnsignedIntTy : Context.IntTy;
16861     } else if (NumPositiveBits <=
16862                (BestWidth = Context.getTargetInfo().getLongWidth())) {
16863       BestType = Context.UnsignedLongTy;
16864       BestPromotionType
16865         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16866                            ? Context.UnsignedLongTy : Context.LongTy;
16867     } else {
16868       BestWidth = Context.getTargetInfo().getLongLongWidth();
16869       assert(NumPositiveBits <= BestWidth &&
16870              "How could an initializer get larger than ULL?");
16871       BestType = Context.UnsignedLongLongTy;
16872       BestPromotionType
16873         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16874                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
16875     }
16876   }
16877 
16878   // Loop over all of the enumerator constants, changing their types to match
16879   // the type of the enum if needed.
16880   for (auto *D : Elements) {
16881     auto *ECD = cast_or_null<EnumConstantDecl>(D);
16882     if (!ECD) continue;  // Already issued a diagnostic.
16883 
16884     // Standard C says the enumerators have int type, but we allow, as an
16885     // extension, the enumerators to be larger than int size.  If each
16886     // enumerator value fits in an int, type it as an int, otherwise type it the
16887     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
16888     // that X has type 'int', not 'unsigned'.
16889 
16890     // Determine whether the value fits into an int.
16891     llvm::APSInt InitVal = ECD->getInitVal();
16892 
16893     // If it fits into an integer type, force it.  Otherwise force it to match
16894     // the enum decl type.
16895     QualType NewTy;
16896     unsigned NewWidth;
16897     bool NewSign;
16898     if (!getLangOpts().CPlusPlus &&
16899         !Enum->isFixed() &&
16900         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
16901       NewTy = Context.IntTy;
16902       NewWidth = IntWidth;
16903       NewSign = true;
16904     } else if (ECD->getType() == BestType) {
16905       // Already the right type!
16906       if (getLangOpts().CPlusPlus)
16907         // C++ [dcl.enum]p4: Following the closing brace of an
16908         // enum-specifier, each enumerator has the type of its
16909         // enumeration.
16910         ECD->setType(EnumType);
16911       continue;
16912     } else {
16913       NewTy = BestType;
16914       NewWidth = BestWidth;
16915       NewSign = BestType->isSignedIntegerOrEnumerationType();
16916     }
16917 
16918     // Adjust the APSInt value.
16919     InitVal = InitVal.extOrTrunc(NewWidth);
16920     InitVal.setIsSigned(NewSign);
16921     ECD->setInitVal(InitVal);
16922 
16923     // Adjust the Expr initializer and type.
16924     if (ECD->getInitExpr() &&
16925         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
16926       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
16927                                                 CK_IntegralCast,
16928                                                 ECD->getInitExpr(),
16929                                                 /*base paths*/ nullptr,
16930                                                 VK_RValue));
16931     if (getLangOpts().CPlusPlus)
16932       // C++ [dcl.enum]p4: Following the closing brace of an
16933       // enum-specifier, each enumerator has the type of its
16934       // enumeration.
16935       ECD->setType(EnumType);
16936     else
16937       ECD->setType(NewTy);
16938   }
16939 
16940   Enum->completeDefinition(BestType, BestPromotionType,
16941                            NumPositiveBits, NumNegativeBits);
16942 
16943   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
16944 
16945   if (Enum->isClosedFlag()) {
16946     for (Decl *D : Elements) {
16947       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
16948       if (!ECD) continue;  // Already issued a diagnostic.
16949 
16950       llvm::APSInt InitVal = ECD->getInitVal();
16951       if (InitVal != 0 && !InitVal.isPowerOf2() &&
16952           !IsValueInFlagEnum(Enum, InitVal, true))
16953         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
16954           << ECD << Enum;
16955     }
16956   }
16957 
16958   // Now that the enum type is defined, ensure it's not been underaligned.
16959   if (Enum->hasAttrs())
16960     CheckAlignasUnderalignment(Enum);
16961 }
16962 
16963 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
16964                                   SourceLocation StartLoc,
16965                                   SourceLocation EndLoc) {
16966   StringLiteral *AsmString = cast<StringLiteral>(expr);
16967 
16968   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
16969                                                    AsmString, StartLoc,
16970                                                    EndLoc);
16971   CurContext->addDecl(New);
16972   return New;
16973 }
16974 
16975 static void checkModuleImportContext(Sema &S, Module *M,
16976                                      SourceLocation ImportLoc, DeclContext *DC,
16977                                      bool FromInclude = false) {
16978   SourceLocation ExternCLoc;
16979 
16980   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
16981     switch (LSD->getLanguage()) {
16982     case LinkageSpecDecl::lang_c:
16983       if (ExternCLoc.isInvalid())
16984         ExternCLoc = LSD->getBeginLoc();
16985       break;
16986     case LinkageSpecDecl::lang_cxx:
16987       break;
16988     }
16989     DC = LSD->getParent();
16990   }
16991 
16992   while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
16993     DC = DC->getParent();
16994 
16995   if (!isa<TranslationUnitDecl>(DC)) {
16996     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
16997                           ? diag::ext_module_import_not_at_top_level_noop
16998                           : diag::err_module_import_not_at_top_level_fatal)
16999         << M->getFullModuleName() << DC;
17000     S.Diag(cast<Decl>(DC)->getBeginLoc(),
17001            diag::note_module_import_not_at_top_level)
17002         << DC;
17003   } else if (!M->IsExternC && ExternCLoc.isValid()) {
17004     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
17005       << M->getFullModuleName();
17006     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
17007   }
17008 }
17009 
17010 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
17011                                            SourceLocation ModuleLoc,
17012                                            ModuleDeclKind MDK,
17013                                            ModuleIdPath Path) {
17014   assert(getLangOpts().ModulesTS &&
17015          "should only have module decl in modules TS");
17016 
17017   // A module implementation unit requires that we are not compiling a module
17018   // of any kind. A module interface unit requires that we are not compiling a
17019   // module map.
17020   switch (getLangOpts().getCompilingModule()) {
17021   case LangOptions::CMK_None:
17022     // It's OK to compile a module interface as a normal translation unit.
17023     break;
17024 
17025   case LangOptions::CMK_ModuleInterface:
17026     if (MDK != ModuleDeclKind::Implementation)
17027       break;
17028 
17029     // We were asked to compile a module interface unit but this is a module
17030     // implementation unit. That indicates the 'export' is missing.
17031     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
17032       << FixItHint::CreateInsertion(ModuleLoc, "export ");
17033     MDK = ModuleDeclKind::Interface;
17034     break;
17035 
17036   case LangOptions::CMK_ModuleMap:
17037     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
17038     return nullptr;
17039 
17040   case LangOptions::CMK_HeaderModule:
17041     Diag(ModuleLoc, diag::err_module_decl_in_header_module);
17042     return nullptr;
17043   }
17044 
17045   assert(ModuleScopes.size() == 1 && "expected to be at global module scope");
17046 
17047   // FIXME: Most of this work should be done by the preprocessor rather than
17048   // here, in order to support macro import.
17049 
17050   // Only one module-declaration is permitted per source file.
17051   if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) {
17052     Diag(ModuleLoc, diag::err_module_redeclaration);
17053     Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
17054          diag::note_prev_module_declaration);
17055     return nullptr;
17056   }
17057 
17058   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
17059   // modules, the dots here are just another character that can appear in a
17060   // module name.
17061   std::string ModuleName;
17062   for (auto &Piece : Path) {
17063     if (!ModuleName.empty())
17064       ModuleName += ".";
17065     ModuleName += Piece.first->getName();
17066   }
17067 
17068   // If a module name was explicitly specified on the command line, it must be
17069   // correct.
17070   if (!getLangOpts().CurrentModule.empty() &&
17071       getLangOpts().CurrentModule != ModuleName) {
17072     Diag(Path.front().second, diag::err_current_module_name_mismatch)
17073         << SourceRange(Path.front().second, Path.back().second)
17074         << getLangOpts().CurrentModule;
17075     return nullptr;
17076   }
17077   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
17078 
17079   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
17080   Module *Mod;
17081 
17082   switch (MDK) {
17083   case ModuleDeclKind::Interface: {
17084     // We can't have parsed or imported a definition of this module or parsed a
17085     // module map defining it already.
17086     if (auto *M = Map.findModule(ModuleName)) {
17087       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
17088       if (M->DefinitionLoc.isValid())
17089         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
17090       else if (const auto *FE = M->getASTFile())
17091         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
17092             << FE->getName();
17093       Mod = M;
17094       break;
17095     }
17096 
17097     // Create a Module for the module that we're defining.
17098     Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
17099                                            ModuleScopes.front().Module);
17100     assert(Mod && "module creation should not fail");
17101     break;
17102   }
17103 
17104   case ModuleDeclKind::Partition:
17105     // FIXME: Check we are in a submodule of the named module.
17106     return nullptr;
17107 
17108   case ModuleDeclKind::Implementation:
17109     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
17110         PP.getIdentifierInfo(ModuleName), Path[0].second);
17111     Mod = getModuleLoader().loadModule(ModuleLoc, {ModuleNameLoc},
17112                                        Module::AllVisible,
17113                                        /*IsIncludeDirective=*/false);
17114     if (!Mod) {
17115       Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
17116       // Create an empty module interface unit for error recovery.
17117       Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
17118                                              ModuleScopes.front().Module);
17119     }
17120     break;
17121   }
17122 
17123   // Switch from the global module to the named module.
17124   ModuleScopes.back().Module = Mod;
17125   ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
17126   VisibleModules.setVisible(Mod, ModuleLoc);
17127 
17128   // From now on, we have an owning module for all declarations we see.
17129   // However, those declarations are module-private unless explicitly
17130   // exported.
17131   auto *TU = Context.getTranslationUnitDecl();
17132   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
17133   TU->setLocalOwningModule(Mod);
17134 
17135   // FIXME: Create a ModuleDecl.
17136   return nullptr;
17137 }
17138 
17139 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
17140                                    SourceLocation ImportLoc,
17141                                    ModuleIdPath Path) {
17142   // Flatten the module path for a Modules TS module name.
17143   std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
17144   if (getLangOpts().ModulesTS) {
17145     std::string ModuleName;
17146     for (auto &Piece : Path) {
17147       if (!ModuleName.empty())
17148         ModuleName += ".";
17149       ModuleName += Piece.first->getName();
17150     }
17151     ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
17152     Path = ModuleIdPath(ModuleNameLoc);
17153   }
17154 
17155   Module *Mod =
17156       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
17157                                    /*IsIncludeDirective=*/false);
17158   if (!Mod)
17159     return true;
17160 
17161   VisibleModules.setVisible(Mod, ImportLoc);
17162 
17163   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
17164 
17165   // FIXME: we should support importing a submodule within a different submodule
17166   // of the same top-level module. Until we do, make it an error rather than
17167   // silently ignoring the import.
17168   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
17169   // warn on a redundant import of the current module?
17170   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
17171       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
17172     Diag(ImportLoc, getLangOpts().isCompilingModule()
17173                         ? diag::err_module_self_import
17174                         : diag::err_module_import_in_implementation)
17175         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
17176 
17177   SmallVector<SourceLocation, 2> IdentifierLocs;
17178   Module *ModCheck = Mod;
17179   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
17180     // If we've run out of module parents, just drop the remaining identifiers.
17181     // We need the length to be consistent.
17182     if (!ModCheck)
17183       break;
17184     ModCheck = ModCheck->Parent;
17185 
17186     IdentifierLocs.push_back(Path[I].second);
17187   }
17188 
17189   ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
17190                                           Mod, IdentifierLocs);
17191   if (!ModuleScopes.empty())
17192     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
17193   CurContext->addDecl(Import);
17194 
17195   // Re-export the module if needed.
17196   if (Import->isExported() &&
17197       !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface)
17198     getCurrentModule()->Exports.emplace_back(Mod, false);
17199 
17200   return Import;
17201 }
17202 
17203 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
17204   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
17205   BuildModuleInclude(DirectiveLoc, Mod);
17206 }
17207 
17208 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
17209   // Determine whether we're in the #include buffer for a module. The #includes
17210   // in that buffer do not qualify as module imports; they're just an
17211   // implementation detail of us building the module.
17212   //
17213   // FIXME: Should we even get ActOnModuleInclude calls for those?
17214   bool IsInModuleIncludes =
17215       TUKind == TU_Module &&
17216       getSourceManager().isWrittenInMainFile(DirectiveLoc);
17217 
17218   bool ShouldAddImport = !IsInModuleIncludes;
17219 
17220   // If this module import was due to an inclusion directive, create an
17221   // implicit import declaration to capture it in the AST.
17222   if (ShouldAddImport) {
17223     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
17224     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
17225                                                      DirectiveLoc, Mod,
17226                                                      DirectiveLoc);
17227     if (!ModuleScopes.empty())
17228       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
17229     TU->addDecl(ImportD);
17230     Consumer.HandleImplicitImportDecl(ImportD);
17231   }
17232 
17233   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
17234   VisibleModules.setVisible(Mod, DirectiveLoc);
17235 }
17236 
17237 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
17238   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
17239 
17240   ModuleScopes.push_back({});
17241   ModuleScopes.back().Module = Mod;
17242   if (getLangOpts().ModulesLocalVisibility)
17243     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
17244 
17245   VisibleModules.setVisible(Mod, DirectiveLoc);
17246 
17247   // The enclosing context is now part of this module.
17248   // FIXME: Consider creating a child DeclContext to hold the entities
17249   // lexically within the module.
17250   if (getLangOpts().trackLocalOwningModule()) {
17251     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
17252       cast<Decl>(DC)->setModuleOwnershipKind(
17253           getLangOpts().ModulesLocalVisibility
17254               ? Decl::ModuleOwnershipKind::VisibleWhenImported
17255               : Decl::ModuleOwnershipKind::Visible);
17256       cast<Decl>(DC)->setLocalOwningModule(Mod);
17257     }
17258   }
17259 }
17260 
17261 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
17262   if (getLangOpts().ModulesLocalVisibility) {
17263     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
17264     // Leaving a module hides namespace names, so our visible namespace cache
17265     // is now out of date.
17266     VisibleNamespaceCache.clear();
17267   }
17268 
17269   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
17270          "left the wrong module scope");
17271   ModuleScopes.pop_back();
17272 
17273   // We got to the end of processing a local module. Create an
17274   // ImportDecl as we would for an imported module.
17275   FileID File = getSourceManager().getFileID(EomLoc);
17276   SourceLocation DirectiveLoc;
17277   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
17278     // We reached the end of a #included module header. Use the #include loc.
17279     assert(File != getSourceManager().getMainFileID() &&
17280            "end of submodule in main source file");
17281     DirectiveLoc = getSourceManager().getIncludeLoc(File);
17282   } else {
17283     // We reached an EOM pragma. Use the pragma location.
17284     DirectiveLoc = EomLoc;
17285   }
17286   BuildModuleInclude(DirectiveLoc, Mod);
17287 
17288   // Any further declarations are in whatever module we returned to.
17289   if (getLangOpts().trackLocalOwningModule()) {
17290     // The parser guarantees that this is the same context that we entered
17291     // the module within.
17292     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
17293       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
17294       if (!getCurrentModule())
17295         cast<Decl>(DC)->setModuleOwnershipKind(
17296             Decl::ModuleOwnershipKind::Unowned);
17297     }
17298   }
17299 }
17300 
17301 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
17302                                                       Module *Mod) {
17303   // Bail if we're not allowed to implicitly import a module here.
17304   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
17305       VisibleModules.isVisible(Mod))
17306     return;
17307 
17308   // Create the implicit import declaration.
17309   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
17310   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
17311                                                    Loc, Mod, Loc);
17312   TU->addDecl(ImportD);
17313   Consumer.HandleImplicitImportDecl(ImportD);
17314 
17315   // Make the module visible.
17316   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
17317   VisibleModules.setVisible(Mod, Loc);
17318 }
17319 
17320 /// We have parsed the start of an export declaration, including the '{'
17321 /// (if present).
17322 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
17323                                  SourceLocation LBraceLoc) {
17324   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
17325 
17326   // C++ Modules TS draft:
17327   //   An export-declaration shall appear in the purview of a module other than
17328   //   the global module.
17329   if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface)
17330     Diag(ExportLoc, diag::err_export_not_in_module_interface);
17331 
17332   //   An export-declaration [...] shall not contain more than one
17333   //   export keyword.
17334   //
17335   // The intent here is that an export-declaration cannot appear within another
17336   // export-declaration.
17337   if (D->isExported())
17338     Diag(ExportLoc, diag::err_export_within_export);
17339 
17340   CurContext->addDecl(D);
17341   PushDeclContext(S, D);
17342   D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
17343   return D;
17344 }
17345 
17346 /// Complete the definition of an export declaration.
17347 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
17348   auto *ED = cast<ExportDecl>(D);
17349   if (RBraceLoc.isValid())
17350     ED->setRBraceLoc(RBraceLoc);
17351 
17352   // FIXME: Diagnose export of internal-linkage declaration (including
17353   // anonymous namespace).
17354 
17355   PopDeclContext();
17356   return D;
17357 }
17358 
17359 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17360                                       IdentifierInfo* AliasName,
17361                                       SourceLocation PragmaLoc,
17362                                       SourceLocation NameLoc,
17363                                       SourceLocation AliasNameLoc) {
17364   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17365                                          LookupOrdinaryName);
17366   AsmLabelAttr *Attr =
17367       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
17368 
17369   // If a declaration that:
17370   // 1) declares a function or a variable
17371   // 2) has external linkage
17372   // already exists, add a label attribute to it.
17373   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17374     if (isDeclExternC(PrevDecl))
17375       PrevDecl->addAttr(Attr);
17376     else
17377       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17378           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17379   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17380   } else
17381     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17382 }
17383 
17384 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17385                              SourceLocation PragmaLoc,
17386                              SourceLocation NameLoc) {
17387   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17388 
17389   if (PrevDecl) {
17390     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
17391   } else {
17392     (void)WeakUndeclaredIdentifiers.insert(
17393       std::pair<IdentifierInfo*,WeakInfo>
17394         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17395   }
17396 }
17397 
17398 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17399                                 IdentifierInfo* AliasName,
17400                                 SourceLocation PragmaLoc,
17401                                 SourceLocation NameLoc,
17402                                 SourceLocation AliasNameLoc) {
17403   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17404                                     LookupOrdinaryName);
17405   WeakInfo W = WeakInfo(Name, NameLoc);
17406 
17407   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17408     if (!PrevDecl->hasAttr<AliasAttr>())
17409       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17410         DeclApplyPragmaWeak(TUScope, ND, W);
17411   } else {
17412     (void)WeakUndeclaredIdentifiers.insert(
17413       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17414   }
17415 }
17416 
17417 Decl *Sema::getObjCDeclContext() const {
17418   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17419 }
17420