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   };
2940 
2941   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2942 }
2943 
2944 /// If necessary, adjust the semantic declaration context for a qualified
2945 /// declaration to name the correct inline namespace within the qualifier.
2946 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
2947                                                DeclaratorDecl *OldD) {
2948   // The only case where we need to update the DeclContext is when
2949   // redeclaration lookup for a qualified name finds a declaration
2950   // in an inline namespace within the context named by the qualifier:
2951   //
2952   //   inline namespace N { int f(); }
2953   //   int ::f(); // Sema DC needs adjusting from :: to N::.
2954   //
2955   // For unqualified declarations, the semantic context *can* change
2956   // along the redeclaration chain (for local extern declarations,
2957   // extern "C" declarations, and friend declarations in particular).
2958   if (!NewD->getQualifier())
2959     return;
2960 
2961   // NewD is probably already in the right context.
2962   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
2963   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
2964   if (NamedDC->Equals(SemaDC))
2965     return;
2966 
2967   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
2968           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
2969          "unexpected context for redeclaration");
2970 
2971   auto *LexDC = NewD->getLexicalDeclContext();
2972   auto FixSemaDC = [=](NamedDecl *D) {
2973     if (!D)
2974       return;
2975     D->setDeclContext(SemaDC);
2976     D->setLexicalDeclContext(LexDC);
2977   };
2978 
2979   FixSemaDC(NewD);
2980   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
2981     FixSemaDC(FD->getDescribedFunctionTemplate());
2982   else if (auto *VD = dyn_cast<VarDecl>(NewD))
2983     FixSemaDC(VD->getDescribedVarTemplate());
2984 }
2985 
2986 /// MergeFunctionDecl - We just parsed a function 'New' from
2987 /// declarator D which has the same name and scope as a previous
2988 /// declaration 'Old'.  Figure out how to resolve this situation,
2989 /// merging decls or emitting diagnostics as appropriate.
2990 ///
2991 /// In C++, New and Old must be declarations that are not
2992 /// overloaded. Use IsOverload to determine whether New and Old are
2993 /// overloaded, and to select the Old declaration that New should be
2994 /// merged with.
2995 ///
2996 /// Returns true if there was an error, false otherwise.
2997 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2998                              Scope *S, bool MergeTypeWithOld) {
2999   // Verify the old decl was also a function.
3000   FunctionDecl *Old = OldD->getAsFunction();
3001   if (!Old) {
3002     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3003       if (New->getFriendObjectKind()) {
3004         Diag(New->getLocation(), diag::err_using_decl_friend);
3005         Diag(Shadow->getTargetDecl()->getLocation(),
3006              diag::note_using_decl_target);
3007         Diag(Shadow->getUsingDecl()->getLocation(),
3008              diag::note_using_decl) << 0;
3009         return true;
3010       }
3011 
3012       // Check whether the two declarations might declare the same function.
3013       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3014         return true;
3015       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3016     } else {
3017       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3018         << New->getDeclName();
3019       notePreviousDefinition(OldD, New->getLocation());
3020       return true;
3021     }
3022   }
3023 
3024   // If the old declaration is invalid, just give up here.
3025   if (Old->isInvalidDecl())
3026     return true;
3027 
3028   // Disallow redeclaration of some builtins.
3029   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3030     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3031     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3032         << Old << Old->getType();
3033     return true;
3034   }
3035 
3036   diag::kind PrevDiag;
3037   SourceLocation OldLocation;
3038   std::tie(PrevDiag, OldLocation) =
3039       getNoteDiagForInvalidRedeclaration(Old, New);
3040 
3041   // Don't complain about this if we're in GNU89 mode and the old function
3042   // is an extern inline function.
3043   // Don't complain about specializations. They are not supposed to have
3044   // storage classes.
3045   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3046       New->getStorageClass() == SC_Static &&
3047       Old->hasExternalFormalLinkage() &&
3048       !New->getTemplateSpecializationInfo() &&
3049       !canRedefineFunction(Old, getLangOpts())) {
3050     if (getLangOpts().MicrosoftExt) {
3051       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3052       Diag(OldLocation, PrevDiag);
3053     } else {
3054       Diag(New->getLocation(), diag::err_static_non_static) << New;
3055       Diag(OldLocation, PrevDiag);
3056       return true;
3057     }
3058   }
3059 
3060   if (New->hasAttr<InternalLinkageAttr>() &&
3061       !Old->hasAttr<InternalLinkageAttr>()) {
3062     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3063         << New->getDeclName();
3064     notePreviousDefinition(Old, New->getLocation());
3065     New->dropAttr<InternalLinkageAttr>();
3066   }
3067 
3068   if (CheckRedeclarationModuleOwnership(New, Old))
3069     return true;
3070 
3071   if (!getLangOpts().CPlusPlus) {
3072     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3073     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3074       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3075         << New << OldOvl;
3076 
3077       // Try our best to find a decl that actually has the overloadable
3078       // attribute for the note. In most cases (e.g. programs with only one
3079       // broken declaration/definition), this won't matter.
3080       //
3081       // FIXME: We could do this if we juggled some extra state in
3082       // OverloadableAttr, rather than just removing it.
3083       const Decl *DiagOld = Old;
3084       if (OldOvl) {
3085         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3086           const auto *A = D->getAttr<OverloadableAttr>();
3087           return A && !A->isImplicit();
3088         });
3089         // If we've implicitly added *all* of the overloadable attrs to this
3090         // chain, emitting a "previous redecl" note is pointless.
3091         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3092       }
3093 
3094       if (DiagOld)
3095         Diag(DiagOld->getLocation(),
3096              diag::note_attribute_overloadable_prev_overload)
3097           << OldOvl;
3098 
3099       if (OldOvl)
3100         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3101       else
3102         New->dropAttr<OverloadableAttr>();
3103     }
3104   }
3105 
3106   // If a function is first declared with a calling convention, but is later
3107   // declared or defined without one, all following decls assume the calling
3108   // convention of the first.
3109   //
3110   // It's OK if a function is first declared without a calling convention,
3111   // but is later declared or defined with the default calling convention.
3112   //
3113   // To test if either decl has an explicit calling convention, we look for
3114   // AttributedType sugar nodes on the type as written.  If they are missing or
3115   // were canonicalized away, we assume the calling convention was implicit.
3116   //
3117   // Note also that we DO NOT return at this point, because we still have
3118   // other tests to run.
3119   QualType OldQType = Context.getCanonicalType(Old->getType());
3120   QualType NewQType = Context.getCanonicalType(New->getType());
3121   const FunctionType *OldType = cast<FunctionType>(OldQType);
3122   const FunctionType *NewType = cast<FunctionType>(NewQType);
3123   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3124   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3125   bool RequiresAdjustment = false;
3126 
3127   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3128     FunctionDecl *First = Old->getFirstDecl();
3129     const FunctionType *FT =
3130         First->getType().getCanonicalType()->castAs<FunctionType>();
3131     FunctionType::ExtInfo FI = FT->getExtInfo();
3132     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3133     if (!NewCCExplicit) {
3134       // Inherit the CC from the previous declaration if it was specified
3135       // there but not here.
3136       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3137       RequiresAdjustment = true;
3138     } else {
3139       // Calling conventions aren't compatible, so complain.
3140       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3141       Diag(New->getLocation(), diag::err_cconv_change)
3142         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3143         << !FirstCCExplicit
3144         << (!FirstCCExplicit ? "" :
3145             FunctionType::getNameForCallConv(FI.getCC()));
3146 
3147       // Put the note on the first decl, since it is the one that matters.
3148       Diag(First->getLocation(), diag::note_previous_declaration);
3149       return true;
3150     }
3151   }
3152 
3153   // FIXME: diagnose the other way around?
3154   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3155     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3156     RequiresAdjustment = true;
3157   }
3158 
3159   // Merge regparm attribute.
3160   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3161       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3162     if (NewTypeInfo.getHasRegParm()) {
3163       Diag(New->getLocation(), diag::err_regparm_mismatch)
3164         << NewType->getRegParmType()
3165         << OldType->getRegParmType();
3166       Diag(OldLocation, diag::note_previous_declaration);
3167       return true;
3168     }
3169 
3170     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3171     RequiresAdjustment = true;
3172   }
3173 
3174   // Merge ns_returns_retained attribute.
3175   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3176     if (NewTypeInfo.getProducesResult()) {
3177       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3178           << "'ns_returns_retained'";
3179       Diag(OldLocation, diag::note_previous_declaration);
3180       return true;
3181     }
3182 
3183     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3184     RequiresAdjustment = true;
3185   }
3186 
3187   if (OldTypeInfo.getNoCallerSavedRegs() !=
3188       NewTypeInfo.getNoCallerSavedRegs()) {
3189     if (NewTypeInfo.getNoCallerSavedRegs()) {
3190       AnyX86NoCallerSavedRegistersAttr *Attr =
3191         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3192       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3193       Diag(OldLocation, diag::note_previous_declaration);
3194       return true;
3195     }
3196 
3197     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3198     RequiresAdjustment = true;
3199   }
3200 
3201   if (RequiresAdjustment) {
3202     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3203     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3204     New->setType(QualType(AdjustedType, 0));
3205     NewQType = Context.getCanonicalType(New->getType());
3206     NewType = cast<FunctionType>(NewQType);
3207   }
3208 
3209   // If this redeclaration makes the function inline, we may need to add it to
3210   // UndefinedButUsed.
3211   if (!Old->isInlined() && New->isInlined() &&
3212       !New->hasAttr<GNUInlineAttr>() &&
3213       !getLangOpts().GNUInline &&
3214       Old->isUsed(false) &&
3215       !Old->isDefined() && !New->isThisDeclarationADefinition())
3216     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3217                                            SourceLocation()));
3218 
3219   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3220   // about it.
3221   if (New->hasAttr<GNUInlineAttr>() &&
3222       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3223     UndefinedButUsed.erase(Old->getCanonicalDecl());
3224   }
3225 
3226   // If pass_object_size params don't match up perfectly, this isn't a valid
3227   // redeclaration.
3228   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3229       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3230     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3231         << New->getDeclName();
3232     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3233     return true;
3234   }
3235 
3236   if (getLangOpts().CPlusPlus) {
3237     // C++1z [over.load]p2
3238     //   Certain function declarations cannot be overloaded:
3239     //     -- Function declarations that differ only in the return type,
3240     //        the exception specification, or both cannot be overloaded.
3241 
3242     // Check the exception specifications match. This may recompute the type of
3243     // both Old and New if it resolved exception specifications, so grab the
3244     // types again after this. Because this updates the type, we do this before
3245     // any of the other checks below, which may update the "de facto" NewQType
3246     // but do not necessarily update the type of New.
3247     if (CheckEquivalentExceptionSpec(Old, New))
3248       return true;
3249     OldQType = Context.getCanonicalType(Old->getType());
3250     NewQType = Context.getCanonicalType(New->getType());
3251 
3252     // Go back to the type source info to compare the declared return types,
3253     // per C++1y [dcl.type.auto]p13:
3254     //   Redeclarations or specializations of a function or function template
3255     //   with a declared return type that uses a placeholder type shall also
3256     //   use that placeholder, not a deduced type.
3257     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3258     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3259     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3260         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3261                                        OldDeclaredReturnType)) {
3262       QualType ResQT;
3263       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3264           OldDeclaredReturnType->isObjCObjectPointerType())
3265         // FIXME: This does the wrong thing for a deduced return type.
3266         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3267       if (ResQT.isNull()) {
3268         if (New->isCXXClassMember() && New->isOutOfLine())
3269           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3270               << New << New->getReturnTypeSourceRange();
3271         else
3272           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3273               << New->getReturnTypeSourceRange();
3274         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3275                                     << Old->getReturnTypeSourceRange();
3276         return true;
3277       }
3278       else
3279         NewQType = ResQT;
3280     }
3281 
3282     QualType OldReturnType = OldType->getReturnType();
3283     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3284     if (OldReturnType != NewReturnType) {
3285       // If this function has a deduced return type and has already been
3286       // defined, copy the deduced value from the old declaration.
3287       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3288       if (OldAT && OldAT->isDeduced()) {
3289         New->setType(
3290             SubstAutoType(New->getType(),
3291                           OldAT->isDependentType() ? Context.DependentTy
3292                                                    : OldAT->getDeducedType()));
3293         NewQType = Context.getCanonicalType(
3294             SubstAutoType(NewQType,
3295                           OldAT->isDependentType() ? Context.DependentTy
3296                                                    : OldAT->getDeducedType()));
3297       }
3298     }
3299 
3300     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3301     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3302     if (OldMethod && NewMethod) {
3303       // Preserve triviality.
3304       NewMethod->setTrivial(OldMethod->isTrivial());
3305 
3306       // MSVC allows explicit template specialization at class scope:
3307       // 2 CXXMethodDecls referring to the same function will be injected.
3308       // We don't want a redeclaration error.
3309       bool IsClassScopeExplicitSpecialization =
3310                               OldMethod->isFunctionTemplateSpecialization() &&
3311                               NewMethod->isFunctionTemplateSpecialization();
3312       bool isFriend = NewMethod->getFriendObjectKind();
3313 
3314       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3315           !IsClassScopeExplicitSpecialization) {
3316         //    -- Member function declarations with the same name and the
3317         //       same parameter types cannot be overloaded if any of them
3318         //       is a static member function declaration.
3319         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3320           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3321           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3322           return true;
3323         }
3324 
3325         // C++ [class.mem]p1:
3326         //   [...] A member shall not be declared twice in the
3327         //   member-specification, except that a nested class or member
3328         //   class template can be declared and then later defined.
3329         if (!inTemplateInstantiation()) {
3330           unsigned NewDiag;
3331           if (isa<CXXConstructorDecl>(OldMethod))
3332             NewDiag = diag::err_constructor_redeclared;
3333           else if (isa<CXXDestructorDecl>(NewMethod))
3334             NewDiag = diag::err_destructor_redeclared;
3335           else if (isa<CXXConversionDecl>(NewMethod))
3336             NewDiag = diag::err_conv_function_redeclared;
3337           else
3338             NewDiag = diag::err_member_redeclared;
3339 
3340           Diag(New->getLocation(), NewDiag);
3341         } else {
3342           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3343             << New << New->getType();
3344         }
3345         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3346         return true;
3347 
3348       // Complain if this is an explicit declaration of a special
3349       // member that was initially declared implicitly.
3350       //
3351       // As an exception, it's okay to befriend such methods in order
3352       // to permit the implicit constructor/destructor/operator calls.
3353       } else if (OldMethod->isImplicit()) {
3354         if (isFriend) {
3355           NewMethod->setImplicit();
3356         } else {
3357           Diag(NewMethod->getLocation(),
3358                diag::err_definition_of_implicitly_declared_member)
3359             << New << getSpecialMember(OldMethod);
3360           return true;
3361         }
3362       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3363         Diag(NewMethod->getLocation(),
3364              diag::err_definition_of_explicitly_defaulted_member)
3365           << getSpecialMember(OldMethod);
3366         return true;
3367       }
3368     }
3369 
3370     // C++11 [dcl.attr.noreturn]p1:
3371     //   The first declaration of a function shall specify the noreturn
3372     //   attribute if any declaration of that function specifies the noreturn
3373     //   attribute.
3374     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3375     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3376       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3377       Diag(Old->getFirstDecl()->getLocation(),
3378            diag::note_noreturn_missing_first_decl);
3379     }
3380 
3381     // C++11 [dcl.attr.depend]p2:
3382     //   The first declaration of a function shall specify the
3383     //   carries_dependency attribute for its declarator-id if any declaration
3384     //   of the function specifies the carries_dependency attribute.
3385     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3386     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3387       Diag(CDA->getLocation(),
3388            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3389       Diag(Old->getFirstDecl()->getLocation(),
3390            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3391     }
3392 
3393     // (C++98 8.3.5p3):
3394     //   All declarations for a function shall agree exactly in both the
3395     //   return type and the parameter-type-list.
3396     // We also want to respect all the extended bits except noreturn.
3397 
3398     // noreturn should now match unless the old type info didn't have it.
3399     QualType OldQTypeForComparison = OldQType;
3400     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3401       auto *OldType = OldQType->castAs<FunctionProtoType>();
3402       const FunctionType *OldTypeForComparison
3403         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3404       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3405       assert(OldQTypeForComparison.isCanonical());
3406     }
3407 
3408     if (haveIncompatibleLanguageLinkages(Old, New)) {
3409       // As a special case, retain the language linkage from previous
3410       // declarations of a friend function as an extension.
3411       //
3412       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3413       // and is useful because there's otherwise no way to specify language
3414       // linkage within class scope.
3415       //
3416       // Check cautiously as the friend object kind isn't yet complete.
3417       if (New->getFriendObjectKind() != Decl::FOK_None) {
3418         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3419         Diag(OldLocation, PrevDiag);
3420       } else {
3421         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3422         Diag(OldLocation, PrevDiag);
3423         return true;
3424       }
3425     }
3426 
3427     if (OldQTypeForComparison == NewQType)
3428       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3429 
3430     // If the types are imprecise (due to dependent constructs in friends or
3431     // local extern declarations), it's OK if they differ. We'll check again
3432     // during instantiation.
3433     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3434       return false;
3435 
3436     // Fall through for conflicting redeclarations and redefinitions.
3437   }
3438 
3439   // C: Function types need to be compatible, not identical. This handles
3440   // duplicate function decls like "void f(int); void f(enum X);" properly.
3441   if (!getLangOpts().CPlusPlus &&
3442       Context.typesAreCompatible(OldQType, NewQType)) {
3443     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3444     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3445     const FunctionProtoType *OldProto = nullptr;
3446     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3447         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3448       // The old declaration provided a function prototype, but the
3449       // new declaration does not. Merge in the prototype.
3450       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3451       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3452       NewQType =
3453           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3454                                   OldProto->getExtProtoInfo());
3455       New->setType(NewQType);
3456       New->setHasInheritedPrototype();
3457 
3458       // Synthesize parameters with the same types.
3459       SmallVector<ParmVarDecl*, 16> Params;
3460       for (const auto &ParamType : OldProto->param_types()) {
3461         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3462                                                  SourceLocation(), nullptr,
3463                                                  ParamType, /*TInfo=*/nullptr,
3464                                                  SC_None, nullptr);
3465         Param->setScopeInfo(0, Params.size());
3466         Param->setImplicit();
3467         Params.push_back(Param);
3468       }
3469 
3470       New->setParams(Params);
3471     }
3472 
3473     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3474   }
3475 
3476   // GNU C permits a K&R definition to follow a prototype declaration
3477   // if the declared types of the parameters in the K&R definition
3478   // match the types in the prototype declaration, even when the
3479   // promoted types of the parameters from the K&R definition differ
3480   // from the types in the prototype. GCC then keeps the types from
3481   // the prototype.
3482   //
3483   // If a variadic prototype is followed by a non-variadic K&R definition,
3484   // the K&R definition becomes variadic.  This is sort of an edge case, but
3485   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3486   // C99 6.9.1p8.
3487   if (!getLangOpts().CPlusPlus &&
3488       Old->hasPrototype() && !New->hasPrototype() &&
3489       New->getType()->getAs<FunctionProtoType>() &&
3490       Old->getNumParams() == New->getNumParams()) {
3491     SmallVector<QualType, 16> ArgTypes;
3492     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3493     const FunctionProtoType *OldProto
3494       = Old->getType()->getAs<FunctionProtoType>();
3495     const FunctionProtoType *NewProto
3496       = New->getType()->getAs<FunctionProtoType>();
3497 
3498     // Determine whether this is the GNU C extension.
3499     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3500                                                NewProto->getReturnType());
3501     bool LooseCompatible = !MergedReturn.isNull();
3502     for (unsigned Idx = 0, End = Old->getNumParams();
3503          LooseCompatible && Idx != End; ++Idx) {
3504       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3505       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3506       if (Context.typesAreCompatible(OldParm->getType(),
3507                                      NewProto->getParamType(Idx))) {
3508         ArgTypes.push_back(NewParm->getType());
3509       } else if (Context.typesAreCompatible(OldParm->getType(),
3510                                             NewParm->getType(),
3511                                             /*CompareUnqualified=*/true)) {
3512         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3513                                            NewProto->getParamType(Idx) };
3514         Warnings.push_back(Warn);
3515         ArgTypes.push_back(NewParm->getType());
3516       } else
3517         LooseCompatible = false;
3518     }
3519 
3520     if (LooseCompatible) {
3521       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3522         Diag(Warnings[Warn].NewParm->getLocation(),
3523              diag::ext_param_promoted_not_compatible_with_prototype)
3524           << Warnings[Warn].PromotedType
3525           << Warnings[Warn].OldParm->getType();
3526         if (Warnings[Warn].OldParm->getLocation().isValid())
3527           Diag(Warnings[Warn].OldParm->getLocation(),
3528                diag::note_previous_declaration);
3529       }
3530 
3531       if (MergeTypeWithOld)
3532         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3533                                              OldProto->getExtProtoInfo()));
3534       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3535     }
3536 
3537     // Fall through to diagnose conflicting types.
3538   }
3539 
3540   // A function that has already been declared has been redeclared or
3541   // defined with a different type; show an appropriate diagnostic.
3542 
3543   // If the previous declaration was an implicitly-generated builtin
3544   // declaration, then at the very least we should use a specialized note.
3545   unsigned BuiltinID;
3546   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3547     // If it's actually a library-defined builtin function like 'malloc'
3548     // or 'printf', just warn about the incompatible redeclaration.
3549     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3550       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3551       Diag(OldLocation, diag::note_previous_builtin_declaration)
3552         << Old << Old->getType();
3553 
3554       // If this is a global redeclaration, just forget hereafter
3555       // about the "builtin-ness" of the function.
3556       //
3557       // Doing this for local extern declarations is problematic.  If
3558       // the builtin declaration remains visible, a second invalid
3559       // local declaration will produce a hard error; if it doesn't
3560       // remain visible, a single bogus local redeclaration (which is
3561       // actually only a warning) could break all the downstream code.
3562       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3563         New->getIdentifier()->revertBuiltin();
3564 
3565       return false;
3566     }
3567 
3568     PrevDiag = diag::note_previous_builtin_declaration;
3569   }
3570 
3571   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3572   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3573   return true;
3574 }
3575 
3576 /// Completes the merge of two function declarations that are
3577 /// known to be compatible.
3578 ///
3579 /// This routine handles the merging of attributes and other
3580 /// properties of function declarations from the old declaration to
3581 /// the new declaration, once we know that New is in fact a
3582 /// redeclaration of Old.
3583 ///
3584 /// \returns false
3585 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3586                                         Scope *S, bool MergeTypeWithOld) {
3587   // Merge the attributes
3588   mergeDeclAttributes(New, Old);
3589 
3590   // Merge "pure" flag.
3591   if (Old->isPure())
3592     New->setPure();
3593 
3594   // Merge "used" flag.
3595   if (Old->getMostRecentDecl()->isUsed(false))
3596     New->setIsUsed();
3597 
3598   // Merge attributes from the parameters.  These can mismatch with K&R
3599   // declarations.
3600   if (New->getNumParams() == Old->getNumParams())
3601       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3602         ParmVarDecl *NewParam = New->getParamDecl(i);
3603         ParmVarDecl *OldParam = Old->getParamDecl(i);
3604         mergeParamDeclAttributes(NewParam, OldParam, *this);
3605         mergeParamDeclTypes(NewParam, OldParam, *this);
3606       }
3607 
3608   if (getLangOpts().CPlusPlus)
3609     return MergeCXXFunctionDecl(New, Old, S);
3610 
3611   // Merge the function types so the we get the composite types for the return
3612   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3613   // was visible.
3614   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3615   if (!Merged.isNull() && MergeTypeWithOld)
3616     New->setType(Merged);
3617 
3618   return false;
3619 }
3620 
3621 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3622                                 ObjCMethodDecl *oldMethod) {
3623   // Merge the attributes, including deprecated/unavailable
3624   AvailabilityMergeKind MergeKind =
3625     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3626       ? AMK_ProtocolImplementation
3627       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3628                                                        : AMK_Override;
3629 
3630   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3631 
3632   // Merge attributes from the parameters.
3633   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3634                                        oe = oldMethod->param_end();
3635   for (ObjCMethodDecl::param_iterator
3636          ni = newMethod->param_begin(), ne = newMethod->param_end();
3637        ni != ne && oi != oe; ++ni, ++oi)
3638     mergeParamDeclAttributes(*ni, *oi, *this);
3639 
3640   CheckObjCMethodOverride(newMethod, oldMethod);
3641 }
3642 
3643 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3644   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3645 
3646   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3647          ? diag::err_redefinition_different_type
3648          : diag::err_redeclaration_different_type)
3649     << New->getDeclName() << New->getType() << Old->getType();
3650 
3651   diag::kind PrevDiag;
3652   SourceLocation OldLocation;
3653   std::tie(PrevDiag, OldLocation)
3654     = getNoteDiagForInvalidRedeclaration(Old, New);
3655   S.Diag(OldLocation, PrevDiag);
3656   New->setInvalidDecl();
3657 }
3658 
3659 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3660 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3661 /// emitting diagnostics as appropriate.
3662 ///
3663 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3664 /// to here in AddInitializerToDecl. We can't check them before the initializer
3665 /// is attached.
3666 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3667                              bool MergeTypeWithOld) {
3668   if (New->isInvalidDecl() || Old->isInvalidDecl())
3669     return;
3670 
3671   QualType MergedT;
3672   if (getLangOpts().CPlusPlus) {
3673     if (New->getType()->isUndeducedType()) {
3674       // We don't know what the new type is until the initializer is attached.
3675       return;
3676     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3677       // These could still be something that needs exception specs checked.
3678       return MergeVarDeclExceptionSpecs(New, Old);
3679     }
3680     // C++ [basic.link]p10:
3681     //   [...] the types specified by all declarations referring to a given
3682     //   object or function shall be identical, except that declarations for an
3683     //   array object can specify array types that differ by the presence or
3684     //   absence of a major array bound (8.3.4).
3685     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3686       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3687       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3688 
3689       // We are merging a variable declaration New into Old. If it has an array
3690       // bound, and that bound differs from Old's bound, we should diagnose the
3691       // mismatch.
3692       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3693         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3694              PrevVD = PrevVD->getPreviousDecl()) {
3695           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3696           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3697             continue;
3698 
3699           if (!Context.hasSameType(NewArray, PrevVDTy))
3700             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3701         }
3702       }
3703 
3704       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3705         if (Context.hasSameType(OldArray->getElementType(),
3706                                 NewArray->getElementType()))
3707           MergedT = New->getType();
3708       }
3709       // FIXME: Check visibility. New is hidden but has a complete type. If New
3710       // has no array bound, it should not inherit one from Old, if Old is not
3711       // visible.
3712       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3713         if (Context.hasSameType(OldArray->getElementType(),
3714                                 NewArray->getElementType()))
3715           MergedT = Old->getType();
3716       }
3717     }
3718     else if (New->getType()->isObjCObjectPointerType() &&
3719                Old->getType()->isObjCObjectPointerType()) {
3720       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3721                                               Old->getType());
3722     }
3723   } else {
3724     // C 6.2.7p2:
3725     //   All declarations that refer to the same object or function shall have
3726     //   compatible type.
3727     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3728   }
3729   if (MergedT.isNull()) {
3730     // It's OK if we couldn't merge types if either type is dependent, for a
3731     // block-scope variable. In other cases (static data members of class
3732     // templates, variable templates, ...), we require the types to be
3733     // equivalent.
3734     // FIXME: The C++ standard doesn't say anything about this.
3735     if ((New->getType()->isDependentType() ||
3736          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3737       // If the old type was dependent, we can't merge with it, so the new type
3738       // becomes dependent for now. We'll reproduce the original type when we
3739       // instantiate the TypeSourceInfo for the variable.
3740       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3741         New->setType(Context.DependentTy);
3742       return;
3743     }
3744     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3745   }
3746 
3747   // Don't actually update the type on the new declaration if the old
3748   // declaration was an extern declaration in a different scope.
3749   if (MergeTypeWithOld)
3750     New->setType(MergedT);
3751 }
3752 
3753 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3754                                   LookupResult &Previous) {
3755   // C11 6.2.7p4:
3756   //   For an identifier with internal or external linkage declared
3757   //   in a scope in which a prior declaration of that identifier is
3758   //   visible, if the prior declaration specifies internal or
3759   //   external linkage, the type of the identifier at the later
3760   //   declaration becomes the composite type.
3761   //
3762   // If the variable isn't visible, we do not merge with its type.
3763   if (Previous.isShadowed())
3764     return false;
3765 
3766   if (S.getLangOpts().CPlusPlus) {
3767     // C++11 [dcl.array]p3:
3768     //   If there is a preceding declaration of the entity in the same
3769     //   scope in which the bound was specified, an omitted array bound
3770     //   is taken to be the same as in that earlier declaration.
3771     return NewVD->isPreviousDeclInSameBlockScope() ||
3772            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3773             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3774   } else {
3775     // If the old declaration was function-local, don't merge with its
3776     // type unless we're in the same function.
3777     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3778            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3779   }
3780 }
3781 
3782 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3783 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3784 /// situation, merging decls or emitting diagnostics as appropriate.
3785 ///
3786 /// Tentative definition rules (C99 6.9.2p2) are checked by
3787 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3788 /// definitions here, since the initializer hasn't been attached.
3789 ///
3790 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3791   // If the new decl is already invalid, don't do any other checking.
3792   if (New->isInvalidDecl())
3793     return;
3794 
3795   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3796     return;
3797 
3798   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3799 
3800   // Verify the old decl was also a variable or variable template.
3801   VarDecl *Old = nullptr;
3802   VarTemplateDecl *OldTemplate = nullptr;
3803   if (Previous.isSingleResult()) {
3804     if (NewTemplate) {
3805       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3806       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3807 
3808       if (auto *Shadow =
3809               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3810         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3811           return New->setInvalidDecl();
3812     } else {
3813       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3814 
3815       if (auto *Shadow =
3816               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3817         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3818           return New->setInvalidDecl();
3819     }
3820   }
3821   if (!Old) {
3822     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3823         << New->getDeclName();
3824     notePreviousDefinition(Previous.getRepresentativeDecl(),
3825                            New->getLocation());
3826     return New->setInvalidDecl();
3827   }
3828 
3829   // Ensure the template parameters are compatible.
3830   if (NewTemplate &&
3831       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3832                                       OldTemplate->getTemplateParameters(),
3833                                       /*Complain=*/true, TPL_TemplateMatch))
3834     return New->setInvalidDecl();
3835 
3836   // C++ [class.mem]p1:
3837   //   A member shall not be declared twice in the member-specification [...]
3838   //
3839   // Here, we need only consider static data members.
3840   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3841     Diag(New->getLocation(), diag::err_duplicate_member)
3842       << New->getIdentifier();
3843     Diag(Old->getLocation(), diag::note_previous_declaration);
3844     New->setInvalidDecl();
3845   }
3846 
3847   mergeDeclAttributes(New, Old);
3848   // Warn if an already-declared variable is made a weak_import in a subsequent
3849   // declaration
3850   if (New->hasAttr<WeakImportAttr>() &&
3851       Old->getStorageClass() == SC_None &&
3852       !Old->hasAttr<WeakImportAttr>()) {
3853     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3854     notePreviousDefinition(Old, New->getLocation());
3855     // Remove weak_import attribute on new declaration.
3856     New->dropAttr<WeakImportAttr>();
3857   }
3858 
3859   if (New->hasAttr<InternalLinkageAttr>() &&
3860       !Old->hasAttr<InternalLinkageAttr>()) {
3861     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3862         << New->getDeclName();
3863     notePreviousDefinition(Old, New->getLocation());
3864     New->dropAttr<InternalLinkageAttr>();
3865   }
3866 
3867   // Merge the types.
3868   VarDecl *MostRecent = Old->getMostRecentDecl();
3869   if (MostRecent != Old) {
3870     MergeVarDeclTypes(New, MostRecent,
3871                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3872     if (New->isInvalidDecl())
3873       return;
3874   }
3875 
3876   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3877   if (New->isInvalidDecl())
3878     return;
3879 
3880   diag::kind PrevDiag;
3881   SourceLocation OldLocation;
3882   std::tie(PrevDiag, OldLocation) =
3883       getNoteDiagForInvalidRedeclaration(Old, New);
3884 
3885   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3886   if (New->getStorageClass() == SC_Static &&
3887       !New->isStaticDataMember() &&
3888       Old->hasExternalFormalLinkage()) {
3889     if (getLangOpts().MicrosoftExt) {
3890       Diag(New->getLocation(), diag::ext_static_non_static)
3891           << New->getDeclName();
3892       Diag(OldLocation, PrevDiag);
3893     } else {
3894       Diag(New->getLocation(), diag::err_static_non_static)
3895           << New->getDeclName();
3896       Diag(OldLocation, PrevDiag);
3897       return New->setInvalidDecl();
3898     }
3899   }
3900   // C99 6.2.2p4:
3901   //   For an identifier declared with the storage-class specifier
3902   //   extern in a scope in which a prior declaration of that
3903   //   identifier is visible,23) if the prior declaration specifies
3904   //   internal or external linkage, the linkage of the identifier at
3905   //   the later declaration is the same as the linkage specified at
3906   //   the prior declaration. If no prior declaration is visible, or
3907   //   if the prior declaration specifies no linkage, then the
3908   //   identifier has external linkage.
3909   if (New->hasExternalStorage() && Old->hasLinkage())
3910     /* Okay */;
3911   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3912            !New->isStaticDataMember() &&
3913            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3914     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3915     Diag(OldLocation, PrevDiag);
3916     return New->setInvalidDecl();
3917   }
3918 
3919   // Check if extern is followed by non-extern and vice-versa.
3920   if (New->hasExternalStorage() &&
3921       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3922     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3923     Diag(OldLocation, PrevDiag);
3924     return New->setInvalidDecl();
3925   }
3926   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3927       !New->hasExternalStorage()) {
3928     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3929     Diag(OldLocation, PrevDiag);
3930     return New->setInvalidDecl();
3931   }
3932 
3933   if (CheckRedeclarationModuleOwnership(New, Old))
3934     return;
3935 
3936   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3937 
3938   // FIXME: The test for external storage here seems wrong? We still
3939   // need to check for mismatches.
3940   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3941       // Don't complain about out-of-line definitions of static members.
3942       !(Old->getLexicalDeclContext()->isRecord() &&
3943         !New->getLexicalDeclContext()->isRecord())) {
3944     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3945     Diag(OldLocation, PrevDiag);
3946     return New->setInvalidDecl();
3947   }
3948 
3949   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3950     if (VarDecl *Def = Old->getDefinition()) {
3951       // C++1z [dcl.fcn.spec]p4:
3952       //   If the definition of a variable appears in a translation unit before
3953       //   its first declaration as inline, the program is ill-formed.
3954       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3955       Diag(Def->getLocation(), diag::note_previous_definition);
3956     }
3957   }
3958 
3959   // If this redeclaration makes the variable inline, we may need to add it to
3960   // UndefinedButUsed.
3961   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3962       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3963     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3964                                            SourceLocation()));
3965 
3966   if (New->getTLSKind() != Old->getTLSKind()) {
3967     if (!Old->getTLSKind()) {
3968       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3969       Diag(OldLocation, PrevDiag);
3970     } else if (!New->getTLSKind()) {
3971       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3972       Diag(OldLocation, PrevDiag);
3973     } else {
3974       // Do not allow redeclaration to change the variable between requiring
3975       // static and dynamic initialization.
3976       // FIXME: GCC allows this, but uses the TLS keyword on the first
3977       // declaration to determine the kind. Do we need to be compatible here?
3978       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3979         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3980       Diag(OldLocation, PrevDiag);
3981     }
3982   }
3983 
3984   // C++ doesn't have tentative definitions, so go right ahead and check here.
3985   if (getLangOpts().CPlusPlus &&
3986       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3987     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3988         Old->getCanonicalDecl()->isConstexpr()) {
3989       // This definition won't be a definition any more once it's been merged.
3990       Diag(New->getLocation(),
3991            diag::warn_deprecated_redundant_constexpr_static_def);
3992     } else if (VarDecl *Def = Old->getDefinition()) {
3993       if (checkVarDeclRedefinition(Def, New))
3994         return;
3995     }
3996   }
3997 
3998   if (haveIncompatibleLanguageLinkages(Old, New)) {
3999     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4000     Diag(OldLocation, PrevDiag);
4001     New->setInvalidDecl();
4002     return;
4003   }
4004 
4005   // Merge "used" flag.
4006   if (Old->getMostRecentDecl()->isUsed(false))
4007     New->setIsUsed();
4008 
4009   // Keep a chain of previous declarations.
4010   New->setPreviousDecl(Old);
4011   if (NewTemplate)
4012     NewTemplate->setPreviousDecl(OldTemplate);
4013   adjustDeclContextForDeclaratorDecl(New, Old);
4014 
4015   // Inherit access appropriately.
4016   New->setAccess(Old->getAccess());
4017   if (NewTemplate)
4018     NewTemplate->setAccess(New->getAccess());
4019 
4020   if (Old->isInline())
4021     New->setImplicitlyInline();
4022 }
4023 
4024 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4025   SourceManager &SrcMgr = getSourceManager();
4026   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4027   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4028   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4029   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4030   auto &HSI = PP.getHeaderSearchInfo();
4031   StringRef HdrFilename =
4032       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4033 
4034   auto noteFromModuleOrInclude = [&](Module *Mod,
4035                                      SourceLocation IncLoc) -> bool {
4036     // Redefinition errors with modules are common with non modular mapped
4037     // headers, example: a non-modular header H in module A that also gets
4038     // included directly in a TU. Pointing twice to the same header/definition
4039     // is confusing, try to get better diagnostics when modules is on.
4040     if (IncLoc.isValid()) {
4041       if (Mod) {
4042         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4043             << HdrFilename.str() << Mod->getFullModuleName();
4044         if (!Mod->DefinitionLoc.isInvalid())
4045           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4046               << Mod->getFullModuleName();
4047       } else {
4048         Diag(IncLoc, diag::note_redefinition_include_same_file)
4049             << HdrFilename.str();
4050       }
4051       return true;
4052     }
4053 
4054     return false;
4055   };
4056 
4057   // Is it the same file and same offset? Provide more information on why
4058   // this leads to a redefinition error.
4059   bool EmittedDiag = false;
4060   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4061     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4062     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4063     EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4064     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4065 
4066     // If the header has no guards, emit a note suggesting one.
4067     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4068       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4069 
4070     if (EmittedDiag)
4071       return;
4072   }
4073 
4074   // Redefinition coming from different files or couldn't do better above.
4075   if (Old->getLocation().isValid())
4076     Diag(Old->getLocation(), diag::note_previous_definition);
4077 }
4078 
4079 /// We've just determined that \p Old and \p New both appear to be definitions
4080 /// of the same variable. Either diagnose or fix the problem.
4081 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4082   if (!hasVisibleDefinition(Old) &&
4083       (New->getFormalLinkage() == InternalLinkage ||
4084        New->isInline() ||
4085        New->getDescribedVarTemplate() ||
4086        New->getNumTemplateParameterLists() ||
4087        New->getDeclContext()->isDependentContext())) {
4088     // The previous definition is hidden, and multiple definitions are
4089     // permitted (in separate TUs). Demote this to a declaration.
4090     New->demoteThisDefinitionToDeclaration();
4091 
4092     // Make the canonical definition visible.
4093     if (auto *OldTD = Old->getDescribedVarTemplate())
4094       makeMergedDefinitionVisible(OldTD);
4095     makeMergedDefinitionVisible(Old);
4096     return false;
4097   } else {
4098     Diag(New->getLocation(), diag::err_redefinition) << New;
4099     notePreviousDefinition(Old, New->getLocation());
4100     New->setInvalidDecl();
4101     return true;
4102   }
4103 }
4104 
4105 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4106 /// no declarator (e.g. "struct foo;") is parsed.
4107 Decl *
4108 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4109                                  RecordDecl *&AnonRecord) {
4110   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4111                                     AnonRecord);
4112 }
4113 
4114 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4115 // disambiguate entities defined in different scopes.
4116 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4117 // compatibility.
4118 // We will pick our mangling number depending on which version of MSVC is being
4119 // targeted.
4120 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4121   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4122              ? S->getMSCurManglingNumber()
4123              : S->getMSLastManglingNumber();
4124 }
4125 
4126 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4127   if (!Context.getLangOpts().CPlusPlus)
4128     return;
4129 
4130   if (isa<CXXRecordDecl>(Tag->getParent())) {
4131     // If this tag is the direct child of a class, number it if
4132     // it is anonymous.
4133     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4134       return;
4135     MangleNumberingContext &MCtx =
4136         Context.getManglingNumberContext(Tag->getParent());
4137     Context.setManglingNumber(
4138         Tag, MCtx.getManglingNumber(
4139                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4140     return;
4141   }
4142 
4143   // If this tag isn't a direct child of a class, number it if it is local.
4144   Decl *ManglingContextDecl;
4145   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4146           Tag->getDeclContext(), ManglingContextDecl)) {
4147     Context.setManglingNumber(
4148         Tag, MCtx->getManglingNumber(
4149                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4150   }
4151 }
4152 
4153 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4154                                         TypedefNameDecl *NewTD) {
4155   if (TagFromDeclSpec->isInvalidDecl())
4156     return;
4157 
4158   // Do nothing if the tag already has a name for linkage purposes.
4159   if (TagFromDeclSpec->hasNameForLinkage())
4160     return;
4161 
4162   // A well-formed anonymous tag must always be a TUK_Definition.
4163   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4164 
4165   // The type must match the tag exactly;  no qualifiers allowed.
4166   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4167                            Context.getTagDeclType(TagFromDeclSpec))) {
4168     if (getLangOpts().CPlusPlus)
4169       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4170     return;
4171   }
4172 
4173   // If we've already computed linkage for the anonymous tag, then
4174   // adding a typedef name for the anonymous decl can change that
4175   // linkage, which might be a serious problem.  Diagnose this as
4176   // unsupported and ignore the typedef name.  TODO: we should
4177   // pursue this as a language defect and establish a formal rule
4178   // for how to handle it.
4179   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4180     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4181 
4182     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4183     tagLoc = getLocForEndOfToken(tagLoc);
4184 
4185     llvm::SmallString<40> textToInsert;
4186     textToInsert += ' ';
4187     textToInsert += NewTD->getIdentifier()->getName();
4188     Diag(tagLoc, diag::note_typedef_changes_linkage)
4189         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4190     return;
4191   }
4192 
4193   // Otherwise, set this is the anon-decl typedef for the tag.
4194   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4195 }
4196 
4197 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4198   switch (T) {
4199   case DeclSpec::TST_class:
4200     return 0;
4201   case DeclSpec::TST_struct:
4202     return 1;
4203   case DeclSpec::TST_interface:
4204     return 2;
4205   case DeclSpec::TST_union:
4206     return 3;
4207   case DeclSpec::TST_enum:
4208     return 4;
4209   default:
4210     llvm_unreachable("unexpected type specifier");
4211   }
4212 }
4213 
4214 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4215 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4216 /// parameters to cope with template friend declarations.
4217 Decl *
4218 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4219                                  MultiTemplateParamsArg TemplateParams,
4220                                  bool IsExplicitInstantiation,
4221                                  RecordDecl *&AnonRecord) {
4222   Decl *TagD = nullptr;
4223   TagDecl *Tag = nullptr;
4224   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4225       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4226       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4227       DS.getTypeSpecType() == DeclSpec::TST_union ||
4228       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4229     TagD = DS.getRepAsDecl();
4230 
4231     if (!TagD) // We probably had an error
4232       return nullptr;
4233 
4234     // Note that the above type specs guarantee that the
4235     // type rep is a Decl, whereas in many of the others
4236     // it's a Type.
4237     if (isa<TagDecl>(TagD))
4238       Tag = cast<TagDecl>(TagD);
4239     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4240       Tag = CTD->getTemplatedDecl();
4241   }
4242 
4243   if (Tag) {
4244     handleTagNumbering(Tag, S);
4245     Tag->setFreeStanding();
4246     if (Tag->isInvalidDecl())
4247       return Tag;
4248   }
4249 
4250   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4251     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4252     // or incomplete types shall not be restrict-qualified."
4253     if (TypeQuals & DeclSpec::TQ_restrict)
4254       Diag(DS.getRestrictSpecLoc(),
4255            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4256            << DS.getSourceRange();
4257   }
4258 
4259   if (DS.isInlineSpecified())
4260     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4261         << getLangOpts().CPlusPlus17;
4262 
4263   if (DS.isConstexprSpecified()) {
4264     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4265     // and definitions of functions and variables.
4266     if (Tag)
4267       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4268           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4269     else
4270       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4271     // Don't emit warnings after this error.
4272     return TagD;
4273   }
4274 
4275   DiagnoseFunctionSpecifiers(DS);
4276 
4277   if (DS.isFriendSpecified()) {
4278     // If we're dealing with a decl but not a TagDecl, assume that
4279     // whatever routines created it handled the friendship aspect.
4280     if (TagD && !Tag)
4281       return nullptr;
4282     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4283   }
4284 
4285   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4286   bool IsExplicitSpecialization =
4287     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4288   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4289       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4290       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4291     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4292     // nested-name-specifier unless it is an explicit instantiation
4293     // or an explicit specialization.
4294     //
4295     // FIXME: We allow class template partial specializations here too, per the
4296     // obvious intent of DR1819.
4297     //
4298     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4299     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4300         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4301     return nullptr;
4302   }
4303 
4304   // Track whether this decl-specifier declares anything.
4305   bool DeclaresAnything = true;
4306 
4307   // Handle anonymous struct definitions.
4308   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4309     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4310         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4311       if (getLangOpts().CPlusPlus ||
4312           Record->getDeclContext()->isRecord()) {
4313         // If CurContext is a DeclContext that can contain statements,
4314         // RecursiveASTVisitor won't visit the decls that
4315         // BuildAnonymousStructOrUnion() will put into CurContext.
4316         // Also store them here so that they can be part of the
4317         // DeclStmt that gets created in this case.
4318         // FIXME: Also return the IndirectFieldDecls created by
4319         // BuildAnonymousStructOr union, for the same reason?
4320         if (CurContext->isFunctionOrMethod())
4321           AnonRecord = Record;
4322         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4323                                            Context.getPrintingPolicy());
4324       }
4325 
4326       DeclaresAnything = false;
4327     }
4328   }
4329 
4330   // C11 6.7.2.1p2:
4331   //   A struct-declaration that does not declare an anonymous structure or
4332   //   anonymous union shall contain a struct-declarator-list.
4333   //
4334   // This rule also existed in C89 and C99; the grammar for struct-declaration
4335   // did not permit a struct-declaration without a struct-declarator-list.
4336   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4337       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4338     // Check for Microsoft C extension: anonymous struct/union member.
4339     // Handle 2 kinds of anonymous struct/union:
4340     //   struct STRUCT;
4341     //   union UNION;
4342     // and
4343     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4344     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4345     if ((Tag && Tag->getDeclName()) ||
4346         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4347       RecordDecl *Record = nullptr;
4348       if (Tag)
4349         Record = dyn_cast<RecordDecl>(Tag);
4350       else if (const RecordType *RT =
4351                    DS.getRepAsType().get()->getAsStructureType())
4352         Record = RT->getDecl();
4353       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4354         Record = UT->getDecl();
4355 
4356       if (Record && getLangOpts().MicrosoftExt) {
4357         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4358             << Record->isUnion() << DS.getSourceRange();
4359         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4360       }
4361 
4362       DeclaresAnything = false;
4363     }
4364   }
4365 
4366   // Skip all the checks below if we have a type error.
4367   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4368       (TagD && TagD->isInvalidDecl()))
4369     return TagD;
4370 
4371   if (getLangOpts().CPlusPlus &&
4372       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4373     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4374       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4375           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4376         DeclaresAnything = false;
4377 
4378   if (!DS.isMissingDeclaratorOk()) {
4379     // Customize diagnostic for a typedef missing a name.
4380     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4381       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4382           << DS.getSourceRange();
4383     else
4384       DeclaresAnything = false;
4385   }
4386 
4387   if (DS.isModulePrivateSpecified() &&
4388       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4389     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4390       << Tag->getTagKind()
4391       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4392 
4393   ActOnDocumentableDecl(TagD);
4394 
4395   // C 6.7/2:
4396   //   A declaration [...] shall declare at least a declarator [...], a tag,
4397   //   or the members of an enumeration.
4398   // C++ [dcl.dcl]p3:
4399   //   [If there are no declarators], and except for the declaration of an
4400   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4401   //   names into the program, or shall redeclare a name introduced by a
4402   //   previous declaration.
4403   if (!DeclaresAnything) {
4404     // In C, we allow this as a (popular) extension / bug. Don't bother
4405     // producing further diagnostics for redundant qualifiers after this.
4406     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4407     return TagD;
4408   }
4409 
4410   // C++ [dcl.stc]p1:
4411   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4412   //   init-declarator-list of the declaration shall not be empty.
4413   // C++ [dcl.fct.spec]p1:
4414   //   If a cv-qualifier appears in a decl-specifier-seq, the
4415   //   init-declarator-list of the declaration shall not be empty.
4416   //
4417   // Spurious qualifiers here appear to be valid in C.
4418   unsigned DiagID = diag::warn_standalone_specifier;
4419   if (getLangOpts().CPlusPlus)
4420     DiagID = diag::ext_standalone_specifier;
4421 
4422   // Note that a linkage-specification sets a storage class, but
4423   // 'extern "C" struct foo;' is actually valid and not theoretically
4424   // useless.
4425   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4426     if (SCS == DeclSpec::SCS_mutable)
4427       // Since mutable is not a viable storage class specifier in C, there is
4428       // no reason to treat it as an extension. Instead, diagnose as an error.
4429       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4430     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4431       Diag(DS.getStorageClassSpecLoc(), DiagID)
4432         << DeclSpec::getSpecifierName(SCS);
4433   }
4434 
4435   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4436     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4437       << DeclSpec::getSpecifierName(TSCS);
4438   if (DS.getTypeQualifiers()) {
4439     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4440       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4441     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4442       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4443     // Restrict is covered above.
4444     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4445       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4446     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4447       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4448   }
4449 
4450   // Warn about ignored type attributes, for example:
4451   // __attribute__((aligned)) struct A;
4452   // Attributes should be placed after tag to apply to type declaration.
4453   if (!DS.getAttributes().empty()) {
4454     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4455     if (TypeSpecType == DeclSpec::TST_class ||
4456         TypeSpecType == DeclSpec::TST_struct ||
4457         TypeSpecType == DeclSpec::TST_interface ||
4458         TypeSpecType == DeclSpec::TST_union ||
4459         TypeSpecType == DeclSpec::TST_enum) {
4460       for (const ParsedAttr &AL : DS.getAttributes())
4461         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4462             << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4463     }
4464   }
4465 
4466   return TagD;
4467 }
4468 
4469 /// We are trying to inject an anonymous member into the given scope;
4470 /// check if there's an existing declaration that can't be overloaded.
4471 ///
4472 /// \return true if this is a forbidden redeclaration
4473 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4474                                          Scope *S,
4475                                          DeclContext *Owner,
4476                                          DeclarationName Name,
4477                                          SourceLocation NameLoc,
4478                                          bool IsUnion) {
4479   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4480                  Sema::ForVisibleRedeclaration);
4481   if (!SemaRef.LookupName(R, S)) return false;
4482 
4483   // Pick a representative declaration.
4484   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4485   assert(PrevDecl && "Expected a non-null Decl");
4486 
4487   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4488     return false;
4489 
4490   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4491     << IsUnion << Name;
4492   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4493 
4494   return true;
4495 }
4496 
4497 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4498 /// anonymous struct or union AnonRecord into the owning context Owner
4499 /// and scope S. This routine will be invoked just after we realize
4500 /// that an unnamed union or struct is actually an anonymous union or
4501 /// struct, e.g.,
4502 ///
4503 /// @code
4504 /// union {
4505 ///   int i;
4506 ///   float f;
4507 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4508 ///    // f into the surrounding scope.x
4509 /// @endcode
4510 ///
4511 /// This routine is recursive, injecting the names of nested anonymous
4512 /// structs/unions into the owning context and scope as well.
4513 static bool
4514 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4515                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4516                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4517   bool Invalid = false;
4518 
4519   // Look every FieldDecl and IndirectFieldDecl with a name.
4520   for (auto *D : AnonRecord->decls()) {
4521     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4522         cast<NamedDecl>(D)->getDeclName()) {
4523       ValueDecl *VD = cast<ValueDecl>(D);
4524       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4525                                        VD->getLocation(),
4526                                        AnonRecord->isUnion())) {
4527         // C++ [class.union]p2:
4528         //   The names of the members of an anonymous union shall be
4529         //   distinct from the names of any other entity in the
4530         //   scope in which the anonymous union is declared.
4531         Invalid = true;
4532       } else {
4533         // C++ [class.union]p2:
4534         //   For the purpose of name lookup, after the anonymous union
4535         //   definition, the members of the anonymous union are
4536         //   considered to have been defined in the scope in which the
4537         //   anonymous union is declared.
4538         unsigned OldChainingSize = Chaining.size();
4539         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4540           Chaining.append(IF->chain_begin(), IF->chain_end());
4541         else
4542           Chaining.push_back(VD);
4543 
4544         assert(Chaining.size() >= 2);
4545         NamedDecl **NamedChain =
4546           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4547         for (unsigned i = 0; i < Chaining.size(); i++)
4548           NamedChain[i] = Chaining[i];
4549 
4550         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4551             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4552             VD->getType(), {NamedChain, Chaining.size()});
4553 
4554         for (const auto *Attr : VD->attrs())
4555           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4556 
4557         IndirectField->setAccess(AS);
4558         IndirectField->setImplicit();
4559         SemaRef.PushOnScopeChains(IndirectField, S);
4560 
4561         // That includes picking up the appropriate access specifier.
4562         if (AS != AS_none) IndirectField->setAccess(AS);
4563 
4564         Chaining.resize(OldChainingSize);
4565       }
4566     }
4567   }
4568 
4569   return Invalid;
4570 }
4571 
4572 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4573 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4574 /// illegal input values are mapped to SC_None.
4575 static StorageClass
4576 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4577   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4578   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4579          "Parser allowed 'typedef' as storage class VarDecl.");
4580   switch (StorageClassSpec) {
4581   case DeclSpec::SCS_unspecified:    return SC_None;
4582   case DeclSpec::SCS_extern:
4583     if (DS.isExternInLinkageSpec())
4584       return SC_None;
4585     return SC_Extern;
4586   case DeclSpec::SCS_static:         return SC_Static;
4587   case DeclSpec::SCS_auto:           return SC_Auto;
4588   case DeclSpec::SCS_register:       return SC_Register;
4589   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4590     // Illegal SCSs map to None: error reporting is up to the caller.
4591   case DeclSpec::SCS_mutable:        // Fall through.
4592   case DeclSpec::SCS_typedef:        return SC_None;
4593   }
4594   llvm_unreachable("unknown storage class specifier");
4595 }
4596 
4597 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4598   assert(Record->hasInClassInitializer());
4599 
4600   for (const auto *I : Record->decls()) {
4601     const auto *FD = dyn_cast<FieldDecl>(I);
4602     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4603       FD = IFD->getAnonField();
4604     if (FD && FD->hasInClassInitializer())
4605       return FD->getLocation();
4606   }
4607 
4608   llvm_unreachable("couldn't find in-class initializer");
4609 }
4610 
4611 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4612                                       SourceLocation DefaultInitLoc) {
4613   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4614     return;
4615 
4616   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4617   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4618 }
4619 
4620 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4621                                       CXXRecordDecl *AnonUnion) {
4622   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4623     return;
4624 
4625   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4626 }
4627 
4628 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4629 /// anonymous structure or union. Anonymous unions are a C++ feature
4630 /// (C++ [class.union]) and a C11 feature; anonymous structures
4631 /// are a C11 feature and GNU C++ extension.
4632 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4633                                         AccessSpecifier AS,
4634                                         RecordDecl *Record,
4635                                         const PrintingPolicy &Policy) {
4636   DeclContext *Owner = Record->getDeclContext();
4637 
4638   // Diagnose whether this anonymous struct/union is an extension.
4639   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4640     Diag(Record->getLocation(), diag::ext_anonymous_union);
4641   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4642     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4643   else if (!Record->isUnion() && !getLangOpts().C11)
4644     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4645 
4646   // C and C++ require different kinds of checks for anonymous
4647   // structs/unions.
4648   bool Invalid = false;
4649   if (getLangOpts().CPlusPlus) {
4650     const char *PrevSpec = nullptr;
4651     unsigned DiagID;
4652     if (Record->isUnion()) {
4653       // C++ [class.union]p6:
4654       // C++17 [class.union.anon]p2:
4655       //   Anonymous unions declared in a named namespace or in the
4656       //   global namespace shall be declared static.
4657       DeclContext *OwnerScope = Owner->getRedeclContext();
4658       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4659           (OwnerScope->isTranslationUnit() ||
4660            (OwnerScope->isNamespace() &&
4661             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4662         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4663           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4664 
4665         // Recover by adding 'static'.
4666         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4667                                PrevSpec, DiagID, Policy);
4668       }
4669       // C++ [class.union]p6:
4670       //   A storage class is not allowed in a declaration of an
4671       //   anonymous union in a class scope.
4672       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4673                isa<RecordDecl>(Owner)) {
4674         Diag(DS.getStorageClassSpecLoc(),
4675              diag::err_anonymous_union_with_storage_spec)
4676           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4677 
4678         // Recover by removing the storage specifier.
4679         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4680                                SourceLocation(),
4681                                PrevSpec, DiagID, Context.getPrintingPolicy());
4682       }
4683     }
4684 
4685     // Ignore const/volatile/restrict qualifiers.
4686     if (DS.getTypeQualifiers()) {
4687       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4688         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4689           << Record->isUnion() << "const"
4690           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4691       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4692         Diag(DS.getVolatileSpecLoc(),
4693              diag::ext_anonymous_struct_union_qualified)
4694           << Record->isUnion() << "volatile"
4695           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4696       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4697         Diag(DS.getRestrictSpecLoc(),
4698              diag::ext_anonymous_struct_union_qualified)
4699           << Record->isUnion() << "restrict"
4700           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4701       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4702         Diag(DS.getAtomicSpecLoc(),
4703              diag::ext_anonymous_struct_union_qualified)
4704           << Record->isUnion() << "_Atomic"
4705           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4706       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4707         Diag(DS.getUnalignedSpecLoc(),
4708              diag::ext_anonymous_struct_union_qualified)
4709           << Record->isUnion() << "__unaligned"
4710           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4711 
4712       DS.ClearTypeQualifiers();
4713     }
4714 
4715     // C++ [class.union]p2:
4716     //   The member-specification of an anonymous union shall only
4717     //   define non-static data members. [Note: nested types and
4718     //   functions cannot be declared within an anonymous union. ]
4719     for (auto *Mem : Record->decls()) {
4720       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4721         // C++ [class.union]p3:
4722         //   An anonymous union shall not have private or protected
4723         //   members (clause 11).
4724         assert(FD->getAccess() != AS_none);
4725         if (FD->getAccess() != AS_public) {
4726           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4727             << Record->isUnion() << (FD->getAccess() == AS_protected);
4728           Invalid = true;
4729         }
4730 
4731         // C++ [class.union]p1
4732         //   An object of a class with a non-trivial constructor, a non-trivial
4733         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4734         //   assignment operator cannot be a member of a union, nor can an
4735         //   array of such objects.
4736         if (CheckNontrivialField(FD))
4737           Invalid = true;
4738       } else if (Mem->isImplicit()) {
4739         // Any implicit members are fine.
4740       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4741         // This is a type that showed up in an
4742         // elaborated-type-specifier inside the anonymous struct or
4743         // union, but which actually declares a type outside of the
4744         // anonymous struct or union. It's okay.
4745       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4746         if (!MemRecord->isAnonymousStructOrUnion() &&
4747             MemRecord->getDeclName()) {
4748           // Visual C++ allows type definition in anonymous struct or union.
4749           if (getLangOpts().MicrosoftExt)
4750             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4751               << Record->isUnion();
4752           else {
4753             // This is a nested type declaration.
4754             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4755               << Record->isUnion();
4756             Invalid = true;
4757           }
4758         } else {
4759           // This is an anonymous type definition within another anonymous type.
4760           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4761           // not part of standard C++.
4762           Diag(MemRecord->getLocation(),
4763                diag::ext_anonymous_record_with_anonymous_type)
4764             << Record->isUnion();
4765         }
4766       } else if (isa<AccessSpecDecl>(Mem)) {
4767         // Any access specifier is fine.
4768       } else if (isa<StaticAssertDecl>(Mem)) {
4769         // In C++1z, static_assert declarations are also fine.
4770       } else {
4771         // We have something that isn't a non-static data
4772         // member. Complain about it.
4773         unsigned DK = diag::err_anonymous_record_bad_member;
4774         if (isa<TypeDecl>(Mem))
4775           DK = diag::err_anonymous_record_with_type;
4776         else if (isa<FunctionDecl>(Mem))
4777           DK = diag::err_anonymous_record_with_function;
4778         else if (isa<VarDecl>(Mem))
4779           DK = diag::err_anonymous_record_with_static;
4780 
4781         // Visual C++ allows type definition in anonymous struct or union.
4782         if (getLangOpts().MicrosoftExt &&
4783             DK == diag::err_anonymous_record_with_type)
4784           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4785             << Record->isUnion();
4786         else {
4787           Diag(Mem->getLocation(), DK) << Record->isUnion();
4788           Invalid = true;
4789         }
4790       }
4791     }
4792 
4793     // C++11 [class.union]p8 (DR1460):
4794     //   At most one variant member of a union may have a
4795     //   brace-or-equal-initializer.
4796     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4797         Owner->isRecord())
4798       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4799                                 cast<CXXRecordDecl>(Record));
4800   }
4801 
4802   if (!Record->isUnion() && !Owner->isRecord()) {
4803     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4804       << getLangOpts().CPlusPlus;
4805     Invalid = true;
4806   }
4807 
4808   // Mock up a declarator.
4809   Declarator Dc(DS, DeclaratorContext::MemberContext);
4810   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4811   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4812 
4813   // Create a declaration for this anonymous struct/union.
4814   NamedDecl *Anon = nullptr;
4815   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4816     Anon = FieldDecl::Create(
4817         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
4818         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
4819         /*BitWidth=*/nullptr, /*Mutable=*/false,
4820         /*InitStyle=*/ICIS_NoInit);
4821     Anon->setAccess(AS);
4822     if (getLangOpts().CPlusPlus)
4823       FieldCollector->Add(cast<FieldDecl>(Anon));
4824   } else {
4825     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4826     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4827     if (SCSpec == DeclSpec::SCS_mutable) {
4828       // mutable can only appear on non-static class members, so it's always
4829       // an error here
4830       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4831       Invalid = true;
4832       SC = SC_None;
4833     }
4834 
4835     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
4836                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4837                            Context.getTypeDeclType(Record), TInfo, SC);
4838 
4839     // Default-initialize the implicit variable. This initialization will be
4840     // trivial in almost all cases, except if a union member has an in-class
4841     // initializer:
4842     //   union { int n = 0; };
4843     ActOnUninitializedDecl(Anon);
4844   }
4845   Anon->setImplicit();
4846 
4847   // Mark this as an anonymous struct/union type.
4848   Record->setAnonymousStructOrUnion(true);
4849 
4850   // Add the anonymous struct/union object to the current
4851   // context. We'll be referencing this object when we refer to one of
4852   // its members.
4853   Owner->addDecl(Anon);
4854 
4855   // Inject the members of the anonymous struct/union into the owning
4856   // context and into the identifier resolver chain for name lookup
4857   // purposes.
4858   SmallVector<NamedDecl*, 2> Chain;
4859   Chain.push_back(Anon);
4860 
4861   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4862     Invalid = true;
4863 
4864   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4865     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4866       Decl *ManglingContextDecl;
4867       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4868               NewVD->getDeclContext(), ManglingContextDecl)) {
4869         Context.setManglingNumber(
4870             NewVD, MCtx->getManglingNumber(
4871                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4872         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4873       }
4874     }
4875   }
4876 
4877   if (Invalid)
4878     Anon->setInvalidDecl();
4879 
4880   return Anon;
4881 }
4882 
4883 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4884 /// Microsoft C anonymous structure.
4885 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4886 /// Example:
4887 ///
4888 /// struct A { int a; };
4889 /// struct B { struct A; int b; };
4890 ///
4891 /// void foo() {
4892 ///   B var;
4893 ///   var.a = 3;
4894 /// }
4895 ///
4896 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4897                                            RecordDecl *Record) {
4898   assert(Record && "expected a record!");
4899 
4900   // Mock up a declarator.
4901   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
4902   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4903   assert(TInfo && "couldn't build declarator info for anonymous struct");
4904 
4905   auto *ParentDecl = cast<RecordDecl>(CurContext);
4906   QualType RecTy = Context.getTypeDeclType(Record);
4907 
4908   // Create a declaration for this anonymous struct.
4909   NamedDecl *Anon =
4910       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
4911                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
4912                         /*BitWidth=*/nullptr, /*Mutable=*/false,
4913                         /*InitStyle=*/ICIS_NoInit);
4914   Anon->setImplicit();
4915 
4916   // Add the anonymous struct object to the current context.
4917   CurContext->addDecl(Anon);
4918 
4919   // Inject the members of the anonymous struct into the current
4920   // context and into the identifier resolver chain for name lookup
4921   // purposes.
4922   SmallVector<NamedDecl*, 2> Chain;
4923   Chain.push_back(Anon);
4924 
4925   RecordDecl *RecordDef = Record->getDefinition();
4926   if (RequireCompleteType(Anon->getLocation(), RecTy,
4927                           diag::err_field_incomplete) ||
4928       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4929                                           AS_none, Chain)) {
4930     Anon->setInvalidDecl();
4931     ParentDecl->setInvalidDecl();
4932   }
4933 
4934   return Anon;
4935 }
4936 
4937 /// GetNameForDeclarator - Determine the full declaration name for the
4938 /// given Declarator.
4939 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4940   return GetNameFromUnqualifiedId(D.getName());
4941 }
4942 
4943 /// Retrieves the declaration name from a parsed unqualified-id.
4944 DeclarationNameInfo
4945 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4946   DeclarationNameInfo NameInfo;
4947   NameInfo.setLoc(Name.StartLocation);
4948 
4949   switch (Name.getKind()) {
4950 
4951   case UnqualifiedIdKind::IK_ImplicitSelfParam:
4952   case UnqualifiedIdKind::IK_Identifier:
4953     NameInfo.setName(Name.Identifier);
4954     return NameInfo;
4955 
4956   case UnqualifiedIdKind::IK_DeductionGuideName: {
4957     // C++ [temp.deduct.guide]p3:
4958     //   The simple-template-id shall name a class template specialization.
4959     //   The template-name shall be the same identifier as the template-name
4960     //   of the simple-template-id.
4961     // These together intend to imply that the template-name shall name a
4962     // class template.
4963     // FIXME: template<typename T> struct X {};
4964     //        template<typename T> using Y = X<T>;
4965     //        Y(int) -> Y<int>;
4966     //   satisfies these rules but does not name a class template.
4967     TemplateName TN = Name.TemplateName.get().get();
4968     auto *Template = TN.getAsTemplateDecl();
4969     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4970       Diag(Name.StartLocation,
4971            diag::err_deduction_guide_name_not_class_template)
4972         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4973       if (Template)
4974         Diag(Template->getLocation(), diag::note_template_decl_here);
4975       return DeclarationNameInfo();
4976     }
4977 
4978     NameInfo.setName(
4979         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4980     return NameInfo;
4981   }
4982 
4983   case UnqualifiedIdKind::IK_OperatorFunctionId:
4984     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4985                                            Name.OperatorFunctionId.Operator));
4986     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4987       = Name.OperatorFunctionId.SymbolLocations[0];
4988     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4989       = Name.EndLocation.getRawEncoding();
4990     return NameInfo;
4991 
4992   case UnqualifiedIdKind::IK_LiteralOperatorId:
4993     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4994                                                            Name.Identifier));
4995     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4996     return NameInfo;
4997 
4998   case UnqualifiedIdKind::IK_ConversionFunctionId: {
4999     TypeSourceInfo *TInfo;
5000     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5001     if (Ty.isNull())
5002       return DeclarationNameInfo();
5003     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5004                                                Context.getCanonicalType(Ty)));
5005     NameInfo.setNamedTypeInfo(TInfo);
5006     return NameInfo;
5007   }
5008 
5009   case UnqualifiedIdKind::IK_ConstructorName: {
5010     TypeSourceInfo *TInfo;
5011     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5012     if (Ty.isNull())
5013       return DeclarationNameInfo();
5014     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5015                                               Context.getCanonicalType(Ty)));
5016     NameInfo.setNamedTypeInfo(TInfo);
5017     return NameInfo;
5018   }
5019 
5020   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5021     // In well-formed code, we can only have a constructor
5022     // template-id that refers to the current context, so go there
5023     // to find the actual type being constructed.
5024     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5025     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5026       return DeclarationNameInfo();
5027 
5028     // Determine the type of the class being constructed.
5029     QualType CurClassType = Context.getTypeDeclType(CurClass);
5030 
5031     // FIXME: Check two things: that the template-id names the same type as
5032     // CurClassType, and that the template-id does not occur when the name
5033     // was qualified.
5034 
5035     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5036                                     Context.getCanonicalType(CurClassType)));
5037     // FIXME: should we retrieve TypeSourceInfo?
5038     NameInfo.setNamedTypeInfo(nullptr);
5039     return NameInfo;
5040   }
5041 
5042   case UnqualifiedIdKind::IK_DestructorName: {
5043     TypeSourceInfo *TInfo;
5044     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5045     if (Ty.isNull())
5046       return DeclarationNameInfo();
5047     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5048                                               Context.getCanonicalType(Ty)));
5049     NameInfo.setNamedTypeInfo(TInfo);
5050     return NameInfo;
5051   }
5052 
5053   case UnqualifiedIdKind::IK_TemplateId: {
5054     TemplateName TName = Name.TemplateId->Template.get();
5055     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5056     return Context.getNameForTemplate(TName, TNameLoc);
5057   }
5058 
5059   } // switch (Name.getKind())
5060 
5061   llvm_unreachable("Unknown name kind");
5062 }
5063 
5064 static QualType getCoreType(QualType Ty) {
5065   do {
5066     if (Ty->isPointerType() || Ty->isReferenceType())
5067       Ty = Ty->getPointeeType();
5068     else if (Ty->isArrayType())
5069       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5070     else
5071       return Ty.withoutLocalFastQualifiers();
5072   } while (true);
5073 }
5074 
5075 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5076 /// and Definition have "nearly" matching parameters. This heuristic is
5077 /// used to improve diagnostics in the case where an out-of-line function
5078 /// definition doesn't match any declaration within the class or namespace.
5079 /// Also sets Params to the list of indices to the parameters that differ
5080 /// between the declaration and the definition. If hasSimilarParameters
5081 /// returns true and Params is empty, then all of the parameters match.
5082 static bool hasSimilarParameters(ASTContext &Context,
5083                                      FunctionDecl *Declaration,
5084                                      FunctionDecl *Definition,
5085                                      SmallVectorImpl<unsigned> &Params) {
5086   Params.clear();
5087   if (Declaration->param_size() != Definition->param_size())
5088     return false;
5089   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5090     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5091     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5092 
5093     // The parameter types are identical
5094     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5095       continue;
5096 
5097     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5098     QualType DefParamBaseTy = getCoreType(DefParamTy);
5099     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5100     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5101 
5102     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5103         (DeclTyName && DeclTyName == DefTyName))
5104       Params.push_back(Idx);
5105     else  // The two parameters aren't even close
5106       return false;
5107   }
5108 
5109   return true;
5110 }
5111 
5112 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5113 /// declarator needs to be rebuilt in the current instantiation.
5114 /// Any bits of declarator which appear before the name are valid for
5115 /// consideration here.  That's specifically the type in the decl spec
5116 /// and the base type in any member-pointer chunks.
5117 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5118                                                     DeclarationName Name) {
5119   // The types we specifically need to rebuild are:
5120   //   - typenames, typeofs, and decltypes
5121   //   - types which will become injected class names
5122   // Of course, we also need to rebuild any type referencing such a
5123   // type.  It's safest to just say "dependent", but we call out a
5124   // few cases here.
5125 
5126   DeclSpec &DS = D.getMutableDeclSpec();
5127   switch (DS.getTypeSpecType()) {
5128   case DeclSpec::TST_typename:
5129   case DeclSpec::TST_typeofType:
5130   case DeclSpec::TST_underlyingType:
5131   case DeclSpec::TST_atomic: {
5132     // Grab the type from the parser.
5133     TypeSourceInfo *TSI = nullptr;
5134     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5135     if (T.isNull() || !T->isDependentType()) break;
5136 
5137     // Make sure there's a type source info.  This isn't really much
5138     // of a waste; most dependent types should have type source info
5139     // attached already.
5140     if (!TSI)
5141       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5142 
5143     // Rebuild the type in the current instantiation.
5144     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5145     if (!TSI) return true;
5146 
5147     // Store the new type back in the decl spec.
5148     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5149     DS.UpdateTypeRep(LocType);
5150     break;
5151   }
5152 
5153   case DeclSpec::TST_decltype:
5154   case DeclSpec::TST_typeofExpr: {
5155     Expr *E = DS.getRepAsExpr();
5156     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5157     if (Result.isInvalid()) return true;
5158     DS.UpdateExprRep(Result.get());
5159     break;
5160   }
5161 
5162   default:
5163     // Nothing to do for these decl specs.
5164     break;
5165   }
5166 
5167   // It doesn't matter what order we do this in.
5168   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5169     DeclaratorChunk &Chunk = D.getTypeObject(I);
5170 
5171     // The only type information in the declarator which can come
5172     // before the declaration name is the base type of a member
5173     // pointer.
5174     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5175       continue;
5176 
5177     // Rebuild the scope specifier in-place.
5178     CXXScopeSpec &SS = Chunk.Mem.Scope();
5179     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5180       return true;
5181   }
5182 
5183   return false;
5184 }
5185 
5186 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5187   D.setFunctionDefinitionKind(FDK_Declaration);
5188   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5189 
5190   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5191       Dcl && Dcl->getDeclContext()->isFileContext())
5192     Dcl->setTopLevelDeclInObjCContainer();
5193 
5194   if (getLangOpts().OpenCL)
5195     setCurrentOpenCLExtensionForDecl(Dcl);
5196 
5197   return Dcl;
5198 }
5199 
5200 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5201 ///   If T is the name of a class, then each of the following shall have a
5202 ///   name different from T:
5203 ///     - every static data member of class T;
5204 ///     - every member function of class T
5205 ///     - every member of class T that is itself a type;
5206 /// \returns true if the declaration name violates these rules.
5207 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5208                                    DeclarationNameInfo NameInfo) {
5209   DeclarationName Name = NameInfo.getName();
5210 
5211   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5212   while (Record && Record->isAnonymousStructOrUnion())
5213     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5214   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5215     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5216     return true;
5217   }
5218 
5219   return false;
5220 }
5221 
5222 /// Diagnose a declaration whose declarator-id has the given
5223 /// nested-name-specifier.
5224 ///
5225 /// \param SS The nested-name-specifier of the declarator-id.
5226 ///
5227 /// \param DC The declaration context to which the nested-name-specifier
5228 /// resolves.
5229 ///
5230 /// \param Name The name of the entity being declared.
5231 ///
5232 /// \param Loc The location of the name of the entity being declared.
5233 ///
5234 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5235 /// we're declaring an explicit / partial specialization / instantiation.
5236 ///
5237 /// \returns true if we cannot safely recover from this error, false otherwise.
5238 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5239                                         DeclarationName Name,
5240                                         SourceLocation Loc, bool IsTemplateId) {
5241   DeclContext *Cur = CurContext;
5242   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5243     Cur = Cur->getParent();
5244 
5245   // If the user provided a superfluous scope specifier that refers back to the
5246   // class in which the entity is already declared, diagnose and ignore it.
5247   //
5248   // class X {
5249   //   void X::f();
5250   // };
5251   //
5252   // Note, it was once ill-formed to give redundant qualification in all
5253   // contexts, but that rule was removed by DR482.
5254   if (Cur->Equals(DC)) {
5255     if (Cur->isRecord()) {
5256       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5257                                       : diag::err_member_extra_qualification)
5258         << Name << FixItHint::CreateRemoval(SS.getRange());
5259       SS.clear();
5260     } else {
5261       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5262     }
5263     return false;
5264   }
5265 
5266   // Check whether the qualifying scope encloses the scope of the original
5267   // declaration. For a template-id, we perform the checks in
5268   // CheckTemplateSpecializationScope.
5269   if (!Cur->Encloses(DC) && !IsTemplateId) {
5270     if (Cur->isRecord())
5271       Diag(Loc, diag::err_member_qualification)
5272         << Name << SS.getRange();
5273     else if (isa<TranslationUnitDecl>(DC))
5274       Diag(Loc, diag::err_invalid_declarator_global_scope)
5275         << Name << SS.getRange();
5276     else if (isa<FunctionDecl>(Cur))
5277       Diag(Loc, diag::err_invalid_declarator_in_function)
5278         << Name << SS.getRange();
5279     else if (isa<BlockDecl>(Cur))
5280       Diag(Loc, diag::err_invalid_declarator_in_block)
5281         << Name << SS.getRange();
5282     else
5283       Diag(Loc, diag::err_invalid_declarator_scope)
5284       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5285 
5286     return true;
5287   }
5288 
5289   if (Cur->isRecord()) {
5290     // Cannot qualify members within a class.
5291     Diag(Loc, diag::err_member_qualification)
5292       << Name << SS.getRange();
5293     SS.clear();
5294 
5295     // C++ constructors and destructors with incorrect scopes can break
5296     // our AST invariants by having the wrong underlying types. If
5297     // that's the case, then drop this declaration entirely.
5298     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5299          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5300         !Context.hasSameType(Name.getCXXNameType(),
5301                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5302       return true;
5303 
5304     return false;
5305   }
5306 
5307   // C++11 [dcl.meaning]p1:
5308   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5309   //   not begin with a decltype-specifer"
5310   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5311   while (SpecLoc.getPrefix())
5312     SpecLoc = SpecLoc.getPrefix();
5313   if (dyn_cast_or_null<DecltypeType>(
5314         SpecLoc.getNestedNameSpecifier()->getAsType()))
5315     Diag(Loc, diag::err_decltype_in_declarator)
5316       << SpecLoc.getTypeLoc().getSourceRange();
5317 
5318   return false;
5319 }
5320 
5321 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5322                                   MultiTemplateParamsArg TemplateParamLists) {
5323   // TODO: consider using NameInfo for diagnostic.
5324   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5325   DeclarationName Name = NameInfo.getName();
5326 
5327   // All of these full declarators require an identifier.  If it doesn't have
5328   // one, the ParsedFreeStandingDeclSpec action should be used.
5329   if (D.isDecompositionDeclarator()) {
5330     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5331   } else if (!Name) {
5332     if (!D.isInvalidType())  // Reject this if we think it is valid.
5333       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5334           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5335     return nullptr;
5336   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5337     return nullptr;
5338 
5339   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5340   // we find one that is.
5341   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5342          (S->getFlags() & Scope::TemplateParamScope) != 0)
5343     S = S->getParent();
5344 
5345   DeclContext *DC = CurContext;
5346   if (D.getCXXScopeSpec().isInvalid())
5347     D.setInvalidType();
5348   else if (D.getCXXScopeSpec().isSet()) {
5349     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5350                                         UPPC_DeclarationQualifier))
5351       return nullptr;
5352 
5353     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5354     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5355     if (!DC || isa<EnumDecl>(DC)) {
5356       // If we could not compute the declaration context, it's because the
5357       // declaration context is dependent but does not refer to a class,
5358       // class template, or class template partial specialization. Complain
5359       // and return early, to avoid the coming semantic disaster.
5360       Diag(D.getIdentifierLoc(),
5361            diag::err_template_qualified_declarator_no_match)
5362         << D.getCXXScopeSpec().getScopeRep()
5363         << D.getCXXScopeSpec().getRange();
5364       return nullptr;
5365     }
5366     bool IsDependentContext = DC->isDependentContext();
5367 
5368     if (!IsDependentContext &&
5369         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5370       return nullptr;
5371 
5372     // If a class is incomplete, do not parse entities inside it.
5373     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5374       Diag(D.getIdentifierLoc(),
5375            diag::err_member_def_undefined_record)
5376         << Name << DC << D.getCXXScopeSpec().getRange();
5377       return nullptr;
5378     }
5379     if (!D.getDeclSpec().isFriendSpecified()) {
5380       if (diagnoseQualifiedDeclaration(
5381               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5382               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5383         if (DC->isRecord())
5384           return nullptr;
5385 
5386         D.setInvalidType();
5387       }
5388     }
5389 
5390     // Check whether we need to rebuild the type of the given
5391     // declaration in the current instantiation.
5392     if (EnteringContext && IsDependentContext &&
5393         TemplateParamLists.size() != 0) {
5394       ContextRAII SavedContext(*this, DC);
5395       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5396         D.setInvalidType();
5397     }
5398   }
5399 
5400   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5401   QualType R = TInfo->getType();
5402 
5403   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5404                                       UPPC_DeclarationType))
5405     D.setInvalidType();
5406 
5407   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5408                         forRedeclarationInCurContext());
5409 
5410   // See if this is a redefinition of a variable in the same scope.
5411   if (!D.getCXXScopeSpec().isSet()) {
5412     bool IsLinkageLookup = false;
5413     bool CreateBuiltins = false;
5414 
5415     // If the declaration we're planning to build will be a function
5416     // or object with linkage, then look for another declaration with
5417     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5418     //
5419     // If the declaration we're planning to build will be declared with
5420     // external linkage in the translation unit, create any builtin with
5421     // the same name.
5422     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5423       /* Do nothing*/;
5424     else if (CurContext->isFunctionOrMethod() &&
5425              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5426               R->isFunctionType())) {
5427       IsLinkageLookup = true;
5428       CreateBuiltins =
5429           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5430     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5431                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5432       CreateBuiltins = true;
5433 
5434     if (IsLinkageLookup) {
5435       Previous.clear(LookupRedeclarationWithLinkage);
5436       Previous.setRedeclarationKind(ForExternalRedeclaration);
5437     }
5438 
5439     LookupName(Previous, S, CreateBuiltins);
5440   } else { // Something like "int foo::x;"
5441     LookupQualifiedName(Previous, DC);
5442 
5443     // C++ [dcl.meaning]p1:
5444     //   When the declarator-id is qualified, the declaration shall refer to a
5445     //  previously declared member of the class or namespace to which the
5446     //  qualifier refers (or, in the case of a namespace, of an element of the
5447     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5448     //  thereof; [...]
5449     //
5450     // Note that we already checked the context above, and that we do not have
5451     // enough information to make sure that Previous contains the declaration
5452     // we want to match. For example, given:
5453     //
5454     //   class X {
5455     //     void f();
5456     //     void f(float);
5457     //   };
5458     //
5459     //   void X::f(int) { } // ill-formed
5460     //
5461     // In this case, Previous will point to the overload set
5462     // containing the two f's declared in X, but neither of them
5463     // matches.
5464 
5465     // C++ [dcl.meaning]p1:
5466     //   [...] the member shall not merely have been introduced by a
5467     //   using-declaration in the scope of the class or namespace nominated by
5468     //   the nested-name-specifier of the declarator-id.
5469     RemoveUsingDecls(Previous);
5470   }
5471 
5472   if (Previous.isSingleResult() &&
5473       Previous.getFoundDecl()->isTemplateParameter()) {
5474     // Maybe we will complain about the shadowed template parameter.
5475     if (!D.isInvalidType())
5476       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5477                                       Previous.getFoundDecl());
5478 
5479     // Just pretend that we didn't see the previous declaration.
5480     Previous.clear();
5481   }
5482 
5483   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5484     // Forget that the previous declaration is the injected-class-name.
5485     Previous.clear();
5486 
5487   // In C++, the previous declaration we find might be a tag type
5488   // (class or enum). In this case, the new declaration will hide the
5489   // tag type. Note that this applies to functions, function templates, and
5490   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5491   if (Previous.isSingleTagDecl() &&
5492       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5493       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5494     Previous.clear();
5495 
5496   // Check that there are no default arguments other than in the parameters
5497   // of a function declaration (C++ only).
5498   if (getLangOpts().CPlusPlus)
5499     CheckExtraCXXDefaultArguments(D);
5500 
5501   NamedDecl *New;
5502 
5503   bool AddToScope = true;
5504   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5505     if (TemplateParamLists.size()) {
5506       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5507       return nullptr;
5508     }
5509 
5510     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5511   } else if (R->isFunctionType()) {
5512     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5513                                   TemplateParamLists,
5514                                   AddToScope);
5515   } else {
5516     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5517                                   AddToScope);
5518   }
5519 
5520   if (!New)
5521     return nullptr;
5522 
5523   // If this has an identifier and is not a function template specialization,
5524   // add it to the scope stack.
5525   if (New->getDeclName() && AddToScope)
5526     PushOnScopeChains(New, S);
5527 
5528   if (isInOpenMPDeclareTargetContext())
5529     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5530 
5531   return New;
5532 }
5533 
5534 /// Helper method to turn variable array types into constant array
5535 /// types in certain situations which would otherwise be errors (for
5536 /// GCC compatibility).
5537 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5538                                                     ASTContext &Context,
5539                                                     bool &SizeIsNegative,
5540                                                     llvm::APSInt &Oversized) {
5541   // This method tries to turn a variable array into a constant
5542   // array even when the size isn't an ICE.  This is necessary
5543   // for compatibility with code that depends on gcc's buggy
5544   // constant expression folding, like struct {char x[(int)(char*)2];}
5545   SizeIsNegative = false;
5546   Oversized = 0;
5547 
5548   if (T->isDependentType())
5549     return QualType();
5550 
5551   QualifierCollector Qs;
5552   const Type *Ty = Qs.strip(T);
5553 
5554   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5555     QualType Pointee = PTy->getPointeeType();
5556     QualType FixedType =
5557         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5558                                             Oversized);
5559     if (FixedType.isNull()) return FixedType;
5560     FixedType = Context.getPointerType(FixedType);
5561     return Qs.apply(Context, FixedType);
5562   }
5563   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5564     QualType Inner = PTy->getInnerType();
5565     QualType FixedType =
5566         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5567                                             Oversized);
5568     if (FixedType.isNull()) return FixedType;
5569     FixedType = Context.getParenType(FixedType);
5570     return Qs.apply(Context, FixedType);
5571   }
5572 
5573   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5574   if (!VLATy)
5575     return QualType();
5576   // FIXME: We should probably handle this case
5577   if (VLATy->getElementType()->isVariablyModifiedType())
5578     return QualType();
5579 
5580   Expr::EvalResult Result;
5581   if (!VLATy->getSizeExpr() ||
5582       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5583     return QualType();
5584 
5585   llvm::APSInt Res = Result.Val.getInt();
5586 
5587   // Check whether the array size is negative.
5588   if (Res.isSigned() && Res.isNegative()) {
5589     SizeIsNegative = true;
5590     return QualType();
5591   }
5592 
5593   // Check whether the array is too large to be addressed.
5594   unsigned ActiveSizeBits
5595     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5596                                               Res);
5597   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5598     Oversized = Res;
5599     return QualType();
5600   }
5601 
5602   return Context.getConstantArrayType(VLATy->getElementType(),
5603                                       Res, ArrayType::Normal, 0);
5604 }
5605 
5606 static void
5607 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5608   SrcTL = SrcTL.getUnqualifiedLoc();
5609   DstTL = DstTL.getUnqualifiedLoc();
5610   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5611     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5612     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5613                                       DstPTL.getPointeeLoc());
5614     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5615     return;
5616   }
5617   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5618     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5619     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5620                                       DstPTL.getInnerLoc());
5621     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5622     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5623     return;
5624   }
5625   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5626   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5627   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5628   TypeLoc DstElemTL = DstATL.getElementLoc();
5629   DstElemTL.initializeFullCopy(SrcElemTL);
5630   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5631   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5632   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5633 }
5634 
5635 /// Helper method to turn variable array types into constant array
5636 /// types in certain situations which would otherwise be errors (for
5637 /// GCC compatibility).
5638 static TypeSourceInfo*
5639 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5640                                               ASTContext &Context,
5641                                               bool &SizeIsNegative,
5642                                               llvm::APSInt &Oversized) {
5643   QualType FixedTy
5644     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5645                                           SizeIsNegative, Oversized);
5646   if (FixedTy.isNull())
5647     return nullptr;
5648   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5649   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5650                                     FixedTInfo->getTypeLoc());
5651   return FixedTInfo;
5652 }
5653 
5654 /// Register the given locally-scoped extern "C" declaration so
5655 /// that it can be found later for redeclarations. We include any extern "C"
5656 /// declaration that is not visible in the translation unit here, not just
5657 /// function-scope declarations.
5658 void
5659 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5660   if (!getLangOpts().CPlusPlus &&
5661       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5662     // Don't need to track declarations in the TU in C.
5663     return;
5664 
5665   // Note that we have a locally-scoped external with this name.
5666   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5667 }
5668 
5669 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5670   // FIXME: We can have multiple results via __attribute__((overloadable)).
5671   auto Result = Context.getExternCContextDecl()->lookup(Name);
5672   return Result.empty() ? nullptr : *Result.begin();
5673 }
5674 
5675 /// Diagnose function specifiers on a declaration of an identifier that
5676 /// does not identify a function.
5677 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5678   // FIXME: We should probably indicate the identifier in question to avoid
5679   // confusion for constructs like "virtual int a(), b;"
5680   if (DS.isVirtualSpecified())
5681     Diag(DS.getVirtualSpecLoc(),
5682          diag::err_virtual_non_function);
5683 
5684   if (DS.isExplicitSpecified())
5685     Diag(DS.getExplicitSpecLoc(),
5686          diag::err_explicit_non_function);
5687 
5688   if (DS.isNoreturnSpecified())
5689     Diag(DS.getNoreturnSpecLoc(),
5690          diag::err_noreturn_non_function);
5691 }
5692 
5693 NamedDecl*
5694 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5695                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5696   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5697   if (D.getCXXScopeSpec().isSet()) {
5698     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5699       << D.getCXXScopeSpec().getRange();
5700     D.setInvalidType();
5701     // Pretend we didn't see the scope specifier.
5702     DC = CurContext;
5703     Previous.clear();
5704   }
5705 
5706   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5707 
5708   if (D.getDeclSpec().isInlineSpecified())
5709     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5710         << getLangOpts().CPlusPlus17;
5711   if (D.getDeclSpec().isConstexprSpecified())
5712     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5713       << 1;
5714 
5715   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5716     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5717       Diag(D.getName().StartLocation,
5718            diag::err_deduction_guide_invalid_specifier)
5719           << "typedef";
5720     else
5721       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5722           << D.getName().getSourceRange();
5723     return nullptr;
5724   }
5725 
5726   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5727   if (!NewTD) return nullptr;
5728 
5729   // Handle attributes prior to checking for duplicates in MergeVarDecl
5730   ProcessDeclAttributes(S, NewTD, D);
5731 
5732   CheckTypedefForVariablyModifiedType(S, NewTD);
5733 
5734   bool Redeclaration = D.isRedeclaration();
5735   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5736   D.setRedeclaration(Redeclaration);
5737   return ND;
5738 }
5739 
5740 void
5741 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5742   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5743   // then it shall have block scope.
5744   // Note that variably modified types must be fixed before merging the decl so
5745   // that redeclarations will match.
5746   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5747   QualType T = TInfo->getType();
5748   if (T->isVariablyModifiedType()) {
5749     setFunctionHasBranchProtectedScope();
5750 
5751     if (S->getFnParent() == nullptr) {
5752       bool SizeIsNegative;
5753       llvm::APSInt Oversized;
5754       TypeSourceInfo *FixedTInfo =
5755         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5756                                                       SizeIsNegative,
5757                                                       Oversized);
5758       if (FixedTInfo) {
5759         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5760         NewTD->setTypeSourceInfo(FixedTInfo);
5761       } else {
5762         if (SizeIsNegative)
5763           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5764         else if (T->isVariableArrayType())
5765           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5766         else if (Oversized.getBoolValue())
5767           Diag(NewTD->getLocation(), diag::err_array_too_large)
5768             << Oversized.toString(10);
5769         else
5770           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5771         NewTD->setInvalidDecl();
5772       }
5773     }
5774   }
5775 }
5776 
5777 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5778 /// declares a typedef-name, either using the 'typedef' type specifier or via
5779 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5780 NamedDecl*
5781 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5782                            LookupResult &Previous, bool &Redeclaration) {
5783 
5784   // Find the shadowed declaration before filtering for scope.
5785   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5786 
5787   // Merge the decl with the existing one if appropriate. If the decl is
5788   // in an outer scope, it isn't the same thing.
5789   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5790                        /*AllowInlineNamespace*/false);
5791   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5792   if (!Previous.empty()) {
5793     Redeclaration = true;
5794     MergeTypedefNameDecl(S, NewTD, Previous);
5795   }
5796 
5797   if (ShadowedDecl && !Redeclaration)
5798     CheckShadow(NewTD, ShadowedDecl, Previous);
5799 
5800   // If this is the C FILE type, notify the AST context.
5801   if (IdentifierInfo *II = NewTD->getIdentifier())
5802     if (!NewTD->isInvalidDecl() &&
5803         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5804       if (II->isStr("FILE"))
5805         Context.setFILEDecl(NewTD);
5806       else if (II->isStr("jmp_buf"))
5807         Context.setjmp_bufDecl(NewTD);
5808       else if (II->isStr("sigjmp_buf"))
5809         Context.setsigjmp_bufDecl(NewTD);
5810       else if (II->isStr("ucontext_t"))
5811         Context.setucontext_tDecl(NewTD);
5812     }
5813 
5814   return NewTD;
5815 }
5816 
5817 /// Determines whether the given declaration is an out-of-scope
5818 /// previous declaration.
5819 ///
5820 /// This routine should be invoked when name lookup has found a
5821 /// previous declaration (PrevDecl) that is not in the scope where a
5822 /// new declaration by the same name is being introduced. If the new
5823 /// declaration occurs in a local scope, previous declarations with
5824 /// linkage may still be considered previous declarations (C99
5825 /// 6.2.2p4-5, C++ [basic.link]p6).
5826 ///
5827 /// \param PrevDecl the previous declaration found by name
5828 /// lookup
5829 ///
5830 /// \param DC the context in which the new declaration is being
5831 /// declared.
5832 ///
5833 /// \returns true if PrevDecl is an out-of-scope previous declaration
5834 /// for a new delcaration with the same name.
5835 static bool
5836 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5837                                 ASTContext &Context) {
5838   if (!PrevDecl)
5839     return false;
5840 
5841   if (!PrevDecl->hasLinkage())
5842     return false;
5843 
5844   if (Context.getLangOpts().CPlusPlus) {
5845     // C++ [basic.link]p6:
5846     //   If there is a visible declaration of an entity with linkage
5847     //   having the same name and type, ignoring entities declared
5848     //   outside the innermost enclosing namespace scope, the block
5849     //   scope declaration declares that same entity and receives the
5850     //   linkage of the previous declaration.
5851     DeclContext *OuterContext = DC->getRedeclContext();
5852     if (!OuterContext->isFunctionOrMethod())
5853       // This rule only applies to block-scope declarations.
5854       return false;
5855 
5856     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5857     if (PrevOuterContext->isRecord())
5858       // We found a member function: ignore it.
5859       return false;
5860 
5861     // Find the innermost enclosing namespace for the new and
5862     // previous declarations.
5863     OuterContext = OuterContext->getEnclosingNamespaceContext();
5864     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5865 
5866     // The previous declaration is in a different namespace, so it
5867     // isn't the same function.
5868     if (!OuterContext->Equals(PrevOuterContext))
5869       return false;
5870   }
5871 
5872   return true;
5873 }
5874 
5875 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
5876   CXXScopeSpec &SS = D.getCXXScopeSpec();
5877   if (!SS.isSet()) return;
5878   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
5879 }
5880 
5881 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5882   QualType type = decl->getType();
5883   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5884   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5885     // Various kinds of declaration aren't allowed to be __autoreleasing.
5886     unsigned kind = -1U;
5887     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5888       if (var->hasAttr<BlocksAttr>())
5889         kind = 0; // __block
5890       else if (!var->hasLocalStorage())
5891         kind = 1; // global
5892     } else if (isa<ObjCIvarDecl>(decl)) {
5893       kind = 3; // ivar
5894     } else if (isa<FieldDecl>(decl)) {
5895       kind = 2; // field
5896     }
5897 
5898     if (kind != -1U) {
5899       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5900         << kind;
5901     }
5902   } else if (lifetime == Qualifiers::OCL_None) {
5903     // Try to infer lifetime.
5904     if (!type->isObjCLifetimeType())
5905       return false;
5906 
5907     lifetime = type->getObjCARCImplicitLifetime();
5908     type = Context.getLifetimeQualifiedType(type, lifetime);
5909     decl->setType(type);
5910   }
5911 
5912   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5913     // Thread-local variables cannot have lifetime.
5914     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5915         var->getTLSKind()) {
5916       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5917         << var->getType();
5918       return true;
5919     }
5920   }
5921 
5922   return false;
5923 }
5924 
5925 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5926   // Ensure that an auto decl is deduced otherwise the checks below might cache
5927   // the wrong linkage.
5928   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5929 
5930   // 'weak' only applies to declarations with external linkage.
5931   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5932     if (!ND.isExternallyVisible()) {
5933       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5934       ND.dropAttr<WeakAttr>();
5935     }
5936   }
5937   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5938     if (ND.isExternallyVisible()) {
5939       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5940       ND.dropAttr<WeakRefAttr>();
5941       ND.dropAttr<AliasAttr>();
5942     }
5943   }
5944 
5945   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5946     if (VD->hasInit()) {
5947       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5948         assert(VD->isThisDeclarationADefinition() &&
5949                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5950         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5951         VD->dropAttr<AliasAttr>();
5952       }
5953     }
5954   }
5955 
5956   // 'selectany' only applies to externally visible variable declarations.
5957   // It does not apply to functions.
5958   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5959     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5960       S.Diag(Attr->getLocation(),
5961              diag::err_attribute_selectany_non_extern_data);
5962       ND.dropAttr<SelectAnyAttr>();
5963     }
5964   }
5965 
5966   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5967     // dll attributes require external linkage. Static locals may have external
5968     // linkage but still cannot be explicitly imported or exported.
5969     auto *VD = dyn_cast<VarDecl>(&ND);
5970     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5971       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5972         << &ND << Attr;
5973       ND.setInvalidDecl();
5974     }
5975   }
5976 
5977   // Virtual functions cannot be marked as 'notail'.
5978   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5979     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5980       if (MD->isVirtual()) {
5981         S.Diag(ND.getLocation(),
5982                diag::err_invalid_attribute_on_virtual_function)
5983             << Attr;
5984         ND.dropAttr<NotTailCalledAttr>();
5985       }
5986 
5987   // Check the attributes on the function type, if any.
5988   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
5989     // Don't declare this variable in the second operand of the for-statement;
5990     // GCC miscompiles that by ending its lifetime before evaluating the
5991     // third operand. See gcc.gnu.org/PR86769.
5992     AttributedTypeLoc ATL;
5993     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
5994          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
5995          TL = ATL.getModifiedLoc()) {
5996       // The [[lifetimebound]] attribute can be applied to the implicit object
5997       // parameter of a non-static member function (other than a ctor or dtor)
5998       // by applying it to the function type.
5999       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6000         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6001         if (!MD || MD->isStatic()) {
6002           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6003               << !MD << A->getRange();
6004         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6005           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6006               << isa<CXXDestructorDecl>(MD) << A->getRange();
6007         }
6008       }
6009     }
6010   }
6011 }
6012 
6013 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6014                                            NamedDecl *NewDecl,
6015                                            bool IsSpecialization,
6016                                            bool IsDefinition) {
6017   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6018     return;
6019 
6020   bool IsTemplate = false;
6021   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6022     OldDecl = OldTD->getTemplatedDecl();
6023     IsTemplate = true;
6024     if (!IsSpecialization)
6025       IsDefinition = false;
6026   }
6027   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6028     NewDecl = NewTD->getTemplatedDecl();
6029     IsTemplate = true;
6030   }
6031 
6032   if (!OldDecl || !NewDecl)
6033     return;
6034 
6035   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6036   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6037   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6038   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6039 
6040   // dllimport and dllexport are inheritable attributes so we have to exclude
6041   // inherited attribute instances.
6042   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6043                     (NewExportAttr && !NewExportAttr->isInherited());
6044 
6045   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6046   // the only exception being explicit specializations.
6047   // Implicitly generated declarations are also excluded for now because there
6048   // is no other way to switch these to use dllimport or dllexport.
6049   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6050 
6051   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6052     // Allow with a warning for free functions and global variables.
6053     bool JustWarn = false;
6054     if (!OldDecl->isCXXClassMember()) {
6055       auto *VD = dyn_cast<VarDecl>(OldDecl);
6056       if (VD && !VD->getDescribedVarTemplate())
6057         JustWarn = true;
6058       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6059       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6060         JustWarn = true;
6061     }
6062 
6063     // We cannot change a declaration that's been used because IR has already
6064     // been emitted. Dllimported functions will still work though (modulo
6065     // address equality) as they can use the thunk.
6066     if (OldDecl->isUsed())
6067       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6068         JustWarn = false;
6069 
6070     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6071                                : diag::err_attribute_dll_redeclaration;
6072     S.Diag(NewDecl->getLocation(), DiagID)
6073         << NewDecl
6074         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6075     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6076     if (!JustWarn) {
6077       NewDecl->setInvalidDecl();
6078       return;
6079     }
6080   }
6081 
6082   // A redeclaration is not allowed to drop a dllimport attribute, the only
6083   // exceptions being inline function definitions (except for function
6084   // templates), local extern declarations, qualified friend declarations or
6085   // special MSVC extension: in the last case, the declaration is treated as if
6086   // it were marked dllexport.
6087   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6088   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6089   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6090     // Ignore static data because out-of-line definitions are diagnosed
6091     // separately.
6092     IsStaticDataMember = VD->isStaticDataMember();
6093     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6094                    VarDecl::DeclarationOnly;
6095   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6096     IsInline = FD->isInlined();
6097     IsQualifiedFriend = FD->getQualifier() &&
6098                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6099   }
6100 
6101   if (OldImportAttr && !HasNewAttr &&
6102       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6103       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6104     if (IsMicrosoft && IsDefinition) {
6105       S.Diag(NewDecl->getLocation(),
6106              diag::warn_redeclaration_without_import_attribute)
6107           << NewDecl;
6108       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6109       NewDecl->dropAttr<DLLImportAttr>();
6110       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6111           NewImportAttr->getRange(), S.Context,
6112           NewImportAttr->getSpellingListIndex()));
6113     } else {
6114       S.Diag(NewDecl->getLocation(),
6115              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6116           << NewDecl << OldImportAttr;
6117       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6118       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6119       OldDecl->dropAttr<DLLImportAttr>();
6120       NewDecl->dropAttr<DLLImportAttr>();
6121     }
6122   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6123     // In MinGW, seeing a function declared inline drops the dllimport
6124     // attribute.
6125     OldDecl->dropAttr<DLLImportAttr>();
6126     NewDecl->dropAttr<DLLImportAttr>();
6127     S.Diag(NewDecl->getLocation(),
6128            diag::warn_dllimport_dropped_from_inline_function)
6129         << NewDecl << OldImportAttr;
6130   }
6131 
6132   // A specialization of a class template member function is processed here
6133   // since it's a redeclaration. If the parent class is dllexport, the
6134   // specialization inherits that attribute. This doesn't happen automatically
6135   // since the parent class isn't instantiated until later.
6136   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6137     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6138         !NewImportAttr && !NewExportAttr) {
6139       if (const DLLExportAttr *ParentExportAttr =
6140               MD->getParent()->getAttr<DLLExportAttr>()) {
6141         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6142         NewAttr->setInherited(true);
6143         NewDecl->addAttr(NewAttr);
6144       }
6145     }
6146   }
6147 }
6148 
6149 /// Given that we are within the definition of the given function,
6150 /// will that definition behave like C99's 'inline', where the
6151 /// definition is discarded except for optimization purposes?
6152 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6153   // Try to avoid calling GetGVALinkageForFunction.
6154 
6155   // All cases of this require the 'inline' keyword.
6156   if (!FD->isInlined()) return false;
6157 
6158   // This is only possible in C++ with the gnu_inline attribute.
6159   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6160     return false;
6161 
6162   // Okay, go ahead and call the relatively-more-expensive function.
6163   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6164 }
6165 
6166 /// Determine whether a variable is extern "C" prior to attaching
6167 /// an initializer. We can't just call isExternC() here, because that
6168 /// will also compute and cache whether the declaration is externally
6169 /// visible, which might change when we attach the initializer.
6170 ///
6171 /// This can only be used if the declaration is known to not be a
6172 /// redeclaration of an internal linkage declaration.
6173 ///
6174 /// For instance:
6175 ///
6176 ///   auto x = []{};
6177 ///
6178 /// Attaching the initializer here makes this declaration not externally
6179 /// visible, because its type has internal linkage.
6180 ///
6181 /// FIXME: This is a hack.
6182 template<typename T>
6183 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6184   if (S.getLangOpts().CPlusPlus) {
6185     // In C++, the overloadable attribute negates the effects of extern "C".
6186     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6187       return false;
6188 
6189     // So do CUDA's host/device attributes.
6190     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6191                                  D->template hasAttr<CUDAHostAttr>()))
6192       return false;
6193   }
6194   return D->isExternC();
6195 }
6196 
6197 static bool shouldConsiderLinkage(const VarDecl *VD) {
6198   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6199   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6200       isa<OMPDeclareMapperDecl>(DC))
6201     return VD->hasExternalStorage();
6202   if (DC->isFileContext())
6203     return true;
6204   if (DC->isRecord())
6205     return false;
6206   llvm_unreachable("Unexpected context");
6207 }
6208 
6209 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6210   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6211   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6212       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6213     return true;
6214   if (DC->isRecord())
6215     return false;
6216   llvm_unreachable("Unexpected context");
6217 }
6218 
6219 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6220                           ParsedAttr::Kind Kind) {
6221   // Check decl attributes on the DeclSpec.
6222   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6223     return true;
6224 
6225   // Walk the declarator structure, checking decl attributes that were in a type
6226   // position to the decl itself.
6227   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6228     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6229       return true;
6230   }
6231 
6232   // Finally, check attributes on the decl itself.
6233   return PD.getAttributes().hasAttribute(Kind);
6234 }
6235 
6236 /// Adjust the \c DeclContext for a function or variable that might be a
6237 /// function-local external declaration.
6238 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6239   if (!DC->isFunctionOrMethod())
6240     return false;
6241 
6242   // If this is a local extern function or variable declared within a function
6243   // template, don't add it into the enclosing namespace scope until it is
6244   // instantiated; it might have a dependent type right now.
6245   if (DC->isDependentContext())
6246     return true;
6247 
6248   // C++11 [basic.link]p7:
6249   //   When a block scope declaration of an entity with linkage is not found to
6250   //   refer to some other declaration, then that entity is a member of the
6251   //   innermost enclosing namespace.
6252   //
6253   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6254   // semantically-enclosing namespace, not a lexically-enclosing one.
6255   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6256     DC = DC->getParent();
6257   return true;
6258 }
6259 
6260 /// Returns true if given declaration has external C language linkage.
6261 static bool isDeclExternC(const Decl *D) {
6262   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6263     return FD->isExternC();
6264   if (const auto *VD = dyn_cast<VarDecl>(D))
6265     return VD->isExternC();
6266 
6267   llvm_unreachable("Unknown type of decl!");
6268 }
6269 
6270 NamedDecl *Sema::ActOnVariableDeclarator(
6271     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6272     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6273     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6274   QualType R = TInfo->getType();
6275   DeclarationName Name = GetNameForDeclarator(D).getName();
6276 
6277   IdentifierInfo *II = Name.getAsIdentifierInfo();
6278 
6279   if (D.isDecompositionDeclarator()) {
6280     // Take the name of the first declarator as our name for diagnostic
6281     // purposes.
6282     auto &Decomp = D.getDecompositionDeclarator();
6283     if (!Decomp.bindings().empty()) {
6284       II = Decomp.bindings()[0].Name;
6285       Name = II;
6286     }
6287   } else if (!II) {
6288     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6289     return nullptr;
6290   }
6291 
6292   if (getLangOpts().OpenCL) {
6293     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6294     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6295     // argument.
6296     if (R->isImageType() || R->isPipeType()) {
6297       Diag(D.getIdentifierLoc(),
6298            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6299           << R;
6300       D.setInvalidType();
6301       return nullptr;
6302     }
6303 
6304     // OpenCL v1.2 s6.9.r:
6305     // The event type cannot be used to declare a program scope variable.
6306     // OpenCL v2.0 s6.9.q:
6307     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6308     if (NULL == S->getParent()) {
6309       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6310         Diag(D.getIdentifierLoc(),
6311              diag::err_invalid_type_for_program_scope_var) << R;
6312         D.setInvalidType();
6313         return nullptr;
6314       }
6315     }
6316 
6317     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6318     QualType NR = R;
6319     while (NR->isPointerType()) {
6320       if (NR->isFunctionPointerType()) {
6321         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6322         D.setInvalidType();
6323         break;
6324       }
6325       NR = NR->getPointeeType();
6326     }
6327 
6328     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6329       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6330       // half array type (unless the cl_khr_fp16 extension is enabled).
6331       if (Context.getBaseElementType(R)->isHalfType()) {
6332         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6333         D.setInvalidType();
6334       }
6335     }
6336 
6337     if (R->isSamplerT()) {
6338       // OpenCL v1.2 s6.9.b p4:
6339       // The sampler type cannot be used with the __local and __global address
6340       // space qualifiers.
6341       if (R.getAddressSpace() == LangAS::opencl_local ||
6342           R.getAddressSpace() == LangAS::opencl_global) {
6343         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6344       }
6345 
6346       // OpenCL v1.2 s6.12.14.1:
6347       // A global sampler must be declared with either the constant address
6348       // space qualifier or with the const qualifier.
6349       if (DC->isTranslationUnit() &&
6350           !(R.getAddressSpace() == LangAS::opencl_constant ||
6351           R.isConstQualified())) {
6352         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6353         D.setInvalidType();
6354       }
6355     }
6356 
6357     // OpenCL v1.2 s6.9.r:
6358     // The event type cannot be used with the __local, __constant and __global
6359     // address space qualifiers.
6360     if (R->isEventT()) {
6361       if (R.getAddressSpace() != LangAS::opencl_private) {
6362         Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6363         D.setInvalidType();
6364       }
6365     }
6366 
6367     // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not
6368     // supported.  OpenCL C does not support thread_local either, and
6369     // also reject all other thread storage class specifiers.
6370     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6371     if (TSC != TSCS_unspecified) {
6372       bool IsCXX = getLangOpts().OpenCLCPlusPlus;
6373       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6374            diag::err_opencl_unknown_type_specifier)
6375           << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
6376           << DeclSpec::getSpecifierName(TSC) << 1;
6377       D.setInvalidType();
6378       return nullptr;
6379     }
6380   }
6381 
6382   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6383   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6384 
6385   // dllimport globals without explicit storage class are treated as extern. We
6386   // have to change the storage class this early to get the right DeclContext.
6387   if (SC == SC_None && !DC->isRecord() &&
6388       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6389       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6390     SC = SC_Extern;
6391 
6392   DeclContext *OriginalDC = DC;
6393   bool IsLocalExternDecl = SC == SC_Extern &&
6394                            adjustContextForLocalExternDecl(DC);
6395 
6396   if (SCSpec == DeclSpec::SCS_mutable) {
6397     // mutable can only appear on non-static class members, so it's always
6398     // an error here
6399     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6400     D.setInvalidType();
6401     SC = SC_None;
6402   }
6403 
6404   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6405       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6406                               D.getDeclSpec().getStorageClassSpecLoc())) {
6407     // In C++11, the 'register' storage class specifier is deprecated.
6408     // Suppress the warning in system macros, it's used in macros in some
6409     // popular C system headers, such as in glibc's htonl() macro.
6410     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6411          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6412                                    : diag::warn_deprecated_register)
6413       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6414   }
6415 
6416   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6417 
6418   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6419     // C99 6.9p2: The storage-class specifiers auto and register shall not
6420     // appear in the declaration specifiers in an external declaration.
6421     // Global Register+Asm is a GNU extension we support.
6422     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6423       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6424       D.setInvalidType();
6425     }
6426   }
6427 
6428   bool IsMemberSpecialization = false;
6429   bool IsVariableTemplateSpecialization = false;
6430   bool IsPartialSpecialization = false;
6431   bool IsVariableTemplate = false;
6432   VarDecl *NewVD = nullptr;
6433   VarTemplateDecl *NewTemplate = nullptr;
6434   TemplateParameterList *TemplateParams = nullptr;
6435   if (!getLangOpts().CPlusPlus) {
6436     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6437                             II, R, TInfo, SC);
6438 
6439     if (R->getContainedDeducedType())
6440       ParsingInitForAutoVars.insert(NewVD);
6441 
6442     if (D.isInvalidType())
6443       NewVD->setInvalidDecl();
6444   } else {
6445     bool Invalid = false;
6446 
6447     if (DC->isRecord() && !CurContext->isRecord()) {
6448       // This is an out-of-line definition of a static data member.
6449       switch (SC) {
6450       case SC_None:
6451         break;
6452       case SC_Static:
6453         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6454              diag::err_static_out_of_line)
6455           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6456         break;
6457       case SC_Auto:
6458       case SC_Register:
6459       case SC_Extern:
6460         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6461         // to names of variables declared in a block or to function parameters.
6462         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6463         // of class members
6464 
6465         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6466              diag::err_storage_class_for_static_member)
6467           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6468         break;
6469       case SC_PrivateExtern:
6470         llvm_unreachable("C storage class in c++!");
6471       }
6472     }
6473 
6474     if (SC == SC_Static && CurContext->isRecord()) {
6475       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6476         if (RD->isLocalClass())
6477           Diag(D.getIdentifierLoc(),
6478                diag::err_static_data_member_not_allowed_in_local_class)
6479             << Name << RD->getDeclName();
6480 
6481         // C++98 [class.union]p1: If a union contains a static data member,
6482         // the program is ill-formed. C++11 drops this restriction.
6483         if (RD->isUnion())
6484           Diag(D.getIdentifierLoc(),
6485                getLangOpts().CPlusPlus11
6486                  ? diag::warn_cxx98_compat_static_data_member_in_union
6487                  : diag::ext_static_data_member_in_union) << Name;
6488         // We conservatively disallow static data members in anonymous structs.
6489         else if (!RD->getDeclName())
6490           Diag(D.getIdentifierLoc(),
6491                diag::err_static_data_member_not_allowed_in_anon_struct)
6492             << Name << RD->isUnion();
6493       }
6494     }
6495 
6496     // Match up the template parameter lists with the scope specifier, then
6497     // determine whether we have a template or a template specialization.
6498     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6499         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6500         D.getCXXScopeSpec(),
6501         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6502             ? D.getName().TemplateId
6503             : nullptr,
6504         TemplateParamLists,
6505         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6506 
6507     if (TemplateParams) {
6508       if (!TemplateParams->size() &&
6509           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6510         // There is an extraneous 'template<>' for this variable. Complain
6511         // about it, but allow the declaration of the variable.
6512         Diag(TemplateParams->getTemplateLoc(),
6513              diag::err_template_variable_noparams)
6514           << II
6515           << SourceRange(TemplateParams->getTemplateLoc(),
6516                          TemplateParams->getRAngleLoc());
6517         TemplateParams = nullptr;
6518       } else {
6519         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6520           // This is an explicit specialization or a partial specialization.
6521           // FIXME: Check that we can declare a specialization here.
6522           IsVariableTemplateSpecialization = true;
6523           IsPartialSpecialization = TemplateParams->size() > 0;
6524         } else { // if (TemplateParams->size() > 0)
6525           // This is a template declaration.
6526           IsVariableTemplate = true;
6527 
6528           // Check that we can declare a template here.
6529           if (CheckTemplateDeclScope(S, TemplateParams))
6530             return nullptr;
6531 
6532           // Only C++1y supports variable templates (N3651).
6533           Diag(D.getIdentifierLoc(),
6534                getLangOpts().CPlusPlus14
6535                    ? diag::warn_cxx11_compat_variable_template
6536                    : diag::ext_variable_template);
6537         }
6538       }
6539     } else {
6540       assert((Invalid ||
6541               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6542              "should have a 'template<>' for this decl");
6543     }
6544 
6545     if (IsVariableTemplateSpecialization) {
6546       SourceLocation TemplateKWLoc =
6547           TemplateParamLists.size() > 0
6548               ? TemplateParamLists[0]->getTemplateLoc()
6549               : SourceLocation();
6550       DeclResult Res = ActOnVarTemplateSpecialization(
6551           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6552           IsPartialSpecialization);
6553       if (Res.isInvalid())
6554         return nullptr;
6555       NewVD = cast<VarDecl>(Res.get());
6556       AddToScope = false;
6557     } else if (D.isDecompositionDeclarator()) {
6558       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6559                                         D.getIdentifierLoc(), R, TInfo, SC,
6560                                         Bindings);
6561     } else
6562       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6563                               D.getIdentifierLoc(), II, R, TInfo, SC);
6564 
6565     // If this is supposed to be a variable template, create it as such.
6566     if (IsVariableTemplate) {
6567       NewTemplate =
6568           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6569                                   TemplateParams, NewVD);
6570       NewVD->setDescribedVarTemplate(NewTemplate);
6571     }
6572 
6573     // If this decl has an auto type in need of deduction, make a note of the
6574     // Decl so we can diagnose uses of it in its own initializer.
6575     if (R->getContainedDeducedType())
6576       ParsingInitForAutoVars.insert(NewVD);
6577 
6578     if (D.isInvalidType() || Invalid) {
6579       NewVD->setInvalidDecl();
6580       if (NewTemplate)
6581         NewTemplate->setInvalidDecl();
6582     }
6583 
6584     SetNestedNameSpecifier(*this, NewVD, D);
6585 
6586     // If we have any template parameter lists that don't directly belong to
6587     // the variable (matching the scope specifier), store them.
6588     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6589     if (TemplateParamLists.size() > VDTemplateParamLists)
6590       NewVD->setTemplateParameterListsInfo(
6591           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6592 
6593     if (D.getDeclSpec().isConstexprSpecified()) {
6594       NewVD->setConstexpr(true);
6595       // C++1z [dcl.spec.constexpr]p1:
6596       //   A static data member declared with the constexpr specifier is
6597       //   implicitly an inline variable.
6598       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
6599         NewVD->setImplicitlyInline();
6600     }
6601   }
6602 
6603   if (D.getDeclSpec().isInlineSpecified()) {
6604     if (!getLangOpts().CPlusPlus) {
6605       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6606           << 0;
6607     } else if (CurContext->isFunctionOrMethod()) {
6608       // 'inline' is not allowed on block scope variable declaration.
6609       Diag(D.getDeclSpec().getInlineSpecLoc(),
6610            diag::err_inline_declaration_block_scope) << Name
6611         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6612     } else {
6613       Diag(D.getDeclSpec().getInlineSpecLoc(),
6614            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6615                                      : diag::ext_inline_variable);
6616       NewVD->setInlineSpecified();
6617     }
6618   }
6619 
6620   // Set the lexical context. If the declarator has a C++ scope specifier, the
6621   // lexical context will be different from the semantic context.
6622   NewVD->setLexicalDeclContext(CurContext);
6623   if (NewTemplate)
6624     NewTemplate->setLexicalDeclContext(CurContext);
6625 
6626   if (IsLocalExternDecl) {
6627     if (D.isDecompositionDeclarator())
6628       for (auto *B : Bindings)
6629         B->setLocalExternDecl();
6630     else
6631       NewVD->setLocalExternDecl();
6632   }
6633 
6634   bool EmitTLSUnsupportedError = false;
6635   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6636     // C++11 [dcl.stc]p4:
6637     //   When thread_local is applied to a variable of block scope the
6638     //   storage-class-specifier static is implied if it does not appear
6639     //   explicitly.
6640     // Core issue: 'static' is not implied if the variable is declared
6641     //   'extern'.
6642     if (NewVD->hasLocalStorage() &&
6643         (SCSpec != DeclSpec::SCS_unspecified ||
6644          TSCS != DeclSpec::TSCS_thread_local ||
6645          !DC->isFunctionOrMethod()))
6646       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6647            diag::err_thread_non_global)
6648         << DeclSpec::getSpecifierName(TSCS);
6649     else if (!Context.getTargetInfo().isTLSSupported()) {
6650       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6651         // Postpone error emission until we've collected attributes required to
6652         // figure out whether it's a host or device variable and whether the
6653         // error should be ignored.
6654         EmitTLSUnsupportedError = true;
6655         // We still need to mark the variable as TLS so it shows up in AST with
6656         // proper storage class for other tools to use even if we're not going
6657         // to emit any code for it.
6658         NewVD->setTSCSpec(TSCS);
6659       } else
6660         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6661              diag::err_thread_unsupported);
6662     } else
6663       NewVD->setTSCSpec(TSCS);
6664   }
6665 
6666   // C99 6.7.4p3
6667   //   An inline definition of a function with external linkage shall
6668   //   not contain a definition of a modifiable object with static or
6669   //   thread storage duration...
6670   // We only apply this when the function is required to be defined
6671   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6672   // that a local variable with thread storage duration still has to
6673   // be marked 'static'.  Also note that it's possible to get these
6674   // semantics in C++ using __attribute__((gnu_inline)).
6675   if (SC == SC_Static && S->getFnParent() != nullptr &&
6676       !NewVD->getType().isConstQualified()) {
6677     FunctionDecl *CurFD = getCurFunctionDecl();
6678     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6679       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6680            diag::warn_static_local_in_extern_inline);
6681       MaybeSuggestAddingStaticToDecl(CurFD);
6682     }
6683   }
6684 
6685   if (D.getDeclSpec().isModulePrivateSpecified()) {
6686     if (IsVariableTemplateSpecialization)
6687       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6688           << (IsPartialSpecialization ? 1 : 0)
6689           << FixItHint::CreateRemoval(
6690                  D.getDeclSpec().getModulePrivateSpecLoc());
6691     else if (IsMemberSpecialization)
6692       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6693         << 2
6694         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6695     else if (NewVD->hasLocalStorage())
6696       Diag(NewVD->getLocation(), diag::err_module_private_local)
6697         << 0 << NewVD->getDeclName()
6698         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6699         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6700     else {
6701       NewVD->setModulePrivate();
6702       if (NewTemplate)
6703         NewTemplate->setModulePrivate();
6704       for (auto *B : Bindings)
6705         B->setModulePrivate();
6706     }
6707   }
6708 
6709   // Handle attributes prior to checking for duplicates in MergeVarDecl
6710   ProcessDeclAttributes(S, NewVD, D);
6711 
6712   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6713     if (EmitTLSUnsupportedError &&
6714         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6715          (getLangOpts().OpenMPIsDevice &&
6716           NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6717       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6718            diag::err_thread_unsupported);
6719     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6720     // storage [duration]."
6721     if (SC == SC_None && S->getFnParent() != nullptr &&
6722         (NewVD->hasAttr<CUDASharedAttr>() ||
6723          NewVD->hasAttr<CUDAConstantAttr>())) {
6724       NewVD->setStorageClass(SC_Static);
6725     }
6726   }
6727 
6728   // Ensure that dllimport globals without explicit storage class are treated as
6729   // extern. The storage class is set above using parsed attributes. Now we can
6730   // check the VarDecl itself.
6731   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6732          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6733          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6734 
6735   // In auto-retain/release, infer strong retension for variables of
6736   // retainable type.
6737   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6738     NewVD->setInvalidDecl();
6739 
6740   // Handle GNU asm-label extension (encoded as an attribute).
6741   if (Expr *E = (Expr*)D.getAsmLabel()) {
6742     // The parser guarantees this is a string.
6743     StringLiteral *SE = cast<StringLiteral>(E);
6744     StringRef Label = SE->getString();
6745     if (S->getFnParent() != nullptr) {
6746       switch (SC) {
6747       case SC_None:
6748       case SC_Auto:
6749         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6750         break;
6751       case SC_Register:
6752         // Local Named register
6753         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6754             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6755           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6756         break;
6757       case SC_Static:
6758       case SC_Extern:
6759       case SC_PrivateExtern:
6760         break;
6761       }
6762     } else if (SC == SC_Register) {
6763       // Global Named register
6764       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6765         const auto &TI = Context.getTargetInfo();
6766         bool HasSizeMismatch;
6767 
6768         if (!TI.isValidGCCRegisterName(Label))
6769           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6770         else if (!TI.validateGlobalRegisterVariable(Label,
6771                                                     Context.getTypeSize(R),
6772                                                     HasSizeMismatch))
6773           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6774         else if (HasSizeMismatch)
6775           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6776       }
6777 
6778       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6779         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
6780         NewVD->setInvalidDecl(true);
6781       }
6782     }
6783 
6784     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6785                                                 Context, Label, 0));
6786   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6787     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6788       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6789     if (I != ExtnameUndeclaredIdentifiers.end()) {
6790       if (isDeclExternC(NewVD)) {
6791         NewVD->addAttr(I->second);
6792         ExtnameUndeclaredIdentifiers.erase(I);
6793       } else
6794         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6795             << /*Variable*/1 << NewVD;
6796     }
6797   }
6798 
6799   // Find the shadowed declaration before filtering for scope.
6800   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6801                                 ? getShadowedDeclaration(NewVD, Previous)
6802                                 : nullptr;
6803 
6804   // Don't consider existing declarations that are in a different
6805   // scope and are out-of-semantic-context declarations (if the new
6806   // declaration has linkage).
6807   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6808                        D.getCXXScopeSpec().isNotEmpty() ||
6809                        IsMemberSpecialization ||
6810                        IsVariableTemplateSpecialization);
6811 
6812   // Check whether the previous declaration is in the same block scope. This
6813   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6814   if (getLangOpts().CPlusPlus &&
6815       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6816     NewVD->setPreviousDeclInSameBlockScope(
6817         Previous.isSingleResult() && !Previous.isShadowed() &&
6818         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6819 
6820   if (!getLangOpts().CPlusPlus) {
6821     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6822   } else {
6823     // If this is an explicit specialization of a static data member, check it.
6824     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6825         CheckMemberSpecialization(NewVD, Previous))
6826       NewVD->setInvalidDecl();
6827 
6828     // Merge the decl with the existing one if appropriate.
6829     if (!Previous.empty()) {
6830       if (Previous.isSingleResult() &&
6831           isa<FieldDecl>(Previous.getFoundDecl()) &&
6832           D.getCXXScopeSpec().isSet()) {
6833         // The user tried to define a non-static data member
6834         // out-of-line (C++ [dcl.meaning]p1).
6835         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6836           << D.getCXXScopeSpec().getRange();
6837         Previous.clear();
6838         NewVD->setInvalidDecl();
6839       }
6840     } else if (D.getCXXScopeSpec().isSet()) {
6841       // No previous declaration in the qualifying scope.
6842       Diag(D.getIdentifierLoc(), diag::err_no_member)
6843         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6844         << D.getCXXScopeSpec().getRange();
6845       NewVD->setInvalidDecl();
6846     }
6847 
6848     if (!IsVariableTemplateSpecialization)
6849       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6850 
6851     if (NewTemplate) {
6852       VarTemplateDecl *PrevVarTemplate =
6853           NewVD->getPreviousDecl()
6854               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6855               : nullptr;
6856 
6857       // Check the template parameter list of this declaration, possibly
6858       // merging in the template parameter list from the previous variable
6859       // template declaration.
6860       if (CheckTemplateParameterList(
6861               TemplateParams,
6862               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6863                               : nullptr,
6864               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6865                DC->isDependentContext())
6866                   ? TPC_ClassTemplateMember
6867                   : TPC_VarTemplate))
6868         NewVD->setInvalidDecl();
6869 
6870       // If we are providing an explicit specialization of a static variable
6871       // template, make a note of that.
6872       if (PrevVarTemplate &&
6873           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6874         PrevVarTemplate->setMemberSpecialization();
6875     }
6876   }
6877 
6878   // Diagnose shadowed variables iff this isn't a redeclaration.
6879   if (ShadowedDecl && !D.isRedeclaration())
6880     CheckShadow(NewVD, ShadowedDecl, Previous);
6881 
6882   ProcessPragmaWeak(S, NewVD);
6883 
6884   // If this is the first declaration of an extern C variable, update
6885   // the map of such variables.
6886   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6887       isIncompleteDeclExternC(*this, NewVD))
6888     RegisterLocallyScopedExternCDecl(NewVD, S);
6889 
6890   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6891     Decl *ManglingContextDecl;
6892     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6893             NewVD->getDeclContext(), ManglingContextDecl)) {
6894       Context.setManglingNumber(
6895           NewVD, MCtx->getManglingNumber(
6896                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6897       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6898     }
6899   }
6900 
6901   // Special handling of variable named 'main'.
6902   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6903       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6904       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6905 
6906     // C++ [basic.start.main]p3
6907     // A program that declares a variable main at global scope is ill-formed.
6908     if (getLangOpts().CPlusPlus)
6909       Diag(D.getBeginLoc(), diag::err_main_global_variable);
6910 
6911     // In C, and external-linkage variable named main results in undefined
6912     // behavior.
6913     else if (NewVD->hasExternalFormalLinkage())
6914       Diag(D.getBeginLoc(), diag::warn_main_redefined);
6915   }
6916 
6917   if (D.isRedeclaration() && !Previous.empty()) {
6918     NamedDecl *Prev = Previous.getRepresentativeDecl();
6919     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
6920                                    D.isFunctionDefinition());
6921   }
6922 
6923   if (NewTemplate) {
6924     if (NewVD->isInvalidDecl())
6925       NewTemplate->setInvalidDecl();
6926     ActOnDocumentableDecl(NewTemplate);
6927     return NewTemplate;
6928   }
6929 
6930   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6931     CompleteMemberSpecialization(NewVD, Previous);
6932 
6933   return NewVD;
6934 }
6935 
6936 /// Enum describing the %select options in diag::warn_decl_shadow.
6937 enum ShadowedDeclKind {
6938   SDK_Local,
6939   SDK_Global,
6940   SDK_StaticMember,
6941   SDK_Field,
6942   SDK_Typedef,
6943   SDK_Using
6944 };
6945 
6946 /// Determine what kind of declaration we're shadowing.
6947 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6948                                                 const DeclContext *OldDC) {
6949   if (isa<TypeAliasDecl>(ShadowedDecl))
6950     return SDK_Using;
6951   else if (isa<TypedefDecl>(ShadowedDecl))
6952     return SDK_Typedef;
6953   else if (isa<RecordDecl>(OldDC))
6954     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6955 
6956   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6957 }
6958 
6959 /// Return the location of the capture if the given lambda captures the given
6960 /// variable \p VD, or an invalid source location otherwise.
6961 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6962                                          const VarDecl *VD) {
6963   for (const Capture &Capture : LSI->Captures) {
6964     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6965       return Capture.getLocation();
6966   }
6967   return SourceLocation();
6968 }
6969 
6970 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6971                                      const LookupResult &R) {
6972   // Only diagnose if we're shadowing an unambiguous field or variable.
6973   if (R.getResultKind() != LookupResult::Found)
6974     return false;
6975 
6976   // Return false if warning is ignored.
6977   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6978 }
6979 
6980 /// Return the declaration shadowed by the given variable \p D, or null
6981 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6982 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6983                                         const LookupResult &R) {
6984   if (!shouldWarnIfShadowedDecl(Diags, R))
6985     return nullptr;
6986 
6987   // Don't diagnose declarations at file scope.
6988   if (D->hasGlobalStorage())
6989     return nullptr;
6990 
6991   NamedDecl *ShadowedDecl = R.getFoundDecl();
6992   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6993              ? ShadowedDecl
6994              : nullptr;
6995 }
6996 
6997 /// Return the declaration shadowed by the given typedef \p D, or null
6998 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6999 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7000                                         const LookupResult &R) {
7001   // Don't warn if typedef declaration is part of a class
7002   if (D->getDeclContext()->isRecord())
7003     return nullptr;
7004 
7005   if (!shouldWarnIfShadowedDecl(Diags, R))
7006     return nullptr;
7007 
7008   NamedDecl *ShadowedDecl = R.getFoundDecl();
7009   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7010 }
7011 
7012 /// Diagnose variable or built-in function shadowing.  Implements
7013 /// -Wshadow.
7014 ///
7015 /// This method is called whenever a VarDecl is added to a "useful"
7016 /// scope.
7017 ///
7018 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7019 /// \param R the lookup of the name
7020 ///
7021 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7022                        const LookupResult &R) {
7023   DeclContext *NewDC = D->getDeclContext();
7024 
7025   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7026     // Fields are not shadowed by variables in C++ static methods.
7027     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7028       if (MD->isStatic())
7029         return;
7030 
7031     // Fields shadowed by constructor parameters are a special case. Usually
7032     // the constructor initializes the field with the parameter.
7033     if (isa<CXXConstructorDecl>(NewDC))
7034       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7035         // Remember that this was shadowed so we can either warn about its
7036         // modification or its existence depending on warning settings.
7037         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7038         return;
7039       }
7040   }
7041 
7042   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7043     if (shadowedVar->isExternC()) {
7044       // For shadowing external vars, make sure that we point to the global
7045       // declaration, not a locally scoped extern declaration.
7046       for (auto I : shadowedVar->redecls())
7047         if (I->isFileVarDecl()) {
7048           ShadowedDecl = I;
7049           break;
7050         }
7051     }
7052 
7053   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7054 
7055   unsigned WarningDiag = diag::warn_decl_shadow;
7056   SourceLocation CaptureLoc;
7057   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7058       isa<CXXMethodDecl>(NewDC)) {
7059     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7060       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7061         if (RD->getLambdaCaptureDefault() == LCD_None) {
7062           // Try to avoid warnings for lambdas with an explicit capture list.
7063           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7064           // Warn only when the lambda captures the shadowed decl explicitly.
7065           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7066           if (CaptureLoc.isInvalid())
7067             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7068         } else {
7069           // Remember that this was shadowed so we can avoid the warning if the
7070           // shadowed decl isn't captured and the warning settings allow it.
7071           cast<LambdaScopeInfo>(getCurFunction())
7072               ->ShadowingDecls.push_back(
7073                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7074           return;
7075         }
7076       }
7077 
7078       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7079         // A variable can't shadow a local variable in an enclosing scope, if
7080         // they are separated by a non-capturing declaration context.
7081         for (DeclContext *ParentDC = NewDC;
7082              ParentDC && !ParentDC->Equals(OldDC);
7083              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7084           // Only block literals, captured statements, and lambda expressions
7085           // can capture; other scopes don't.
7086           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7087               !isLambdaCallOperator(ParentDC)) {
7088             return;
7089           }
7090         }
7091       }
7092     }
7093   }
7094 
7095   // Only warn about certain kinds of shadowing for class members.
7096   if (NewDC && NewDC->isRecord()) {
7097     // In particular, don't warn about shadowing non-class members.
7098     if (!OldDC->isRecord())
7099       return;
7100 
7101     // TODO: should we warn about static data members shadowing
7102     // static data members from base classes?
7103 
7104     // TODO: don't diagnose for inaccessible shadowed members.
7105     // This is hard to do perfectly because we might friend the
7106     // shadowing context, but that's just a false negative.
7107   }
7108 
7109 
7110   DeclarationName Name = R.getLookupName();
7111 
7112   // Emit warning and note.
7113   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7114     return;
7115   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7116   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7117   if (!CaptureLoc.isInvalid())
7118     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7119         << Name << /*explicitly*/ 1;
7120   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7121 }
7122 
7123 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7124 /// when these variables are captured by the lambda.
7125 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7126   for (const auto &Shadow : LSI->ShadowingDecls) {
7127     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7128     // Try to avoid the warning when the shadowed decl isn't captured.
7129     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7130     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7131     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7132                                        ? diag::warn_decl_shadow_uncaptured_local
7133                                        : diag::warn_decl_shadow)
7134         << Shadow.VD->getDeclName()
7135         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7136     if (!CaptureLoc.isInvalid())
7137       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7138           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7139     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7140   }
7141 }
7142 
7143 /// Check -Wshadow without the advantage of a previous lookup.
7144 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7145   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7146     return;
7147 
7148   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7149                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7150   LookupName(R, S);
7151   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7152     CheckShadow(D, ShadowedDecl, R);
7153 }
7154 
7155 /// Check if 'E', which is an expression that is about to be modified, refers
7156 /// to a constructor parameter that shadows a field.
7157 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7158   // Quickly ignore expressions that can't be shadowing ctor parameters.
7159   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7160     return;
7161   E = E->IgnoreParenImpCasts();
7162   auto *DRE = dyn_cast<DeclRefExpr>(E);
7163   if (!DRE)
7164     return;
7165   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7166   auto I = ShadowingDecls.find(D);
7167   if (I == ShadowingDecls.end())
7168     return;
7169   const NamedDecl *ShadowedDecl = I->second;
7170   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7171   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7172   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7173   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7174 
7175   // Avoid issuing multiple warnings about the same decl.
7176   ShadowingDecls.erase(I);
7177 }
7178 
7179 /// Check for conflict between this global or extern "C" declaration and
7180 /// previous global or extern "C" declarations. This is only used in C++.
7181 template<typename T>
7182 static bool checkGlobalOrExternCConflict(
7183     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7184   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7185   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7186 
7187   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7188     // The common case: this global doesn't conflict with any extern "C"
7189     // declaration.
7190     return false;
7191   }
7192 
7193   if (Prev) {
7194     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7195       // Both the old and new declarations have C language linkage. This is a
7196       // redeclaration.
7197       Previous.clear();
7198       Previous.addDecl(Prev);
7199       return true;
7200     }
7201 
7202     // This is a global, non-extern "C" declaration, and there is a previous
7203     // non-global extern "C" declaration. Diagnose if this is a variable
7204     // declaration.
7205     if (!isa<VarDecl>(ND))
7206       return false;
7207   } else {
7208     // The declaration is extern "C". Check for any declaration in the
7209     // translation unit which might conflict.
7210     if (IsGlobal) {
7211       // We have already performed the lookup into the translation unit.
7212       IsGlobal = false;
7213       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7214            I != E; ++I) {
7215         if (isa<VarDecl>(*I)) {
7216           Prev = *I;
7217           break;
7218         }
7219       }
7220     } else {
7221       DeclContext::lookup_result R =
7222           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7223       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7224            I != E; ++I) {
7225         if (isa<VarDecl>(*I)) {
7226           Prev = *I;
7227           break;
7228         }
7229         // FIXME: If we have any other entity with this name in global scope,
7230         // the declaration is ill-formed, but that is a defect: it breaks the
7231         // 'stat' hack, for instance. Only variables can have mangled name
7232         // clashes with extern "C" declarations, so only they deserve a
7233         // diagnostic.
7234       }
7235     }
7236 
7237     if (!Prev)
7238       return false;
7239   }
7240 
7241   // Use the first declaration's location to ensure we point at something which
7242   // is lexically inside an extern "C" linkage-spec.
7243   assert(Prev && "should have found a previous declaration to diagnose");
7244   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7245     Prev = FD->getFirstDecl();
7246   else
7247     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7248 
7249   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7250     << IsGlobal << ND;
7251   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7252     << IsGlobal;
7253   return false;
7254 }
7255 
7256 /// Apply special rules for handling extern "C" declarations. Returns \c true
7257 /// if we have found that this is a redeclaration of some prior entity.
7258 ///
7259 /// Per C++ [dcl.link]p6:
7260 ///   Two declarations [for a function or variable] with C language linkage
7261 ///   with the same name that appear in different scopes refer to the same
7262 ///   [entity]. An entity with C language linkage shall not be declared with
7263 ///   the same name as an entity in global scope.
7264 template<typename T>
7265 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7266                                                   LookupResult &Previous) {
7267   if (!S.getLangOpts().CPlusPlus) {
7268     // In C, when declaring a global variable, look for a corresponding 'extern'
7269     // variable declared in function scope. We don't need this in C++, because
7270     // we find local extern decls in the surrounding file-scope DeclContext.
7271     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7272       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7273         Previous.clear();
7274         Previous.addDecl(Prev);
7275         return true;
7276       }
7277     }
7278     return false;
7279   }
7280 
7281   // A declaration in the translation unit can conflict with an extern "C"
7282   // declaration.
7283   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7284     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7285 
7286   // An extern "C" declaration can conflict with a declaration in the
7287   // translation unit or can be a redeclaration of an extern "C" declaration
7288   // in another scope.
7289   if (isIncompleteDeclExternC(S,ND))
7290     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7291 
7292   // Neither global nor extern "C": nothing to do.
7293   return false;
7294 }
7295 
7296 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7297   // If the decl is already known invalid, don't check it.
7298   if (NewVD->isInvalidDecl())
7299     return;
7300 
7301   QualType T = NewVD->getType();
7302 
7303   // Defer checking an 'auto' type until its initializer is attached.
7304   if (T->isUndeducedType())
7305     return;
7306 
7307   if (NewVD->hasAttrs())
7308     CheckAlignasUnderalignment(NewVD);
7309 
7310   if (T->isObjCObjectType()) {
7311     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7312       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7313     T = Context.getObjCObjectPointerType(T);
7314     NewVD->setType(T);
7315   }
7316 
7317   // Emit an error if an address space was applied to decl with local storage.
7318   // This includes arrays of objects with address space qualifiers, but not
7319   // automatic variables that point to other address spaces.
7320   // ISO/IEC TR 18037 S5.1.2
7321   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7322       T.getAddressSpace() != LangAS::Default) {
7323     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7324     NewVD->setInvalidDecl();
7325     return;
7326   }
7327 
7328   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7329   // scope.
7330   if (getLangOpts().OpenCLVersion == 120 &&
7331       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7332       NewVD->isStaticLocal()) {
7333     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7334     NewVD->setInvalidDecl();
7335     return;
7336   }
7337 
7338   if (getLangOpts().OpenCL) {
7339     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7340     if (NewVD->hasAttr<BlocksAttr>()) {
7341       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7342       return;
7343     }
7344 
7345     if (T->isBlockPointerType()) {
7346       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7347       // can't use 'extern' storage class.
7348       if (!T.isConstQualified()) {
7349         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7350             << 0 /*const*/;
7351         NewVD->setInvalidDecl();
7352         return;
7353       }
7354       if (NewVD->hasExternalStorage()) {
7355         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7356         NewVD->setInvalidDecl();
7357         return;
7358       }
7359     }
7360     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7361     // __constant address space.
7362     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7363     // variables inside a function can also be declared in the global
7364     // address space.
7365     // OpenCL C++ v1.0 s2.5 inherits rule from OpenCL C v2.0 and allows local
7366     // address space additionally.
7367     // FIXME: Add local AS for OpenCL C++.
7368     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7369         NewVD->hasExternalStorage()) {
7370       if (!T->isSamplerT() &&
7371           !(T.getAddressSpace() == LangAS::opencl_constant ||
7372             (T.getAddressSpace() == LangAS::opencl_global &&
7373              (getLangOpts().OpenCLVersion == 200 ||
7374               getLangOpts().OpenCLCPlusPlus)))) {
7375         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7376         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7377           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7378               << Scope << "global or constant";
7379         else
7380           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7381               << Scope << "constant";
7382         NewVD->setInvalidDecl();
7383         return;
7384       }
7385     } else {
7386       if (T.getAddressSpace() == LangAS::opencl_global) {
7387         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7388             << 1 /*is any function*/ << "global";
7389         NewVD->setInvalidDecl();
7390         return;
7391       }
7392       if (T.getAddressSpace() == LangAS::opencl_constant ||
7393           T.getAddressSpace() == LangAS::opencl_local) {
7394         FunctionDecl *FD = getCurFunctionDecl();
7395         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7396         // in functions.
7397         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7398           if (T.getAddressSpace() == LangAS::opencl_constant)
7399             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7400                 << 0 /*non-kernel only*/ << "constant";
7401           else
7402             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7403                 << 0 /*non-kernel only*/ << "local";
7404           NewVD->setInvalidDecl();
7405           return;
7406         }
7407         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7408         // in the outermost scope of a kernel function.
7409         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7410           if (!getCurScope()->isFunctionScope()) {
7411             if (T.getAddressSpace() == LangAS::opencl_constant)
7412               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7413                   << "constant";
7414             else
7415               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7416                   << "local";
7417             NewVD->setInvalidDecl();
7418             return;
7419           }
7420         }
7421       } else if (T.getAddressSpace() != LangAS::opencl_private) {
7422         // Do not allow other address spaces on automatic variable.
7423         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7424         NewVD->setInvalidDecl();
7425         return;
7426       }
7427     }
7428   }
7429 
7430   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7431       && !NewVD->hasAttr<BlocksAttr>()) {
7432     if (getLangOpts().getGC() != LangOptions::NonGC)
7433       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7434     else {
7435       assert(!getLangOpts().ObjCAutoRefCount);
7436       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7437     }
7438   }
7439 
7440   bool isVM = T->isVariablyModifiedType();
7441   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7442       NewVD->hasAttr<BlocksAttr>())
7443     setFunctionHasBranchProtectedScope();
7444 
7445   if ((isVM && NewVD->hasLinkage()) ||
7446       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7447     bool SizeIsNegative;
7448     llvm::APSInt Oversized;
7449     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7450         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7451     QualType FixedT;
7452     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7453       FixedT = FixedTInfo->getType();
7454     else if (FixedTInfo) {
7455       // Type and type-as-written are canonically different. We need to fix up
7456       // both types separately.
7457       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7458                                                    Oversized);
7459     }
7460     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7461       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7462       // FIXME: This won't give the correct result for
7463       // int a[10][n];
7464       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7465 
7466       if (NewVD->isFileVarDecl())
7467         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7468         << SizeRange;
7469       else if (NewVD->isStaticLocal())
7470         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7471         << SizeRange;
7472       else
7473         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7474         << SizeRange;
7475       NewVD->setInvalidDecl();
7476       return;
7477     }
7478 
7479     if (!FixedTInfo) {
7480       if (NewVD->isFileVarDecl())
7481         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7482       else
7483         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7484       NewVD->setInvalidDecl();
7485       return;
7486     }
7487 
7488     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7489     NewVD->setType(FixedT);
7490     NewVD->setTypeSourceInfo(FixedTInfo);
7491   }
7492 
7493   if (T->isVoidType()) {
7494     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7495     //                    of objects and functions.
7496     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7497       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7498         << T;
7499       NewVD->setInvalidDecl();
7500       return;
7501     }
7502   }
7503 
7504   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7505     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7506     NewVD->setInvalidDecl();
7507     return;
7508   }
7509 
7510   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7511     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7512     NewVD->setInvalidDecl();
7513     return;
7514   }
7515 
7516   if (NewVD->isConstexpr() && !T->isDependentType() &&
7517       RequireLiteralType(NewVD->getLocation(), T,
7518                          diag::err_constexpr_var_non_literal)) {
7519     NewVD->setInvalidDecl();
7520     return;
7521   }
7522 }
7523 
7524 /// Perform semantic checking on a newly-created variable
7525 /// declaration.
7526 ///
7527 /// This routine performs all of the type-checking required for a
7528 /// variable declaration once it has been built. It is used both to
7529 /// check variables after they have been parsed and their declarators
7530 /// have been translated into a declaration, and to check variables
7531 /// that have been instantiated from a template.
7532 ///
7533 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7534 ///
7535 /// Returns true if the variable declaration is a redeclaration.
7536 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7537   CheckVariableDeclarationType(NewVD);
7538 
7539   // If the decl is already known invalid, don't check it.
7540   if (NewVD->isInvalidDecl())
7541     return false;
7542 
7543   // If we did not find anything by this name, look for a non-visible
7544   // extern "C" declaration with the same name.
7545   if (Previous.empty() &&
7546       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7547     Previous.setShadowed();
7548 
7549   if (!Previous.empty()) {
7550     MergeVarDecl(NewVD, Previous);
7551     return true;
7552   }
7553   return false;
7554 }
7555 
7556 namespace {
7557 struct FindOverriddenMethod {
7558   Sema *S;
7559   CXXMethodDecl *Method;
7560 
7561   /// Member lookup function that determines whether a given C++
7562   /// method overrides a method in a base class, to be used with
7563   /// CXXRecordDecl::lookupInBases().
7564   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7565     RecordDecl *BaseRecord =
7566         Specifier->getType()->getAs<RecordType>()->getDecl();
7567 
7568     DeclarationName Name = Method->getDeclName();
7569 
7570     // FIXME: Do we care about other names here too?
7571     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7572       // We really want to find the base class destructor here.
7573       QualType T = S->Context.getTypeDeclType(BaseRecord);
7574       CanQualType CT = S->Context.getCanonicalType(T);
7575 
7576       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7577     }
7578 
7579     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7580          Path.Decls = Path.Decls.slice(1)) {
7581       NamedDecl *D = Path.Decls.front();
7582       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7583         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7584           return true;
7585       }
7586     }
7587 
7588     return false;
7589   }
7590 };
7591 
7592 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7593 } // end anonymous namespace
7594 
7595 /// Report an error regarding overriding, along with any relevant
7596 /// overridden methods.
7597 ///
7598 /// \param DiagID the primary error to report.
7599 /// \param MD the overriding method.
7600 /// \param OEK which overrides to include as notes.
7601 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7602                             OverrideErrorKind OEK = OEK_All) {
7603   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7604   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7605     // This check (& the OEK parameter) could be replaced by a predicate, but
7606     // without lambdas that would be overkill. This is still nicer than writing
7607     // out the diag loop 3 times.
7608     if ((OEK == OEK_All) ||
7609         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7610         (OEK == OEK_Deleted && O->isDeleted()))
7611       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7612   }
7613 }
7614 
7615 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7616 /// and if so, check that it's a valid override and remember it.
7617 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7618   // Look for methods in base classes that this method might override.
7619   CXXBasePaths Paths;
7620   FindOverriddenMethod FOM;
7621   FOM.Method = MD;
7622   FOM.S = this;
7623   bool hasDeletedOverridenMethods = false;
7624   bool hasNonDeletedOverridenMethods = false;
7625   bool AddedAny = false;
7626   if (DC->lookupInBases(FOM, Paths)) {
7627     for (auto *I : Paths.found_decls()) {
7628       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7629         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7630         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7631             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7632             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7633             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7634           hasDeletedOverridenMethods |= OldMD->isDeleted();
7635           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7636           AddedAny = true;
7637         }
7638       }
7639     }
7640   }
7641 
7642   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7643     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7644   }
7645   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7646     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7647   }
7648 
7649   return AddedAny;
7650 }
7651 
7652 namespace {
7653   // Struct for holding all of the extra arguments needed by
7654   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7655   struct ActOnFDArgs {
7656     Scope *S;
7657     Declarator &D;
7658     MultiTemplateParamsArg TemplateParamLists;
7659     bool AddToScope;
7660   };
7661 } // end anonymous namespace
7662 
7663 namespace {
7664 
7665 // Callback to only accept typo corrections that have a non-zero edit distance.
7666 // Also only accept corrections that have the same parent decl.
7667 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7668  public:
7669   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7670                             CXXRecordDecl *Parent)
7671       : Context(Context), OriginalFD(TypoFD),
7672         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7673 
7674   bool ValidateCandidate(const TypoCorrection &candidate) override {
7675     if (candidate.getEditDistance() == 0)
7676       return false;
7677 
7678     SmallVector<unsigned, 1> MismatchedParams;
7679     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7680                                           CDeclEnd = candidate.end();
7681          CDecl != CDeclEnd; ++CDecl) {
7682       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7683 
7684       if (FD && !FD->hasBody() &&
7685           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7686         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7687           CXXRecordDecl *Parent = MD->getParent();
7688           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7689             return true;
7690         } else if (!ExpectedParent) {
7691           return true;
7692         }
7693       }
7694     }
7695 
7696     return false;
7697   }
7698 
7699  private:
7700   ASTContext &Context;
7701   FunctionDecl *OriginalFD;
7702   CXXRecordDecl *ExpectedParent;
7703 };
7704 
7705 } // end anonymous namespace
7706 
7707 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7708   TypoCorrectedFunctionDefinitions.insert(F);
7709 }
7710 
7711 /// Generate diagnostics for an invalid function redeclaration.
7712 ///
7713 /// This routine handles generating the diagnostic messages for an invalid
7714 /// function redeclaration, including finding possible similar declarations
7715 /// or performing typo correction if there are no previous declarations with
7716 /// the same name.
7717 ///
7718 /// Returns a NamedDecl iff typo correction was performed and substituting in
7719 /// the new declaration name does not cause new errors.
7720 static NamedDecl *DiagnoseInvalidRedeclaration(
7721     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7722     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7723   DeclarationName Name = NewFD->getDeclName();
7724   DeclContext *NewDC = NewFD->getDeclContext();
7725   SmallVector<unsigned, 1> MismatchedParams;
7726   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7727   TypoCorrection Correction;
7728   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7729   unsigned DiagMsg =
7730     IsLocalFriend ? diag::err_no_matching_local_friend :
7731     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
7732     diag::err_member_decl_does_not_match;
7733   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7734                     IsLocalFriend ? Sema::LookupLocalFriendName
7735                                   : Sema::LookupOrdinaryName,
7736                     Sema::ForVisibleRedeclaration);
7737 
7738   NewFD->setInvalidDecl();
7739   if (IsLocalFriend)
7740     SemaRef.LookupName(Prev, S);
7741   else
7742     SemaRef.LookupQualifiedName(Prev, NewDC);
7743   assert(!Prev.isAmbiguous() &&
7744          "Cannot have an ambiguity in previous-declaration lookup");
7745   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7746   if (!Prev.empty()) {
7747     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7748          Func != FuncEnd; ++Func) {
7749       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7750       if (FD &&
7751           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7752         // Add 1 to the index so that 0 can mean the mismatch didn't
7753         // involve a parameter
7754         unsigned ParamNum =
7755             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7756         NearMatches.push_back(std::make_pair(FD, ParamNum));
7757       }
7758     }
7759   // If the qualified name lookup yielded nothing, try typo correction
7760   } else if ((Correction = SemaRef.CorrectTypo(
7761                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7762                   &ExtraArgs.D.getCXXScopeSpec(),
7763                   llvm::make_unique<DifferentNameValidatorCCC>(
7764                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7765                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7766     // Set up everything for the call to ActOnFunctionDeclarator
7767     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7768                               ExtraArgs.D.getIdentifierLoc());
7769     Previous.clear();
7770     Previous.setLookupName(Correction.getCorrection());
7771     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7772                                     CDeclEnd = Correction.end();
7773          CDecl != CDeclEnd; ++CDecl) {
7774       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7775       if (FD && !FD->hasBody() &&
7776           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7777         Previous.addDecl(FD);
7778       }
7779     }
7780     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7781 
7782     NamedDecl *Result;
7783     // Retry building the function declaration with the new previous
7784     // declarations, and with errors suppressed.
7785     {
7786       // Trap errors.
7787       Sema::SFINAETrap Trap(SemaRef);
7788 
7789       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7790       // pieces need to verify the typo-corrected C++ declaration and hopefully
7791       // eliminate the need for the parameter pack ExtraArgs.
7792       Result = SemaRef.ActOnFunctionDeclarator(
7793           ExtraArgs.S, ExtraArgs.D,
7794           Correction.getCorrectionDecl()->getDeclContext(),
7795           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7796           ExtraArgs.AddToScope);
7797 
7798       if (Trap.hasErrorOccurred())
7799         Result = nullptr;
7800     }
7801 
7802     if (Result) {
7803       // Determine which correction we picked.
7804       Decl *Canonical = Result->getCanonicalDecl();
7805       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7806            I != E; ++I)
7807         if ((*I)->getCanonicalDecl() == Canonical)
7808           Correction.setCorrectionDecl(*I);
7809 
7810       // Let Sema know about the correction.
7811       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7812       SemaRef.diagnoseTypo(
7813           Correction,
7814           SemaRef.PDiag(IsLocalFriend
7815                           ? diag::err_no_matching_local_friend_suggest
7816                           : diag::err_member_decl_does_not_match_suggest)
7817             << Name << NewDC << IsDefinition);
7818       return Result;
7819     }
7820 
7821     // Pretend the typo correction never occurred
7822     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7823                               ExtraArgs.D.getIdentifierLoc());
7824     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7825     Previous.clear();
7826     Previous.setLookupName(Name);
7827   }
7828 
7829   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7830       << Name << NewDC << IsDefinition << NewFD->getLocation();
7831 
7832   bool NewFDisConst = false;
7833   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7834     NewFDisConst = NewMD->isConst();
7835 
7836   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7837        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7838        NearMatch != NearMatchEnd; ++NearMatch) {
7839     FunctionDecl *FD = NearMatch->first;
7840     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7841     bool FDisConst = MD && MD->isConst();
7842     bool IsMember = MD || !IsLocalFriend;
7843 
7844     // FIXME: These notes are poorly worded for the local friend case.
7845     if (unsigned Idx = NearMatch->second) {
7846       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7847       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7848       if (Loc.isInvalid()) Loc = FD->getLocation();
7849       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7850                                  : diag::note_local_decl_close_param_match)
7851         << Idx << FDParam->getType()
7852         << NewFD->getParamDecl(Idx - 1)->getType();
7853     } else if (FDisConst != NewFDisConst) {
7854       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7855           << NewFDisConst << FD->getSourceRange().getEnd();
7856     } else
7857       SemaRef.Diag(FD->getLocation(),
7858                    IsMember ? diag::note_member_def_close_match
7859                             : diag::note_local_decl_close_match);
7860   }
7861   return nullptr;
7862 }
7863 
7864 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7865   switch (D.getDeclSpec().getStorageClassSpec()) {
7866   default: llvm_unreachable("Unknown storage class!");
7867   case DeclSpec::SCS_auto:
7868   case DeclSpec::SCS_register:
7869   case DeclSpec::SCS_mutable:
7870     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7871                  diag::err_typecheck_sclass_func);
7872     D.getMutableDeclSpec().ClearStorageClassSpecs();
7873     D.setInvalidType();
7874     break;
7875   case DeclSpec::SCS_unspecified: break;
7876   case DeclSpec::SCS_extern:
7877     if (D.getDeclSpec().isExternInLinkageSpec())
7878       return SC_None;
7879     return SC_Extern;
7880   case DeclSpec::SCS_static: {
7881     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7882       // C99 6.7.1p5:
7883       //   The declaration of an identifier for a function that has
7884       //   block scope shall have no explicit storage-class specifier
7885       //   other than extern
7886       // See also (C++ [dcl.stc]p4).
7887       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7888                    diag::err_static_block_func);
7889       break;
7890     } else
7891       return SC_Static;
7892   }
7893   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7894   }
7895 
7896   // No explicit storage class has already been returned
7897   return SC_None;
7898 }
7899 
7900 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7901                                            DeclContext *DC, QualType &R,
7902                                            TypeSourceInfo *TInfo,
7903                                            StorageClass SC,
7904                                            bool &IsVirtualOkay) {
7905   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7906   DeclarationName Name = NameInfo.getName();
7907 
7908   FunctionDecl *NewFD = nullptr;
7909   bool isInline = D.getDeclSpec().isInlineSpecified();
7910 
7911   if (!SemaRef.getLangOpts().CPlusPlus) {
7912     // Determine whether the function was written with a
7913     // prototype. This true when:
7914     //   - there is a prototype in the declarator, or
7915     //   - the type R of the function is some kind of typedef or other non-
7916     //     attributed reference to a type name (which eventually refers to a
7917     //     function type).
7918     bool HasPrototype =
7919       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7920       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7921 
7922     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
7923                                  R, TInfo, SC, isInline, HasPrototype, false);
7924     if (D.isInvalidType())
7925       NewFD->setInvalidDecl();
7926 
7927     return NewFD;
7928   }
7929 
7930   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7931   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7932 
7933   // Check that the return type is not an abstract class type.
7934   // For record types, this is done by the AbstractClassUsageDiagnoser once
7935   // the class has been completely parsed.
7936   if (!DC->isRecord() &&
7937       SemaRef.RequireNonAbstractType(
7938           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7939           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7940     D.setInvalidType();
7941 
7942   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7943     // This is a C++ constructor declaration.
7944     assert(DC->isRecord() &&
7945            "Constructors can only be declared in a member context");
7946 
7947     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7948     return CXXConstructorDecl::Create(
7949         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
7950         TInfo, isExplicit, isInline,
7951         /*isImplicitlyDeclared=*/false, isConstexpr);
7952 
7953   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7954     // This is a C++ destructor declaration.
7955     if (DC->isRecord()) {
7956       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7957       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7958       CXXDestructorDecl *NewDD =
7959           CXXDestructorDecl::Create(SemaRef.Context, Record, D.getBeginLoc(),
7960                                     NameInfo, R, TInfo, isInline,
7961                                     /*isImplicitlyDeclared=*/false);
7962 
7963       // If the destructor needs an implicit exception specification, set it
7964       // now. FIXME: It'd be nice to be able to create the right type to start
7965       // with, but the type needs to reference the destructor declaration.
7966       if (SemaRef.getLangOpts().CPlusPlus11)
7967         SemaRef.AdjustDestructorExceptionSpec(NewDD);
7968 
7969       IsVirtualOkay = true;
7970       return NewDD;
7971 
7972     } else {
7973       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7974       D.setInvalidType();
7975 
7976       // Create a FunctionDecl to satisfy the function definition parsing
7977       // code path.
7978       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
7979                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
7980                                   isInline,
7981                                   /*hasPrototype=*/true, isConstexpr);
7982     }
7983 
7984   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7985     if (!DC->isRecord()) {
7986       SemaRef.Diag(D.getIdentifierLoc(),
7987            diag::err_conv_function_not_member);
7988       return nullptr;
7989     }
7990 
7991     SemaRef.CheckConversionDeclarator(D, R, SC);
7992     IsVirtualOkay = true;
7993     return CXXConversionDecl::Create(
7994         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
7995         TInfo, isInline, isExplicit, isConstexpr, SourceLocation());
7996 
7997   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7998     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7999 
8000     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8001                                          isExplicit, NameInfo, R, TInfo,
8002                                          D.getEndLoc());
8003   } else if (DC->isRecord()) {
8004     // If the name of the function is the same as the name of the record,
8005     // then this must be an invalid constructor that has a return type.
8006     // (The parser checks for a return type and makes the declarator a
8007     // constructor if it has no return type).
8008     if (Name.getAsIdentifierInfo() &&
8009         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8010       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8011         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8012         << SourceRange(D.getIdentifierLoc());
8013       return nullptr;
8014     }
8015 
8016     // This is a C++ method declaration.
8017     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8018         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8019         TInfo, SC, isInline, isConstexpr, SourceLocation());
8020     IsVirtualOkay = !Ret->isStatic();
8021     return Ret;
8022   } else {
8023     bool isFriend =
8024         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8025     if (!isFriend && SemaRef.CurContext->isRecord())
8026       return nullptr;
8027 
8028     // Determine whether the function was written with a
8029     // prototype. This true when:
8030     //   - we're in C++ (where every function has a prototype),
8031     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8032                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8033                                 isConstexpr);
8034   }
8035 }
8036 
8037 enum OpenCLParamType {
8038   ValidKernelParam,
8039   PtrPtrKernelParam,
8040   PtrKernelParam,
8041   InvalidAddrSpacePtrKernelParam,
8042   InvalidKernelParam,
8043   RecordKernelParam
8044 };
8045 
8046 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8047   // Size dependent types are just typedefs to normal integer types
8048   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8049   // integers other than by their names.
8050   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8051 
8052   // Remove typedefs one by one until we reach a typedef
8053   // for a size dependent type.
8054   QualType DesugaredTy = Ty;
8055   do {
8056     ArrayRef<StringRef> Names(SizeTypeNames);
8057     auto Match =
8058         std::find(Names.begin(), Names.end(), DesugaredTy.getAsString());
8059     if (Names.end() != Match)
8060       return true;
8061 
8062     Ty = DesugaredTy;
8063     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8064   } while (DesugaredTy != Ty);
8065 
8066   return false;
8067 }
8068 
8069 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8070   if (PT->isPointerType()) {
8071     QualType PointeeType = PT->getPointeeType();
8072     if (PointeeType->isPointerType())
8073       return PtrPtrKernelParam;
8074     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8075         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8076         PointeeType.getAddressSpace() == LangAS::Default)
8077       return InvalidAddrSpacePtrKernelParam;
8078     return PtrKernelParam;
8079   }
8080 
8081   // OpenCL v1.2 s6.9.k:
8082   // Arguments to kernel functions in a program cannot be declared with the
8083   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8084   // uintptr_t or a struct and/or union that contain fields declared to be one
8085   // of these built-in scalar types.
8086   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8087     return InvalidKernelParam;
8088 
8089   if (PT->isImageType())
8090     return PtrKernelParam;
8091 
8092   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8093     return InvalidKernelParam;
8094 
8095   // OpenCL extension spec v1.2 s9.5:
8096   // This extension adds support for half scalar and vector types as built-in
8097   // types that can be used for arithmetic operations, conversions etc.
8098   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8099     return InvalidKernelParam;
8100 
8101   if (PT->isRecordType())
8102     return RecordKernelParam;
8103 
8104   // Look into an array argument to check if it has a forbidden type.
8105   if (PT->isArrayType()) {
8106     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8107     // Call ourself to check an underlying type of an array. Since the
8108     // getPointeeOrArrayElementType returns an innermost type which is not an
8109     // array, this recursive call only happens once.
8110     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8111   }
8112 
8113   return ValidKernelParam;
8114 }
8115 
8116 static void checkIsValidOpenCLKernelParameter(
8117   Sema &S,
8118   Declarator &D,
8119   ParmVarDecl *Param,
8120   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8121   QualType PT = Param->getType();
8122 
8123   // Cache the valid types we encounter to avoid rechecking structs that are
8124   // used again
8125   if (ValidTypes.count(PT.getTypePtr()))
8126     return;
8127 
8128   switch (getOpenCLKernelParameterType(S, PT)) {
8129   case PtrPtrKernelParam:
8130     // OpenCL v1.2 s6.9.a:
8131     // A kernel function argument cannot be declared as a
8132     // pointer to a pointer type.
8133     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8134     D.setInvalidType();
8135     return;
8136 
8137   case InvalidAddrSpacePtrKernelParam:
8138     // OpenCL v1.0 s6.5:
8139     // __kernel function arguments declared to be a pointer of a type can point
8140     // to one of the following address spaces only : __global, __local or
8141     // __constant.
8142     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8143     D.setInvalidType();
8144     return;
8145 
8146     // OpenCL v1.2 s6.9.k:
8147     // Arguments to kernel functions in a program cannot be declared with the
8148     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8149     // uintptr_t or a struct and/or union that contain fields declared to be
8150     // one of these built-in scalar types.
8151 
8152   case InvalidKernelParam:
8153     // OpenCL v1.2 s6.8 n:
8154     // A kernel function argument cannot be declared
8155     // of event_t type.
8156     // Do not diagnose half type since it is diagnosed as invalid argument
8157     // type for any function elsewhere.
8158     if (!PT->isHalfType()) {
8159       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8160 
8161       // Explain what typedefs are involved.
8162       const TypedefType *Typedef = nullptr;
8163       while ((Typedef = PT->getAs<TypedefType>())) {
8164         SourceLocation Loc = Typedef->getDecl()->getLocation();
8165         // SourceLocation may be invalid for a built-in type.
8166         if (Loc.isValid())
8167           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8168         PT = Typedef->desugar();
8169       }
8170     }
8171 
8172     D.setInvalidType();
8173     return;
8174 
8175   case PtrKernelParam:
8176   case ValidKernelParam:
8177     ValidTypes.insert(PT.getTypePtr());
8178     return;
8179 
8180   case RecordKernelParam:
8181     break;
8182   }
8183 
8184   // Track nested structs we will inspect
8185   SmallVector<const Decl *, 4> VisitStack;
8186 
8187   // Track where we are in the nested structs. Items will migrate from
8188   // VisitStack to HistoryStack as we do the DFS for bad field.
8189   SmallVector<const FieldDecl *, 4> HistoryStack;
8190   HistoryStack.push_back(nullptr);
8191 
8192   // At this point we already handled everything except of a RecordType or
8193   // an ArrayType of a RecordType.
8194   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8195   const RecordType *RecTy =
8196       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8197   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8198 
8199   VisitStack.push_back(RecTy->getDecl());
8200   assert(VisitStack.back() && "First decl null?");
8201 
8202   do {
8203     const Decl *Next = VisitStack.pop_back_val();
8204     if (!Next) {
8205       assert(!HistoryStack.empty());
8206       // Found a marker, we have gone up a level
8207       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8208         ValidTypes.insert(Hist->getType().getTypePtr());
8209 
8210       continue;
8211     }
8212 
8213     // Adds everything except the original parameter declaration (which is not a
8214     // field itself) to the history stack.
8215     const RecordDecl *RD;
8216     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8217       HistoryStack.push_back(Field);
8218 
8219       QualType FieldTy = Field->getType();
8220       // Other field types (known to be valid or invalid) are handled while we
8221       // walk around RecordDecl::fields().
8222       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8223              "Unexpected type.");
8224       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8225 
8226       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8227     } else {
8228       RD = cast<RecordDecl>(Next);
8229     }
8230 
8231     // Add a null marker so we know when we've gone back up a level
8232     VisitStack.push_back(nullptr);
8233 
8234     for (const auto *FD : RD->fields()) {
8235       QualType QT = FD->getType();
8236 
8237       if (ValidTypes.count(QT.getTypePtr()))
8238         continue;
8239 
8240       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8241       if (ParamType == ValidKernelParam)
8242         continue;
8243 
8244       if (ParamType == RecordKernelParam) {
8245         VisitStack.push_back(FD);
8246         continue;
8247       }
8248 
8249       // OpenCL v1.2 s6.9.p:
8250       // Arguments to kernel functions that are declared to be a struct or union
8251       // do not allow OpenCL objects to be passed as elements of the struct or
8252       // union.
8253       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8254           ParamType == InvalidAddrSpacePtrKernelParam) {
8255         S.Diag(Param->getLocation(),
8256                diag::err_record_with_pointers_kernel_param)
8257           << PT->isUnionType()
8258           << PT;
8259       } else {
8260         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8261       }
8262 
8263       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8264           << OrigRecDecl->getDeclName();
8265 
8266       // We have an error, now let's go back up through history and show where
8267       // the offending field came from
8268       for (ArrayRef<const FieldDecl *>::const_iterator
8269                I = HistoryStack.begin() + 1,
8270                E = HistoryStack.end();
8271            I != E; ++I) {
8272         const FieldDecl *OuterField = *I;
8273         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8274           << OuterField->getType();
8275       }
8276 
8277       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8278         << QT->isPointerType()
8279         << QT;
8280       D.setInvalidType();
8281       return;
8282     }
8283   } while (!VisitStack.empty());
8284 }
8285 
8286 /// Find the DeclContext in which a tag is implicitly declared if we see an
8287 /// elaborated type specifier in the specified context, and lookup finds
8288 /// nothing.
8289 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8290   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8291     DC = DC->getParent();
8292   return DC;
8293 }
8294 
8295 /// Find the Scope in which a tag is implicitly declared if we see an
8296 /// elaborated type specifier in the specified context, and lookup finds
8297 /// nothing.
8298 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8299   while (S->isClassScope() ||
8300          (LangOpts.CPlusPlus &&
8301           S->isFunctionPrototypeScope()) ||
8302          ((S->getFlags() & Scope::DeclScope) == 0) ||
8303          (S->getEntity() && S->getEntity()->isTransparentContext()))
8304     S = S->getParent();
8305   return S;
8306 }
8307 
8308 NamedDecl*
8309 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8310                               TypeSourceInfo *TInfo, LookupResult &Previous,
8311                               MultiTemplateParamsArg TemplateParamLists,
8312                               bool &AddToScope) {
8313   QualType R = TInfo->getType();
8314 
8315   assert(R->isFunctionType());
8316 
8317   // TODO: consider using NameInfo for diagnostic.
8318   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8319   DeclarationName Name = NameInfo.getName();
8320   StorageClass SC = getFunctionStorageClass(*this, D);
8321 
8322   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8323     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8324          diag::err_invalid_thread)
8325       << DeclSpec::getSpecifierName(TSCS);
8326 
8327   if (D.isFirstDeclarationOfMember())
8328     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8329                            D.getIdentifierLoc());
8330 
8331   bool isFriend = false;
8332   FunctionTemplateDecl *FunctionTemplate = nullptr;
8333   bool isMemberSpecialization = false;
8334   bool isFunctionTemplateSpecialization = false;
8335 
8336   bool isDependentClassScopeExplicitSpecialization = false;
8337   bool HasExplicitTemplateArgs = false;
8338   TemplateArgumentListInfo TemplateArgs;
8339 
8340   bool isVirtualOkay = false;
8341 
8342   DeclContext *OriginalDC = DC;
8343   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8344 
8345   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8346                                               isVirtualOkay);
8347   if (!NewFD) return nullptr;
8348 
8349   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8350     NewFD->setTopLevelDeclInObjCContainer();
8351 
8352   // Set the lexical context. If this is a function-scope declaration, or has a
8353   // C++ scope specifier, or is the object of a friend declaration, the lexical
8354   // context will be different from the semantic context.
8355   NewFD->setLexicalDeclContext(CurContext);
8356 
8357   if (IsLocalExternDecl)
8358     NewFD->setLocalExternDecl();
8359 
8360   if (getLangOpts().CPlusPlus) {
8361     bool isInline = D.getDeclSpec().isInlineSpecified();
8362     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8363     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8364     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8365     isFriend = D.getDeclSpec().isFriendSpecified();
8366     if (isFriend && !isInline && D.isFunctionDefinition()) {
8367       // C++ [class.friend]p5
8368       //   A function can be defined in a friend declaration of a
8369       //   class . . . . Such a function is implicitly inline.
8370       NewFD->setImplicitlyInline();
8371     }
8372 
8373     // If this is a method defined in an __interface, and is not a constructor
8374     // or an overloaded operator, then set the pure flag (isVirtual will already
8375     // return true).
8376     if (const CXXRecordDecl *Parent =
8377           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8378       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8379         NewFD->setPure(true);
8380 
8381       // C++ [class.union]p2
8382       //   A union can have member functions, but not virtual functions.
8383       if (isVirtual && Parent->isUnion())
8384         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8385     }
8386 
8387     SetNestedNameSpecifier(*this, NewFD, D);
8388     isMemberSpecialization = false;
8389     isFunctionTemplateSpecialization = false;
8390     if (D.isInvalidType())
8391       NewFD->setInvalidDecl();
8392 
8393     // Match up the template parameter lists with the scope specifier, then
8394     // determine whether we have a template or a template specialization.
8395     bool Invalid = false;
8396     if (TemplateParameterList *TemplateParams =
8397             MatchTemplateParametersToScopeSpecifier(
8398                 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8399                 D.getCXXScopeSpec(),
8400                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8401                     ? D.getName().TemplateId
8402                     : nullptr,
8403                 TemplateParamLists, isFriend, isMemberSpecialization,
8404                 Invalid)) {
8405       if (TemplateParams->size() > 0) {
8406         // This is a function template
8407 
8408         // Check that we can declare a template here.
8409         if (CheckTemplateDeclScope(S, TemplateParams))
8410           NewFD->setInvalidDecl();
8411 
8412         // A destructor cannot be a template.
8413         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8414           Diag(NewFD->getLocation(), diag::err_destructor_template);
8415           NewFD->setInvalidDecl();
8416         }
8417 
8418         // If we're adding a template to a dependent context, we may need to
8419         // rebuilding some of the types used within the template parameter list,
8420         // now that we know what the current instantiation is.
8421         if (DC->isDependentContext()) {
8422           ContextRAII SavedContext(*this, DC);
8423           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8424             Invalid = true;
8425         }
8426 
8427         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8428                                                         NewFD->getLocation(),
8429                                                         Name, TemplateParams,
8430                                                         NewFD);
8431         FunctionTemplate->setLexicalDeclContext(CurContext);
8432         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8433 
8434         // For source fidelity, store the other template param lists.
8435         if (TemplateParamLists.size() > 1) {
8436           NewFD->setTemplateParameterListsInfo(Context,
8437                                                TemplateParamLists.drop_back(1));
8438         }
8439       } else {
8440         // This is a function template specialization.
8441         isFunctionTemplateSpecialization = true;
8442         // For source fidelity, store all the template param lists.
8443         if (TemplateParamLists.size() > 0)
8444           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8445 
8446         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8447         if (isFriend) {
8448           // We want to remove the "template<>", found here.
8449           SourceRange RemoveRange = TemplateParams->getSourceRange();
8450 
8451           // If we remove the template<> and the name is not a
8452           // template-id, we're actually silently creating a problem:
8453           // the friend declaration will refer to an untemplated decl,
8454           // and clearly the user wants a template specialization.  So
8455           // we need to insert '<>' after the name.
8456           SourceLocation InsertLoc;
8457           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8458             InsertLoc = D.getName().getSourceRange().getEnd();
8459             InsertLoc = getLocForEndOfToken(InsertLoc);
8460           }
8461 
8462           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8463             << Name << RemoveRange
8464             << FixItHint::CreateRemoval(RemoveRange)
8465             << FixItHint::CreateInsertion(InsertLoc, "<>");
8466         }
8467       }
8468     } else {
8469       // All template param lists were matched against the scope specifier:
8470       // this is NOT (an explicit specialization of) a template.
8471       if (TemplateParamLists.size() > 0)
8472         // For source fidelity, store all the template param lists.
8473         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8474     }
8475 
8476     if (Invalid) {
8477       NewFD->setInvalidDecl();
8478       if (FunctionTemplate)
8479         FunctionTemplate->setInvalidDecl();
8480     }
8481 
8482     // C++ [dcl.fct.spec]p5:
8483     //   The virtual specifier shall only be used in declarations of
8484     //   nonstatic class member functions that appear within a
8485     //   member-specification of a class declaration; see 10.3.
8486     //
8487     if (isVirtual && !NewFD->isInvalidDecl()) {
8488       if (!isVirtualOkay) {
8489         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8490              diag::err_virtual_non_function);
8491       } else if (!CurContext->isRecord()) {
8492         // 'virtual' was specified outside of the class.
8493         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8494              diag::err_virtual_out_of_class)
8495           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8496       } else if (NewFD->getDescribedFunctionTemplate()) {
8497         // C++ [temp.mem]p3:
8498         //  A member function template shall not be virtual.
8499         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8500              diag::err_virtual_member_function_template)
8501           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8502       } else {
8503         // Okay: Add virtual to the method.
8504         NewFD->setVirtualAsWritten(true);
8505       }
8506 
8507       if (getLangOpts().CPlusPlus14 &&
8508           NewFD->getReturnType()->isUndeducedType())
8509         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8510     }
8511 
8512     if (getLangOpts().CPlusPlus14 &&
8513         (NewFD->isDependentContext() ||
8514          (isFriend && CurContext->isDependentContext())) &&
8515         NewFD->getReturnType()->isUndeducedType()) {
8516       // If the function template is referenced directly (for instance, as a
8517       // member of the current instantiation), pretend it has a dependent type.
8518       // This is not really justified by the standard, but is the only sane
8519       // thing to do.
8520       // FIXME: For a friend function, we have not marked the function as being
8521       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8522       const FunctionProtoType *FPT =
8523           NewFD->getType()->castAs<FunctionProtoType>();
8524       QualType Result =
8525           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8526       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8527                                              FPT->getExtProtoInfo()));
8528     }
8529 
8530     // C++ [dcl.fct.spec]p3:
8531     //  The inline specifier shall not appear on a block scope function
8532     //  declaration.
8533     if (isInline && !NewFD->isInvalidDecl()) {
8534       if (CurContext->isFunctionOrMethod()) {
8535         // 'inline' is not allowed on block scope function declaration.
8536         Diag(D.getDeclSpec().getInlineSpecLoc(),
8537              diag::err_inline_declaration_block_scope) << Name
8538           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8539       }
8540     }
8541 
8542     // C++ [dcl.fct.spec]p6:
8543     //  The explicit specifier shall be used only in the declaration of a
8544     //  constructor or conversion function within its class definition;
8545     //  see 12.3.1 and 12.3.2.
8546     if (isExplicit && !NewFD->isInvalidDecl() &&
8547         !isa<CXXDeductionGuideDecl>(NewFD)) {
8548       if (!CurContext->isRecord()) {
8549         // 'explicit' was specified outside of the class.
8550         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8551              diag::err_explicit_out_of_class)
8552           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8553       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8554                  !isa<CXXConversionDecl>(NewFD)) {
8555         // 'explicit' was specified on a function that wasn't a constructor
8556         // or conversion function.
8557         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8558              diag::err_explicit_non_ctor_or_conv_function)
8559           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8560       }
8561     }
8562 
8563     if (isConstexpr) {
8564       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8565       // are implicitly inline.
8566       NewFD->setImplicitlyInline();
8567 
8568       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8569       // be either constructors or to return a literal type. Therefore,
8570       // destructors cannot be declared constexpr.
8571       if (isa<CXXDestructorDecl>(NewFD))
8572         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8573     }
8574 
8575     // If __module_private__ was specified, mark the function accordingly.
8576     if (D.getDeclSpec().isModulePrivateSpecified()) {
8577       if (isFunctionTemplateSpecialization) {
8578         SourceLocation ModulePrivateLoc
8579           = D.getDeclSpec().getModulePrivateSpecLoc();
8580         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8581           << 0
8582           << FixItHint::CreateRemoval(ModulePrivateLoc);
8583       } else {
8584         NewFD->setModulePrivate();
8585         if (FunctionTemplate)
8586           FunctionTemplate->setModulePrivate();
8587       }
8588     }
8589 
8590     if (isFriend) {
8591       if (FunctionTemplate) {
8592         FunctionTemplate->setObjectOfFriendDecl();
8593         FunctionTemplate->setAccess(AS_public);
8594       }
8595       NewFD->setObjectOfFriendDecl();
8596       NewFD->setAccess(AS_public);
8597     }
8598 
8599     // If a function is defined as defaulted or deleted, mark it as such now.
8600     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8601     // definition kind to FDK_Definition.
8602     switch (D.getFunctionDefinitionKind()) {
8603       case FDK_Declaration:
8604       case FDK_Definition:
8605         break;
8606 
8607       case FDK_Defaulted:
8608         NewFD->setDefaulted();
8609         break;
8610 
8611       case FDK_Deleted:
8612         NewFD->setDeletedAsWritten();
8613         break;
8614     }
8615 
8616     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8617         D.isFunctionDefinition()) {
8618       // C++ [class.mfct]p2:
8619       //   A member function may be defined (8.4) in its class definition, in
8620       //   which case it is an inline member function (7.1.2)
8621       NewFD->setImplicitlyInline();
8622     }
8623 
8624     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8625         !CurContext->isRecord()) {
8626       // C++ [class.static]p1:
8627       //   A data or function member of a class may be declared static
8628       //   in a class definition, in which case it is a static member of
8629       //   the class.
8630 
8631       // Complain about the 'static' specifier if it's on an out-of-line
8632       // member function definition.
8633 
8634       // MSVC permits the use of a 'static' storage specifier on an out-of-line
8635       // member function template declaration, warn about this.
8636       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8637            NewFD->getDescribedFunctionTemplate() && getLangOpts().MSVCCompat
8638            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
8639         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8640     }
8641 
8642     // C++11 [except.spec]p15:
8643     //   A deallocation function with no exception-specification is treated
8644     //   as if it were specified with noexcept(true).
8645     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8646     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8647          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8648         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8649       NewFD->setType(Context.getFunctionType(
8650           FPT->getReturnType(), FPT->getParamTypes(),
8651           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8652   }
8653 
8654   // Filter out previous declarations that don't match the scope.
8655   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8656                        D.getCXXScopeSpec().isNotEmpty() ||
8657                        isMemberSpecialization ||
8658                        isFunctionTemplateSpecialization);
8659 
8660   // Handle GNU asm-label extension (encoded as an attribute).
8661   if (Expr *E = (Expr*) D.getAsmLabel()) {
8662     // The parser guarantees this is a string.
8663     StringLiteral *SE = cast<StringLiteral>(E);
8664     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8665                                                 SE->getString(), 0));
8666   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8667     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8668       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8669     if (I != ExtnameUndeclaredIdentifiers.end()) {
8670       if (isDeclExternC(NewFD)) {
8671         NewFD->addAttr(I->second);
8672         ExtnameUndeclaredIdentifiers.erase(I);
8673       } else
8674         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8675             << /*Variable*/0 << NewFD;
8676     }
8677   }
8678 
8679   // Copy the parameter declarations from the declarator D to the function
8680   // declaration NewFD, if they are available.  First scavenge them into Params.
8681   SmallVector<ParmVarDecl*, 16> Params;
8682   unsigned FTIIdx;
8683   if (D.isFunctionDeclarator(FTIIdx)) {
8684     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8685 
8686     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8687     // function that takes no arguments, not a function that takes a
8688     // single void argument.
8689     // We let through "const void" here because Sema::GetTypeForDeclarator
8690     // already checks for that case.
8691     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8692       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8693         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8694         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8695         Param->setDeclContext(NewFD);
8696         Params.push_back(Param);
8697 
8698         if (Param->isInvalidDecl())
8699           NewFD->setInvalidDecl();
8700       }
8701     }
8702 
8703     if (!getLangOpts().CPlusPlus) {
8704       // In C, find all the tag declarations from the prototype and move them
8705       // into the function DeclContext. Remove them from the surrounding tag
8706       // injection context of the function, which is typically but not always
8707       // the TU.
8708       DeclContext *PrototypeTagContext =
8709           getTagInjectionContext(NewFD->getLexicalDeclContext());
8710       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8711         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8712 
8713         // We don't want to reparent enumerators. Look at their parent enum
8714         // instead.
8715         if (!TD) {
8716           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8717             TD = cast<EnumDecl>(ECD->getDeclContext());
8718         }
8719         if (!TD)
8720           continue;
8721         DeclContext *TagDC = TD->getLexicalDeclContext();
8722         if (!TagDC->containsDecl(TD))
8723           continue;
8724         TagDC->removeDecl(TD);
8725         TD->setDeclContext(NewFD);
8726         NewFD->addDecl(TD);
8727 
8728         // Preserve the lexical DeclContext if it is not the surrounding tag
8729         // injection context of the FD. In this example, the semantic context of
8730         // E will be f and the lexical context will be S, while both the
8731         // semantic and lexical contexts of S will be f:
8732         //   void f(struct S { enum E { a } f; } s);
8733         if (TagDC != PrototypeTagContext)
8734           TD->setLexicalDeclContext(TagDC);
8735       }
8736     }
8737   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8738     // When we're declaring a function with a typedef, typeof, etc as in the
8739     // following example, we'll need to synthesize (unnamed)
8740     // parameters for use in the declaration.
8741     //
8742     // @code
8743     // typedef void fn(int);
8744     // fn f;
8745     // @endcode
8746 
8747     // Synthesize a parameter for each argument type.
8748     for (const auto &AI : FT->param_types()) {
8749       ParmVarDecl *Param =
8750           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8751       Param->setScopeInfo(0, Params.size());
8752       Params.push_back(Param);
8753     }
8754   } else {
8755     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8756            "Should not need args for typedef of non-prototype fn");
8757   }
8758 
8759   // Finally, we know we have the right number of parameters, install them.
8760   NewFD->setParams(Params);
8761 
8762   if (D.getDeclSpec().isNoreturnSpecified())
8763     NewFD->addAttr(
8764         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8765                                        Context, 0));
8766 
8767   // Functions returning a variably modified type violate C99 6.7.5.2p2
8768   // because all functions have linkage.
8769   if (!NewFD->isInvalidDecl() &&
8770       NewFD->getReturnType()->isVariablyModifiedType()) {
8771     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8772     NewFD->setInvalidDecl();
8773   }
8774 
8775   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8776   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8777       !NewFD->hasAttr<SectionAttr>()) {
8778     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8779                                                  PragmaClangTextSection.SectionName,
8780                                                  PragmaClangTextSection.PragmaLocation));
8781   }
8782 
8783   // Apply an implicit SectionAttr if #pragma code_seg is active.
8784   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8785       !NewFD->hasAttr<SectionAttr>()) {
8786     NewFD->addAttr(
8787         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8788                                     CodeSegStack.CurrentValue->getString(),
8789                                     CodeSegStack.CurrentPragmaLocation));
8790     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8791                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8792                          ASTContext::PSF_Read,
8793                      NewFD))
8794       NewFD->dropAttr<SectionAttr>();
8795   }
8796 
8797   // Apply an implicit CodeSegAttr from class declspec or
8798   // apply an implicit SectionAttr from #pragma code_seg if active.
8799   if (!NewFD->hasAttr<CodeSegAttr>()) {
8800     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
8801                                                                  D.isFunctionDefinition())) {
8802       NewFD->addAttr(SAttr);
8803     }
8804   }
8805 
8806   // Handle attributes.
8807   ProcessDeclAttributes(S, NewFD, D);
8808 
8809   if (getLangOpts().OpenCL) {
8810     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8811     // type declaration will generate a compilation error.
8812     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
8813     if (AddressSpace != LangAS::Default) {
8814       Diag(NewFD->getLocation(),
8815            diag::err_opencl_return_value_with_address_space);
8816       NewFD->setInvalidDecl();
8817     }
8818   }
8819 
8820   if (!getLangOpts().CPlusPlus) {
8821     // Perform semantic checking on the function declaration.
8822     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8823       CheckMain(NewFD, D.getDeclSpec());
8824 
8825     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8826       CheckMSVCRTEntryPoint(NewFD);
8827 
8828     if (!NewFD->isInvalidDecl())
8829       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8830                                                   isMemberSpecialization));
8831     else if (!Previous.empty())
8832       // Recover gracefully from an invalid redeclaration.
8833       D.setRedeclaration(true);
8834     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8835             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8836            "previous declaration set still overloaded");
8837 
8838     // Diagnose no-prototype function declarations with calling conventions that
8839     // don't support variadic calls. Only do this in C and do it after merging
8840     // possibly prototyped redeclarations.
8841     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8842     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8843       CallingConv CC = FT->getExtInfo().getCC();
8844       if (!supportsVariadicCall(CC)) {
8845         // Windows system headers sometimes accidentally use stdcall without
8846         // (void) parameters, so we relax this to a warning.
8847         int DiagID =
8848             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8849         Diag(NewFD->getLocation(), DiagID)
8850             << FunctionType::getNameForCallConv(CC);
8851       }
8852     }
8853   } else {
8854     // C++11 [replacement.functions]p3:
8855     //  The program's definitions shall not be specified as inline.
8856     //
8857     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8858     //
8859     // Suppress the diagnostic if the function is __attribute__((used)), since
8860     // that forces an external definition to be emitted.
8861     if (D.getDeclSpec().isInlineSpecified() &&
8862         NewFD->isReplaceableGlobalAllocationFunction() &&
8863         !NewFD->hasAttr<UsedAttr>())
8864       Diag(D.getDeclSpec().getInlineSpecLoc(),
8865            diag::ext_operator_new_delete_declared_inline)
8866         << NewFD->getDeclName();
8867 
8868     // If the declarator is a template-id, translate the parser's template
8869     // argument list into our AST format.
8870     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
8871       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8872       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8873       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8874       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8875                                          TemplateId->NumArgs);
8876       translateTemplateArguments(TemplateArgsPtr,
8877                                  TemplateArgs);
8878 
8879       HasExplicitTemplateArgs = true;
8880 
8881       if (NewFD->isInvalidDecl()) {
8882         HasExplicitTemplateArgs = false;
8883       } else if (FunctionTemplate) {
8884         // Function template with explicit template arguments.
8885         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8886           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8887 
8888         HasExplicitTemplateArgs = false;
8889       } else {
8890         assert((isFunctionTemplateSpecialization ||
8891                 D.getDeclSpec().isFriendSpecified()) &&
8892                "should have a 'template<>' for this decl");
8893         // "friend void foo<>(int);" is an implicit specialization decl.
8894         isFunctionTemplateSpecialization = true;
8895       }
8896     } else if (isFriend && isFunctionTemplateSpecialization) {
8897       // This combination is only possible in a recovery case;  the user
8898       // wrote something like:
8899       //   template <> friend void foo(int);
8900       // which we're recovering from as if the user had written:
8901       //   friend void foo<>(int);
8902       // Go ahead and fake up a template id.
8903       HasExplicitTemplateArgs = true;
8904       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8905       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8906     }
8907 
8908     // We do not add HD attributes to specializations here because
8909     // they may have different constexpr-ness compared to their
8910     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8911     // may end up with different effective targets. Instead, a
8912     // specialization inherits its target attributes from its template
8913     // in the CheckFunctionTemplateSpecialization() call below.
8914     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8915       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8916 
8917     // If it's a friend (and only if it's a friend), it's possible
8918     // that either the specialized function type or the specialized
8919     // template is dependent, and therefore matching will fail.  In
8920     // this case, don't check the specialization yet.
8921     bool InstantiationDependent = false;
8922     if (isFunctionTemplateSpecialization && isFriend &&
8923         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8924          TemplateSpecializationType::anyDependentTemplateArguments(
8925             TemplateArgs,
8926             InstantiationDependent))) {
8927       assert(HasExplicitTemplateArgs &&
8928              "friend function specialization without template args");
8929       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8930                                                        Previous))
8931         NewFD->setInvalidDecl();
8932     } else if (isFunctionTemplateSpecialization) {
8933       if (CurContext->isDependentContext() && CurContext->isRecord()
8934           && !isFriend) {
8935         isDependentClassScopeExplicitSpecialization = true;
8936       } else if (!NewFD->isInvalidDecl() &&
8937                  CheckFunctionTemplateSpecialization(
8938                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
8939                      Previous))
8940         NewFD->setInvalidDecl();
8941 
8942       // C++ [dcl.stc]p1:
8943       //   A storage-class-specifier shall not be specified in an explicit
8944       //   specialization (14.7.3)
8945       FunctionTemplateSpecializationInfo *Info =
8946           NewFD->getTemplateSpecializationInfo();
8947       if (Info && SC != SC_None) {
8948         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8949           Diag(NewFD->getLocation(),
8950                diag::err_explicit_specialization_inconsistent_storage_class)
8951             << SC
8952             << FixItHint::CreateRemoval(
8953                                       D.getDeclSpec().getStorageClassSpecLoc());
8954 
8955         else
8956           Diag(NewFD->getLocation(),
8957                diag::ext_explicit_specialization_storage_class)
8958             << FixItHint::CreateRemoval(
8959                                       D.getDeclSpec().getStorageClassSpecLoc());
8960       }
8961     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8962       if (CheckMemberSpecialization(NewFD, Previous))
8963           NewFD->setInvalidDecl();
8964     }
8965 
8966     // Perform semantic checking on the function declaration.
8967     if (!isDependentClassScopeExplicitSpecialization) {
8968       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8969         CheckMain(NewFD, D.getDeclSpec());
8970 
8971       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8972         CheckMSVCRTEntryPoint(NewFD);
8973 
8974       if (!NewFD->isInvalidDecl())
8975         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8976                                                     isMemberSpecialization));
8977       else if (!Previous.empty())
8978         // Recover gracefully from an invalid redeclaration.
8979         D.setRedeclaration(true);
8980     }
8981 
8982     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8983             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8984            "previous declaration set still overloaded");
8985 
8986     NamedDecl *PrincipalDecl = (FunctionTemplate
8987                                 ? cast<NamedDecl>(FunctionTemplate)
8988                                 : NewFD);
8989 
8990     if (isFriend && NewFD->getPreviousDecl()) {
8991       AccessSpecifier Access = AS_public;
8992       if (!NewFD->isInvalidDecl())
8993         Access = NewFD->getPreviousDecl()->getAccess();
8994 
8995       NewFD->setAccess(Access);
8996       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8997     }
8998 
8999     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9000         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9001       PrincipalDecl->setNonMemberOperator();
9002 
9003     // If we have a function template, check the template parameter
9004     // list. This will check and merge default template arguments.
9005     if (FunctionTemplate) {
9006       FunctionTemplateDecl *PrevTemplate =
9007                                      FunctionTemplate->getPreviousDecl();
9008       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9009                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9010                                     : nullptr,
9011                             D.getDeclSpec().isFriendSpecified()
9012                               ? (D.isFunctionDefinition()
9013                                    ? TPC_FriendFunctionTemplateDefinition
9014                                    : TPC_FriendFunctionTemplate)
9015                               : (D.getCXXScopeSpec().isSet() &&
9016                                  DC && DC->isRecord() &&
9017                                  DC->isDependentContext())
9018                                   ? TPC_ClassTemplateMember
9019                                   : TPC_FunctionTemplate);
9020     }
9021 
9022     if (NewFD->isInvalidDecl()) {
9023       // Ignore all the rest of this.
9024     } else if (!D.isRedeclaration()) {
9025       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9026                                        AddToScope };
9027       // Fake up an access specifier if it's supposed to be a class member.
9028       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9029         NewFD->setAccess(AS_public);
9030 
9031       // Qualified decls generally require a previous declaration.
9032       if (D.getCXXScopeSpec().isSet()) {
9033         // ...with the major exception of templated-scope or
9034         // dependent-scope friend declarations.
9035 
9036         // TODO: we currently also suppress this check in dependent
9037         // contexts because (1) the parameter depth will be off when
9038         // matching friend templates and (2) we might actually be
9039         // selecting a friend based on a dependent factor.  But there
9040         // are situations where these conditions don't apply and we
9041         // can actually do this check immediately.
9042         //
9043         // Unless the scope is dependent, it's always an error if qualified
9044         // redeclaration lookup found nothing at all. Diagnose that now;
9045         // nothing will diagnose that error later.
9046         if (isFriend &&
9047             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9048              (!Previous.empty() && (TemplateParamLists.size() ||
9049                                     CurContext->isDependentContext())))) {
9050           // ignore these
9051         } else {
9052           // The user tried to provide an out-of-line definition for a
9053           // function that is a member of a class or namespace, but there
9054           // was no such member function declared (C++ [class.mfct]p2,
9055           // C++ [namespace.memdef]p2). For example:
9056           //
9057           // class X {
9058           //   void f() const;
9059           // };
9060           //
9061           // void X::f() { } // ill-formed
9062           //
9063           // Complain about this problem, and attempt to suggest close
9064           // matches (e.g., those that differ only in cv-qualifiers and
9065           // whether the parameter types are references).
9066 
9067           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9068                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9069             AddToScope = ExtraArgs.AddToScope;
9070             return Result;
9071           }
9072         }
9073 
9074         // Unqualified local friend declarations are required to resolve
9075         // to something.
9076       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9077         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9078                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9079           AddToScope = ExtraArgs.AddToScope;
9080           return Result;
9081         }
9082       }
9083     } else if (!D.isFunctionDefinition() &&
9084                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9085                !isFriend && !isFunctionTemplateSpecialization &&
9086                !isMemberSpecialization) {
9087       // An out-of-line member function declaration must also be a
9088       // definition (C++ [class.mfct]p2).
9089       // Note that this is not the case for explicit specializations of
9090       // function templates or member functions of class templates, per
9091       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9092       // extension for compatibility with old SWIG code which likes to
9093       // generate them.
9094       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9095         << D.getCXXScopeSpec().getRange();
9096     }
9097   }
9098 
9099   ProcessPragmaWeak(S, NewFD);
9100   checkAttributesAfterMerging(*this, *NewFD);
9101 
9102   AddKnownFunctionAttributes(NewFD);
9103 
9104   if (NewFD->hasAttr<OverloadableAttr>() &&
9105       !NewFD->getType()->getAs<FunctionProtoType>()) {
9106     Diag(NewFD->getLocation(),
9107          diag::err_attribute_overloadable_no_prototype)
9108       << NewFD;
9109 
9110     // Turn this into a variadic function with no parameters.
9111     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9112     FunctionProtoType::ExtProtoInfo EPI(
9113         Context.getDefaultCallingConvention(true, false));
9114     EPI.Variadic = true;
9115     EPI.ExtInfo = FT->getExtInfo();
9116 
9117     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9118     NewFD->setType(R);
9119   }
9120 
9121   // If there's a #pragma GCC visibility in scope, and this isn't a class
9122   // member, set the visibility of this function.
9123   if (!DC->isRecord() && NewFD->isExternallyVisible())
9124     AddPushedVisibilityAttribute(NewFD);
9125 
9126   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9127   // marking the function.
9128   AddCFAuditedAttribute(NewFD);
9129 
9130   // If this is a function definition, check if we have to apply optnone due to
9131   // a pragma.
9132   if(D.isFunctionDefinition())
9133     AddRangeBasedOptnone(NewFD);
9134 
9135   // If this is the first declaration of an extern C variable, update
9136   // the map of such variables.
9137   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9138       isIncompleteDeclExternC(*this, NewFD))
9139     RegisterLocallyScopedExternCDecl(NewFD, S);
9140 
9141   // Set this FunctionDecl's range up to the right paren.
9142   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9143 
9144   if (D.isRedeclaration() && !Previous.empty()) {
9145     NamedDecl *Prev = Previous.getRepresentativeDecl();
9146     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9147                                    isMemberSpecialization ||
9148                                        isFunctionTemplateSpecialization,
9149                                    D.isFunctionDefinition());
9150   }
9151 
9152   if (getLangOpts().CUDA) {
9153     IdentifierInfo *II = NewFD->getIdentifier();
9154     if (II && II->isStr(getCudaConfigureFuncName()) &&
9155         !NewFD->isInvalidDecl() &&
9156         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9157       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9158         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9159             << getCudaConfigureFuncName();
9160       Context.setcudaConfigureCallDecl(NewFD);
9161     }
9162 
9163     // Variadic functions, other than a *declaration* of printf, are not allowed
9164     // in device-side CUDA code, unless someone passed
9165     // -fcuda-allow-variadic-functions.
9166     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9167         (NewFD->hasAttr<CUDADeviceAttr>() ||
9168          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9169         !(II && II->isStr("printf") && NewFD->isExternC() &&
9170           !D.isFunctionDefinition())) {
9171       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9172     }
9173   }
9174 
9175   MarkUnusedFileScopedDecl(NewFD);
9176 
9177   if (getLangOpts().CPlusPlus) {
9178     if (FunctionTemplate) {
9179       if (NewFD->isInvalidDecl())
9180         FunctionTemplate->setInvalidDecl();
9181       return FunctionTemplate;
9182     }
9183 
9184     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9185       CompleteMemberSpecialization(NewFD, Previous);
9186   }
9187 
9188   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9189     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9190     if ((getLangOpts().OpenCLVersion >= 120)
9191         && (SC == SC_Static)) {
9192       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9193       D.setInvalidType();
9194     }
9195 
9196     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9197     if (!NewFD->getReturnType()->isVoidType()) {
9198       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9199       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9200           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9201                                 : FixItHint());
9202       D.setInvalidType();
9203     }
9204 
9205     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9206     for (auto Param : NewFD->parameters())
9207       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9208   }
9209   for (const ParmVarDecl *Param : NewFD->parameters()) {
9210     QualType PT = Param->getType();
9211 
9212     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9213     // types.
9214     if (getLangOpts().OpenCLVersion >= 200) {
9215       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9216         QualType ElemTy = PipeTy->getElementType();
9217           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9218             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9219             D.setInvalidType();
9220           }
9221       }
9222     }
9223   }
9224 
9225   // Here we have an function template explicit specialization at class scope.
9226   // The actual specialization will be postponed to template instatiation
9227   // time via the ClassScopeFunctionSpecializationDecl node.
9228   if (isDependentClassScopeExplicitSpecialization) {
9229     ClassScopeFunctionSpecializationDecl *NewSpec =
9230                          ClassScopeFunctionSpecializationDecl::Create(
9231                                 Context, CurContext, NewFD->getLocation(),
9232                                 cast<CXXMethodDecl>(NewFD),
9233                                 HasExplicitTemplateArgs, TemplateArgs);
9234     CurContext->addDecl(NewSpec);
9235     AddToScope = false;
9236   }
9237 
9238   // Diagnose availability attributes. Availability cannot be used on functions
9239   // that are run during load/unload.
9240   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9241     if (NewFD->hasAttr<ConstructorAttr>()) {
9242       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9243           << 1;
9244       NewFD->dropAttr<AvailabilityAttr>();
9245     }
9246     if (NewFD->hasAttr<DestructorAttr>()) {
9247       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9248           << 2;
9249       NewFD->dropAttr<AvailabilityAttr>();
9250     }
9251   }
9252 
9253   return NewFD;
9254 }
9255 
9256 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9257 /// when __declspec(code_seg) "is applied to a class, all member functions of
9258 /// the class and nested classes -- this includes compiler-generated special
9259 /// member functions -- are put in the specified segment."
9260 /// The actual behavior is a little more complicated. The Microsoft compiler
9261 /// won't check outer classes if there is an active value from #pragma code_seg.
9262 /// The CodeSeg is always applied from the direct parent but only from outer
9263 /// classes when the #pragma code_seg stack is empty. See:
9264 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9265 /// available since MS has removed the page.
9266 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9267   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9268   if (!Method)
9269     return nullptr;
9270   const CXXRecordDecl *Parent = Method->getParent();
9271   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9272     Attr *NewAttr = SAttr->clone(S.getASTContext());
9273     NewAttr->setImplicit(true);
9274     return NewAttr;
9275   }
9276 
9277   // The Microsoft compiler won't check outer classes for the CodeSeg
9278   // when the #pragma code_seg stack is active.
9279   if (S.CodeSegStack.CurrentValue)
9280    return nullptr;
9281 
9282   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9283     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9284       Attr *NewAttr = SAttr->clone(S.getASTContext());
9285       NewAttr->setImplicit(true);
9286       return NewAttr;
9287     }
9288   }
9289   return nullptr;
9290 }
9291 
9292 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9293 /// containing class. Otherwise it will return implicit SectionAttr if the
9294 /// function is a definition and there is an active value on CodeSegStack
9295 /// (from the current #pragma code-seg value).
9296 ///
9297 /// \param FD Function being declared.
9298 /// \param IsDefinition Whether it is a definition or just a declarartion.
9299 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9300 ///          nullptr if no attribute should be added.
9301 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9302                                                        bool IsDefinition) {
9303   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9304     return A;
9305   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9306       CodeSegStack.CurrentValue) {
9307     return SectionAttr::CreateImplicit(getASTContext(),
9308                                        SectionAttr::Declspec_allocate,
9309                                        CodeSegStack.CurrentValue->getString(),
9310                                        CodeSegStack.CurrentPragmaLocation);
9311   }
9312   return nullptr;
9313 }
9314 
9315 /// Determines if we can perform a correct type check for \p D as a
9316 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9317 /// best-effort check.
9318 ///
9319 /// \param NewD The new declaration.
9320 /// \param OldD The old declaration.
9321 /// \param NewT The portion of the type of the new declaration to check.
9322 /// \param OldT The portion of the type of the old declaration to check.
9323 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9324                                           QualType NewT, QualType OldT) {
9325   if (!NewD->getLexicalDeclContext()->isDependentContext())
9326     return true;
9327 
9328   // For dependently-typed local extern declarations and friends, we can't
9329   // perform a correct type check in general until instantiation:
9330   //
9331   //   int f();
9332   //   template<typename T> void g() { T f(); }
9333   //
9334   // (valid if g() is only instantiated with T = int).
9335   if (NewT->isDependentType() &&
9336       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9337     return false;
9338 
9339   // Similarly, if the previous declaration was a dependent local extern
9340   // declaration, we don't really know its type yet.
9341   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9342     return false;
9343 
9344   return true;
9345 }
9346 
9347 /// Checks if the new declaration declared in dependent context must be
9348 /// put in the same redeclaration chain as the specified declaration.
9349 ///
9350 /// \param D Declaration that is checked.
9351 /// \param PrevDecl Previous declaration found with proper lookup method for the
9352 ///                 same declaration name.
9353 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9354 ///          belongs to.
9355 ///
9356 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9357   if (!D->getLexicalDeclContext()->isDependentContext())
9358     return true;
9359 
9360   // Don't chain dependent friend function definitions until instantiation, to
9361   // permit cases like
9362   //
9363   //   void func();
9364   //   template<typename T> class C1 { friend void func() {} };
9365   //   template<typename T> class C2 { friend void func() {} };
9366   //
9367   // ... which is valid if only one of C1 and C2 is ever instantiated.
9368   //
9369   // FIXME: This need only apply to function definitions. For now, we proxy
9370   // this by checking for a file-scope function. We do not want this to apply
9371   // to friend declarations nominating member functions, because that gets in
9372   // the way of access checks.
9373   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9374     return false;
9375 
9376   auto *VD = dyn_cast<ValueDecl>(D);
9377   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9378   return !VD || !PrevVD ||
9379          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9380                                         PrevVD->getType());
9381 }
9382 
9383 /// Check the target attribute of the function for MultiVersion
9384 /// validity.
9385 ///
9386 /// Returns true if there was an error, false otherwise.
9387 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9388   const auto *TA = FD->getAttr<TargetAttr>();
9389   assert(TA && "MultiVersion Candidate requires a target attribute");
9390   TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9391   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9392   enum ErrType { Feature = 0, Architecture = 1 };
9393 
9394   if (!ParseInfo.Architecture.empty() &&
9395       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9396     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9397         << Architecture << ParseInfo.Architecture;
9398     return true;
9399   }
9400 
9401   for (const auto &Feat : ParseInfo.Features) {
9402     auto BareFeat = StringRef{Feat}.substr(1);
9403     if (Feat[0] == '-') {
9404       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9405           << Feature << ("no-" + BareFeat).str();
9406       return true;
9407     }
9408 
9409     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9410         !TargetInfo.isValidFeatureName(BareFeat)) {
9411       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9412           << Feature << BareFeat;
9413       return true;
9414     }
9415   }
9416   return false;
9417 }
9418 
9419 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9420                                          MultiVersionKind MVType) {
9421   for (const Attr *A : FD->attrs()) {
9422     switch (A->getKind()) {
9423     case attr::CPUDispatch:
9424     case attr::CPUSpecific:
9425       if (MVType != MultiVersionKind::CPUDispatch &&
9426           MVType != MultiVersionKind::CPUSpecific)
9427         return true;
9428       break;
9429     case attr::Target:
9430       if (MVType != MultiVersionKind::Target)
9431         return true;
9432       break;
9433     default:
9434       return true;
9435     }
9436   }
9437   return false;
9438 }
9439 
9440 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9441                                              const FunctionDecl *NewFD,
9442                                              bool CausesMV,
9443                                              MultiVersionKind MVType) {
9444   enum DoesntSupport {
9445     FuncTemplates = 0,
9446     VirtFuncs = 1,
9447     DeducedReturn = 2,
9448     Constructors = 3,
9449     Destructors = 4,
9450     DeletedFuncs = 5,
9451     DefaultedFuncs = 6,
9452     ConstexprFuncs = 7,
9453   };
9454   enum Different {
9455     CallingConv = 0,
9456     ReturnType = 1,
9457     ConstexprSpec = 2,
9458     InlineSpec = 3,
9459     StorageClass = 4,
9460     Linkage = 5
9461   };
9462 
9463   bool IsCPUSpecificCPUDispatchMVType =
9464       MVType == MultiVersionKind::CPUDispatch ||
9465       MVType == MultiVersionKind::CPUSpecific;
9466 
9467   if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
9468     S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
9469     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9470     return true;
9471   }
9472 
9473   if (!NewFD->getType()->getAs<FunctionProtoType>())
9474     return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
9475 
9476   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9477     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9478     if (OldFD)
9479       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9480     return true;
9481   }
9482 
9483   // For now, disallow all other attributes.  These should be opt-in, but
9484   // an analysis of all of them is a future FIXME.
9485   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
9486     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9487         << IsCPUSpecificCPUDispatchMVType;
9488     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9489     return true;
9490   }
9491 
9492   if (HasNonMultiVersionAttributes(NewFD, MVType))
9493     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9494            << IsCPUSpecificCPUDispatchMVType;
9495 
9496   if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9497     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9498            << IsCPUSpecificCPUDispatchMVType << FuncTemplates;
9499 
9500   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9501     if (NewCXXFD->isVirtual())
9502       return S.Diag(NewCXXFD->getLocation(),
9503                     diag::err_multiversion_doesnt_support)
9504              << IsCPUSpecificCPUDispatchMVType << VirtFuncs;
9505 
9506     if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
9507       return S.Diag(NewCXXCtor->getLocation(),
9508                     diag::err_multiversion_doesnt_support)
9509              << IsCPUSpecificCPUDispatchMVType << Constructors;
9510 
9511     if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
9512       return S.Diag(NewCXXDtor->getLocation(),
9513                     diag::err_multiversion_doesnt_support)
9514              << IsCPUSpecificCPUDispatchMVType << Destructors;
9515   }
9516 
9517   if (NewFD->isDeleted())
9518     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9519            << IsCPUSpecificCPUDispatchMVType << DeletedFuncs;
9520 
9521   if (NewFD->isDefaulted())
9522     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9523            << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs;
9524 
9525   if (NewFD->isConstexpr() && (MVType == MultiVersionKind::CPUDispatch ||
9526                                MVType == MultiVersionKind::CPUSpecific))
9527     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9528            << IsCPUSpecificCPUDispatchMVType << ConstexprFuncs;
9529 
9530   QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
9531   const auto *NewType = cast<FunctionType>(NewQType);
9532   QualType NewReturnType = NewType->getReturnType();
9533 
9534   if (NewReturnType->isUndeducedType())
9535     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9536            << IsCPUSpecificCPUDispatchMVType << DeducedReturn;
9537 
9538   // Only allow transition to MultiVersion if it hasn't been used.
9539   if (OldFD && CausesMV && OldFD->isUsed(false))
9540     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9541 
9542   // Ensure the return type is identical.
9543   if (OldFD) {
9544     QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
9545     const auto *OldType = cast<FunctionType>(OldQType);
9546     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9547     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9548 
9549     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9550       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9551              << CallingConv;
9552 
9553     QualType OldReturnType = OldType->getReturnType();
9554 
9555     if (OldReturnType != NewReturnType)
9556       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9557              << ReturnType;
9558 
9559     if (OldFD->isConstexpr() != NewFD->isConstexpr())
9560       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9561              << ConstexprSpec;
9562 
9563     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9564       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9565              << InlineSpec;
9566 
9567     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9568       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9569              << StorageClass;
9570 
9571     if (OldFD->isExternC() != NewFD->isExternC())
9572       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9573              << Linkage;
9574 
9575     if (S.CheckEquivalentExceptionSpec(
9576             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9577             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9578       return true;
9579   }
9580   return false;
9581 }
9582 
9583 /// Check the validity of a multiversion function declaration that is the
9584 /// first of its kind. Also sets the multiversion'ness' of the function itself.
9585 ///
9586 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9587 ///
9588 /// Returns true if there was an error, false otherwise.
9589 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
9590                                            MultiVersionKind MVType,
9591                                            const TargetAttr *TA,
9592                                            const CPUDispatchAttr *CPUDisp,
9593                                            const CPUSpecificAttr *CPUSpec) {
9594   assert(MVType != MultiVersionKind::None &&
9595          "Function lacks multiversion attribute");
9596 
9597   // Target only causes MV if it is default, otherwise this is a normal
9598   // function.
9599   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
9600     return false;
9601 
9602   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
9603     FD->setInvalidDecl();
9604     return true;
9605   }
9606 
9607   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
9608     FD->setInvalidDecl();
9609     return true;
9610   }
9611 
9612   FD->setIsMultiVersion();
9613   return false;
9614 }
9615 
9616 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
9617   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
9618     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
9619       return true;
9620   }
9621 
9622   return false;
9623 }
9624 
9625 static bool CheckTargetCausesMultiVersioning(
9626     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
9627     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9628     LookupResult &Previous) {
9629   const auto *OldTA = OldFD->getAttr<TargetAttr>();
9630   TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9631   // Sort order doesn't matter, it just needs to be consistent.
9632   llvm::sort(NewParsed.Features);
9633 
9634   // If the old decl is NOT MultiVersioned yet, and we don't cause that
9635   // to change, this is a simple redeclaration.
9636   if (!NewTA->isDefaultVersion() &&
9637       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
9638     return false;
9639 
9640   // Otherwise, this decl causes MultiVersioning.
9641   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9642     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9643     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9644     NewFD->setInvalidDecl();
9645     return true;
9646   }
9647 
9648   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
9649                                        MultiVersionKind::Target)) {
9650     NewFD->setInvalidDecl();
9651     return true;
9652   }
9653 
9654   if (CheckMultiVersionValue(S, NewFD)) {
9655     NewFD->setInvalidDecl();
9656     return true;
9657   }
9658 
9659   // If this is 'default', permit the forward declaration.
9660   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
9661     Redeclaration = true;
9662     OldDecl = OldFD;
9663     OldFD->setIsMultiVersion();
9664     NewFD->setIsMultiVersion();
9665     return false;
9666   }
9667 
9668   if (CheckMultiVersionValue(S, OldFD)) {
9669     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9670     NewFD->setInvalidDecl();
9671     return true;
9672   }
9673 
9674   TargetAttr::ParsedTargetAttr OldParsed =
9675       OldTA->parse(std::less<std::string>());
9676 
9677   if (OldParsed == NewParsed) {
9678     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9679     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9680     NewFD->setInvalidDecl();
9681     return true;
9682   }
9683 
9684   for (const auto *FD : OldFD->redecls()) {
9685     const auto *CurTA = FD->getAttr<TargetAttr>();
9686     // We allow forward declarations before ANY multiversioning attributes, but
9687     // nothing after the fact.
9688     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
9689         (!CurTA || CurTA->isInherited())) {
9690       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
9691           << 0;
9692       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9693       NewFD->setInvalidDecl();
9694       return true;
9695     }
9696   }
9697 
9698   OldFD->setIsMultiVersion();
9699   NewFD->setIsMultiVersion();
9700   Redeclaration = false;
9701   MergeTypeWithPrevious = false;
9702   OldDecl = nullptr;
9703   Previous.clear();
9704   return false;
9705 }
9706 
9707 /// Check the validity of a new function declaration being added to an existing
9708 /// multiversioned declaration collection.
9709 static bool CheckMultiVersionAdditionalDecl(
9710     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
9711     MultiVersionKind NewMVType, const TargetAttr *NewTA,
9712     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
9713     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9714     LookupResult &Previous) {
9715 
9716   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
9717   // Disallow mixing of multiversioning types.
9718   if ((OldMVType == MultiVersionKind::Target &&
9719        NewMVType != MultiVersionKind::Target) ||
9720       (NewMVType == MultiVersionKind::Target &&
9721        OldMVType != MultiVersionKind::Target)) {
9722     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9723     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9724     NewFD->setInvalidDecl();
9725     return true;
9726   }
9727 
9728   TargetAttr::ParsedTargetAttr NewParsed;
9729   if (NewTA) {
9730     NewParsed = NewTA->parse();
9731     llvm::sort(NewParsed.Features);
9732   }
9733 
9734   bool UseMemberUsingDeclRules =
9735       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
9736 
9737   // Next, check ALL non-overloads to see if this is a redeclaration of a
9738   // previous member of the MultiVersion set.
9739   for (NamedDecl *ND : Previous) {
9740     FunctionDecl *CurFD = ND->getAsFunction();
9741     if (!CurFD)
9742       continue;
9743     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
9744       continue;
9745 
9746     if (NewMVType == MultiVersionKind::Target) {
9747       const auto *CurTA = CurFD->getAttr<TargetAttr>();
9748       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
9749         NewFD->setIsMultiVersion();
9750         Redeclaration = true;
9751         OldDecl = ND;
9752         return false;
9753       }
9754 
9755       TargetAttr::ParsedTargetAttr CurParsed =
9756           CurTA->parse(std::less<std::string>());
9757       if (CurParsed == NewParsed) {
9758         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9759         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9760         NewFD->setInvalidDecl();
9761         return true;
9762       }
9763     } else {
9764       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
9765       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
9766       // Handle CPUDispatch/CPUSpecific versions.
9767       // Only 1 CPUDispatch function is allowed, this will make it go through
9768       // the redeclaration errors.
9769       if (NewMVType == MultiVersionKind::CPUDispatch &&
9770           CurFD->hasAttr<CPUDispatchAttr>()) {
9771         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
9772             std::equal(
9773                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
9774                 NewCPUDisp->cpus_begin(),
9775                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9776                   return Cur->getName() == New->getName();
9777                 })) {
9778           NewFD->setIsMultiVersion();
9779           Redeclaration = true;
9780           OldDecl = ND;
9781           return false;
9782         }
9783 
9784         // If the declarations don't match, this is an error condition.
9785         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
9786         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9787         NewFD->setInvalidDecl();
9788         return true;
9789       }
9790       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
9791 
9792         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
9793             std::equal(
9794                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
9795                 NewCPUSpec->cpus_begin(),
9796                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9797                   return Cur->getName() == New->getName();
9798                 })) {
9799           NewFD->setIsMultiVersion();
9800           Redeclaration = true;
9801           OldDecl = ND;
9802           return false;
9803         }
9804 
9805         // Only 1 version of CPUSpecific is allowed for each CPU.
9806         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
9807           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
9808             if (CurII == NewII) {
9809               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
9810                   << NewII;
9811               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9812               NewFD->setInvalidDecl();
9813               return true;
9814             }
9815           }
9816         }
9817       }
9818       // If the two decls aren't the same MVType, there is no possible error
9819       // condition.
9820     }
9821   }
9822 
9823   // Else, this is simply a non-redecl case.  Checking the 'value' is only
9824   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
9825   // handled in the attribute adding step.
9826   if (NewMVType == MultiVersionKind::Target &&
9827       CheckMultiVersionValue(S, NewFD)) {
9828     NewFD->setInvalidDecl();
9829     return true;
9830   }
9831 
9832   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
9833                                        !OldFD->isMultiVersion(), NewMVType)) {
9834     NewFD->setInvalidDecl();
9835     return true;
9836   }
9837 
9838   // Permit forward declarations in the case where these two are compatible.
9839   if (!OldFD->isMultiVersion()) {
9840     OldFD->setIsMultiVersion();
9841     NewFD->setIsMultiVersion();
9842     Redeclaration = true;
9843     OldDecl = OldFD;
9844     return false;
9845   }
9846 
9847   NewFD->setIsMultiVersion();
9848   Redeclaration = false;
9849   MergeTypeWithPrevious = false;
9850   OldDecl = nullptr;
9851   Previous.clear();
9852   return false;
9853 }
9854 
9855 
9856 /// Check the validity of a mulitversion function declaration.
9857 /// Also sets the multiversion'ness' of the function itself.
9858 ///
9859 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9860 ///
9861 /// Returns true if there was an error, false otherwise.
9862 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
9863                                       bool &Redeclaration, NamedDecl *&OldDecl,
9864                                       bool &MergeTypeWithPrevious,
9865                                       LookupResult &Previous) {
9866   const auto *NewTA = NewFD->getAttr<TargetAttr>();
9867   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
9868   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
9869 
9870   // Mixing Multiversioning types is prohibited.
9871   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
9872       (NewCPUDisp && NewCPUSpec)) {
9873     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9874     NewFD->setInvalidDecl();
9875     return true;
9876   }
9877 
9878   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
9879 
9880   // Main isn't allowed to become a multiversion function, however it IS
9881   // permitted to have 'main' be marked with the 'target' optimization hint.
9882   if (NewFD->isMain()) {
9883     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
9884         MVType == MultiVersionKind::CPUDispatch ||
9885         MVType == MultiVersionKind::CPUSpecific) {
9886       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
9887       NewFD->setInvalidDecl();
9888       return true;
9889     }
9890     return false;
9891   }
9892 
9893   if (!OldDecl || !OldDecl->getAsFunction() ||
9894       OldDecl->getDeclContext()->getRedeclContext() !=
9895           NewFD->getDeclContext()->getRedeclContext()) {
9896     // If there's no previous declaration, AND this isn't attempting to cause
9897     // multiversioning, this isn't an error condition.
9898     if (MVType == MultiVersionKind::None)
9899       return false;
9900     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA, NewCPUDisp,
9901                                           NewCPUSpec);
9902   }
9903 
9904   FunctionDecl *OldFD = OldDecl->getAsFunction();
9905 
9906   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
9907     return false;
9908 
9909   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
9910     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
9911         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
9912     NewFD->setInvalidDecl();
9913     return true;
9914   }
9915 
9916   // Handle the target potentially causes multiversioning case.
9917   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
9918     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
9919                                             Redeclaration, OldDecl,
9920                                             MergeTypeWithPrevious, Previous);
9921 
9922   // At this point, we have a multiversion function decl (in OldFD) AND an
9923   // appropriate attribute in the current function decl.  Resolve that these are
9924   // still compatible with previous declarations.
9925   return CheckMultiVersionAdditionalDecl(
9926       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
9927       OldDecl, MergeTypeWithPrevious, Previous);
9928 }
9929 
9930 /// Perform semantic checking of a new function declaration.
9931 ///
9932 /// Performs semantic analysis of the new function declaration
9933 /// NewFD. This routine performs all semantic checking that does not
9934 /// require the actual declarator involved in the declaration, and is
9935 /// used both for the declaration of functions as they are parsed
9936 /// (called via ActOnDeclarator) and for the declaration of functions
9937 /// that have been instantiated via C++ template instantiation (called
9938 /// via InstantiateDecl).
9939 ///
9940 /// \param IsMemberSpecialization whether this new function declaration is
9941 /// a member specialization (that replaces any definition provided by the
9942 /// previous declaration).
9943 ///
9944 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9945 ///
9946 /// \returns true if the function declaration is a redeclaration.
9947 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9948                                     LookupResult &Previous,
9949                                     bool IsMemberSpecialization) {
9950   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9951          "Variably modified return types are not handled here");
9952 
9953   // Determine whether the type of this function should be merged with
9954   // a previous visible declaration. This never happens for functions in C++,
9955   // and always happens in C if the previous declaration was visible.
9956   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9957                                !Previous.isShadowed();
9958 
9959   bool Redeclaration = false;
9960   NamedDecl *OldDecl = nullptr;
9961   bool MayNeedOverloadableChecks = false;
9962 
9963   // Merge or overload the declaration with an existing declaration of
9964   // the same name, if appropriate.
9965   if (!Previous.empty()) {
9966     // Determine whether NewFD is an overload of PrevDecl or
9967     // a declaration that requires merging. If it's an overload,
9968     // there's no more work to do here; we'll just add the new
9969     // function to the scope.
9970     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
9971       NamedDecl *Candidate = Previous.getRepresentativeDecl();
9972       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9973         Redeclaration = true;
9974         OldDecl = Candidate;
9975       }
9976     } else {
9977       MayNeedOverloadableChecks = true;
9978       switch (CheckOverload(S, NewFD, Previous, OldDecl,
9979                             /*NewIsUsingDecl*/ false)) {
9980       case Ovl_Match:
9981         Redeclaration = true;
9982         break;
9983 
9984       case Ovl_NonFunction:
9985         Redeclaration = true;
9986         break;
9987 
9988       case Ovl_Overload:
9989         Redeclaration = false;
9990         break;
9991       }
9992     }
9993   }
9994 
9995   // Check for a previous extern "C" declaration with this name.
9996   if (!Redeclaration &&
9997       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9998     if (!Previous.empty()) {
9999       // This is an extern "C" declaration with the same name as a previous
10000       // declaration, and thus redeclares that entity...
10001       Redeclaration = true;
10002       OldDecl = Previous.getFoundDecl();
10003       MergeTypeWithPrevious = false;
10004 
10005       // ... except in the presence of __attribute__((overloadable)).
10006       if (OldDecl->hasAttr<OverloadableAttr>() ||
10007           NewFD->hasAttr<OverloadableAttr>()) {
10008         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10009           MayNeedOverloadableChecks = true;
10010           Redeclaration = false;
10011           OldDecl = nullptr;
10012         }
10013       }
10014     }
10015   }
10016 
10017   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10018                                 MergeTypeWithPrevious, Previous))
10019     return Redeclaration;
10020 
10021   // C++11 [dcl.constexpr]p8:
10022   //   A constexpr specifier for a non-static member function that is not
10023   //   a constructor declares that member function to be const.
10024   //
10025   // This needs to be delayed until we know whether this is an out-of-line
10026   // definition of a static member function.
10027   //
10028   // This rule is not present in C++1y, so we produce a backwards
10029   // compatibility warning whenever it happens in C++11.
10030   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10031   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10032       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10033       !MD->getMethodQualifiers().hasConst()) {
10034     CXXMethodDecl *OldMD = nullptr;
10035     if (OldDecl)
10036       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10037     if (!OldMD || !OldMD->isStatic()) {
10038       const FunctionProtoType *FPT =
10039         MD->getType()->castAs<FunctionProtoType>();
10040       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10041       EPI.TypeQuals.addConst();
10042       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10043                                           FPT->getParamTypes(), EPI));
10044 
10045       // Warn that we did this, if we're not performing template instantiation.
10046       // In that case, we'll have warned already when the template was defined.
10047       if (!inTemplateInstantiation()) {
10048         SourceLocation AddConstLoc;
10049         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10050                 .IgnoreParens().getAs<FunctionTypeLoc>())
10051           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10052 
10053         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10054           << FixItHint::CreateInsertion(AddConstLoc, " const");
10055       }
10056     }
10057   }
10058 
10059   if (Redeclaration) {
10060     // NewFD and OldDecl represent declarations that need to be
10061     // merged.
10062     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10063       NewFD->setInvalidDecl();
10064       return Redeclaration;
10065     }
10066 
10067     Previous.clear();
10068     Previous.addDecl(OldDecl);
10069 
10070     if (FunctionTemplateDecl *OldTemplateDecl =
10071             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10072       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10073       FunctionTemplateDecl *NewTemplateDecl
10074         = NewFD->getDescribedFunctionTemplate();
10075       assert(NewTemplateDecl && "Template/non-template mismatch");
10076 
10077       // The call to MergeFunctionDecl above may have created some state in
10078       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10079       // can add it as a redeclaration.
10080       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10081 
10082       NewFD->setPreviousDeclaration(OldFD);
10083       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10084       if (NewFD->isCXXClassMember()) {
10085         NewFD->setAccess(OldTemplateDecl->getAccess());
10086         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10087       }
10088 
10089       // If this is an explicit specialization of a member that is a function
10090       // template, mark it as a member specialization.
10091       if (IsMemberSpecialization &&
10092           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10093         NewTemplateDecl->setMemberSpecialization();
10094         assert(OldTemplateDecl->isMemberSpecialization());
10095         // Explicit specializations of a member template do not inherit deleted
10096         // status from the parent member template that they are specializing.
10097         if (OldFD->isDeleted()) {
10098           // FIXME: This assert will not hold in the presence of modules.
10099           assert(OldFD->getCanonicalDecl() == OldFD);
10100           // FIXME: We need an update record for this AST mutation.
10101           OldFD->setDeletedAsWritten(false);
10102         }
10103       }
10104 
10105     } else {
10106       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10107         auto *OldFD = cast<FunctionDecl>(OldDecl);
10108         // This needs to happen first so that 'inline' propagates.
10109         NewFD->setPreviousDeclaration(OldFD);
10110         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10111         if (NewFD->isCXXClassMember())
10112           NewFD->setAccess(OldFD->getAccess());
10113       }
10114     }
10115   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10116              !NewFD->getAttr<OverloadableAttr>()) {
10117     assert((Previous.empty() ||
10118             llvm::any_of(Previous,
10119                          [](const NamedDecl *ND) {
10120                            return ND->hasAttr<OverloadableAttr>();
10121                          })) &&
10122            "Non-redecls shouldn't happen without overloadable present");
10123 
10124     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10125       const auto *FD = dyn_cast<FunctionDecl>(ND);
10126       return FD && !FD->hasAttr<OverloadableAttr>();
10127     });
10128 
10129     if (OtherUnmarkedIter != Previous.end()) {
10130       Diag(NewFD->getLocation(),
10131            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10132       Diag((*OtherUnmarkedIter)->getLocation(),
10133            diag::note_attribute_overloadable_prev_overload)
10134           << false;
10135 
10136       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10137     }
10138   }
10139 
10140   // Semantic checking for this function declaration (in isolation).
10141 
10142   if (getLangOpts().CPlusPlus) {
10143     // C++-specific checks.
10144     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10145       CheckConstructor(Constructor);
10146     } else if (CXXDestructorDecl *Destructor =
10147                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10148       CXXRecordDecl *Record = Destructor->getParent();
10149       QualType ClassType = Context.getTypeDeclType(Record);
10150 
10151       // FIXME: Shouldn't we be able to perform this check even when the class
10152       // type is dependent? Both gcc and edg can handle that.
10153       if (!ClassType->isDependentType()) {
10154         DeclarationName Name
10155           = Context.DeclarationNames.getCXXDestructorName(
10156                                         Context.getCanonicalType(ClassType));
10157         if (NewFD->getDeclName() != Name) {
10158           Diag(NewFD->getLocation(), diag::err_destructor_name);
10159           NewFD->setInvalidDecl();
10160           return Redeclaration;
10161         }
10162       }
10163     } else if (CXXConversionDecl *Conversion
10164                = dyn_cast<CXXConversionDecl>(NewFD)) {
10165       ActOnConversionDeclarator(Conversion);
10166     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10167       if (auto *TD = Guide->getDescribedFunctionTemplate())
10168         CheckDeductionGuideTemplate(TD);
10169 
10170       // A deduction guide is not on the list of entities that can be
10171       // explicitly specialized.
10172       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10173         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10174             << /*explicit specialization*/ 1;
10175     }
10176 
10177     // Find any virtual functions that this function overrides.
10178     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10179       if (!Method->isFunctionTemplateSpecialization() &&
10180           !Method->getDescribedFunctionTemplate() &&
10181           Method->isCanonicalDecl()) {
10182         if (AddOverriddenMethods(Method->getParent(), Method)) {
10183           // If the function was marked as "static", we have a problem.
10184           if (NewFD->getStorageClass() == SC_Static) {
10185             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10186           }
10187         }
10188       }
10189 
10190       if (Method->isStatic())
10191         checkThisInStaticMemberFunctionType(Method);
10192     }
10193 
10194     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10195     if (NewFD->isOverloadedOperator() &&
10196         CheckOverloadedOperatorDeclaration(NewFD)) {
10197       NewFD->setInvalidDecl();
10198       return Redeclaration;
10199     }
10200 
10201     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10202     if (NewFD->getLiteralIdentifier() &&
10203         CheckLiteralOperatorDeclaration(NewFD)) {
10204       NewFD->setInvalidDecl();
10205       return Redeclaration;
10206     }
10207 
10208     // In C++, check default arguments now that we have merged decls. Unless
10209     // the lexical context is the class, because in this case this is done
10210     // during delayed parsing anyway.
10211     if (!CurContext->isRecord())
10212       CheckCXXDefaultArguments(NewFD);
10213 
10214     // If this function declares a builtin function, check the type of this
10215     // declaration against the expected type for the builtin.
10216     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10217       ASTContext::GetBuiltinTypeError Error;
10218       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10219       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10220       // If the type of the builtin differs only in its exception
10221       // specification, that's OK.
10222       // FIXME: If the types do differ in this way, it would be better to
10223       // retain the 'noexcept' form of the type.
10224       if (!T.isNull() &&
10225           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10226                                                             NewFD->getType()))
10227         // The type of this function differs from the type of the builtin,
10228         // so forget about the builtin entirely.
10229         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10230     }
10231 
10232     // If this function is declared as being extern "C", then check to see if
10233     // the function returns a UDT (class, struct, or union type) that is not C
10234     // compatible, and if it does, warn the user.
10235     // But, issue any diagnostic on the first declaration only.
10236     if (Previous.empty() && NewFD->isExternC()) {
10237       QualType R = NewFD->getReturnType();
10238       if (R->isIncompleteType() && !R->isVoidType())
10239         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10240             << NewFD << R;
10241       else if (!R.isPODType(Context) && !R->isVoidType() &&
10242                !R->isObjCObjectPointerType())
10243         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10244     }
10245 
10246     // C++1z [dcl.fct]p6:
10247     //   [...] whether the function has a non-throwing exception-specification
10248     //   [is] part of the function type
10249     //
10250     // This results in an ABI break between C++14 and C++17 for functions whose
10251     // declared type includes an exception-specification in a parameter or
10252     // return type. (Exception specifications on the function itself are OK in
10253     // most cases, and exception specifications are not permitted in most other
10254     // contexts where they could make it into a mangling.)
10255     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10256       auto HasNoexcept = [&](QualType T) -> bool {
10257         // Strip off declarator chunks that could be between us and a function
10258         // type. We don't need to look far, exception specifications are very
10259         // restricted prior to C++17.
10260         if (auto *RT = T->getAs<ReferenceType>())
10261           T = RT->getPointeeType();
10262         else if (T->isAnyPointerType())
10263           T = T->getPointeeType();
10264         else if (auto *MPT = T->getAs<MemberPointerType>())
10265           T = MPT->getPointeeType();
10266         if (auto *FPT = T->getAs<FunctionProtoType>())
10267           if (FPT->isNothrow())
10268             return true;
10269         return false;
10270       };
10271 
10272       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10273       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10274       for (QualType T : FPT->param_types())
10275         AnyNoexcept |= HasNoexcept(T);
10276       if (AnyNoexcept)
10277         Diag(NewFD->getLocation(),
10278              diag::warn_cxx17_compat_exception_spec_in_signature)
10279             << NewFD;
10280     }
10281 
10282     if (!Redeclaration && LangOpts.CUDA)
10283       checkCUDATargetOverload(NewFD, Previous);
10284   }
10285   return Redeclaration;
10286 }
10287 
10288 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10289   // C++11 [basic.start.main]p3:
10290   //   A program that [...] declares main to be inline, static or
10291   //   constexpr is ill-formed.
10292   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10293   //   appear in a declaration of main.
10294   // static main is not an error under C99, but we should warn about it.
10295   // We accept _Noreturn main as an extension.
10296   if (FD->getStorageClass() == SC_Static)
10297     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10298          ? diag::err_static_main : diag::warn_static_main)
10299       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10300   if (FD->isInlineSpecified())
10301     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10302       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10303   if (DS.isNoreturnSpecified()) {
10304     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10305     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10306     Diag(NoreturnLoc, diag::ext_noreturn_main);
10307     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10308       << FixItHint::CreateRemoval(NoreturnRange);
10309   }
10310   if (FD->isConstexpr()) {
10311     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10312       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10313     FD->setConstexpr(false);
10314   }
10315 
10316   if (getLangOpts().OpenCL) {
10317     Diag(FD->getLocation(), diag::err_opencl_no_main)
10318         << FD->hasAttr<OpenCLKernelAttr>();
10319     FD->setInvalidDecl();
10320     return;
10321   }
10322 
10323   QualType T = FD->getType();
10324   assert(T->isFunctionType() && "function decl is not of function type");
10325   const FunctionType* FT = T->castAs<FunctionType>();
10326 
10327   // Set default calling convention for main()
10328   if (FT->getCallConv() != CC_C) {
10329     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10330     FD->setType(QualType(FT, 0));
10331     T = Context.getCanonicalType(FD->getType());
10332   }
10333 
10334   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10335     // In C with GNU extensions we allow main() to have non-integer return
10336     // type, but we should warn about the extension, and we disable the
10337     // implicit-return-zero rule.
10338 
10339     // GCC in C mode accepts qualified 'int'.
10340     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10341       FD->setHasImplicitReturnZero(true);
10342     else {
10343       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10344       SourceRange RTRange = FD->getReturnTypeSourceRange();
10345       if (RTRange.isValid())
10346         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10347             << FixItHint::CreateReplacement(RTRange, "int");
10348     }
10349   } else {
10350     // In C and C++, main magically returns 0 if you fall off the end;
10351     // set the flag which tells us that.
10352     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10353 
10354     // All the standards say that main() should return 'int'.
10355     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10356       FD->setHasImplicitReturnZero(true);
10357     else {
10358       // Otherwise, this is just a flat-out error.
10359       SourceRange RTRange = FD->getReturnTypeSourceRange();
10360       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10361           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10362                                 : FixItHint());
10363       FD->setInvalidDecl(true);
10364     }
10365   }
10366 
10367   // Treat protoless main() as nullary.
10368   if (isa<FunctionNoProtoType>(FT)) return;
10369 
10370   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10371   unsigned nparams = FTP->getNumParams();
10372   assert(FD->getNumParams() == nparams);
10373 
10374   bool HasExtraParameters = (nparams > 3);
10375 
10376   if (FTP->isVariadic()) {
10377     Diag(FD->getLocation(), diag::ext_variadic_main);
10378     // FIXME: if we had information about the location of the ellipsis, we
10379     // could add a FixIt hint to remove it as a parameter.
10380   }
10381 
10382   // Darwin passes an undocumented fourth argument of type char**.  If
10383   // other platforms start sprouting these, the logic below will start
10384   // getting shifty.
10385   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10386     HasExtraParameters = false;
10387 
10388   if (HasExtraParameters) {
10389     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10390     FD->setInvalidDecl(true);
10391     nparams = 3;
10392   }
10393 
10394   // FIXME: a lot of the following diagnostics would be improved
10395   // if we had some location information about types.
10396 
10397   QualType CharPP =
10398     Context.getPointerType(Context.getPointerType(Context.CharTy));
10399   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10400 
10401   for (unsigned i = 0; i < nparams; ++i) {
10402     QualType AT = FTP->getParamType(i);
10403 
10404     bool mismatch = true;
10405 
10406     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10407       mismatch = false;
10408     else if (Expected[i] == CharPP) {
10409       // As an extension, the following forms are okay:
10410       //   char const **
10411       //   char const * const *
10412       //   char * const *
10413 
10414       QualifierCollector qs;
10415       const PointerType* PT;
10416       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10417           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10418           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10419                               Context.CharTy)) {
10420         qs.removeConst();
10421         mismatch = !qs.empty();
10422       }
10423     }
10424 
10425     if (mismatch) {
10426       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10427       // TODO: suggest replacing given type with expected type
10428       FD->setInvalidDecl(true);
10429     }
10430   }
10431 
10432   if (nparams == 1 && !FD->isInvalidDecl()) {
10433     Diag(FD->getLocation(), diag::warn_main_one_arg);
10434   }
10435 
10436   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10437     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10438     FD->setInvalidDecl();
10439   }
10440 }
10441 
10442 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10443   QualType T = FD->getType();
10444   assert(T->isFunctionType() && "function decl is not of function type");
10445   const FunctionType *FT = T->castAs<FunctionType>();
10446 
10447   // Set an implicit return of 'zero' if the function can return some integral,
10448   // enumeration, pointer or nullptr type.
10449   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10450       FT->getReturnType()->isAnyPointerType() ||
10451       FT->getReturnType()->isNullPtrType())
10452     // DllMain is exempt because a return value of zero means it failed.
10453     if (FD->getName() != "DllMain")
10454       FD->setHasImplicitReturnZero(true);
10455 
10456   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10457     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10458     FD->setInvalidDecl();
10459   }
10460 }
10461 
10462 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10463   // FIXME: Need strict checking.  In C89, we need to check for
10464   // any assignment, increment, decrement, function-calls, or
10465   // commas outside of a sizeof.  In C99, it's the same list,
10466   // except that the aforementioned are allowed in unevaluated
10467   // expressions.  Everything else falls under the
10468   // "may accept other forms of constant expressions" exception.
10469   // (We never end up here for C++, so the constant expression
10470   // rules there don't matter.)
10471   const Expr *Culprit;
10472   if (Init->isConstantInitializer(Context, false, &Culprit))
10473     return false;
10474   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10475     << Culprit->getSourceRange();
10476   return true;
10477 }
10478 
10479 namespace {
10480   // Visits an initialization expression to see if OrigDecl is evaluated in
10481   // its own initialization and throws a warning if it does.
10482   class SelfReferenceChecker
10483       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10484     Sema &S;
10485     Decl *OrigDecl;
10486     bool isRecordType;
10487     bool isPODType;
10488     bool isReferenceType;
10489 
10490     bool isInitList;
10491     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10492 
10493   public:
10494     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10495 
10496     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10497                                                     S(S), OrigDecl(OrigDecl) {
10498       isPODType = false;
10499       isRecordType = false;
10500       isReferenceType = false;
10501       isInitList = false;
10502       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10503         isPODType = VD->getType().isPODType(S.Context);
10504         isRecordType = VD->getType()->isRecordType();
10505         isReferenceType = VD->getType()->isReferenceType();
10506       }
10507     }
10508 
10509     // For most expressions, just call the visitor.  For initializer lists,
10510     // track the index of the field being initialized since fields are
10511     // initialized in order allowing use of previously initialized fields.
10512     void CheckExpr(Expr *E) {
10513       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10514       if (!InitList) {
10515         Visit(E);
10516         return;
10517       }
10518 
10519       // Track and increment the index here.
10520       isInitList = true;
10521       InitFieldIndex.push_back(0);
10522       for (auto Child : InitList->children()) {
10523         CheckExpr(cast<Expr>(Child));
10524         ++InitFieldIndex.back();
10525       }
10526       InitFieldIndex.pop_back();
10527     }
10528 
10529     // Returns true if MemberExpr is checked and no further checking is needed.
10530     // Returns false if additional checking is required.
10531     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10532       llvm::SmallVector<FieldDecl*, 4> Fields;
10533       Expr *Base = E;
10534       bool ReferenceField = false;
10535 
10536       // Get the field members used.
10537       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10538         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10539         if (!FD)
10540           return false;
10541         Fields.push_back(FD);
10542         if (FD->getType()->isReferenceType())
10543           ReferenceField = true;
10544         Base = ME->getBase()->IgnoreParenImpCasts();
10545       }
10546 
10547       // Keep checking only if the base Decl is the same.
10548       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10549       if (!DRE || DRE->getDecl() != OrigDecl)
10550         return false;
10551 
10552       // A reference field can be bound to an unininitialized field.
10553       if (CheckReference && !ReferenceField)
10554         return true;
10555 
10556       // Convert FieldDecls to their index number.
10557       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10558       for (const FieldDecl *I : llvm::reverse(Fields))
10559         UsedFieldIndex.push_back(I->getFieldIndex());
10560 
10561       // See if a warning is needed by checking the first difference in index
10562       // numbers.  If field being used has index less than the field being
10563       // initialized, then the use is safe.
10564       for (auto UsedIter = UsedFieldIndex.begin(),
10565                 UsedEnd = UsedFieldIndex.end(),
10566                 OrigIter = InitFieldIndex.begin(),
10567                 OrigEnd = InitFieldIndex.end();
10568            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10569         if (*UsedIter < *OrigIter)
10570           return true;
10571         if (*UsedIter > *OrigIter)
10572           break;
10573       }
10574 
10575       // TODO: Add a different warning which will print the field names.
10576       HandleDeclRefExpr(DRE);
10577       return true;
10578     }
10579 
10580     // For most expressions, the cast is directly above the DeclRefExpr.
10581     // For conditional operators, the cast can be outside the conditional
10582     // operator if both expressions are DeclRefExpr's.
10583     void HandleValue(Expr *E) {
10584       E = E->IgnoreParens();
10585       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10586         HandleDeclRefExpr(DRE);
10587         return;
10588       }
10589 
10590       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10591         Visit(CO->getCond());
10592         HandleValue(CO->getTrueExpr());
10593         HandleValue(CO->getFalseExpr());
10594         return;
10595       }
10596 
10597       if (BinaryConditionalOperator *BCO =
10598               dyn_cast<BinaryConditionalOperator>(E)) {
10599         Visit(BCO->getCond());
10600         HandleValue(BCO->getFalseExpr());
10601         return;
10602       }
10603 
10604       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10605         HandleValue(OVE->getSourceExpr());
10606         return;
10607       }
10608 
10609       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10610         if (BO->getOpcode() == BO_Comma) {
10611           Visit(BO->getLHS());
10612           HandleValue(BO->getRHS());
10613           return;
10614         }
10615       }
10616 
10617       if (isa<MemberExpr>(E)) {
10618         if (isInitList) {
10619           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10620                                       false /*CheckReference*/))
10621             return;
10622         }
10623 
10624         Expr *Base = E->IgnoreParenImpCasts();
10625         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10626           // Check for static member variables and don't warn on them.
10627           if (!isa<FieldDecl>(ME->getMemberDecl()))
10628             return;
10629           Base = ME->getBase()->IgnoreParenImpCasts();
10630         }
10631         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10632           HandleDeclRefExpr(DRE);
10633         return;
10634       }
10635 
10636       Visit(E);
10637     }
10638 
10639     // Reference types not handled in HandleValue are handled here since all
10640     // uses of references are bad, not just r-value uses.
10641     void VisitDeclRefExpr(DeclRefExpr *E) {
10642       if (isReferenceType)
10643         HandleDeclRefExpr(E);
10644     }
10645 
10646     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10647       if (E->getCastKind() == CK_LValueToRValue) {
10648         HandleValue(E->getSubExpr());
10649         return;
10650       }
10651 
10652       Inherited::VisitImplicitCastExpr(E);
10653     }
10654 
10655     void VisitMemberExpr(MemberExpr *E) {
10656       if (isInitList) {
10657         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
10658           return;
10659       }
10660 
10661       // Don't warn on arrays since they can be treated as pointers.
10662       if (E->getType()->canDecayToPointerType()) return;
10663 
10664       // Warn when a non-static method call is followed by non-static member
10665       // field accesses, which is followed by a DeclRefExpr.
10666       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10667       bool Warn = (MD && !MD->isStatic());
10668       Expr *Base = E->getBase()->IgnoreParenImpCasts();
10669       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10670         if (!isa<FieldDecl>(ME->getMemberDecl()))
10671           Warn = false;
10672         Base = ME->getBase()->IgnoreParenImpCasts();
10673       }
10674 
10675       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10676         if (Warn)
10677           HandleDeclRefExpr(DRE);
10678         return;
10679       }
10680 
10681       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10682       // Visit that expression.
10683       Visit(Base);
10684     }
10685 
10686     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10687       Expr *Callee = E->getCallee();
10688 
10689       if (isa<UnresolvedLookupExpr>(Callee))
10690         return Inherited::VisitCXXOperatorCallExpr(E);
10691 
10692       Visit(Callee);
10693       for (auto Arg: E->arguments())
10694         HandleValue(Arg->IgnoreParenImpCasts());
10695     }
10696 
10697     void VisitUnaryOperator(UnaryOperator *E) {
10698       // For POD record types, addresses of its own members are well-defined.
10699       if (E->getOpcode() == UO_AddrOf && isRecordType &&
10700           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
10701         if (!isPODType)
10702           HandleValue(E->getSubExpr());
10703         return;
10704       }
10705 
10706       if (E->isIncrementDecrementOp()) {
10707         HandleValue(E->getSubExpr());
10708         return;
10709       }
10710 
10711       Inherited::VisitUnaryOperator(E);
10712     }
10713 
10714     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
10715 
10716     void VisitCXXConstructExpr(CXXConstructExpr *E) {
10717       if (E->getConstructor()->isCopyConstructor()) {
10718         Expr *ArgExpr = E->getArg(0);
10719         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
10720           if (ILE->getNumInits() == 1)
10721             ArgExpr = ILE->getInit(0);
10722         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
10723           if (ICE->getCastKind() == CK_NoOp)
10724             ArgExpr = ICE->getSubExpr();
10725         HandleValue(ArgExpr);
10726         return;
10727       }
10728       Inherited::VisitCXXConstructExpr(E);
10729     }
10730 
10731     void VisitCallExpr(CallExpr *E) {
10732       // Treat std::move as a use.
10733       if (E->isCallToStdMove()) {
10734         HandleValue(E->getArg(0));
10735         return;
10736       }
10737 
10738       Inherited::VisitCallExpr(E);
10739     }
10740 
10741     void VisitBinaryOperator(BinaryOperator *E) {
10742       if (E->isCompoundAssignmentOp()) {
10743         HandleValue(E->getLHS());
10744         Visit(E->getRHS());
10745         return;
10746       }
10747 
10748       Inherited::VisitBinaryOperator(E);
10749     }
10750 
10751     // A custom visitor for BinaryConditionalOperator is needed because the
10752     // regular visitor would check the condition and true expression separately
10753     // but both point to the same place giving duplicate diagnostics.
10754     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10755       Visit(E->getCond());
10756       Visit(E->getFalseExpr());
10757     }
10758 
10759     void HandleDeclRefExpr(DeclRefExpr *DRE) {
10760       Decl* ReferenceDecl = DRE->getDecl();
10761       if (OrigDecl != ReferenceDecl) return;
10762       unsigned diag;
10763       if (isReferenceType) {
10764         diag = diag::warn_uninit_self_reference_in_reference_init;
10765       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10766         diag = diag::warn_static_self_reference_in_init;
10767       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10768                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10769                  DRE->getDecl()->getType()->isRecordType()) {
10770         diag = diag::warn_uninit_self_reference_in_init;
10771       } else {
10772         // Local variables will be handled by the CFG analysis.
10773         return;
10774       }
10775 
10776       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
10777                             S.PDiag(diag)
10778                                 << DRE->getDecl() << OrigDecl->getLocation()
10779                                 << DRE->getSourceRange());
10780     }
10781   };
10782 
10783   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10784   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10785                                  bool DirectInit) {
10786     // Parameters arguments are occassionially constructed with itself,
10787     // for instance, in recursive functions.  Skip them.
10788     if (isa<ParmVarDecl>(OrigDecl))
10789       return;
10790 
10791     E = E->IgnoreParens();
10792 
10793     // Skip checking T a = a where T is not a record or reference type.
10794     // Doing so is a way to silence uninitialized warnings.
10795     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10796       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10797         if (ICE->getCastKind() == CK_LValueToRValue)
10798           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10799             if (DRE->getDecl() == OrigDecl)
10800               return;
10801 
10802     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10803   }
10804 } // end anonymous namespace
10805 
10806 namespace {
10807   // Simple wrapper to add the name of a variable or (if no variable is
10808   // available) a DeclarationName into a diagnostic.
10809   struct VarDeclOrName {
10810     VarDecl *VDecl;
10811     DeclarationName Name;
10812 
10813     friend const Sema::SemaDiagnosticBuilder &
10814     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10815       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10816     }
10817   };
10818 } // end anonymous namespace
10819 
10820 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10821                                             DeclarationName Name, QualType Type,
10822                                             TypeSourceInfo *TSI,
10823                                             SourceRange Range, bool DirectInit,
10824                                             Expr *&Init) {
10825   bool IsInitCapture = !VDecl;
10826   assert((!VDecl || !VDecl->isInitCapture()) &&
10827          "init captures are expected to be deduced prior to initialization");
10828 
10829   VarDeclOrName VN{VDecl, Name};
10830 
10831   DeducedType *Deduced = Type->getContainedDeducedType();
10832   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10833 
10834   // C++11 [dcl.spec.auto]p3
10835   if (!Init) {
10836     assert(VDecl && "no init for init capture deduction?");
10837 
10838     // Except for class argument deduction, and then for an initializing
10839     // declaration only, i.e. no static at class scope or extern.
10840     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
10841         VDecl->hasExternalStorage() ||
10842         VDecl->isStaticDataMember()) {
10843       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10844         << VDecl->getDeclName() << Type;
10845       return QualType();
10846     }
10847   }
10848 
10849   ArrayRef<Expr*> DeduceInits;
10850   if (Init)
10851     DeduceInits = Init;
10852 
10853   if (DirectInit) {
10854     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10855       DeduceInits = PL->exprs();
10856   }
10857 
10858   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10859     assert(VDecl && "non-auto type for init capture deduction?");
10860     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10861     InitializationKind Kind = InitializationKind::CreateForInit(
10862         VDecl->getLocation(), DirectInit, Init);
10863     // FIXME: Initialization should not be taking a mutable list of inits.
10864     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10865     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10866                                                        InitsCopy);
10867   }
10868 
10869   if (DirectInit) {
10870     if (auto *IL = dyn_cast<InitListExpr>(Init))
10871       DeduceInits = IL->inits();
10872   }
10873 
10874   // Deduction only works if we have exactly one source expression.
10875   if (DeduceInits.empty()) {
10876     // It isn't possible to write this directly, but it is possible to
10877     // end up in this situation with "auto x(some_pack...);"
10878     Diag(Init->getBeginLoc(), IsInitCapture
10879                                   ? diag::err_init_capture_no_expression
10880                                   : diag::err_auto_var_init_no_expression)
10881         << VN << Type << Range;
10882     return QualType();
10883   }
10884 
10885   if (DeduceInits.size() > 1) {
10886     Diag(DeduceInits[1]->getBeginLoc(),
10887          IsInitCapture ? diag::err_init_capture_multiple_expressions
10888                        : diag::err_auto_var_init_multiple_expressions)
10889         << VN << Type << Range;
10890     return QualType();
10891   }
10892 
10893   Expr *DeduceInit = DeduceInits[0];
10894   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10895     Diag(Init->getBeginLoc(), IsInitCapture
10896                                   ? diag::err_init_capture_paren_braces
10897                                   : diag::err_auto_var_init_paren_braces)
10898         << isa<InitListExpr>(Init) << VN << Type << Range;
10899     return QualType();
10900   }
10901 
10902   // Expressions default to 'id' when we're in a debugger.
10903   bool DefaultedAnyToId = false;
10904   if (getLangOpts().DebuggerCastResultToId &&
10905       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10906     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10907     if (Result.isInvalid()) {
10908       return QualType();
10909     }
10910     Init = Result.get();
10911     DefaultedAnyToId = true;
10912   }
10913 
10914   // C++ [dcl.decomp]p1:
10915   //   If the assignment-expression [...] has array type A and no ref-qualifier
10916   //   is present, e has type cv A
10917   if (VDecl && isa<DecompositionDecl>(VDecl) &&
10918       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10919       DeduceInit->getType()->isConstantArrayType())
10920     return Context.getQualifiedType(DeduceInit->getType(),
10921                                     Type.getQualifiers());
10922 
10923   QualType DeducedType;
10924   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
10925     if (!IsInitCapture)
10926       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
10927     else if (isa<InitListExpr>(Init))
10928       Diag(Range.getBegin(),
10929            diag::err_init_capture_deduction_failure_from_init_list)
10930           << VN
10931           << (DeduceInit->getType().isNull() ? TSI->getType()
10932                                              : DeduceInit->getType())
10933           << DeduceInit->getSourceRange();
10934     else
10935       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10936           << VN << TSI->getType()
10937           << (DeduceInit->getType().isNull() ? TSI->getType()
10938                                              : DeduceInit->getType())
10939           << DeduceInit->getSourceRange();
10940   } else
10941     Init = DeduceInit;
10942 
10943   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10944   // 'id' instead of a specific object type prevents most of our usual
10945   // checks.
10946   // We only want to warn outside of template instantiations, though:
10947   // inside a template, the 'id' could have come from a parameter.
10948   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10949       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10950     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10951     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10952   }
10953 
10954   return DeducedType;
10955 }
10956 
10957 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
10958                                          Expr *&Init) {
10959   QualType DeducedType = deduceVarTypeFromInitializer(
10960       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10961       VDecl->getSourceRange(), DirectInit, Init);
10962   if (DeducedType.isNull()) {
10963     VDecl->setInvalidDecl();
10964     return true;
10965   }
10966 
10967   VDecl->setType(DeducedType);
10968   assert(VDecl->isLinkageValid());
10969 
10970   // In ARC, infer lifetime.
10971   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10972     VDecl->setInvalidDecl();
10973 
10974   // If this is a redeclaration, check that the type we just deduced matches
10975   // the previously declared type.
10976   if (VarDecl *Old = VDecl->getPreviousDecl()) {
10977     // We never need to merge the type, because we cannot form an incomplete
10978     // array of auto, nor deduce such a type.
10979     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
10980   }
10981 
10982   // Check the deduced type is valid for a variable declaration.
10983   CheckVariableDeclarationType(VDecl);
10984   return VDecl->isInvalidDecl();
10985 }
10986 
10987 /// AddInitializerToDecl - Adds the initializer Init to the
10988 /// declaration dcl. If DirectInit is true, this is C++ direct
10989 /// initialization rather than copy initialization.
10990 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10991   // If there is no declaration, there was an error parsing it.  Just ignore
10992   // the initializer.
10993   if (!RealDecl || RealDecl->isInvalidDecl()) {
10994     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10995     return;
10996   }
10997 
10998   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10999     // Pure-specifiers are handled in ActOnPureSpecifier.
11000     Diag(Method->getLocation(), diag::err_member_function_initialization)
11001       << Method->getDeclName() << Init->getSourceRange();
11002     Method->setInvalidDecl();
11003     return;
11004   }
11005 
11006   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11007   if (!VDecl) {
11008     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11009     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11010     RealDecl->setInvalidDecl();
11011     return;
11012   }
11013 
11014   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11015   if (VDecl->getType()->isUndeducedType()) {
11016     // Attempt typo correction early so that the type of the init expression can
11017     // be deduced based on the chosen correction if the original init contains a
11018     // TypoExpr.
11019     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11020     if (!Res.isUsable()) {
11021       RealDecl->setInvalidDecl();
11022       return;
11023     }
11024     Init = Res.get();
11025 
11026     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11027       return;
11028   }
11029 
11030   // dllimport cannot be used on variable definitions.
11031   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11032     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11033     VDecl->setInvalidDecl();
11034     return;
11035   }
11036 
11037   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11038     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11039     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11040     VDecl->setInvalidDecl();
11041     return;
11042   }
11043 
11044   if (!VDecl->getType()->isDependentType()) {
11045     // A definition must end up with a complete type, which means it must be
11046     // complete with the restriction that an array type might be completed by
11047     // the initializer; note that later code assumes this restriction.
11048     QualType BaseDeclType = VDecl->getType();
11049     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11050       BaseDeclType = Array->getElementType();
11051     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11052                             diag::err_typecheck_decl_incomplete_type)) {
11053       RealDecl->setInvalidDecl();
11054       return;
11055     }
11056 
11057     // The variable can not have an abstract class type.
11058     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11059                                diag::err_abstract_type_in_decl,
11060                                AbstractVariableType))
11061       VDecl->setInvalidDecl();
11062   }
11063 
11064   // If adding the initializer will turn this declaration into a definition,
11065   // and we already have a definition for this variable, diagnose or otherwise
11066   // handle the situation.
11067   VarDecl *Def;
11068   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11069       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11070       !VDecl->isThisDeclarationADemotedDefinition() &&
11071       checkVarDeclRedefinition(Def, VDecl))
11072     return;
11073 
11074   if (getLangOpts().CPlusPlus) {
11075     // C++ [class.static.data]p4
11076     //   If a static data member is of const integral or const
11077     //   enumeration type, its declaration in the class definition can
11078     //   specify a constant-initializer which shall be an integral
11079     //   constant expression (5.19). In that case, the member can appear
11080     //   in integral constant expressions. The member shall still be
11081     //   defined in a namespace scope if it is used in the program and the
11082     //   namespace scope definition shall not contain an initializer.
11083     //
11084     // We already performed a redefinition check above, but for static
11085     // data members we also need to check whether there was an in-class
11086     // declaration with an initializer.
11087     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11088       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11089           << VDecl->getDeclName();
11090       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11091            diag::note_previous_initializer)
11092           << 0;
11093       return;
11094     }
11095 
11096     if (VDecl->hasLocalStorage())
11097       setFunctionHasBranchProtectedScope();
11098 
11099     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11100       VDecl->setInvalidDecl();
11101       return;
11102     }
11103   }
11104 
11105   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11106   // a kernel function cannot be initialized."
11107   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11108     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11109     VDecl->setInvalidDecl();
11110     return;
11111   }
11112 
11113   // Get the decls type and save a reference for later, since
11114   // CheckInitializerTypes may change it.
11115   QualType DclT = VDecl->getType(), SavT = DclT;
11116 
11117   // Expressions default to 'id' when we're in a debugger
11118   // and we are assigning it to a variable of Objective-C pointer type.
11119   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11120       Init->getType() == Context.UnknownAnyTy) {
11121     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11122     if (Result.isInvalid()) {
11123       VDecl->setInvalidDecl();
11124       return;
11125     }
11126     Init = Result.get();
11127   }
11128 
11129   // Perform the initialization.
11130   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11131   if (!VDecl->isInvalidDecl()) {
11132     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11133     InitializationKind Kind = InitializationKind::CreateForInit(
11134         VDecl->getLocation(), DirectInit, Init);
11135 
11136     MultiExprArg Args = Init;
11137     if (CXXDirectInit)
11138       Args = MultiExprArg(CXXDirectInit->getExprs(),
11139                           CXXDirectInit->getNumExprs());
11140 
11141     // Try to correct any TypoExprs in the initialization arguments.
11142     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11143       ExprResult Res = CorrectDelayedTyposInExpr(
11144           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11145             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11146             return Init.Failed() ? ExprError() : E;
11147           });
11148       if (Res.isInvalid()) {
11149         VDecl->setInvalidDecl();
11150       } else if (Res.get() != Args[Idx]) {
11151         Args[Idx] = Res.get();
11152       }
11153     }
11154     if (VDecl->isInvalidDecl())
11155       return;
11156 
11157     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11158                                    /*TopLevelOfInitList=*/false,
11159                                    /*TreatUnavailableAsInvalid=*/false);
11160     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11161     if (Result.isInvalid()) {
11162       VDecl->setInvalidDecl();
11163       return;
11164     }
11165 
11166     Init = Result.getAs<Expr>();
11167   }
11168 
11169   // Check for self-references within variable initializers.
11170   // Variables declared within a function/method body (except for references)
11171   // are handled by a dataflow analysis.
11172   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11173       VDecl->getType()->isReferenceType()) {
11174     CheckSelfReference(*this, RealDecl, Init, DirectInit);
11175   }
11176 
11177   // If the type changed, it means we had an incomplete type that was
11178   // completed by the initializer. For example:
11179   //   int ary[] = { 1, 3, 5 };
11180   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11181   if (!VDecl->isInvalidDecl() && (DclT != SavT))
11182     VDecl->setType(DclT);
11183 
11184   if (!VDecl->isInvalidDecl()) {
11185     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11186 
11187     if (VDecl->hasAttr<BlocksAttr>())
11188       checkRetainCycles(VDecl, Init);
11189 
11190     // It is safe to assign a weak reference into a strong variable.
11191     // Although this code can still have problems:
11192     //   id x = self.weakProp;
11193     //   id y = self.weakProp;
11194     // we do not warn to warn spuriously when 'x' and 'y' are on separate
11195     // paths through the function. This should be revisited if
11196     // -Wrepeated-use-of-weak is made flow-sensitive.
11197     if (FunctionScopeInfo *FSI = getCurFunction())
11198       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11199            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11200           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11201                            Init->getBeginLoc()))
11202         FSI->markSafeWeakUse(Init);
11203   }
11204 
11205   // The initialization is usually a full-expression.
11206   //
11207   // FIXME: If this is a braced initialization of an aggregate, it is not
11208   // an expression, and each individual field initializer is a separate
11209   // full-expression. For instance, in:
11210   //
11211   //   struct Temp { ~Temp(); };
11212   //   struct S { S(Temp); };
11213   //   struct T { S a, b; } t = { Temp(), Temp() }
11214   //
11215   // we should destroy the first Temp before constructing the second.
11216   ExprResult Result =
11217       ActOnFinishFullExpr(Init, VDecl->getLocation(),
11218                           /*DiscardedValue*/ false, VDecl->isConstexpr());
11219   if (Result.isInvalid()) {
11220     VDecl->setInvalidDecl();
11221     return;
11222   }
11223   Init = Result.get();
11224 
11225   // Attach the initializer to the decl.
11226   VDecl->setInit(Init);
11227 
11228   if (VDecl->isLocalVarDecl()) {
11229     // Don't check the initializer if the declaration is malformed.
11230     if (VDecl->isInvalidDecl()) {
11231       // do nothing
11232 
11233     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11234     // This is true even in OpenCL C++.
11235     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11236       CheckForConstantInitializer(Init, DclT);
11237 
11238     // Otherwise, C++ does not restrict the initializer.
11239     } else if (getLangOpts().CPlusPlus) {
11240       // do nothing
11241 
11242     // C99 6.7.8p4: All the expressions in an initializer for an object that has
11243     // static storage duration shall be constant expressions or string literals.
11244     } else if (VDecl->getStorageClass() == SC_Static) {
11245       CheckForConstantInitializer(Init, DclT);
11246 
11247     // C89 is stricter than C99 for aggregate initializers.
11248     // C89 6.5.7p3: All the expressions [...] in an initializer list
11249     // for an object that has aggregate or union type shall be
11250     // constant expressions.
11251     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11252                isa<InitListExpr>(Init)) {
11253       const Expr *Culprit;
11254       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11255         Diag(Culprit->getExprLoc(),
11256              diag::ext_aggregate_init_not_constant)
11257           << Culprit->getSourceRange();
11258       }
11259     }
11260 
11261     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
11262       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
11263         if (VDecl->hasLocalStorage())
11264           BE->getBlockDecl()->setCanAvoidCopyToHeap();
11265   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11266              VDecl->getLexicalDeclContext()->isRecord()) {
11267     // This is an in-class initialization for a static data member, e.g.,
11268     //
11269     // struct S {
11270     //   static const int value = 17;
11271     // };
11272 
11273     // C++ [class.mem]p4:
11274     //   A member-declarator can contain a constant-initializer only
11275     //   if it declares a static member (9.4) of const integral or
11276     //   const enumeration type, see 9.4.2.
11277     //
11278     // C++11 [class.static.data]p3:
11279     //   If a non-volatile non-inline const static data member is of integral
11280     //   or enumeration type, its declaration in the class definition can
11281     //   specify a brace-or-equal-initializer in which every initializer-clause
11282     //   that is an assignment-expression is a constant expression. A static
11283     //   data member of literal type can be declared in the class definition
11284     //   with the constexpr specifier; if so, its declaration shall specify a
11285     //   brace-or-equal-initializer in which every initializer-clause that is
11286     //   an assignment-expression is a constant expression.
11287 
11288     // Do nothing on dependent types.
11289     if (DclT->isDependentType()) {
11290 
11291     // Allow any 'static constexpr' members, whether or not they are of literal
11292     // type. We separately check that every constexpr variable is of literal
11293     // type.
11294     } else if (VDecl->isConstexpr()) {
11295 
11296     // Require constness.
11297     } else if (!DclT.isConstQualified()) {
11298       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11299         << Init->getSourceRange();
11300       VDecl->setInvalidDecl();
11301 
11302     // We allow integer constant expressions in all cases.
11303     } else if (DclT->isIntegralOrEnumerationType()) {
11304       // Check whether the expression is a constant expression.
11305       SourceLocation Loc;
11306       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11307         // In C++11, a non-constexpr const static data member with an
11308         // in-class initializer cannot be volatile.
11309         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11310       else if (Init->isValueDependent())
11311         ; // Nothing to check.
11312       else if (Init->isIntegerConstantExpr(Context, &Loc))
11313         ; // Ok, it's an ICE!
11314       else if (Init->getType()->isScopedEnumeralType() &&
11315                Init->isCXX11ConstantExpr(Context))
11316         ; // Ok, it is a scoped-enum constant expression.
11317       else if (Init->isEvaluatable(Context)) {
11318         // If we can constant fold the initializer through heroics, accept it,
11319         // but report this as a use of an extension for -pedantic.
11320         Diag(Loc, diag::ext_in_class_initializer_non_constant)
11321           << Init->getSourceRange();
11322       } else {
11323         // Otherwise, this is some crazy unknown case.  Report the issue at the
11324         // location provided by the isIntegerConstantExpr failed check.
11325         Diag(Loc, diag::err_in_class_initializer_non_constant)
11326           << Init->getSourceRange();
11327         VDecl->setInvalidDecl();
11328       }
11329 
11330     // We allow foldable floating-point constants as an extension.
11331     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
11332       // In C++98, this is a GNU extension. In C++11, it is not, but we support
11333       // it anyway and provide a fixit to add the 'constexpr'.
11334       if (getLangOpts().CPlusPlus11) {
11335         Diag(VDecl->getLocation(),
11336              diag::ext_in_class_initializer_float_type_cxx11)
11337             << DclT << Init->getSourceRange();
11338         Diag(VDecl->getBeginLoc(),
11339              diag::note_in_class_initializer_float_type_cxx11)
11340             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11341       } else {
11342         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
11343           << DclT << Init->getSourceRange();
11344 
11345         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
11346           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
11347             << Init->getSourceRange();
11348           VDecl->setInvalidDecl();
11349         }
11350       }
11351 
11352     // Suggest adding 'constexpr' in C++11 for literal types.
11353     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
11354       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
11355           << DclT << Init->getSourceRange()
11356           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11357       VDecl->setConstexpr(true);
11358 
11359     } else {
11360       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
11361         << DclT << Init->getSourceRange();
11362       VDecl->setInvalidDecl();
11363     }
11364   } else if (VDecl->isFileVarDecl()) {
11365     // In C, extern is typically used to avoid tentative definitions when
11366     // declaring variables in headers, but adding an intializer makes it a
11367     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
11368     // In C++, extern is often used to give implictly static const variables
11369     // external linkage, so don't warn in that case. If selectany is present,
11370     // this might be header code intended for C and C++ inclusion, so apply the
11371     // C++ rules.
11372     if (VDecl->getStorageClass() == SC_Extern &&
11373         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
11374          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
11375         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
11376         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
11377       Diag(VDecl->getLocation(), diag::warn_extern_init);
11378 
11379     // C99 6.7.8p4. All file scoped initializers need to be constant.
11380     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
11381       CheckForConstantInitializer(Init, DclT);
11382   }
11383 
11384   // We will represent direct-initialization similarly to copy-initialization:
11385   //    int x(1);  -as-> int x = 1;
11386   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
11387   //
11388   // Clients that want to distinguish between the two forms, can check for
11389   // direct initializer using VarDecl::getInitStyle().
11390   // A major benefit is that clients that don't particularly care about which
11391   // exactly form was it (like the CodeGen) can handle both cases without
11392   // special case code.
11393 
11394   // C++ 8.5p11:
11395   // The form of initialization (using parentheses or '=') is generally
11396   // insignificant, but does matter when the entity being initialized has a
11397   // class type.
11398   if (CXXDirectInit) {
11399     assert(DirectInit && "Call-style initializer must be direct init.");
11400     VDecl->setInitStyle(VarDecl::CallInit);
11401   } else if (DirectInit) {
11402     // This must be list-initialization. No other way is direct-initialization.
11403     VDecl->setInitStyle(VarDecl::ListInit);
11404   }
11405 
11406   CheckCompleteVariableDeclaration(VDecl);
11407 }
11408 
11409 /// ActOnInitializerError - Given that there was an error parsing an
11410 /// initializer for the given declaration, try to return to some form
11411 /// of sanity.
11412 void Sema::ActOnInitializerError(Decl *D) {
11413   // Our main concern here is re-establishing invariants like "a
11414   // variable's type is either dependent or complete".
11415   if (!D || D->isInvalidDecl()) return;
11416 
11417   VarDecl *VD = dyn_cast<VarDecl>(D);
11418   if (!VD) return;
11419 
11420   // Bindings are not usable if we can't make sense of the initializer.
11421   if (auto *DD = dyn_cast<DecompositionDecl>(D))
11422     for (auto *BD : DD->bindings())
11423       BD->setInvalidDecl();
11424 
11425   // Auto types are meaningless if we can't make sense of the initializer.
11426   if (ParsingInitForAutoVars.count(D)) {
11427     D->setInvalidDecl();
11428     return;
11429   }
11430 
11431   QualType Ty = VD->getType();
11432   if (Ty->isDependentType()) return;
11433 
11434   // Require a complete type.
11435   if (RequireCompleteType(VD->getLocation(),
11436                           Context.getBaseElementType(Ty),
11437                           diag::err_typecheck_decl_incomplete_type)) {
11438     VD->setInvalidDecl();
11439     return;
11440   }
11441 
11442   // Require a non-abstract type.
11443   if (RequireNonAbstractType(VD->getLocation(), Ty,
11444                              diag::err_abstract_type_in_decl,
11445                              AbstractVariableType)) {
11446     VD->setInvalidDecl();
11447     return;
11448   }
11449 
11450   // Don't bother complaining about constructors or destructors,
11451   // though.
11452 }
11453 
11454 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
11455   // If there is no declaration, there was an error parsing it. Just ignore it.
11456   if (!RealDecl)
11457     return;
11458 
11459   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
11460     QualType Type = Var->getType();
11461 
11462     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
11463     if (isa<DecompositionDecl>(RealDecl)) {
11464       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
11465       Var->setInvalidDecl();
11466       return;
11467     }
11468 
11469     Expr *TmpInit = nullptr;
11470     if (Type->isUndeducedType() &&
11471         DeduceVariableDeclarationType(Var, false, TmpInit))
11472       return;
11473 
11474     // C++11 [class.static.data]p3: A static data member can be declared with
11475     // the constexpr specifier; if so, its declaration shall specify
11476     // a brace-or-equal-initializer.
11477     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
11478     // the definition of a variable [...] or the declaration of a static data
11479     // member.
11480     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
11481         !Var->isThisDeclarationADemotedDefinition()) {
11482       if (Var->isStaticDataMember()) {
11483         // C++1z removes the relevant rule; the in-class declaration is always
11484         // a definition there.
11485         if (!getLangOpts().CPlusPlus17) {
11486           Diag(Var->getLocation(),
11487                diag::err_constexpr_static_mem_var_requires_init)
11488             << Var->getDeclName();
11489           Var->setInvalidDecl();
11490           return;
11491         }
11492       } else {
11493         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
11494         Var->setInvalidDecl();
11495         return;
11496       }
11497     }
11498 
11499     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
11500     // be initialized.
11501     if (!Var->isInvalidDecl() &&
11502         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
11503         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
11504       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
11505       Var->setInvalidDecl();
11506       return;
11507     }
11508 
11509     switch (Var->isThisDeclarationADefinition()) {
11510     case VarDecl::Definition:
11511       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
11512         break;
11513 
11514       // We have an out-of-line definition of a static data member
11515       // that has an in-class initializer, so we type-check this like
11516       // a declaration.
11517       //
11518       LLVM_FALLTHROUGH;
11519 
11520     case VarDecl::DeclarationOnly:
11521       // It's only a declaration.
11522 
11523       // Block scope. C99 6.7p7: If an identifier for an object is
11524       // declared with no linkage (C99 6.2.2p6), the type for the
11525       // object shall be complete.
11526       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
11527           !Var->hasLinkage() && !Var->isInvalidDecl() &&
11528           RequireCompleteType(Var->getLocation(), Type,
11529                               diag::err_typecheck_decl_incomplete_type))
11530         Var->setInvalidDecl();
11531 
11532       // Make sure that the type is not abstract.
11533       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11534           RequireNonAbstractType(Var->getLocation(), Type,
11535                                  diag::err_abstract_type_in_decl,
11536                                  AbstractVariableType))
11537         Var->setInvalidDecl();
11538       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11539           Var->getStorageClass() == SC_PrivateExtern) {
11540         Diag(Var->getLocation(), diag::warn_private_extern);
11541         Diag(Var->getLocation(), diag::note_private_extern);
11542       }
11543 
11544       return;
11545 
11546     case VarDecl::TentativeDefinition:
11547       // File scope. C99 6.9.2p2: A declaration of an identifier for an
11548       // object that has file scope without an initializer, and without a
11549       // storage-class specifier or with the storage-class specifier "static",
11550       // constitutes a tentative definition. Note: A tentative definition with
11551       // external linkage is valid (C99 6.2.2p5).
11552       if (!Var->isInvalidDecl()) {
11553         if (const IncompleteArrayType *ArrayT
11554                                     = Context.getAsIncompleteArrayType(Type)) {
11555           if (RequireCompleteType(Var->getLocation(),
11556                                   ArrayT->getElementType(),
11557                                   diag::err_illegal_decl_array_incomplete_type))
11558             Var->setInvalidDecl();
11559         } else if (Var->getStorageClass() == SC_Static) {
11560           // C99 6.9.2p3: If the declaration of an identifier for an object is
11561           // a tentative definition and has internal linkage (C99 6.2.2p3), the
11562           // declared type shall not be an incomplete type.
11563           // NOTE: code such as the following
11564           //     static struct s;
11565           //     struct s { int a; };
11566           // is accepted by gcc. Hence here we issue a warning instead of
11567           // an error and we do not invalidate the static declaration.
11568           // NOTE: to avoid multiple warnings, only check the first declaration.
11569           if (Var->isFirstDecl())
11570             RequireCompleteType(Var->getLocation(), Type,
11571                                 diag::ext_typecheck_decl_incomplete_type);
11572         }
11573       }
11574 
11575       // Record the tentative definition; we're done.
11576       if (!Var->isInvalidDecl())
11577         TentativeDefinitions.push_back(Var);
11578       return;
11579     }
11580 
11581     // Provide a specific diagnostic for uninitialized variable
11582     // definitions with incomplete array type.
11583     if (Type->isIncompleteArrayType()) {
11584       Diag(Var->getLocation(),
11585            diag::err_typecheck_incomplete_array_needs_initializer);
11586       Var->setInvalidDecl();
11587       return;
11588     }
11589 
11590     // Provide a specific diagnostic for uninitialized variable
11591     // definitions with reference type.
11592     if (Type->isReferenceType()) {
11593       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
11594         << Var->getDeclName()
11595         << SourceRange(Var->getLocation(), Var->getLocation());
11596       Var->setInvalidDecl();
11597       return;
11598     }
11599 
11600     // Do not attempt to type-check the default initializer for a
11601     // variable with dependent type.
11602     if (Type->isDependentType())
11603       return;
11604 
11605     if (Var->isInvalidDecl())
11606       return;
11607 
11608     if (!Var->hasAttr<AliasAttr>()) {
11609       if (RequireCompleteType(Var->getLocation(),
11610                               Context.getBaseElementType(Type),
11611                               diag::err_typecheck_decl_incomplete_type)) {
11612         Var->setInvalidDecl();
11613         return;
11614       }
11615     } else {
11616       return;
11617     }
11618 
11619     // The variable can not have an abstract class type.
11620     if (RequireNonAbstractType(Var->getLocation(), Type,
11621                                diag::err_abstract_type_in_decl,
11622                                AbstractVariableType)) {
11623       Var->setInvalidDecl();
11624       return;
11625     }
11626 
11627     // Check for jumps past the implicit initializer.  C++0x
11628     // clarifies that this applies to a "variable with automatic
11629     // storage duration", not a "local variable".
11630     // C++11 [stmt.dcl]p3
11631     //   A program that jumps from a point where a variable with automatic
11632     //   storage duration is not in scope to a point where it is in scope is
11633     //   ill-formed unless the variable has scalar type, class type with a
11634     //   trivial default constructor and a trivial destructor, a cv-qualified
11635     //   version of one of these types, or an array of one of the preceding
11636     //   types and is declared without an initializer.
11637     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
11638       if (const RecordType *Record
11639             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
11640         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
11641         // Mark the function (if we're in one) for further checking even if the
11642         // looser rules of C++11 do not require such checks, so that we can
11643         // diagnose incompatibilities with C++98.
11644         if (!CXXRecord->isPOD())
11645           setFunctionHasBranchProtectedScope();
11646       }
11647     }
11648 
11649     // C++03 [dcl.init]p9:
11650     //   If no initializer is specified for an object, and the
11651     //   object is of (possibly cv-qualified) non-POD class type (or
11652     //   array thereof), the object shall be default-initialized; if
11653     //   the object is of const-qualified type, the underlying class
11654     //   type shall have a user-declared default
11655     //   constructor. Otherwise, if no initializer is specified for
11656     //   a non- static object, the object and its subobjects, if
11657     //   any, have an indeterminate initial value); if the object
11658     //   or any of its subobjects are of const-qualified type, the
11659     //   program is ill-formed.
11660     // C++0x [dcl.init]p11:
11661     //   If no initializer is specified for an object, the object is
11662     //   default-initialized; [...].
11663     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
11664     InitializationKind Kind
11665       = InitializationKind::CreateDefault(Var->getLocation());
11666 
11667     InitializationSequence InitSeq(*this, Entity, Kind, None);
11668     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
11669     if (Init.isInvalid())
11670       Var->setInvalidDecl();
11671     else if (Init.get()) {
11672       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
11673       // This is important for template substitution.
11674       Var->setInitStyle(VarDecl::CallInit);
11675     }
11676 
11677     CheckCompleteVariableDeclaration(Var);
11678   }
11679 }
11680 
11681 void Sema::ActOnCXXForRangeDecl(Decl *D) {
11682   // If there is no declaration, there was an error parsing it. Ignore it.
11683   if (!D)
11684     return;
11685 
11686   VarDecl *VD = dyn_cast<VarDecl>(D);
11687   if (!VD) {
11688     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
11689     D->setInvalidDecl();
11690     return;
11691   }
11692 
11693   VD->setCXXForRangeDecl(true);
11694 
11695   // for-range-declaration cannot be given a storage class specifier.
11696   int Error = -1;
11697   switch (VD->getStorageClass()) {
11698   case SC_None:
11699     break;
11700   case SC_Extern:
11701     Error = 0;
11702     break;
11703   case SC_Static:
11704     Error = 1;
11705     break;
11706   case SC_PrivateExtern:
11707     Error = 2;
11708     break;
11709   case SC_Auto:
11710     Error = 3;
11711     break;
11712   case SC_Register:
11713     Error = 4;
11714     break;
11715   }
11716   if (Error != -1) {
11717     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
11718       << VD->getDeclName() << Error;
11719     D->setInvalidDecl();
11720   }
11721 }
11722 
11723 StmtResult
11724 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
11725                                  IdentifierInfo *Ident,
11726                                  ParsedAttributes &Attrs,
11727                                  SourceLocation AttrEnd) {
11728   // C++1y [stmt.iter]p1:
11729   //   A range-based for statement of the form
11730   //      for ( for-range-identifier : for-range-initializer ) statement
11731   //   is equivalent to
11732   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
11733   DeclSpec DS(Attrs.getPool().getFactory());
11734 
11735   const char *PrevSpec;
11736   unsigned DiagID;
11737   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
11738                      getPrintingPolicy());
11739 
11740   Declarator D(DS, DeclaratorContext::ForContext);
11741   D.SetIdentifier(Ident, IdentLoc);
11742   D.takeAttributes(Attrs, AttrEnd);
11743 
11744   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
11745   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
11746                 IdentLoc);
11747   Decl *Var = ActOnDeclarator(S, D);
11748   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
11749   FinalizeDeclaration(Var);
11750   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
11751                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
11752 }
11753 
11754 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
11755   if (var->isInvalidDecl()) return;
11756 
11757   if (getLangOpts().OpenCL) {
11758     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
11759     // initialiser
11760     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
11761         !var->hasInit()) {
11762       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
11763           << 1 /*Init*/;
11764       var->setInvalidDecl();
11765       return;
11766     }
11767   }
11768 
11769   // In Objective-C, don't allow jumps past the implicit initialization of a
11770   // local retaining variable.
11771   if (getLangOpts().ObjC &&
11772       var->hasLocalStorage()) {
11773     switch (var->getType().getObjCLifetime()) {
11774     case Qualifiers::OCL_None:
11775     case Qualifiers::OCL_ExplicitNone:
11776     case Qualifiers::OCL_Autoreleasing:
11777       break;
11778 
11779     case Qualifiers::OCL_Weak:
11780     case Qualifiers::OCL_Strong:
11781       setFunctionHasBranchProtectedScope();
11782       break;
11783     }
11784   }
11785 
11786   if (var->hasLocalStorage() &&
11787       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
11788     setFunctionHasBranchProtectedScope();
11789 
11790   // Warn about externally-visible variables being defined without a
11791   // prior declaration.  We only want to do this for global
11792   // declarations, but we also specifically need to avoid doing it for
11793   // class members because the linkage of an anonymous class can
11794   // change if it's later given a typedef name.
11795   if (var->isThisDeclarationADefinition() &&
11796       var->getDeclContext()->getRedeclContext()->isFileContext() &&
11797       var->isExternallyVisible() && var->hasLinkage() &&
11798       !var->isInline() && !var->getDescribedVarTemplate() &&
11799       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
11800       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11801                                   var->getLocation())) {
11802     // Find a previous declaration that's not a definition.
11803     VarDecl *prev = var->getPreviousDecl();
11804     while (prev && prev->isThisDeclarationADefinition())
11805       prev = prev->getPreviousDecl();
11806 
11807     if (!prev)
11808       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11809   }
11810 
11811   // Cache the result of checking for constant initialization.
11812   Optional<bool> CacheHasConstInit;
11813   const Expr *CacheCulprit;
11814   auto checkConstInit = [&]() mutable {
11815     if (!CacheHasConstInit)
11816       CacheHasConstInit = var->getInit()->isConstantInitializer(
11817             Context, var->getType()->isReferenceType(), &CacheCulprit);
11818     return *CacheHasConstInit;
11819   };
11820 
11821   if (var->getTLSKind() == VarDecl::TLS_Static) {
11822     if (var->getType().isDestructedType()) {
11823       // GNU C++98 edits for __thread, [basic.start.term]p3:
11824       //   The type of an object with thread storage duration shall not
11825       //   have a non-trivial destructor.
11826       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11827       if (getLangOpts().CPlusPlus11)
11828         Diag(var->getLocation(), diag::note_use_thread_local);
11829     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11830       if (!checkConstInit()) {
11831         // GNU C++98 edits for __thread, [basic.start.init]p4:
11832         //   An object of thread storage duration shall not require dynamic
11833         //   initialization.
11834         // FIXME: Need strict checking here.
11835         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11836           << CacheCulprit->getSourceRange();
11837         if (getLangOpts().CPlusPlus11)
11838           Diag(var->getLocation(), diag::note_use_thread_local);
11839       }
11840     }
11841   }
11842 
11843   // Apply section attributes and pragmas to global variables.
11844   bool GlobalStorage = var->hasGlobalStorage();
11845   if (GlobalStorage && var->isThisDeclarationADefinition() &&
11846       !inTemplateInstantiation()) {
11847     PragmaStack<StringLiteral *> *Stack = nullptr;
11848     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11849     if (var->getType().isConstQualified())
11850       Stack = &ConstSegStack;
11851     else if (!var->getInit()) {
11852       Stack = &BSSSegStack;
11853       SectionFlags |= ASTContext::PSF_Write;
11854     } else {
11855       Stack = &DataSegStack;
11856       SectionFlags |= ASTContext::PSF_Write;
11857     }
11858     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11859       var->addAttr(SectionAttr::CreateImplicit(
11860           Context, SectionAttr::Declspec_allocate,
11861           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11862     }
11863     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11864       if (UnifySection(SA->getName(), SectionFlags, var))
11865         var->dropAttr<SectionAttr>();
11866 
11867     // Apply the init_seg attribute if this has an initializer.  If the
11868     // initializer turns out to not be dynamic, we'll end up ignoring this
11869     // attribute.
11870     if (CurInitSeg && var->getInit())
11871       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11872                                                CurInitSegLoc));
11873   }
11874 
11875   // All the following checks are C++ only.
11876   if (!getLangOpts().CPlusPlus) {
11877       // If this variable must be emitted, add it as an initializer for the
11878       // current module.
11879      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11880        Context.addModuleInitializer(ModuleScopes.back().Module, var);
11881      return;
11882   }
11883 
11884   if (auto *DD = dyn_cast<DecompositionDecl>(var))
11885     CheckCompleteDecompositionDeclaration(DD);
11886 
11887   QualType type = var->getType();
11888   if (type->isDependentType()) return;
11889 
11890   if (var->hasAttr<BlocksAttr>())
11891     getCurFunction()->addByrefBlockVar(var);
11892 
11893   Expr *Init = var->getInit();
11894   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11895   QualType baseType = Context.getBaseElementType(type);
11896 
11897   if (Init && !Init->isValueDependent()) {
11898     if (var->isConstexpr()) {
11899       SmallVector<PartialDiagnosticAt, 8> Notes;
11900       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11901         SourceLocation DiagLoc = var->getLocation();
11902         // If the note doesn't add any useful information other than a source
11903         // location, fold it into the primary diagnostic.
11904         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11905               diag::note_invalid_subexpr_in_const_expr) {
11906           DiagLoc = Notes[0].first;
11907           Notes.clear();
11908         }
11909         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11910           << var << Init->getSourceRange();
11911         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11912           Diag(Notes[I].first, Notes[I].second);
11913       }
11914     } else if (var->isUsableInConstantExpressions(Context)) {
11915       // Check whether the initializer of a const variable of integral or
11916       // enumeration type is an ICE now, since we can't tell whether it was
11917       // initialized by a constant expression if we check later.
11918       var->checkInitIsICE();
11919     }
11920 
11921     // Don't emit further diagnostics about constexpr globals since they
11922     // were just diagnosed.
11923     if (!var->isConstexpr() && GlobalStorage &&
11924             var->hasAttr<RequireConstantInitAttr>()) {
11925       // FIXME: Need strict checking in C++03 here.
11926       bool DiagErr = getLangOpts().CPlusPlus11
11927           ? !var->checkInitIsICE() : !checkConstInit();
11928       if (DiagErr) {
11929         auto attr = var->getAttr<RequireConstantInitAttr>();
11930         Diag(var->getLocation(), diag::err_require_constant_init_failed)
11931           << Init->getSourceRange();
11932         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11933           << attr->getRange();
11934         if (getLangOpts().CPlusPlus11) {
11935           APValue Value;
11936           SmallVector<PartialDiagnosticAt, 8> Notes;
11937           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11938           for (auto &it : Notes)
11939             Diag(it.first, it.second);
11940         } else {
11941           Diag(CacheCulprit->getExprLoc(),
11942                diag::note_invalid_subexpr_in_const_expr)
11943               << CacheCulprit->getSourceRange();
11944         }
11945       }
11946     }
11947     else if (!var->isConstexpr() && IsGlobal &&
11948              !getDiagnostics().isIgnored(diag::warn_global_constructor,
11949                                     var->getLocation())) {
11950       // Warn about globals which don't have a constant initializer.  Don't
11951       // warn about globals with a non-trivial destructor because we already
11952       // warned about them.
11953       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11954       if (!(RD && !RD->hasTrivialDestructor())) {
11955         if (!checkConstInit())
11956           Diag(var->getLocation(), diag::warn_global_constructor)
11957             << Init->getSourceRange();
11958       }
11959     }
11960   }
11961 
11962   // Require the destructor.
11963   if (const RecordType *recordType = baseType->getAs<RecordType>())
11964     FinalizeVarWithDestructor(var, recordType);
11965 
11966   // If this variable must be emitted, add it as an initializer for the current
11967   // module.
11968   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11969     Context.addModuleInitializer(ModuleScopes.back().Module, var);
11970 }
11971 
11972 /// Determines if a variable's alignment is dependent.
11973 static bool hasDependentAlignment(VarDecl *VD) {
11974   if (VD->getType()->isDependentType())
11975     return true;
11976   for (auto *I : VD->specific_attrs<AlignedAttr>())
11977     if (I->isAlignmentDependent())
11978       return true;
11979   return false;
11980 }
11981 
11982 /// Check if VD needs to be dllexport/dllimport due to being in a
11983 /// dllexport/import function.
11984 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
11985   assert(VD->isStaticLocal());
11986 
11987   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11988 
11989   // Find outermost function when VD is in lambda function.
11990   while (FD && !getDLLAttr(FD) &&
11991          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
11992          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
11993     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
11994   }
11995 
11996   if (!FD)
11997     return;
11998 
11999   // Static locals inherit dll attributes from their function.
12000   if (Attr *A = getDLLAttr(FD)) {
12001     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12002     NewAttr->setInherited(true);
12003     VD->addAttr(NewAttr);
12004   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12005     auto *NewAttr = ::new (getASTContext()) DLLExportAttr(A->getRange(),
12006                                                           getASTContext(),
12007                                                           A->getSpellingListIndex());
12008     NewAttr->setInherited(true);
12009     VD->addAttr(NewAttr);
12010 
12011     // Export this function to enforce exporting this static variable even
12012     // if it is not used in this compilation unit.
12013     if (!FD->hasAttr<DLLExportAttr>())
12014       FD->addAttr(NewAttr);
12015 
12016   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12017     auto *NewAttr = ::new (getASTContext()) DLLImportAttr(A->getRange(),
12018                                                           getASTContext(),
12019                                                           A->getSpellingListIndex());
12020     NewAttr->setInherited(true);
12021     VD->addAttr(NewAttr);
12022   }
12023 }
12024 
12025 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12026 /// any semantic actions necessary after any initializer has been attached.
12027 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12028   // Note that we are no longer parsing the initializer for this declaration.
12029   ParsingInitForAutoVars.erase(ThisDecl);
12030 
12031   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12032   if (!VD)
12033     return;
12034 
12035   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12036   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12037       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12038     if (PragmaClangBSSSection.Valid)
12039       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
12040                                                             PragmaClangBSSSection.SectionName,
12041                                                             PragmaClangBSSSection.PragmaLocation));
12042     if (PragmaClangDataSection.Valid)
12043       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
12044                                                              PragmaClangDataSection.SectionName,
12045                                                              PragmaClangDataSection.PragmaLocation));
12046     if (PragmaClangRodataSection.Valid)
12047       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
12048                                                                PragmaClangRodataSection.SectionName,
12049                                                                PragmaClangRodataSection.PragmaLocation));
12050   }
12051 
12052   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12053     for (auto *BD : DD->bindings()) {
12054       FinalizeDeclaration(BD);
12055     }
12056   }
12057 
12058   checkAttributesAfterMerging(*this, *VD);
12059 
12060   // Perform TLS alignment check here after attributes attached to the variable
12061   // which may affect the alignment have been processed. Only perform the check
12062   // if the target has a maximum TLS alignment (zero means no constraints).
12063   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12064     // Protect the check so that it's not performed on dependent types and
12065     // dependent alignments (we can't determine the alignment in that case).
12066     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12067         !VD->isInvalidDecl()) {
12068       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12069       if (Context.getDeclAlign(VD) > MaxAlignChars) {
12070         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12071           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12072           << (unsigned)MaxAlignChars.getQuantity();
12073       }
12074     }
12075   }
12076 
12077   if (VD->isStaticLocal()) {
12078     CheckStaticLocalForDllExport(VD);
12079 
12080     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12081       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12082       // function, only __shared__ variables or variables without any device
12083       // memory qualifiers may be declared with static storage class.
12084       // Note: It is unclear how a function-scope non-const static variable
12085       // without device memory qualifier is implemented, therefore only static
12086       // const variable without device memory qualifier is allowed.
12087       [&]() {
12088         if (!getLangOpts().CUDA)
12089           return;
12090         if (VD->hasAttr<CUDASharedAttr>())
12091           return;
12092         if (VD->getType().isConstQualified() &&
12093             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12094           return;
12095         if (CUDADiagIfDeviceCode(VD->getLocation(),
12096                                  diag::err_device_static_local_var)
12097             << CurrentCUDATarget())
12098           VD->setInvalidDecl();
12099       }();
12100     }
12101   }
12102 
12103   // Perform check for initializers of device-side global variables.
12104   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12105   // 7.5). We must also apply the same checks to all __shared__
12106   // variables whether they are local or not. CUDA also allows
12107   // constant initializers for __constant__ and __device__ variables.
12108   if (getLangOpts().CUDA)
12109     checkAllowedCUDAInitializer(VD);
12110 
12111   // Grab the dllimport or dllexport attribute off of the VarDecl.
12112   const InheritableAttr *DLLAttr = getDLLAttr(VD);
12113 
12114   // Imported static data members cannot be defined out-of-line.
12115   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12116     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12117         VD->isThisDeclarationADefinition()) {
12118       // We allow definitions of dllimport class template static data members
12119       // with a warning.
12120       CXXRecordDecl *Context =
12121         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12122       bool IsClassTemplateMember =
12123           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12124           Context->getDescribedClassTemplate();
12125 
12126       Diag(VD->getLocation(),
12127            IsClassTemplateMember
12128                ? diag::warn_attribute_dllimport_static_field_definition
12129                : diag::err_attribute_dllimport_static_field_definition);
12130       Diag(IA->getLocation(), diag::note_attribute);
12131       if (!IsClassTemplateMember)
12132         VD->setInvalidDecl();
12133     }
12134   }
12135 
12136   // dllimport/dllexport variables cannot be thread local, their TLS index
12137   // isn't exported with the variable.
12138   if (DLLAttr && VD->getTLSKind()) {
12139     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12140     if (F && getDLLAttr(F)) {
12141       assert(VD->isStaticLocal());
12142       // But if this is a static local in a dlimport/dllexport function, the
12143       // function will never be inlined, which means the var would never be
12144       // imported, so having it marked import/export is safe.
12145     } else {
12146       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12147                                                                     << DLLAttr;
12148       VD->setInvalidDecl();
12149     }
12150   }
12151 
12152   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12153     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12154       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12155       VD->dropAttr<UsedAttr>();
12156     }
12157   }
12158 
12159   const DeclContext *DC = VD->getDeclContext();
12160   // If there's a #pragma GCC visibility in scope, and this isn't a class
12161   // member, set the visibility of this variable.
12162   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12163     AddPushedVisibilityAttribute(VD);
12164 
12165   // FIXME: Warn on unused var template partial specializations.
12166   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12167     MarkUnusedFileScopedDecl(VD);
12168 
12169   // Now we have parsed the initializer and can update the table of magic
12170   // tag values.
12171   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12172       !VD->getType()->isIntegralOrEnumerationType())
12173     return;
12174 
12175   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12176     const Expr *MagicValueExpr = VD->getInit();
12177     if (!MagicValueExpr) {
12178       continue;
12179     }
12180     llvm::APSInt MagicValueInt;
12181     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12182       Diag(I->getRange().getBegin(),
12183            diag::err_type_tag_for_datatype_not_ice)
12184         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12185       continue;
12186     }
12187     if (MagicValueInt.getActiveBits() > 64) {
12188       Diag(I->getRange().getBegin(),
12189            diag::err_type_tag_for_datatype_too_large)
12190         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12191       continue;
12192     }
12193     uint64_t MagicValue = MagicValueInt.getZExtValue();
12194     RegisterTypeTagForDatatype(I->getArgumentKind(),
12195                                MagicValue,
12196                                I->getMatchingCType(),
12197                                I->getLayoutCompatible(),
12198                                I->getMustBeNull());
12199   }
12200 }
12201 
12202 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12203   auto *VD = dyn_cast<VarDecl>(DD);
12204   return VD && !VD->getType()->hasAutoForTrailingReturnType();
12205 }
12206 
12207 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12208                                                    ArrayRef<Decl *> Group) {
12209   SmallVector<Decl*, 8> Decls;
12210 
12211   if (DS.isTypeSpecOwned())
12212     Decls.push_back(DS.getRepAsDecl());
12213 
12214   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12215   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12216   bool DiagnosedMultipleDecomps = false;
12217   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12218   bool DiagnosedNonDeducedAuto = false;
12219 
12220   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12221     if (Decl *D = Group[i]) {
12222       // For declarators, there are some additional syntactic-ish checks we need
12223       // to perform.
12224       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12225         if (!FirstDeclaratorInGroup)
12226           FirstDeclaratorInGroup = DD;
12227         if (!FirstDecompDeclaratorInGroup)
12228           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12229         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12230             !hasDeducedAuto(DD))
12231           FirstNonDeducedAutoInGroup = DD;
12232 
12233         if (FirstDeclaratorInGroup != DD) {
12234           // A decomposition declaration cannot be combined with any other
12235           // declaration in the same group.
12236           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12237             Diag(FirstDecompDeclaratorInGroup->getLocation(),
12238                  diag::err_decomp_decl_not_alone)
12239                 << FirstDeclaratorInGroup->getSourceRange()
12240                 << DD->getSourceRange();
12241             DiagnosedMultipleDecomps = true;
12242           }
12243 
12244           // A declarator that uses 'auto' in any way other than to declare a
12245           // variable with a deduced type cannot be combined with any other
12246           // declarator in the same group.
12247           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12248             Diag(FirstNonDeducedAutoInGroup->getLocation(),
12249                  diag::err_auto_non_deduced_not_alone)
12250                 << FirstNonDeducedAutoInGroup->getType()
12251                        ->hasAutoForTrailingReturnType()
12252                 << FirstDeclaratorInGroup->getSourceRange()
12253                 << DD->getSourceRange();
12254             DiagnosedNonDeducedAuto = true;
12255           }
12256         }
12257       }
12258 
12259       Decls.push_back(D);
12260     }
12261   }
12262 
12263   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12264     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12265       handleTagNumbering(Tag, S);
12266       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12267           getLangOpts().CPlusPlus)
12268         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
12269     }
12270   }
12271 
12272   return BuildDeclaratorGroup(Decls);
12273 }
12274 
12275 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
12276 /// group, performing any necessary semantic checking.
12277 Sema::DeclGroupPtrTy
12278 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
12279   // C++14 [dcl.spec.auto]p7: (DR1347)
12280   //   If the type that replaces the placeholder type is not the same in each
12281   //   deduction, the program is ill-formed.
12282   if (Group.size() > 1) {
12283     QualType Deduced;
12284     VarDecl *DeducedDecl = nullptr;
12285     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12286       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
12287       if (!D || D->isInvalidDecl())
12288         break;
12289       DeducedType *DT = D->getType()->getContainedDeducedType();
12290       if (!DT || DT->getDeducedType().isNull())
12291         continue;
12292       if (Deduced.isNull()) {
12293         Deduced = DT->getDeducedType();
12294         DeducedDecl = D;
12295       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
12296         auto *AT = dyn_cast<AutoType>(DT);
12297         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
12298              diag::err_auto_different_deductions)
12299           << (AT ? (unsigned)AT->getKeyword() : 3)
12300           << Deduced << DeducedDecl->getDeclName()
12301           << DT->getDeducedType() << D->getDeclName()
12302           << DeducedDecl->getInit()->getSourceRange()
12303           << D->getInit()->getSourceRange();
12304         D->setInvalidDecl();
12305         break;
12306       }
12307     }
12308   }
12309 
12310   ActOnDocumentableDecls(Group);
12311 
12312   return DeclGroupPtrTy::make(
12313       DeclGroupRef::Create(Context, Group.data(), Group.size()));
12314 }
12315 
12316 void Sema::ActOnDocumentableDecl(Decl *D) {
12317   ActOnDocumentableDecls(D);
12318 }
12319 
12320 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
12321   // Don't parse the comment if Doxygen diagnostics are ignored.
12322   if (Group.empty() || !Group[0])
12323     return;
12324 
12325   if (Diags.isIgnored(diag::warn_doc_param_not_found,
12326                       Group[0]->getLocation()) &&
12327       Diags.isIgnored(diag::warn_unknown_comment_command_name,
12328                       Group[0]->getLocation()))
12329     return;
12330 
12331   if (Group.size() >= 2) {
12332     // This is a decl group.  Normally it will contain only declarations
12333     // produced from declarator list.  But in case we have any definitions or
12334     // additional declaration references:
12335     //   'typedef struct S {} S;'
12336     //   'typedef struct S *S;'
12337     //   'struct S *pS;'
12338     // FinalizeDeclaratorGroup adds these as separate declarations.
12339     Decl *MaybeTagDecl = Group[0];
12340     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
12341       Group = Group.slice(1);
12342     }
12343   }
12344 
12345   // See if there are any new comments that are not attached to a decl.
12346   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
12347   if (!Comments.empty() &&
12348       !Comments.back()->isAttached()) {
12349     // There is at least one comment that not attached to a decl.
12350     // Maybe it should be attached to one of these decls?
12351     //
12352     // Note that this way we pick up not only comments that precede the
12353     // declaration, but also comments that *follow* the declaration -- thanks to
12354     // the lookahead in the lexer: we've consumed the semicolon and looked
12355     // ahead through comments.
12356     for (unsigned i = 0, e = Group.size(); i != e; ++i)
12357       Context.getCommentForDecl(Group[i], &PP);
12358   }
12359 }
12360 
12361 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
12362 /// to introduce parameters into function prototype scope.
12363 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
12364   const DeclSpec &DS = D.getDeclSpec();
12365 
12366   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
12367 
12368   // C++03 [dcl.stc]p2 also permits 'auto'.
12369   StorageClass SC = SC_None;
12370   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
12371     SC = SC_Register;
12372     // In C++11, the 'register' storage class specifier is deprecated.
12373     // In C++17, it is not allowed, but we tolerate it as an extension.
12374     if (getLangOpts().CPlusPlus11) {
12375       Diag(DS.getStorageClassSpecLoc(),
12376            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
12377                                      : diag::warn_deprecated_register)
12378         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12379     }
12380   } else if (getLangOpts().CPlusPlus &&
12381              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
12382     SC = SC_Auto;
12383   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
12384     Diag(DS.getStorageClassSpecLoc(),
12385          diag::err_invalid_storage_class_in_func_decl);
12386     D.getMutableDeclSpec().ClearStorageClassSpecs();
12387   }
12388 
12389   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
12390     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
12391       << DeclSpec::getSpecifierName(TSCS);
12392   if (DS.isInlineSpecified())
12393     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
12394         << getLangOpts().CPlusPlus17;
12395   if (DS.isConstexprSpecified())
12396     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
12397       << 0;
12398 
12399   DiagnoseFunctionSpecifiers(DS);
12400 
12401   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12402   QualType parmDeclType = TInfo->getType();
12403 
12404   if (getLangOpts().CPlusPlus) {
12405     // Check that there are no default arguments inside the type of this
12406     // parameter.
12407     CheckExtraCXXDefaultArguments(D);
12408 
12409     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
12410     if (D.getCXXScopeSpec().isSet()) {
12411       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
12412         << D.getCXXScopeSpec().getRange();
12413       D.getCXXScopeSpec().clear();
12414     }
12415   }
12416 
12417   // Ensure we have a valid name
12418   IdentifierInfo *II = nullptr;
12419   if (D.hasName()) {
12420     II = D.getIdentifier();
12421     if (!II) {
12422       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
12423         << GetNameForDeclarator(D).getName();
12424       D.setInvalidType(true);
12425     }
12426   }
12427 
12428   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
12429   if (II) {
12430     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
12431                    ForVisibleRedeclaration);
12432     LookupName(R, S);
12433     if (R.isSingleResult()) {
12434       NamedDecl *PrevDecl = R.getFoundDecl();
12435       if (PrevDecl->isTemplateParameter()) {
12436         // Maybe we will complain about the shadowed template parameter.
12437         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12438         // Just pretend that we didn't see the previous declaration.
12439         PrevDecl = nullptr;
12440       } else if (S->isDeclScope(PrevDecl)) {
12441         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
12442         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12443 
12444         // Recover by removing the name
12445         II = nullptr;
12446         D.SetIdentifier(nullptr, D.getIdentifierLoc());
12447         D.setInvalidType(true);
12448       }
12449     }
12450   }
12451 
12452   // Temporarily put parameter variables in the translation unit, not
12453   // the enclosing context.  This prevents them from accidentally
12454   // looking like class members in C++.
12455   ParmVarDecl *New =
12456       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
12457                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
12458 
12459   if (D.isInvalidType())
12460     New->setInvalidDecl();
12461 
12462   assert(S->isFunctionPrototypeScope());
12463   assert(S->getFunctionPrototypeDepth() >= 1);
12464   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
12465                     S->getNextFunctionPrototypeIndex());
12466 
12467   // Add the parameter declaration into this scope.
12468   S->AddDecl(New);
12469   if (II)
12470     IdResolver.AddDecl(New);
12471 
12472   ProcessDeclAttributes(S, New, D);
12473 
12474   if (D.getDeclSpec().isModulePrivateSpecified())
12475     Diag(New->getLocation(), diag::err_module_private_local)
12476       << 1 << New->getDeclName()
12477       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12478       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12479 
12480   if (New->hasAttr<BlocksAttr>()) {
12481     Diag(New->getLocation(), diag::err_block_on_nonlocal);
12482   }
12483   return New;
12484 }
12485 
12486 /// Synthesizes a variable for a parameter arising from a
12487 /// typedef.
12488 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
12489                                               SourceLocation Loc,
12490                                               QualType T) {
12491   /* FIXME: setting StartLoc == Loc.
12492      Would it be worth to modify callers so as to provide proper source
12493      location for the unnamed parameters, embedding the parameter's type? */
12494   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
12495                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
12496                                            SC_None, nullptr);
12497   Param->setImplicit();
12498   return Param;
12499 }
12500 
12501 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
12502   // Don't diagnose unused-parameter errors in template instantiations; we
12503   // will already have done so in the template itself.
12504   if (inTemplateInstantiation())
12505     return;
12506 
12507   for (const ParmVarDecl *Parameter : Parameters) {
12508     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
12509         !Parameter->hasAttr<UnusedAttr>()) {
12510       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
12511         << Parameter->getDeclName();
12512     }
12513   }
12514 }
12515 
12516 void Sema::DiagnoseSizeOfParametersAndReturnValue(
12517     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
12518   if (LangOpts.NumLargeByValueCopy == 0) // No check.
12519     return;
12520 
12521   // Warn if the return value is pass-by-value and larger than the specified
12522   // threshold.
12523   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
12524     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
12525     if (Size > LangOpts.NumLargeByValueCopy)
12526       Diag(D->getLocation(), diag::warn_return_value_size)
12527           << D->getDeclName() << Size;
12528   }
12529 
12530   // Warn if any parameter is pass-by-value and larger than the specified
12531   // threshold.
12532   for (const ParmVarDecl *Parameter : Parameters) {
12533     QualType T = Parameter->getType();
12534     if (T->isDependentType() || !T.isPODType(Context))
12535       continue;
12536     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
12537     if (Size > LangOpts.NumLargeByValueCopy)
12538       Diag(Parameter->getLocation(), diag::warn_parameter_size)
12539           << Parameter->getDeclName() << Size;
12540   }
12541 }
12542 
12543 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
12544                                   SourceLocation NameLoc, IdentifierInfo *Name,
12545                                   QualType T, TypeSourceInfo *TSInfo,
12546                                   StorageClass SC) {
12547   // In ARC, infer a lifetime qualifier for appropriate parameter types.
12548   if (getLangOpts().ObjCAutoRefCount &&
12549       T.getObjCLifetime() == Qualifiers::OCL_None &&
12550       T->isObjCLifetimeType()) {
12551 
12552     Qualifiers::ObjCLifetime lifetime;
12553 
12554     // Special cases for arrays:
12555     //   - if it's const, use __unsafe_unretained
12556     //   - otherwise, it's an error
12557     if (T->isArrayType()) {
12558       if (!T.isConstQualified()) {
12559         if (DelayedDiagnostics.shouldDelayDiagnostics())
12560           DelayedDiagnostics.add(
12561               sema::DelayedDiagnostic::makeForbiddenType(
12562               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
12563         else
12564           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
12565               << TSInfo->getTypeLoc().getSourceRange();
12566       }
12567       lifetime = Qualifiers::OCL_ExplicitNone;
12568     } else {
12569       lifetime = T->getObjCARCImplicitLifetime();
12570     }
12571     T = Context.getLifetimeQualifiedType(T, lifetime);
12572   }
12573 
12574   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
12575                                          Context.getAdjustedParameterType(T),
12576                                          TSInfo, SC, nullptr);
12577 
12578   // Parameters can not be abstract class types.
12579   // For record types, this is done by the AbstractClassUsageDiagnoser once
12580   // the class has been completely parsed.
12581   if (!CurContext->isRecord() &&
12582       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
12583                              AbstractParamType))
12584     New->setInvalidDecl();
12585 
12586   // Parameter declarators cannot be interface types. All ObjC objects are
12587   // passed by reference.
12588   if (T->isObjCObjectType()) {
12589     SourceLocation TypeEndLoc =
12590         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
12591     Diag(NameLoc,
12592          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
12593       << FixItHint::CreateInsertion(TypeEndLoc, "*");
12594     T = Context.getObjCObjectPointerType(T);
12595     New->setType(T);
12596   }
12597 
12598   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
12599   // duration shall not be qualified by an address-space qualifier."
12600   // Since all parameters have automatic store duration, they can not have
12601   // an address space.
12602   if (T.getAddressSpace() != LangAS::Default &&
12603       // OpenCL allows function arguments declared to be an array of a type
12604       // to be qualified with an address space.
12605       !(getLangOpts().OpenCL &&
12606         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
12607     Diag(NameLoc, diag::err_arg_with_address_space);
12608     New->setInvalidDecl();
12609   }
12610 
12611   return New;
12612 }
12613 
12614 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
12615                                            SourceLocation LocAfterDecls) {
12616   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
12617 
12618   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
12619   // for a K&R function.
12620   if (!FTI.hasPrototype) {
12621     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
12622       --i;
12623       if (FTI.Params[i].Param == nullptr) {
12624         SmallString<256> Code;
12625         llvm::raw_svector_ostream(Code)
12626             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
12627         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
12628             << FTI.Params[i].Ident
12629             << FixItHint::CreateInsertion(LocAfterDecls, Code);
12630 
12631         // Implicitly declare the argument as type 'int' for lack of a better
12632         // type.
12633         AttributeFactory attrs;
12634         DeclSpec DS(attrs);
12635         const char* PrevSpec; // unused
12636         unsigned DiagID; // unused
12637         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
12638                            DiagID, Context.getPrintingPolicy());
12639         // Use the identifier location for the type source range.
12640         DS.SetRangeStart(FTI.Params[i].IdentLoc);
12641         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
12642         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
12643         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
12644         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
12645       }
12646     }
12647   }
12648 }
12649 
12650 Decl *
12651 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
12652                               MultiTemplateParamsArg TemplateParameterLists,
12653                               SkipBodyInfo *SkipBody) {
12654   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
12655   assert(D.isFunctionDeclarator() && "Not a function declarator!");
12656   Scope *ParentScope = FnBodyScope->getParent();
12657 
12658   D.setFunctionDefinitionKind(FDK_Definition);
12659   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
12660   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
12661 }
12662 
12663 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
12664   Consumer.HandleInlineFunctionDefinition(D);
12665 }
12666 
12667 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
12668                              const FunctionDecl*& PossibleZeroParamPrototype) {
12669   // Don't warn about invalid declarations.
12670   if (FD->isInvalidDecl())
12671     return false;
12672 
12673   // Or declarations that aren't global.
12674   if (!FD->isGlobal())
12675     return false;
12676 
12677   // Don't warn about C++ member functions.
12678   if (isa<CXXMethodDecl>(FD))
12679     return false;
12680 
12681   // Don't warn about 'main'.
12682   if (FD->isMain())
12683     return false;
12684 
12685   // Don't warn about inline functions.
12686   if (FD->isInlined())
12687     return false;
12688 
12689   // Don't warn about function templates.
12690   if (FD->getDescribedFunctionTemplate())
12691     return false;
12692 
12693   // Don't warn about function template specializations.
12694   if (FD->isFunctionTemplateSpecialization())
12695     return false;
12696 
12697   // Don't warn for OpenCL kernels.
12698   if (FD->hasAttr<OpenCLKernelAttr>())
12699     return false;
12700 
12701   // Don't warn on explicitly deleted functions.
12702   if (FD->isDeleted())
12703     return false;
12704 
12705   bool MissingPrototype = true;
12706   for (const FunctionDecl *Prev = FD->getPreviousDecl();
12707        Prev; Prev = Prev->getPreviousDecl()) {
12708     // Ignore any declarations that occur in function or method
12709     // scope, because they aren't visible from the header.
12710     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
12711       continue;
12712 
12713     MissingPrototype = !Prev->getType()->isFunctionProtoType();
12714     if (FD->getNumParams() == 0)
12715       PossibleZeroParamPrototype = Prev;
12716     break;
12717   }
12718 
12719   return MissingPrototype;
12720 }
12721 
12722 void
12723 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
12724                                    const FunctionDecl *EffectiveDefinition,
12725                                    SkipBodyInfo *SkipBody) {
12726   const FunctionDecl *Definition = EffectiveDefinition;
12727   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
12728     // If this is a friend function defined in a class template, it does not
12729     // have a body until it is used, nevertheless it is a definition, see
12730     // [temp.inst]p2:
12731     //
12732     // ... for the purpose of determining whether an instantiated redeclaration
12733     // is valid according to [basic.def.odr] and [class.mem], a declaration that
12734     // corresponds to a definition in the template is considered to be a
12735     // definition.
12736     //
12737     // The following code must produce redefinition error:
12738     //
12739     //     template<typename T> struct C20 { friend void func_20() {} };
12740     //     C20<int> c20i;
12741     //     void func_20() {}
12742     //
12743     for (auto I : FD->redecls()) {
12744       if (I != FD && !I->isInvalidDecl() &&
12745           I->getFriendObjectKind() != Decl::FOK_None) {
12746         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
12747           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
12748             // A merged copy of the same function, instantiated as a member of
12749             // the same class, is OK.
12750             if (declaresSameEntity(OrigFD, Original) &&
12751                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
12752                                    cast<Decl>(FD->getLexicalDeclContext())))
12753               continue;
12754           }
12755 
12756           if (Original->isThisDeclarationADefinition()) {
12757             Definition = I;
12758             break;
12759           }
12760         }
12761       }
12762     }
12763   }
12764 
12765   if (!Definition)
12766     // Similar to friend functions a friend function template may be a
12767     // definition and do not have a body if it is instantiated in a class
12768     // template.
12769     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
12770       for (auto I : FTD->redecls()) {
12771         auto D = cast<FunctionTemplateDecl>(I);
12772         if (D != FTD) {
12773           assert(!D->isThisDeclarationADefinition() &&
12774                  "More than one definition in redeclaration chain");
12775           if (D->getFriendObjectKind() != Decl::FOK_None)
12776             if (FunctionTemplateDecl *FT =
12777                                        D->getInstantiatedFromMemberTemplate()) {
12778               if (FT->isThisDeclarationADefinition()) {
12779                 Definition = D->getTemplatedDecl();
12780                 break;
12781               }
12782             }
12783         }
12784       }
12785     }
12786 
12787   if (!Definition)
12788     return;
12789 
12790   if (canRedefineFunction(Definition, getLangOpts()))
12791     return;
12792 
12793   // Don't emit an error when this is redefinition of a typo-corrected
12794   // definition.
12795   if (TypoCorrectedFunctionDefinitions.count(Definition))
12796     return;
12797 
12798   // If we don't have a visible definition of the function, and it's inline or
12799   // a template, skip the new definition.
12800   if (SkipBody && !hasVisibleDefinition(Definition) &&
12801       (Definition->getFormalLinkage() == InternalLinkage ||
12802        Definition->isInlined() ||
12803        Definition->getDescribedFunctionTemplate() ||
12804        Definition->getNumTemplateParameterLists())) {
12805     SkipBody->ShouldSkip = true;
12806     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
12807     if (auto *TD = Definition->getDescribedFunctionTemplate())
12808       makeMergedDefinitionVisible(TD);
12809     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
12810     return;
12811   }
12812 
12813   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
12814       Definition->getStorageClass() == SC_Extern)
12815     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
12816         << FD->getDeclName() << getLangOpts().CPlusPlus;
12817   else
12818     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12819 
12820   Diag(Definition->getLocation(), diag::note_previous_definition);
12821   FD->setInvalidDecl();
12822 }
12823 
12824 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12825                                    Sema &S) {
12826   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12827 
12828   LambdaScopeInfo *LSI = S.PushLambdaScope();
12829   LSI->CallOperator = CallOperator;
12830   LSI->Lambda = LambdaClass;
12831   LSI->ReturnType = CallOperator->getReturnType();
12832   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12833 
12834   if (LCD == LCD_None)
12835     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12836   else if (LCD == LCD_ByCopy)
12837     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12838   else if (LCD == LCD_ByRef)
12839     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12840   DeclarationNameInfo DNI = CallOperator->getNameInfo();
12841 
12842   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12843   LSI->Mutable = !CallOperator->isConst();
12844 
12845   // Add the captures to the LSI so they can be noted as already
12846   // captured within tryCaptureVar.
12847   auto I = LambdaClass->field_begin();
12848   for (const auto &C : LambdaClass->captures()) {
12849     if (C.capturesVariable()) {
12850       VarDecl *VD = C.getCapturedVar();
12851       if (VD->isInitCapture())
12852         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12853       QualType CaptureType = VD->getType();
12854       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12855       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12856           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12857           /*EllipsisLoc*/C.isPackExpansion()
12858                          ? C.getEllipsisLoc() : SourceLocation(),
12859           CaptureType, /*Expr*/ nullptr);
12860 
12861     } else if (C.capturesThis()) {
12862       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
12863                               /*Expr*/ nullptr,
12864                               C.getCaptureKind() == LCK_StarThis);
12865     } else {
12866       LSI->addVLATypeCapture(C.getLocation(), I->getType());
12867     }
12868     ++I;
12869   }
12870 }
12871 
12872 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12873                                     SkipBodyInfo *SkipBody) {
12874   if (!D) {
12875     // Parsing the function declaration failed in some way. Push on a fake scope
12876     // anyway so we can try to parse the function body.
12877     PushFunctionScope();
12878     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12879     return D;
12880   }
12881 
12882   FunctionDecl *FD = nullptr;
12883 
12884   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
12885     FD = FunTmpl->getTemplatedDecl();
12886   else
12887     FD = cast<FunctionDecl>(D);
12888 
12889   // Do not push if it is a lambda because one is already pushed when building
12890   // the lambda in ActOnStartOfLambdaDefinition().
12891   if (!isLambdaCallOperator(FD))
12892     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12893 
12894   // Check for defining attributes before the check for redefinition.
12895   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
12896     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
12897     FD->dropAttr<AliasAttr>();
12898     FD->setInvalidDecl();
12899   }
12900   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12901     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12902     FD->dropAttr<IFuncAttr>();
12903     FD->setInvalidDecl();
12904   }
12905 
12906   // See if this is a redefinition. If 'will have body' is already set, then
12907   // these checks were already performed when it was set.
12908   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
12909     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
12910 
12911     // If we're skipping the body, we're done. Don't enter the scope.
12912     if (SkipBody && SkipBody->ShouldSkip)
12913       return D;
12914   }
12915 
12916   // Mark this function as "will have a body eventually".  This lets users to
12917   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12918   // this function.
12919   FD->setWillHaveBody();
12920 
12921   // If we are instantiating a generic lambda call operator, push
12922   // a LambdaScopeInfo onto the function stack.  But use the information
12923   // that's already been calculated (ActOnLambdaExpr) to prime the current
12924   // LambdaScopeInfo.
12925   // When the template operator is being specialized, the LambdaScopeInfo,
12926   // has to be properly restored so that tryCaptureVariable doesn't try
12927   // and capture any new variables. In addition when calculating potential
12928   // captures during transformation of nested lambdas, it is necessary to
12929   // have the LSI properly restored.
12930   if (isGenericLambdaCallOperatorSpecialization(FD)) {
12931     assert(inTemplateInstantiation() &&
12932            "There should be an active template instantiation on the stack "
12933            "when instantiating a generic lambda!");
12934     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12935   } else {
12936     // Enter a new function scope
12937     PushFunctionScope();
12938   }
12939 
12940   // Builtin functions cannot be defined.
12941   if (unsigned BuiltinID = FD->getBuiltinID()) {
12942     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12943         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12944       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12945       FD->setInvalidDecl();
12946     }
12947   }
12948 
12949   // The return type of a function definition must be complete
12950   // (C99 6.9.1p3, C++ [dcl.fct]p6).
12951   QualType ResultType = FD->getReturnType();
12952   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12953       !FD->isInvalidDecl() &&
12954       RequireCompleteType(FD->getLocation(), ResultType,
12955                           diag::err_func_def_incomplete_result))
12956     FD->setInvalidDecl();
12957 
12958   if (FnBodyScope)
12959     PushDeclContext(FnBodyScope, FD);
12960 
12961   // Check the validity of our function parameters
12962   CheckParmsForFunctionDef(FD->parameters(),
12963                            /*CheckParameterNames=*/true);
12964 
12965   // Add non-parameter declarations already in the function to the current
12966   // scope.
12967   if (FnBodyScope) {
12968     for (Decl *NPD : FD->decls()) {
12969       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
12970       if (!NonParmDecl)
12971         continue;
12972       assert(!isa<ParmVarDecl>(NonParmDecl) &&
12973              "parameters should not be in newly created FD yet");
12974 
12975       // If the decl has a name, make it accessible in the current scope.
12976       if (NonParmDecl->getDeclName())
12977         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
12978 
12979       // Similarly, dive into enums and fish their constants out, making them
12980       // accessible in this scope.
12981       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
12982         for (auto *EI : ED->enumerators())
12983           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
12984       }
12985     }
12986   }
12987 
12988   // Introduce our parameters into the function scope
12989   for (auto Param : FD->parameters()) {
12990     Param->setOwningFunction(FD);
12991 
12992     // If this has an identifier, add it to the scope stack.
12993     if (Param->getIdentifier() && FnBodyScope) {
12994       CheckShadow(FnBodyScope, Param);
12995 
12996       PushOnScopeChains(Param, FnBodyScope);
12997     }
12998   }
12999 
13000   // Ensure that the function's exception specification is instantiated.
13001   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13002     ResolveExceptionSpec(D->getLocation(), FPT);
13003 
13004   // dllimport cannot be applied to non-inline function definitions.
13005   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13006       !FD->isTemplateInstantiation()) {
13007     assert(!FD->hasAttr<DLLExportAttr>());
13008     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13009     FD->setInvalidDecl();
13010     return D;
13011   }
13012   // We want to attach documentation to original Decl (which might be
13013   // a function template).
13014   ActOnDocumentableDecl(D);
13015   if (getCurLexicalContext()->isObjCContainer() &&
13016       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13017       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13018     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13019 
13020   return D;
13021 }
13022 
13023 /// Given the set of return statements within a function body,
13024 /// compute the variables that are subject to the named return value
13025 /// optimization.
13026 ///
13027 /// Each of the variables that is subject to the named return value
13028 /// optimization will be marked as NRVO variables in the AST, and any
13029 /// return statement that has a marked NRVO variable as its NRVO candidate can
13030 /// use the named return value optimization.
13031 ///
13032 /// This function applies a very simplistic algorithm for NRVO: if every return
13033 /// statement in the scope of a variable has the same NRVO candidate, that
13034 /// candidate is an NRVO variable.
13035 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13036   ReturnStmt **Returns = Scope->Returns.data();
13037 
13038   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13039     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13040       if (!NRVOCandidate->isNRVOVariable())
13041         Returns[I]->setNRVOCandidate(nullptr);
13042     }
13043   }
13044 }
13045 
13046 bool Sema::canDelayFunctionBody(const Declarator &D) {
13047   // We can't delay parsing the body of a constexpr function template (yet).
13048   if (D.getDeclSpec().isConstexprSpecified())
13049     return false;
13050 
13051   // We can't delay parsing the body of a function template with a deduced
13052   // return type (yet).
13053   if (D.getDeclSpec().hasAutoTypeSpec()) {
13054     // If the placeholder introduces a non-deduced trailing return type,
13055     // we can still delay parsing it.
13056     if (D.getNumTypeObjects()) {
13057       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13058       if (Outer.Kind == DeclaratorChunk::Function &&
13059           Outer.Fun.hasTrailingReturnType()) {
13060         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13061         return Ty.isNull() || !Ty->isUndeducedType();
13062       }
13063     }
13064     return false;
13065   }
13066 
13067   return true;
13068 }
13069 
13070 bool Sema::canSkipFunctionBody(Decl *D) {
13071   // We cannot skip the body of a function (or function template) which is
13072   // constexpr, since we may need to evaluate its body in order to parse the
13073   // rest of the file.
13074   // We cannot skip the body of a function with an undeduced return type,
13075   // because any callers of that function need to know the type.
13076   if (const FunctionDecl *FD = D->getAsFunction()) {
13077     if (FD->isConstexpr())
13078       return false;
13079     // We can't simply call Type::isUndeducedType here, because inside template
13080     // auto can be deduced to a dependent type, which is not considered
13081     // "undeduced".
13082     if (FD->getReturnType()->getContainedDeducedType())
13083       return false;
13084   }
13085   return Consumer.shouldSkipFunctionBody(D);
13086 }
13087 
13088 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13089   if (!Decl)
13090     return nullptr;
13091   if (FunctionDecl *FD = Decl->getAsFunction())
13092     FD->setHasSkippedBody();
13093   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13094     MD->setHasSkippedBody();
13095   return Decl;
13096 }
13097 
13098 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13099   return ActOnFinishFunctionBody(D, BodyArg, false);
13100 }
13101 
13102 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
13103 /// body.
13104 class ExitFunctionBodyRAII {
13105 public:
13106   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
13107   ~ExitFunctionBodyRAII() {
13108     if (!IsLambda)
13109       S.PopExpressionEvaluationContext();
13110   }
13111 
13112 private:
13113   Sema &S;
13114   bool IsLambda = false;
13115 };
13116 
13117 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13118                                     bool IsInstantiation) {
13119   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13120 
13121   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13122   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13123 
13124   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
13125     CheckCompletedCoroutineBody(FD, Body);
13126 
13127   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13128   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13129   // meant to pop the context added in ActOnStartOfFunctionDef().
13130   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13131 
13132   if (FD) {
13133     FD->setBody(Body);
13134     FD->setWillHaveBody(false);
13135 
13136     if (getLangOpts().CPlusPlus14) {
13137       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13138           FD->getReturnType()->isUndeducedType()) {
13139         // If the function has a deduced result type but contains no 'return'
13140         // statements, the result type as written must be exactly 'auto', and
13141         // the deduced result type is 'void'.
13142         if (!FD->getReturnType()->getAs<AutoType>()) {
13143           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13144               << FD->getReturnType();
13145           FD->setInvalidDecl();
13146         } else {
13147           // Substitute 'void' for the 'auto' in the type.
13148           TypeLoc ResultType = getReturnTypeLoc(FD);
13149           Context.adjustDeducedFunctionResultType(
13150               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13151         }
13152       }
13153     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13154       // In C++11, we don't use 'auto' deduction rules for lambda call
13155       // operators because we don't support return type deduction.
13156       auto *LSI = getCurLambda();
13157       if (LSI->HasImplicitReturnType) {
13158         deduceClosureReturnType(*LSI);
13159 
13160         // C++11 [expr.prim.lambda]p4:
13161         //   [...] if there are no return statements in the compound-statement
13162         //   [the deduced type is] the type void
13163         QualType RetType =
13164             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13165 
13166         // Update the return type to the deduced type.
13167         const FunctionProtoType *Proto =
13168             FD->getType()->getAs<FunctionProtoType>();
13169         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13170                                             Proto->getExtProtoInfo()));
13171       }
13172     }
13173 
13174     // If the function implicitly returns zero (like 'main') or is naked,
13175     // don't complain about missing return statements.
13176     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13177       WP.disableCheckFallThrough();
13178 
13179     // MSVC permits the use of pure specifier (=0) on function definition,
13180     // defined at class scope, warn about this non-standard construct.
13181     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
13182       Diag(FD->getLocation(), diag::ext_pure_function_definition);
13183 
13184     if (!FD->isInvalidDecl()) {
13185       // Don't diagnose unused parameters of defaulted or deleted functions.
13186       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13187         DiagnoseUnusedParameters(FD->parameters());
13188       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13189                                              FD->getReturnType(), FD);
13190 
13191       // If this is a structor, we need a vtable.
13192       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13193         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13194       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13195         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13196 
13197       // Try to apply the named return value optimization. We have to check
13198       // if we can do this here because lambdas keep return statements around
13199       // to deduce an implicit return type.
13200       if (FD->getReturnType()->isRecordType() &&
13201           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13202         computeNRVO(Body, getCurFunction());
13203     }
13204 
13205     // GNU warning -Wmissing-prototypes:
13206     //   Warn if a global function is defined without a previous
13207     //   prototype declaration. This warning is issued even if the
13208     //   definition itself provides a prototype. The aim is to detect
13209     //   global functions that fail to be declared in header files.
13210     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
13211     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
13212       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
13213 
13214       if (PossibleZeroParamPrototype) {
13215         // We found a declaration that is not a prototype,
13216         // but that could be a zero-parameter prototype
13217         if (TypeSourceInfo *TI =
13218                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
13219           TypeLoc TL = TI->getTypeLoc();
13220           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
13221             Diag(PossibleZeroParamPrototype->getLocation(),
13222                  diag::note_declaration_not_a_prototype)
13223                 << PossibleZeroParamPrototype
13224                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
13225         }
13226       }
13227 
13228       // GNU warning -Wstrict-prototypes
13229       //   Warn if K&R function is defined without a previous declaration.
13230       //   This warning is issued only if the definition itself does not provide
13231       //   a prototype. Only K&R definitions do not provide a prototype.
13232       //   An empty list in a function declarator that is part of a definition
13233       //   of that function specifies that the function has no parameters
13234       //   (C99 6.7.5.3p14)
13235       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
13236           !LangOpts.CPlusPlus) {
13237         TypeSourceInfo *TI = FD->getTypeSourceInfo();
13238         TypeLoc TL = TI->getTypeLoc();
13239         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
13240         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
13241       }
13242     }
13243 
13244     // Warn on CPUDispatch with an actual body.
13245     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
13246       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
13247         if (!CmpndBody->body_empty())
13248           Diag(CmpndBody->body_front()->getBeginLoc(),
13249                diag::warn_dispatch_body_ignored);
13250 
13251     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13252       const CXXMethodDecl *KeyFunction;
13253       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
13254           MD->isVirtual() &&
13255           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
13256           MD == KeyFunction->getCanonicalDecl()) {
13257         // Update the key-function state if necessary for this ABI.
13258         if (FD->isInlined() &&
13259             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13260           Context.setNonKeyFunction(MD);
13261 
13262           // If the newly-chosen key function is already defined, then we
13263           // need to mark the vtable as used retroactively.
13264           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
13265           const FunctionDecl *Definition;
13266           if (KeyFunction && KeyFunction->isDefined(Definition))
13267             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
13268         } else {
13269           // We just defined they key function; mark the vtable as used.
13270           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
13271         }
13272       }
13273     }
13274 
13275     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
13276            "Function parsing confused");
13277   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
13278     assert(MD == getCurMethodDecl() && "Method parsing confused");
13279     MD->setBody(Body);
13280     if (!MD->isInvalidDecl()) {
13281       if (!MD->hasSkippedBody())
13282         DiagnoseUnusedParameters(MD->parameters());
13283       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
13284                                              MD->getReturnType(), MD);
13285 
13286       if (Body)
13287         computeNRVO(Body, getCurFunction());
13288     }
13289     if (getCurFunction()->ObjCShouldCallSuper) {
13290       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
13291           << MD->getSelector().getAsString();
13292       getCurFunction()->ObjCShouldCallSuper = false;
13293     }
13294     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
13295       const ObjCMethodDecl *InitMethod = nullptr;
13296       bool isDesignated =
13297           MD->isDesignatedInitializerForTheInterface(&InitMethod);
13298       assert(isDesignated && InitMethod);
13299       (void)isDesignated;
13300 
13301       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
13302         auto IFace = MD->getClassInterface();
13303         if (!IFace)
13304           return false;
13305         auto SuperD = IFace->getSuperClass();
13306         if (!SuperD)
13307           return false;
13308         return SuperD->getIdentifier() ==
13309             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
13310       };
13311       // Don't issue this warning for unavailable inits or direct subclasses
13312       // of NSObject.
13313       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
13314         Diag(MD->getLocation(),
13315              diag::warn_objc_designated_init_missing_super_call);
13316         Diag(InitMethod->getLocation(),
13317              diag::note_objc_designated_init_marked_here);
13318       }
13319       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
13320     }
13321     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
13322       // Don't issue this warning for unavaialable inits.
13323       if (!MD->isUnavailable())
13324         Diag(MD->getLocation(),
13325              diag::warn_objc_secondary_init_missing_init_call);
13326       getCurFunction()->ObjCWarnForNoInitDelegation = false;
13327     }
13328   } else {
13329     // Parsing the function declaration failed in some way. Pop the fake scope
13330     // we pushed on.
13331     PopFunctionScopeInfo(ActivePolicy, dcl);
13332     return nullptr;
13333   }
13334 
13335   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13336     DiagnoseUnguardedAvailabilityViolations(dcl);
13337 
13338   assert(!getCurFunction()->ObjCShouldCallSuper &&
13339          "This should only be set for ObjC methods, which should have been "
13340          "handled in the block above.");
13341 
13342   // Verify and clean out per-function state.
13343   if (Body && (!FD || !FD->isDefaulted())) {
13344     // C++ constructors that have function-try-blocks can't have return
13345     // statements in the handlers of that block. (C++ [except.handle]p14)
13346     // Verify this.
13347     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
13348       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
13349 
13350     // Verify that gotos and switch cases don't jump into scopes illegally.
13351     if (getCurFunction()->NeedsScopeChecking() &&
13352         !PP.isCodeCompletionEnabled())
13353       DiagnoseInvalidJumps(Body);
13354 
13355     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
13356       if (!Destructor->getParent()->isDependentType())
13357         CheckDestructor(Destructor);
13358 
13359       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13360                                              Destructor->getParent());
13361     }
13362 
13363     // If any errors have occurred, clear out any temporaries that may have
13364     // been leftover. This ensures that these temporaries won't be picked up for
13365     // deletion in some later function.
13366     if (getDiagnostics().hasErrorOccurred() ||
13367         getDiagnostics().getSuppressAllDiagnostics()) {
13368       DiscardCleanupsInEvaluationContext();
13369     }
13370     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
13371         !isa<FunctionTemplateDecl>(dcl)) {
13372       // Since the body is valid, issue any analysis-based warnings that are
13373       // enabled.
13374       ActivePolicy = &WP;
13375     }
13376 
13377     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
13378         (!CheckConstexprFunctionDecl(FD) ||
13379          !CheckConstexprFunctionBody(FD, Body)))
13380       FD->setInvalidDecl();
13381 
13382     if (FD && FD->hasAttr<NakedAttr>()) {
13383       for (const Stmt *S : Body->children()) {
13384         // Allow local register variables without initializer as they don't
13385         // require prologue.
13386         bool RegisterVariables = false;
13387         if (auto *DS = dyn_cast<DeclStmt>(S)) {
13388           for (const auto *Decl : DS->decls()) {
13389             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
13390               RegisterVariables =
13391                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
13392               if (!RegisterVariables)
13393                 break;
13394             }
13395           }
13396         }
13397         if (RegisterVariables)
13398           continue;
13399         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
13400           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
13401           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
13402           FD->setInvalidDecl();
13403           break;
13404         }
13405       }
13406     }
13407 
13408     assert(ExprCleanupObjects.size() ==
13409                ExprEvalContexts.back().NumCleanupObjects &&
13410            "Leftover temporaries in function");
13411     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
13412     assert(MaybeODRUseExprs.empty() &&
13413            "Leftover expressions for odr-use checking");
13414   }
13415 
13416   if (!IsInstantiation)
13417     PopDeclContext();
13418 
13419   PopFunctionScopeInfo(ActivePolicy, dcl);
13420   // If any errors have occurred, clear out any temporaries that may have
13421   // been leftover. This ensures that these temporaries won't be picked up for
13422   // deletion in some later function.
13423   if (getDiagnostics().hasErrorOccurred()) {
13424     DiscardCleanupsInEvaluationContext();
13425   }
13426 
13427   return dcl;
13428 }
13429 
13430 /// When we finish delayed parsing of an attribute, we must attach it to the
13431 /// relevant Decl.
13432 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
13433                                        ParsedAttributes &Attrs) {
13434   // Always attach attributes to the underlying decl.
13435   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
13436     D = TD->getTemplatedDecl();
13437   ProcessDeclAttributeList(S, D, Attrs);
13438 
13439   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
13440     if (Method->isStatic())
13441       checkThisInStaticMemberFunctionAttributes(Method);
13442 }
13443 
13444 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
13445 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
13446 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
13447                                           IdentifierInfo &II, Scope *S) {
13448   // Find the scope in which the identifier is injected and the corresponding
13449   // DeclContext.
13450   // FIXME: C89 does not say what happens if there is no enclosing block scope.
13451   // In that case, we inject the declaration into the translation unit scope
13452   // instead.
13453   Scope *BlockScope = S;
13454   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
13455     BlockScope = BlockScope->getParent();
13456 
13457   Scope *ContextScope = BlockScope;
13458   while (!ContextScope->getEntity())
13459     ContextScope = ContextScope->getParent();
13460   ContextRAII SavedContext(*this, ContextScope->getEntity());
13461 
13462   // Before we produce a declaration for an implicitly defined
13463   // function, see whether there was a locally-scoped declaration of
13464   // this name as a function or variable. If so, use that
13465   // (non-visible) declaration, and complain about it.
13466   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
13467   if (ExternCPrev) {
13468     // We still need to inject the function into the enclosing block scope so
13469     // that later (non-call) uses can see it.
13470     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
13471 
13472     // C89 footnote 38:
13473     //   If in fact it is not defined as having type "function returning int",
13474     //   the behavior is undefined.
13475     if (!isa<FunctionDecl>(ExternCPrev) ||
13476         !Context.typesAreCompatible(
13477             cast<FunctionDecl>(ExternCPrev)->getType(),
13478             Context.getFunctionNoProtoType(Context.IntTy))) {
13479       Diag(Loc, diag::ext_use_out_of_scope_declaration)
13480           << ExternCPrev << !getLangOpts().C99;
13481       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
13482       return ExternCPrev;
13483     }
13484   }
13485 
13486   // Extension in C99.  Legal in C90, but warn about it.
13487   unsigned diag_id;
13488   if (II.getName().startswith("__builtin_"))
13489     diag_id = diag::warn_builtin_unknown;
13490   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
13491   else if (getLangOpts().OpenCL)
13492     diag_id = diag::err_opencl_implicit_function_decl;
13493   else if (getLangOpts().C99)
13494     diag_id = diag::ext_implicit_function_decl;
13495   else
13496     diag_id = diag::warn_implicit_function_decl;
13497   Diag(Loc, diag_id) << &II;
13498 
13499   // If we found a prior declaration of this function, don't bother building
13500   // another one. We've already pushed that one into scope, so there's nothing
13501   // more to do.
13502   if (ExternCPrev)
13503     return ExternCPrev;
13504 
13505   // Because typo correction is expensive, only do it if the implicit
13506   // function declaration is going to be treated as an error.
13507   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
13508     TypoCorrection Corrected;
13509     if (S &&
13510         (Corrected = CorrectTypo(
13511              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
13512              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
13513       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
13514                    /*ErrorRecovery*/false);
13515   }
13516 
13517   // Set a Declarator for the implicit definition: int foo();
13518   const char *Dummy;
13519   AttributeFactory attrFactory;
13520   DeclSpec DS(attrFactory);
13521   unsigned DiagID;
13522   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
13523                                   Context.getPrintingPolicy());
13524   (void)Error; // Silence warning.
13525   assert(!Error && "Error setting up implicit decl!");
13526   SourceLocation NoLoc;
13527   Declarator D(DS, DeclaratorContext::BlockContext);
13528   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
13529                                              /*IsAmbiguous=*/false,
13530                                              /*LParenLoc=*/NoLoc,
13531                                              /*Params=*/nullptr,
13532                                              /*NumParams=*/0,
13533                                              /*EllipsisLoc=*/NoLoc,
13534                                              /*RParenLoc=*/NoLoc,
13535                                              /*RefQualifierIsLvalueRef=*/true,
13536                                              /*RefQualifierLoc=*/NoLoc,
13537                                              /*MutableLoc=*/NoLoc, EST_None,
13538                                              /*ESpecRange=*/SourceRange(),
13539                                              /*Exceptions=*/nullptr,
13540                                              /*ExceptionRanges=*/nullptr,
13541                                              /*NumExceptions=*/0,
13542                                              /*NoexceptExpr=*/nullptr,
13543                                              /*ExceptionSpecTokens=*/nullptr,
13544                                              /*DeclsInPrototype=*/None, Loc,
13545                                              Loc, D),
13546                 std::move(DS.getAttributes()), SourceLocation());
13547   D.SetIdentifier(&II, Loc);
13548 
13549   // Insert this function into the enclosing block scope.
13550   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
13551   FD->setImplicit();
13552 
13553   AddKnownFunctionAttributes(FD);
13554 
13555   return FD;
13556 }
13557 
13558 /// Adds any function attributes that we know a priori based on
13559 /// the declaration of this function.
13560 ///
13561 /// These attributes can apply both to implicitly-declared builtins
13562 /// (like __builtin___printf_chk) or to library-declared functions
13563 /// like NSLog or printf.
13564 ///
13565 /// We need to check for duplicate attributes both here and where user-written
13566 /// attributes are applied to declarations.
13567 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
13568   if (FD->isInvalidDecl())
13569     return;
13570 
13571   // If this is a built-in function, map its builtin attributes to
13572   // actual attributes.
13573   if (unsigned BuiltinID = FD->getBuiltinID()) {
13574     // Handle printf-formatting attributes.
13575     unsigned FormatIdx;
13576     bool HasVAListArg;
13577     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
13578       if (!FD->hasAttr<FormatAttr>()) {
13579         const char *fmt = "printf";
13580         unsigned int NumParams = FD->getNumParams();
13581         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
13582             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
13583           fmt = "NSString";
13584         FD->addAttr(FormatAttr::CreateImplicit(Context,
13585                                                &Context.Idents.get(fmt),
13586                                                FormatIdx+1,
13587                                                HasVAListArg ? 0 : FormatIdx+2,
13588                                                FD->getLocation()));
13589       }
13590     }
13591     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
13592                                              HasVAListArg)) {
13593      if (!FD->hasAttr<FormatAttr>())
13594        FD->addAttr(FormatAttr::CreateImplicit(Context,
13595                                               &Context.Idents.get("scanf"),
13596                                               FormatIdx+1,
13597                                               HasVAListArg ? 0 : FormatIdx+2,
13598                                               FD->getLocation()));
13599     }
13600 
13601     // Handle automatically recognized callbacks.
13602     SmallVector<int, 4> Encoding;
13603     if (!FD->hasAttr<CallbackAttr>() &&
13604         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
13605       FD->addAttr(CallbackAttr::CreateImplicit(
13606           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
13607 
13608     // Mark const if we don't care about errno and that is the only thing
13609     // preventing the function from being const. This allows IRgen to use LLVM
13610     // intrinsics for such functions.
13611     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
13612         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
13613       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13614 
13615     // We make "fma" on some platforms const because we know it does not set
13616     // errno in those environments even though it could set errno based on the
13617     // C standard.
13618     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
13619     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
13620         !FD->hasAttr<ConstAttr>()) {
13621       switch (BuiltinID) {
13622       case Builtin::BI__builtin_fma:
13623       case Builtin::BI__builtin_fmaf:
13624       case Builtin::BI__builtin_fmal:
13625       case Builtin::BIfma:
13626       case Builtin::BIfmaf:
13627       case Builtin::BIfmal:
13628         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13629         break;
13630       default:
13631         break;
13632       }
13633     }
13634 
13635     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
13636         !FD->hasAttr<ReturnsTwiceAttr>())
13637       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
13638                                          FD->getLocation()));
13639     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
13640       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13641     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
13642       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
13643     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
13644       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13645     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
13646         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
13647       // Add the appropriate attribute, depending on the CUDA compilation mode
13648       // and which target the builtin belongs to. For example, during host
13649       // compilation, aux builtins are __device__, while the rest are __host__.
13650       if (getLangOpts().CUDAIsDevice !=
13651           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
13652         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
13653       else
13654         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
13655     }
13656   }
13657 
13658   // If C++ exceptions are enabled but we are told extern "C" functions cannot
13659   // throw, add an implicit nothrow attribute to any extern "C" function we come
13660   // across.
13661   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
13662       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
13663     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
13664     if (!FPT || FPT->getExceptionSpecType() == EST_None)
13665       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13666   }
13667 
13668   IdentifierInfo *Name = FD->getIdentifier();
13669   if (!Name)
13670     return;
13671   if ((!getLangOpts().CPlusPlus &&
13672        FD->getDeclContext()->isTranslationUnit()) ||
13673       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
13674        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
13675        LinkageSpecDecl::lang_c)) {
13676     // Okay: this could be a libc/libm/Objective-C function we know
13677     // about.
13678   } else
13679     return;
13680 
13681   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
13682     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
13683     // target-specific builtins, perhaps?
13684     if (!FD->hasAttr<FormatAttr>())
13685       FD->addAttr(FormatAttr::CreateImplicit(Context,
13686                                              &Context.Idents.get("printf"), 2,
13687                                              Name->isStr("vasprintf") ? 0 : 3,
13688                                              FD->getLocation()));
13689   }
13690 
13691   if (Name->isStr("__CFStringMakeConstantString")) {
13692     // We already have a __builtin___CFStringMakeConstantString,
13693     // but builds that use -fno-constant-cfstrings don't go through that.
13694     if (!FD->hasAttr<FormatArgAttr>())
13695       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
13696                                                 FD->getLocation()));
13697   }
13698 }
13699 
13700 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
13701                                     TypeSourceInfo *TInfo) {
13702   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
13703   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
13704 
13705   if (!TInfo) {
13706     assert(D.isInvalidType() && "no declarator info for valid type");
13707     TInfo = Context.getTrivialTypeSourceInfo(T);
13708   }
13709 
13710   // Scope manipulation handled by caller.
13711   TypedefDecl *NewTD =
13712       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
13713                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
13714 
13715   // Bail out immediately if we have an invalid declaration.
13716   if (D.isInvalidType()) {
13717     NewTD->setInvalidDecl();
13718     return NewTD;
13719   }
13720 
13721   if (D.getDeclSpec().isModulePrivateSpecified()) {
13722     if (CurContext->isFunctionOrMethod())
13723       Diag(NewTD->getLocation(), diag::err_module_private_local)
13724         << 2 << NewTD->getDeclName()
13725         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13726         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13727     else
13728       NewTD->setModulePrivate();
13729   }
13730 
13731   // C++ [dcl.typedef]p8:
13732   //   If the typedef declaration defines an unnamed class (or
13733   //   enum), the first typedef-name declared by the declaration
13734   //   to be that class type (or enum type) is used to denote the
13735   //   class type (or enum type) for linkage purposes only.
13736   // We need to check whether the type was declared in the declaration.
13737   switch (D.getDeclSpec().getTypeSpecType()) {
13738   case TST_enum:
13739   case TST_struct:
13740   case TST_interface:
13741   case TST_union:
13742   case TST_class: {
13743     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
13744     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
13745     break;
13746   }
13747 
13748   default:
13749     break;
13750   }
13751 
13752   return NewTD;
13753 }
13754 
13755 /// Check that this is a valid underlying type for an enum declaration.
13756 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
13757   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
13758   QualType T = TI->getType();
13759 
13760   if (T->isDependentType())
13761     return false;
13762 
13763   if (const BuiltinType *BT = T->getAs<BuiltinType>())
13764     if (BT->isInteger())
13765       return false;
13766 
13767   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
13768   return true;
13769 }
13770 
13771 /// Check whether this is a valid redeclaration of a previous enumeration.
13772 /// \return true if the redeclaration was invalid.
13773 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
13774                                   QualType EnumUnderlyingTy, bool IsFixed,
13775                                   const EnumDecl *Prev) {
13776   if (IsScoped != Prev->isScoped()) {
13777     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
13778       << Prev->isScoped();
13779     Diag(Prev->getLocation(), diag::note_previous_declaration);
13780     return true;
13781   }
13782 
13783   if (IsFixed && Prev->isFixed()) {
13784     if (!EnumUnderlyingTy->isDependentType() &&
13785         !Prev->getIntegerType()->isDependentType() &&
13786         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
13787                                         Prev->getIntegerType())) {
13788       // TODO: Highlight the underlying type of the redeclaration.
13789       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
13790         << EnumUnderlyingTy << Prev->getIntegerType();
13791       Diag(Prev->getLocation(), diag::note_previous_declaration)
13792           << Prev->getIntegerTypeRange();
13793       return true;
13794     }
13795   } else if (IsFixed != Prev->isFixed()) {
13796     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
13797       << Prev->isFixed();
13798     Diag(Prev->getLocation(), diag::note_previous_declaration);
13799     return true;
13800   }
13801 
13802   return false;
13803 }
13804 
13805 /// Get diagnostic %select index for tag kind for
13806 /// redeclaration diagnostic message.
13807 /// WARNING: Indexes apply to particular diagnostics only!
13808 ///
13809 /// \returns diagnostic %select index.
13810 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
13811   switch (Tag) {
13812   case TTK_Struct: return 0;
13813   case TTK_Interface: return 1;
13814   case TTK_Class:  return 2;
13815   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
13816   }
13817 }
13818 
13819 /// Determine if tag kind is a class-key compatible with
13820 /// class for redeclaration (class, struct, or __interface).
13821 ///
13822 /// \returns true iff the tag kind is compatible.
13823 static bool isClassCompatTagKind(TagTypeKind Tag)
13824 {
13825   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
13826 }
13827 
13828 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
13829                                              TagTypeKind TTK) {
13830   if (isa<TypedefDecl>(PrevDecl))
13831     return NTK_Typedef;
13832   else if (isa<TypeAliasDecl>(PrevDecl))
13833     return NTK_TypeAlias;
13834   else if (isa<ClassTemplateDecl>(PrevDecl))
13835     return NTK_Template;
13836   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
13837     return NTK_TypeAliasTemplate;
13838   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
13839     return NTK_TemplateTemplateArgument;
13840   switch (TTK) {
13841   case TTK_Struct:
13842   case TTK_Interface:
13843   case TTK_Class:
13844     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
13845   case TTK_Union:
13846     return NTK_NonUnion;
13847   case TTK_Enum:
13848     return NTK_NonEnum;
13849   }
13850   llvm_unreachable("invalid TTK");
13851 }
13852 
13853 /// Determine whether a tag with a given kind is acceptable
13854 /// as a redeclaration of the given tag declaration.
13855 ///
13856 /// \returns true if the new tag kind is acceptable, false otherwise.
13857 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
13858                                         TagTypeKind NewTag, bool isDefinition,
13859                                         SourceLocation NewTagLoc,
13860                                         const IdentifierInfo *Name) {
13861   // C++ [dcl.type.elab]p3:
13862   //   The class-key or enum keyword present in the
13863   //   elaborated-type-specifier shall agree in kind with the
13864   //   declaration to which the name in the elaborated-type-specifier
13865   //   refers. This rule also applies to the form of
13866   //   elaborated-type-specifier that declares a class-name or
13867   //   friend class since it can be construed as referring to the
13868   //   definition of the class. Thus, in any
13869   //   elaborated-type-specifier, the enum keyword shall be used to
13870   //   refer to an enumeration (7.2), the union class-key shall be
13871   //   used to refer to a union (clause 9), and either the class or
13872   //   struct class-key shall be used to refer to a class (clause 9)
13873   //   declared using the class or struct class-key.
13874   TagTypeKind OldTag = Previous->getTagKind();
13875   if (OldTag != NewTag &&
13876       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
13877     return false;
13878 
13879   // Tags are compatible, but we might still want to warn on mismatched tags.
13880   // Non-class tags can't be mismatched at this point.
13881   if (!isClassCompatTagKind(NewTag))
13882     return true;
13883 
13884   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
13885   // by our warning analysis. We don't want to warn about mismatches with (eg)
13886   // declarations in system headers that are designed to be specialized, but if
13887   // a user asks us to warn, we should warn if their code contains mismatched
13888   // declarations.
13889   auto IsIgnoredLoc = [&](SourceLocation Loc) {
13890     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
13891                                       Loc);
13892   };
13893   if (IsIgnoredLoc(NewTagLoc))
13894     return true;
13895 
13896   auto IsIgnored = [&](const TagDecl *Tag) {
13897     return IsIgnoredLoc(Tag->getLocation());
13898   };
13899   while (IsIgnored(Previous)) {
13900     Previous = Previous->getPreviousDecl();
13901     if (!Previous)
13902       return true;
13903     OldTag = Previous->getTagKind();
13904   }
13905 
13906   bool isTemplate = false;
13907   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
13908     isTemplate = Record->getDescribedClassTemplate();
13909 
13910   if (inTemplateInstantiation()) {
13911     if (OldTag != NewTag) {
13912       // In a template instantiation, do not offer fix-its for tag mismatches
13913       // since they usually mess up the template instead of fixing the problem.
13914       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13915         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13916         << getRedeclDiagFromTagKind(OldTag);
13917       // FIXME: Note previous location?
13918     }
13919     return true;
13920   }
13921 
13922   if (isDefinition) {
13923     // On definitions, check all previous tags and issue a fix-it for each
13924     // one that doesn't match the current tag.
13925     if (Previous->getDefinition()) {
13926       // Don't suggest fix-its for redefinitions.
13927       return true;
13928     }
13929 
13930     bool previousMismatch = false;
13931     for (const TagDecl *I : Previous->redecls()) {
13932       if (I->getTagKind() != NewTag) {
13933         // Ignore previous declarations for which the warning was disabled.
13934         if (IsIgnored(I))
13935           continue;
13936 
13937         if (!previousMismatch) {
13938           previousMismatch = true;
13939           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
13940             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13941             << getRedeclDiagFromTagKind(I->getTagKind());
13942         }
13943         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
13944           << getRedeclDiagFromTagKind(NewTag)
13945           << FixItHint::CreateReplacement(I->getInnerLocStart(),
13946                TypeWithKeyword::getTagTypeKindName(NewTag));
13947       }
13948     }
13949     return true;
13950   }
13951 
13952   // Identify the prevailing tag kind: this is the kind of the definition (if
13953   // there is a non-ignored definition), or otherwise the kind of the prior
13954   // (non-ignored) declaration.
13955   const TagDecl *PrevDef = Previous->getDefinition();
13956   if (PrevDef && IsIgnored(PrevDef))
13957     PrevDef = nullptr;
13958   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
13959   if (Redecl->getTagKind() != NewTag) {
13960     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13961       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13962       << getRedeclDiagFromTagKind(OldTag);
13963     Diag(Redecl->getLocation(), diag::note_previous_use);
13964 
13965     // If there is a previous definition, suggest a fix-it.
13966     if (PrevDef) {
13967       Diag(NewTagLoc, diag::note_struct_class_suggestion)
13968         << getRedeclDiagFromTagKind(Redecl->getTagKind())
13969         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
13970              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
13971     }
13972   }
13973 
13974   return true;
13975 }
13976 
13977 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
13978 /// from an outer enclosing namespace or file scope inside a friend declaration.
13979 /// This should provide the commented out code in the following snippet:
13980 ///   namespace N {
13981 ///     struct X;
13982 ///     namespace M {
13983 ///       struct Y { friend struct /*N::*/ X; };
13984 ///     }
13985 ///   }
13986 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
13987                                          SourceLocation NameLoc) {
13988   // While the decl is in a namespace, do repeated lookup of that name and see
13989   // if we get the same namespace back.  If we do not, continue until
13990   // translation unit scope, at which point we have a fully qualified NNS.
13991   SmallVector<IdentifierInfo *, 4> Namespaces;
13992   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13993   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
13994     // This tag should be declared in a namespace, which can only be enclosed by
13995     // other namespaces.  Bail if there's an anonymous namespace in the chain.
13996     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
13997     if (!Namespace || Namespace->isAnonymousNamespace())
13998       return FixItHint();
13999     IdentifierInfo *II = Namespace->getIdentifier();
14000     Namespaces.push_back(II);
14001     NamedDecl *Lookup = SemaRef.LookupSingleName(
14002         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
14003     if (Lookup == Namespace)
14004       break;
14005   }
14006 
14007   // Once we have all the namespaces, reverse them to go outermost first, and
14008   // build an NNS.
14009   SmallString<64> Insertion;
14010   llvm::raw_svector_ostream OS(Insertion);
14011   if (DC->isTranslationUnit())
14012     OS << "::";
14013   std::reverse(Namespaces.begin(), Namespaces.end());
14014   for (auto *II : Namespaces)
14015     OS << II->getName() << "::";
14016   return FixItHint::CreateInsertion(NameLoc, Insertion);
14017 }
14018 
14019 /// Determine whether a tag originally declared in context \p OldDC can
14020 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14021 /// found a declaration in \p OldDC as a previous decl, perhaps through a
14022 /// using-declaration).
14023 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
14024                                          DeclContext *NewDC) {
14025   OldDC = OldDC->getRedeclContext();
14026   NewDC = NewDC->getRedeclContext();
14027 
14028   if (OldDC->Equals(NewDC))
14029     return true;
14030 
14031   // In MSVC mode, we allow a redeclaration if the contexts are related (either
14032   // encloses the other).
14033   if (S.getLangOpts().MSVCCompat &&
14034       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14035     return true;
14036 
14037   return false;
14038 }
14039 
14040 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
14041 /// former case, Name will be non-null.  In the later case, Name will be null.
14042 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14043 /// reference/declaration/definition of a tag.
14044 ///
14045 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
14046 /// trailing-type-specifier) other than one in an alias-declaration.
14047 ///
14048 /// \param SkipBody If non-null, will be set to indicate if the caller should
14049 /// skip the definition of this tag and treat it as if it were a declaration.
14050 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
14051                      SourceLocation KWLoc, CXXScopeSpec &SS,
14052                      IdentifierInfo *Name, SourceLocation NameLoc,
14053                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
14054                      SourceLocation ModulePrivateLoc,
14055                      MultiTemplateParamsArg TemplateParameterLists,
14056                      bool &OwnedDecl, bool &IsDependent,
14057                      SourceLocation ScopedEnumKWLoc,
14058                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
14059                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
14060                      SkipBodyInfo *SkipBody) {
14061   // If this is not a definition, it must have a name.
14062   IdentifierInfo *OrigName = Name;
14063   assert((Name != nullptr || TUK == TUK_Definition) &&
14064          "Nameless record must be a definition!");
14065   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14066 
14067   OwnedDecl = false;
14068   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14069   bool ScopedEnum = ScopedEnumKWLoc.isValid();
14070 
14071   // FIXME: Check member specializations more carefully.
14072   bool isMemberSpecialization = false;
14073   bool Invalid = false;
14074 
14075   // We only need to do this matching if we have template parameters
14076   // or a scope specifier, which also conveniently avoids this work
14077   // for non-C++ cases.
14078   if (TemplateParameterLists.size() > 0 ||
14079       (SS.isNotEmpty() && TUK != TUK_Reference)) {
14080     if (TemplateParameterList *TemplateParams =
14081             MatchTemplateParametersToScopeSpecifier(
14082                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14083                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14084       if (Kind == TTK_Enum) {
14085         Diag(KWLoc, diag::err_enum_template);
14086         return nullptr;
14087       }
14088 
14089       if (TemplateParams->size() > 0) {
14090         // This is a declaration or definition of a class template (which may
14091         // be a member of another template).
14092 
14093         if (Invalid)
14094           return nullptr;
14095 
14096         OwnedDecl = false;
14097         DeclResult Result = CheckClassTemplate(
14098             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14099             AS, ModulePrivateLoc,
14100             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14101             TemplateParameterLists.data(), SkipBody);
14102         return Result.get();
14103       } else {
14104         // The "template<>" header is extraneous.
14105         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14106           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14107         isMemberSpecialization = true;
14108       }
14109     }
14110   }
14111 
14112   // Figure out the underlying type if this a enum declaration. We need to do
14113   // this early, because it's needed to detect if this is an incompatible
14114   // redeclaration.
14115   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14116   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14117 
14118   if (Kind == TTK_Enum) {
14119     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14120       // No underlying type explicitly specified, or we failed to parse the
14121       // type, default to int.
14122       EnumUnderlying = Context.IntTy.getTypePtr();
14123     } else if (UnderlyingType.get()) {
14124       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14125       // integral type; any cv-qualification is ignored.
14126       TypeSourceInfo *TI = nullptr;
14127       GetTypeFromParser(UnderlyingType.get(), &TI);
14128       EnumUnderlying = TI;
14129 
14130       if (CheckEnumUnderlyingType(TI))
14131         // Recover by falling back to int.
14132         EnumUnderlying = Context.IntTy.getTypePtr();
14133 
14134       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14135                                           UPPC_FixedUnderlyingType))
14136         EnumUnderlying = Context.IntTy.getTypePtr();
14137 
14138     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14139       // For MSVC ABI compatibility, unfixed enums must use an underlying type
14140       // of 'int'. However, if this is an unfixed forward declaration, don't set
14141       // the underlying type unless the user enables -fms-compatibility. This
14142       // makes unfixed forward declared enums incomplete and is more conforming.
14143       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14144         EnumUnderlying = Context.IntTy.getTypePtr();
14145     }
14146   }
14147 
14148   DeclContext *SearchDC = CurContext;
14149   DeclContext *DC = CurContext;
14150   bool isStdBadAlloc = false;
14151   bool isStdAlignValT = false;
14152 
14153   RedeclarationKind Redecl = forRedeclarationInCurContext();
14154   if (TUK == TUK_Friend || TUK == TUK_Reference)
14155     Redecl = NotForRedeclaration;
14156 
14157   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14158   /// implemented asks for structural equivalence checking, the returned decl
14159   /// here is passed back to the parser, allowing the tag body to be parsed.
14160   auto createTagFromNewDecl = [&]() -> TagDecl * {
14161     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14162     // If there is an identifier, use the location of the identifier as the
14163     // location of the decl, otherwise use the location of the struct/union
14164     // keyword.
14165     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14166     TagDecl *New = nullptr;
14167 
14168     if (Kind == TTK_Enum) {
14169       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14170                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14171       // If this is an undefined enum, bail.
14172       if (TUK != TUK_Definition && !Invalid)
14173         return nullptr;
14174       if (EnumUnderlying) {
14175         EnumDecl *ED = cast<EnumDecl>(New);
14176         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14177           ED->setIntegerTypeSourceInfo(TI);
14178         else
14179           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14180         ED->setPromotionType(ED->getIntegerType());
14181       }
14182     } else { // struct/union
14183       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14184                                nullptr);
14185     }
14186 
14187     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14188       // Add alignment attributes if necessary; these attributes are checked
14189       // when the ASTContext lays out the structure.
14190       //
14191       // It is important for implementing the correct semantics that this
14192       // happen here (in ActOnTag). The #pragma pack stack is
14193       // maintained as a result of parser callbacks which can occur at
14194       // many points during the parsing of a struct declaration (because
14195       // the #pragma tokens are effectively skipped over during the
14196       // parsing of the struct).
14197       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14198         AddAlignmentAttributesForRecord(RD);
14199         AddMsStructLayoutForRecord(RD);
14200       }
14201     }
14202     New->setLexicalDeclContext(CurContext);
14203     return New;
14204   };
14205 
14206   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
14207   if (Name && SS.isNotEmpty()) {
14208     // We have a nested-name tag ('struct foo::bar').
14209 
14210     // Check for invalid 'foo::'.
14211     if (SS.isInvalid()) {
14212       Name = nullptr;
14213       goto CreateNewDecl;
14214     }
14215 
14216     // If this is a friend or a reference to a class in a dependent
14217     // context, don't try to make a decl for it.
14218     if (TUK == TUK_Friend || TUK == TUK_Reference) {
14219       DC = computeDeclContext(SS, false);
14220       if (!DC) {
14221         IsDependent = true;
14222         return nullptr;
14223       }
14224     } else {
14225       DC = computeDeclContext(SS, true);
14226       if (!DC) {
14227         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
14228           << SS.getRange();
14229         return nullptr;
14230       }
14231     }
14232 
14233     if (RequireCompleteDeclContext(SS, DC))
14234       return nullptr;
14235 
14236     SearchDC = DC;
14237     // Look-up name inside 'foo::'.
14238     LookupQualifiedName(Previous, DC);
14239 
14240     if (Previous.isAmbiguous())
14241       return nullptr;
14242 
14243     if (Previous.empty()) {
14244       // Name lookup did not find anything. However, if the
14245       // nested-name-specifier refers to the current instantiation,
14246       // and that current instantiation has any dependent base
14247       // classes, we might find something at instantiation time: treat
14248       // this as a dependent elaborated-type-specifier.
14249       // But this only makes any sense for reference-like lookups.
14250       if (Previous.wasNotFoundInCurrentInstantiation() &&
14251           (TUK == TUK_Reference || TUK == TUK_Friend)) {
14252         IsDependent = true;
14253         return nullptr;
14254       }
14255 
14256       // A tag 'foo::bar' must already exist.
14257       Diag(NameLoc, diag::err_not_tag_in_scope)
14258         << Kind << Name << DC << SS.getRange();
14259       Name = nullptr;
14260       Invalid = true;
14261       goto CreateNewDecl;
14262     }
14263   } else if (Name) {
14264     // C++14 [class.mem]p14:
14265     //   If T is the name of a class, then each of the following shall have a
14266     //   name different from T:
14267     //    -- every member of class T that is itself a type
14268     if (TUK != TUK_Reference && TUK != TUK_Friend &&
14269         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
14270       return nullptr;
14271 
14272     // If this is a named struct, check to see if there was a previous forward
14273     // declaration or definition.
14274     // FIXME: We're looking into outer scopes here, even when we
14275     // shouldn't be. Doing so can result in ambiguities that we
14276     // shouldn't be diagnosing.
14277     LookupName(Previous, S);
14278 
14279     // When declaring or defining a tag, ignore ambiguities introduced
14280     // by types using'ed into this scope.
14281     if (Previous.isAmbiguous() &&
14282         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
14283       LookupResult::Filter F = Previous.makeFilter();
14284       while (F.hasNext()) {
14285         NamedDecl *ND = F.next();
14286         if (!ND->getDeclContext()->getRedeclContext()->Equals(
14287                 SearchDC->getRedeclContext()))
14288           F.erase();
14289       }
14290       F.done();
14291     }
14292 
14293     // C++11 [namespace.memdef]p3:
14294     //   If the name in a friend declaration is neither qualified nor
14295     //   a template-id and the declaration is a function or an
14296     //   elaborated-type-specifier, the lookup to determine whether
14297     //   the entity has been previously declared shall not consider
14298     //   any scopes outside the innermost enclosing namespace.
14299     //
14300     // MSVC doesn't implement the above rule for types, so a friend tag
14301     // declaration may be a redeclaration of a type declared in an enclosing
14302     // scope.  They do implement this rule for friend functions.
14303     //
14304     // Does it matter that this should be by scope instead of by
14305     // semantic context?
14306     if (!Previous.empty() && TUK == TUK_Friend) {
14307       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
14308       LookupResult::Filter F = Previous.makeFilter();
14309       bool FriendSawTagOutsideEnclosingNamespace = false;
14310       while (F.hasNext()) {
14311         NamedDecl *ND = F.next();
14312         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14313         if (DC->isFileContext() &&
14314             !EnclosingNS->Encloses(ND->getDeclContext())) {
14315           if (getLangOpts().MSVCCompat)
14316             FriendSawTagOutsideEnclosingNamespace = true;
14317           else
14318             F.erase();
14319         }
14320       }
14321       F.done();
14322 
14323       // Diagnose this MSVC extension in the easy case where lookup would have
14324       // unambiguously found something outside the enclosing namespace.
14325       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
14326         NamedDecl *ND = Previous.getFoundDecl();
14327         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
14328             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
14329       }
14330     }
14331 
14332     // Note:  there used to be some attempt at recovery here.
14333     if (Previous.isAmbiguous())
14334       return nullptr;
14335 
14336     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
14337       // FIXME: This makes sure that we ignore the contexts associated
14338       // with C structs, unions, and enums when looking for a matching
14339       // tag declaration or definition. See the similar lookup tweak
14340       // in Sema::LookupName; is there a better way to deal with this?
14341       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
14342         SearchDC = SearchDC->getParent();
14343     }
14344   }
14345 
14346   if (Previous.isSingleResult() &&
14347       Previous.getFoundDecl()->isTemplateParameter()) {
14348     // Maybe we will complain about the shadowed template parameter.
14349     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
14350     // Just pretend that we didn't see the previous declaration.
14351     Previous.clear();
14352   }
14353 
14354   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
14355       DC->Equals(getStdNamespace())) {
14356     if (Name->isStr("bad_alloc")) {
14357       // This is a declaration of or a reference to "std::bad_alloc".
14358       isStdBadAlloc = true;
14359 
14360       // If std::bad_alloc has been implicitly declared (but made invisible to
14361       // name lookup), fill in this implicit declaration as the previous
14362       // declaration, so that the declarations get chained appropriately.
14363       if (Previous.empty() && StdBadAlloc)
14364         Previous.addDecl(getStdBadAlloc());
14365     } else if (Name->isStr("align_val_t")) {
14366       isStdAlignValT = true;
14367       if (Previous.empty() && StdAlignValT)
14368         Previous.addDecl(getStdAlignValT());
14369     }
14370   }
14371 
14372   // If we didn't find a previous declaration, and this is a reference
14373   // (or friend reference), move to the correct scope.  In C++, we
14374   // also need to do a redeclaration lookup there, just in case
14375   // there's a shadow friend decl.
14376   if (Name && Previous.empty() &&
14377       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
14378     if (Invalid) goto CreateNewDecl;
14379     assert(SS.isEmpty());
14380 
14381     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
14382       // C++ [basic.scope.pdecl]p5:
14383       //   -- for an elaborated-type-specifier of the form
14384       //
14385       //          class-key identifier
14386       //
14387       //      if the elaborated-type-specifier is used in the
14388       //      decl-specifier-seq or parameter-declaration-clause of a
14389       //      function defined in namespace scope, the identifier is
14390       //      declared as a class-name in the namespace that contains
14391       //      the declaration; otherwise, except as a friend
14392       //      declaration, the identifier is declared in the smallest
14393       //      non-class, non-function-prototype scope that contains the
14394       //      declaration.
14395       //
14396       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
14397       // C structs and unions.
14398       //
14399       // It is an error in C++ to declare (rather than define) an enum
14400       // type, including via an elaborated type specifier.  We'll
14401       // diagnose that later; for now, declare the enum in the same
14402       // scope as we would have picked for any other tag type.
14403       //
14404       // GNU C also supports this behavior as part of its incomplete
14405       // enum types extension, while GNU C++ does not.
14406       //
14407       // Find the context where we'll be declaring the tag.
14408       // FIXME: We would like to maintain the current DeclContext as the
14409       // lexical context,
14410       SearchDC = getTagInjectionContext(SearchDC);
14411 
14412       // Find the scope where we'll be declaring the tag.
14413       S = getTagInjectionScope(S, getLangOpts());
14414     } else {
14415       assert(TUK == TUK_Friend);
14416       // C++ [namespace.memdef]p3:
14417       //   If a friend declaration in a non-local class first declares a
14418       //   class or function, the friend class or function is a member of
14419       //   the innermost enclosing namespace.
14420       SearchDC = SearchDC->getEnclosingNamespaceContext();
14421     }
14422 
14423     // In C++, we need to do a redeclaration lookup to properly
14424     // diagnose some problems.
14425     // FIXME: redeclaration lookup is also used (with and without C++) to find a
14426     // hidden declaration so that we don't get ambiguity errors when using a
14427     // type declared by an elaborated-type-specifier.  In C that is not correct
14428     // and we should instead merge compatible types found by lookup.
14429     if (getLangOpts().CPlusPlus) {
14430       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14431       LookupQualifiedName(Previous, SearchDC);
14432     } else {
14433       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14434       LookupName(Previous, S);
14435     }
14436   }
14437 
14438   // If we have a known previous declaration to use, then use it.
14439   if (Previous.empty() && SkipBody && SkipBody->Previous)
14440     Previous.addDecl(SkipBody->Previous);
14441 
14442   if (!Previous.empty()) {
14443     NamedDecl *PrevDecl = Previous.getFoundDecl();
14444     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
14445 
14446     // It's okay to have a tag decl in the same scope as a typedef
14447     // which hides a tag decl in the same scope.  Finding this
14448     // insanity with a redeclaration lookup can only actually happen
14449     // in C++.
14450     //
14451     // This is also okay for elaborated-type-specifiers, which is
14452     // technically forbidden by the current standard but which is
14453     // okay according to the likely resolution of an open issue;
14454     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
14455     if (getLangOpts().CPlusPlus) {
14456       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14457         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
14458           TagDecl *Tag = TT->getDecl();
14459           if (Tag->getDeclName() == Name &&
14460               Tag->getDeclContext()->getRedeclContext()
14461                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
14462             PrevDecl = Tag;
14463             Previous.clear();
14464             Previous.addDecl(Tag);
14465             Previous.resolveKind();
14466           }
14467         }
14468       }
14469     }
14470 
14471     // If this is a redeclaration of a using shadow declaration, it must
14472     // declare a tag in the same context. In MSVC mode, we allow a
14473     // redefinition if either context is within the other.
14474     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
14475       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
14476       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
14477           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
14478           !(OldTag && isAcceptableTagRedeclContext(
14479                           *this, OldTag->getDeclContext(), SearchDC))) {
14480         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
14481         Diag(Shadow->getTargetDecl()->getLocation(),
14482              diag::note_using_decl_target);
14483         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
14484             << 0;
14485         // Recover by ignoring the old declaration.
14486         Previous.clear();
14487         goto CreateNewDecl;
14488       }
14489     }
14490 
14491     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
14492       // If this is a use of a previous tag, or if the tag is already declared
14493       // in the same scope (so that the definition/declaration completes or
14494       // rementions the tag), reuse the decl.
14495       if (TUK == TUK_Reference || TUK == TUK_Friend ||
14496           isDeclInScope(DirectPrevDecl, SearchDC, S,
14497                         SS.isNotEmpty() || isMemberSpecialization)) {
14498         // Make sure that this wasn't declared as an enum and now used as a
14499         // struct or something similar.
14500         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
14501                                           TUK == TUK_Definition, KWLoc,
14502                                           Name)) {
14503           bool SafeToContinue
14504             = (PrevTagDecl->getTagKind() != TTK_Enum &&
14505                Kind != TTK_Enum);
14506           if (SafeToContinue)
14507             Diag(KWLoc, diag::err_use_with_wrong_tag)
14508               << Name
14509               << FixItHint::CreateReplacement(SourceRange(KWLoc),
14510                                               PrevTagDecl->getKindName());
14511           else
14512             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
14513           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
14514 
14515           if (SafeToContinue)
14516             Kind = PrevTagDecl->getTagKind();
14517           else {
14518             // Recover by making this an anonymous redefinition.
14519             Name = nullptr;
14520             Previous.clear();
14521             Invalid = true;
14522           }
14523         }
14524 
14525         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
14526           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
14527 
14528           // If this is an elaborated-type-specifier for a scoped enumeration,
14529           // the 'class' keyword is not necessary and not permitted.
14530           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14531             if (ScopedEnum)
14532               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
14533                 << PrevEnum->isScoped()
14534                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
14535             return PrevTagDecl;
14536           }
14537 
14538           QualType EnumUnderlyingTy;
14539           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14540             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
14541           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
14542             EnumUnderlyingTy = QualType(T, 0);
14543 
14544           // All conflicts with previous declarations are recovered by
14545           // returning the previous declaration, unless this is a definition,
14546           // in which case we want the caller to bail out.
14547           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
14548                                      ScopedEnum, EnumUnderlyingTy,
14549                                      IsFixed, PrevEnum))
14550             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
14551         }
14552 
14553         // C++11 [class.mem]p1:
14554         //   A member shall not be declared twice in the member-specification,
14555         //   except that a nested class or member class template can be declared
14556         //   and then later defined.
14557         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
14558             S->isDeclScope(PrevDecl)) {
14559           Diag(NameLoc, diag::ext_member_redeclared);
14560           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
14561         }
14562 
14563         if (!Invalid) {
14564           // If this is a use, just return the declaration we found, unless
14565           // we have attributes.
14566           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14567             if (!Attrs.empty()) {
14568               // FIXME: Diagnose these attributes. For now, we create a new
14569               // declaration to hold them.
14570             } else if (TUK == TUK_Reference &&
14571                        (PrevTagDecl->getFriendObjectKind() ==
14572                             Decl::FOK_Undeclared ||
14573                         PrevDecl->getOwningModule() != getCurrentModule()) &&
14574                        SS.isEmpty()) {
14575               // This declaration is a reference to an existing entity, but
14576               // has different visibility from that entity: it either makes
14577               // a friend visible or it makes a type visible in a new module.
14578               // In either case, create a new declaration. We only do this if
14579               // the declaration would have meant the same thing if no prior
14580               // declaration were found, that is, if it was found in the same
14581               // scope where we would have injected a declaration.
14582               if (!getTagInjectionContext(CurContext)->getRedeclContext()
14583                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
14584                 return PrevTagDecl;
14585               // This is in the injected scope, create a new declaration in
14586               // that scope.
14587               S = getTagInjectionScope(S, getLangOpts());
14588             } else {
14589               return PrevTagDecl;
14590             }
14591           }
14592 
14593           // Diagnose attempts to redefine a tag.
14594           if (TUK == TUK_Definition) {
14595             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
14596               // If we're defining a specialization and the previous definition
14597               // is from an implicit instantiation, don't emit an error
14598               // here; we'll catch this in the general case below.
14599               bool IsExplicitSpecializationAfterInstantiation = false;
14600               if (isMemberSpecialization) {
14601                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
14602                   IsExplicitSpecializationAfterInstantiation =
14603                     RD->getTemplateSpecializationKind() !=
14604                     TSK_ExplicitSpecialization;
14605                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
14606                   IsExplicitSpecializationAfterInstantiation =
14607                     ED->getTemplateSpecializationKind() !=
14608                     TSK_ExplicitSpecialization;
14609               }
14610 
14611               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
14612               // not keep more that one definition around (merge them). However,
14613               // ensure the decl passes the structural compatibility check in
14614               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
14615               NamedDecl *Hidden = nullptr;
14616               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
14617                 // There is a definition of this tag, but it is not visible. We
14618                 // explicitly make use of C++'s one definition rule here, and
14619                 // assume that this definition is identical to the hidden one
14620                 // we already have. Make the existing definition visible and
14621                 // use it in place of this one.
14622                 if (!getLangOpts().CPlusPlus) {
14623                   // Postpone making the old definition visible until after we
14624                   // complete parsing the new one and do the structural
14625                   // comparison.
14626                   SkipBody->CheckSameAsPrevious = true;
14627                   SkipBody->New = createTagFromNewDecl();
14628                   SkipBody->Previous = Def;
14629                   return Def;
14630                 } else {
14631                   SkipBody->ShouldSkip = true;
14632                   SkipBody->Previous = Def;
14633                   makeMergedDefinitionVisible(Hidden);
14634                   // Carry on and handle it like a normal definition. We'll
14635                   // skip starting the definitiion later.
14636                 }
14637               } else if (!IsExplicitSpecializationAfterInstantiation) {
14638                 // A redeclaration in function prototype scope in C isn't
14639                 // visible elsewhere, so merely issue a warning.
14640                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
14641                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
14642                 else
14643                   Diag(NameLoc, diag::err_redefinition) << Name;
14644                 notePreviousDefinition(Def,
14645                                        NameLoc.isValid() ? NameLoc : KWLoc);
14646                 // If this is a redefinition, recover by making this
14647                 // struct be anonymous, which will make any later
14648                 // references get the previous definition.
14649                 Name = nullptr;
14650                 Previous.clear();
14651                 Invalid = true;
14652               }
14653             } else {
14654               // If the type is currently being defined, complain
14655               // about a nested redefinition.
14656               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
14657               if (TD->isBeingDefined()) {
14658                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
14659                 Diag(PrevTagDecl->getLocation(),
14660                      diag::note_previous_definition);
14661                 Name = nullptr;
14662                 Previous.clear();
14663                 Invalid = true;
14664               }
14665             }
14666 
14667             // Okay, this is definition of a previously declared or referenced
14668             // tag. We're going to create a new Decl for it.
14669           }
14670 
14671           // Okay, we're going to make a redeclaration.  If this is some kind
14672           // of reference, make sure we build the redeclaration in the same DC
14673           // as the original, and ignore the current access specifier.
14674           if (TUK == TUK_Friend || TUK == TUK_Reference) {
14675             SearchDC = PrevTagDecl->getDeclContext();
14676             AS = AS_none;
14677           }
14678         }
14679         // If we get here we have (another) forward declaration or we
14680         // have a definition.  Just create a new decl.
14681 
14682       } else {
14683         // If we get here, this is a definition of a new tag type in a nested
14684         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
14685         // new decl/type.  We set PrevDecl to NULL so that the entities
14686         // have distinct types.
14687         Previous.clear();
14688       }
14689       // If we get here, we're going to create a new Decl. If PrevDecl
14690       // is non-NULL, it's a definition of the tag declared by
14691       // PrevDecl. If it's NULL, we have a new definition.
14692 
14693     // Otherwise, PrevDecl is not a tag, but was found with tag
14694     // lookup.  This is only actually possible in C++, where a few
14695     // things like templates still live in the tag namespace.
14696     } else {
14697       // Use a better diagnostic if an elaborated-type-specifier
14698       // found the wrong kind of type on the first
14699       // (non-redeclaration) lookup.
14700       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
14701           !Previous.isForRedeclaration()) {
14702         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14703         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
14704                                                        << Kind;
14705         Diag(PrevDecl->getLocation(), diag::note_declared_at);
14706         Invalid = true;
14707 
14708       // Otherwise, only diagnose if the declaration is in scope.
14709       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
14710                                 SS.isNotEmpty() || isMemberSpecialization)) {
14711         // do nothing
14712 
14713       // Diagnose implicit declarations introduced by elaborated types.
14714       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
14715         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14716         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
14717         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14718         Invalid = true;
14719 
14720       // Otherwise it's a declaration.  Call out a particularly common
14721       // case here.
14722       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14723         unsigned Kind = 0;
14724         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
14725         Diag(NameLoc, diag::err_tag_definition_of_typedef)
14726           << Name << Kind << TND->getUnderlyingType();
14727         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14728         Invalid = true;
14729 
14730       // Otherwise, diagnose.
14731       } else {
14732         // The tag name clashes with something else in the target scope,
14733         // issue an error and recover by making this tag be anonymous.
14734         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
14735         notePreviousDefinition(PrevDecl, NameLoc);
14736         Name = nullptr;
14737         Invalid = true;
14738       }
14739 
14740       // The existing declaration isn't relevant to us; we're in a
14741       // new scope, so clear out the previous declaration.
14742       Previous.clear();
14743     }
14744   }
14745 
14746 CreateNewDecl:
14747 
14748   TagDecl *PrevDecl = nullptr;
14749   if (Previous.isSingleResult())
14750     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
14751 
14752   // If there is an identifier, use the location of the identifier as the
14753   // location of the decl, otherwise use the location of the struct/union
14754   // keyword.
14755   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14756 
14757   // Otherwise, create a new declaration. If there is a previous
14758   // declaration of the same entity, the two will be linked via
14759   // PrevDecl.
14760   TagDecl *New;
14761 
14762   if (Kind == TTK_Enum) {
14763     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14764     // enum X { A, B, C } D;    D should chain to X.
14765     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
14766                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
14767                            ScopedEnumUsesClassTag, IsFixed);
14768 
14769     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
14770       StdAlignValT = cast<EnumDecl>(New);
14771 
14772     // If this is an undefined enum, warn.
14773     if (TUK != TUK_Definition && !Invalid) {
14774       TagDecl *Def;
14775       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
14776         // C++0x: 7.2p2: opaque-enum-declaration.
14777         // Conflicts are diagnosed above. Do nothing.
14778       }
14779       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
14780         Diag(Loc, diag::ext_forward_ref_enum_def)
14781           << New;
14782         Diag(Def->getLocation(), diag::note_previous_definition);
14783       } else {
14784         unsigned DiagID = diag::ext_forward_ref_enum;
14785         if (getLangOpts().MSVCCompat)
14786           DiagID = diag::ext_ms_forward_ref_enum;
14787         else if (getLangOpts().CPlusPlus)
14788           DiagID = diag::err_forward_ref_enum;
14789         Diag(Loc, DiagID);
14790       }
14791     }
14792 
14793     if (EnumUnderlying) {
14794       EnumDecl *ED = cast<EnumDecl>(New);
14795       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14796         ED->setIntegerTypeSourceInfo(TI);
14797       else
14798         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
14799       ED->setPromotionType(ED->getIntegerType());
14800       assert(ED->isComplete() && "enum with type should be complete");
14801     }
14802   } else {
14803     // struct/union/class
14804 
14805     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14806     // struct X { int A; } D;    D should chain to X.
14807     if (getLangOpts().CPlusPlus) {
14808       // FIXME: Look for a way to use RecordDecl for simple structs.
14809       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14810                                   cast_or_null<CXXRecordDecl>(PrevDecl));
14811 
14812       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
14813         StdBadAlloc = cast<CXXRecordDecl>(New);
14814     } else
14815       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14816                                cast_or_null<RecordDecl>(PrevDecl));
14817   }
14818 
14819   // C++11 [dcl.type]p3:
14820   //   A type-specifier-seq shall not define a class or enumeration [...].
14821   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
14822       TUK == TUK_Definition) {
14823     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
14824       << Context.getTagDeclType(New);
14825     Invalid = true;
14826   }
14827 
14828   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
14829       DC->getDeclKind() == Decl::Enum) {
14830     Diag(New->getLocation(), diag::err_type_defined_in_enum)
14831       << Context.getTagDeclType(New);
14832     Invalid = true;
14833   }
14834 
14835   // Maybe add qualifier info.
14836   if (SS.isNotEmpty()) {
14837     if (SS.isSet()) {
14838       // If this is either a declaration or a definition, check the
14839       // nested-name-specifier against the current context.
14840       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
14841           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
14842                                        isMemberSpecialization))
14843         Invalid = true;
14844 
14845       New->setQualifierInfo(SS.getWithLocInContext(Context));
14846       if (TemplateParameterLists.size() > 0) {
14847         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
14848       }
14849     }
14850     else
14851       Invalid = true;
14852   }
14853 
14854   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14855     // Add alignment attributes if necessary; these attributes are checked when
14856     // the ASTContext lays out the structure.
14857     //
14858     // It is important for implementing the correct semantics that this
14859     // happen here (in ActOnTag). The #pragma pack stack is
14860     // maintained as a result of parser callbacks which can occur at
14861     // many points during the parsing of a struct declaration (because
14862     // the #pragma tokens are effectively skipped over during the
14863     // parsing of the struct).
14864     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14865       AddAlignmentAttributesForRecord(RD);
14866       AddMsStructLayoutForRecord(RD);
14867     }
14868   }
14869 
14870   if (ModulePrivateLoc.isValid()) {
14871     if (isMemberSpecialization)
14872       Diag(New->getLocation(), diag::err_module_private_specialization)
14873         << 2
14874         << FixItHint::CreateRemoval(ModulePrivateLoc);
14875     // __module_private__ does not apply to local classes. However, we only
14876     // diagnose this as an error when the declaration specifiers are
14877     // freestanding. Here, we just ignore the __module_private__.
14878     else if (!SearchDC->isFunctionOrMethod())
14879       New->setModulePrivate();
14880   }
14881 
14882   // If this is a specialization of a member class (of a class template),
14883   // check the specialization.
14884   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
14885     Invalid = true;
14886 
14887   // If we're declaring or defining a tag in function prototype scope in C,
14888   // note that this type can only be used within the function and add it to
14889   // the list of decls to inject into the function definition scope.
14890   if ((Name || Kind == TTK_Enum) &&
14891       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
14892     if (getLangOpts().CPlusPlus) {
14893       // C++ [dcl.fct]p6:
14894       //   Types shall not be defined in return or parameter types.
14895       if (TUK == TUK_Definition && !IsTypeSpecifier) {
14896         Diag(Loc, diag::err_type_defined_in_param_type)
14897             << Name;
14898         Invalid = true;
14899       }
14900     } else if (!PrevDecl) {
14901       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
14902     }
14903   }
14904 
14905   if (Invalid)
14906     New->setInvalidDecl();
14907 
14908   // Set the lexical context. If the tag has a C++ scope specifier, the
14909   // lexical context will be different from the semantic context.
14910   New->setLexicalDeclContext(CurContext);
14911 
14912   // Mark this as a friend decl if applicable.
14913   // In Microsoft mode, a friend declaration also acts as a forward
14914   // declaration so we always pass true to setObjectOfFriendDecl to make
14915   // the tag name visible.
14916   if (TUK == TUK_Friend)
14917     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
14918 
14919   // Set the access specifier.
14920   if (!Invalid && SearchDC->isRecord())
14921     SetMemberAccessSpecifier(New, PrevDecl, AS);
14922 
14923   if (PrevDecl)
14924     CheckRedeclarationModuleOwnership(New, PrevDecl);
14925 
14926   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
14927     New->startDefinition();
14928 
14929   ProcessDeclAttributeList(S, New, Attrs);
14930   AddPragmaAttributes(S, New);
14931 
14932   // If this has an identifier, add it to the scope stack.
14933   if (TUK == TUK_Friend) {
14934     // We might be replacing an existing declaration in the lookup tables;
14935     // if so, borrow its access specifier.
14936     if (PrevDecl)
14937       New->setAccess(PrevDecl->getAccess());
14938 
14939     DeclContext *DC = New->getDeclContext()->getRedeclContext();
14940     DC->makeDeclVisibleInContext(New);
14941     if (Name) // can be null along some error paths
14942       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14943         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
14944   } else if (Name) {
14945     S = getNonFieldDeclScope(S);
14946     PushOnScopeChains(New, S, true);
14947   } else {
14948     CurContext->addDecl(New);
14949   }
14950 
14951   // If this is the C FILE type, notify the AST context.
14952   if (IdentifierInfo *II = New->getIdentifier())
14953     if (!New->isInvalidDecl() &&
14954         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
14955         II->isStr("FILE"))
14956       Context.setFILEDecl(New);
14957 
14958   if (PrevDecl)
14959     mergeDeclAttributes(New, PrevDecl);
14960 
14961   // If there's a #pragma GCC visibility in scope, set the visibility of this
14962   // record.
14963   AddPushedVisibilityAttribute(New);
14964 
14965   if (isMemberSpecialization && !New->isInvalidDecl())
14966     CompleteMemberSpecialization(New, Previous);
14967 
14968   OwnedDecl = true;
14969   // In C++, don't return an invalid declaration. We can't recover well from
14970   // the cases where we make the type anonymous.
14971   if (Invalid && getLangOpts().CPlusPlus) {
14972     if (New->isBeingDefined())
14973       if (auto RD = dyn_cast<RecordDecl>(New))
14974         RD->completeDefinition();
14975     return nullptr;
14976   } else if (SkipBody && SkipBody->ShouldSkip) {
14977     return SkipBody->Previous;
14978   } else {
14979     return New;
14980   }
14981 }
14982 
14983 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
14984   AdjustDeclIfTemplate(TagD);
14985   TagDecl *Tag = cast<TagDecl>(TagD);
14986 
14987   // Enter the tag context.
14988   PushDeclContext(S, Tag);
14989 
14990   ActOnDocumentableDecl(TagD);
14991 
14992   // If there's a #pragma GCC visibility in scope, set the visibility of this
14993   // record.
14994   AddPushedVisibilityAttribute(Tag);
14995 }
14996 
14997 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
14998                                     SkipBodyInfo &SkipBody) {
14999   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
15000     return false;
15001 
15002   // Make the previous decl visible.
15003   makeMergedDefinitionVisible(SkipBody.Previous);
15004   return true;
15005 }
15006 
15007 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
15008   assert(isa<ObjCContainerDecl>(IDecl) &&
15009          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15010   DeclContext *OCD = cast<DeclContext>(IDecl);
15011   assert(getContainingDC(OCD) == CurContext &&
15012       "The next DeclContext should be lexically contained in the current one.");
15013   CurContext = OCD;
15014   return IDecl;
15015 }
15016 
15017 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
15018                                            SourceLocation FinalLoc,
15019                                            bool IsFinalSpelledSealed,
15020                                            SourceLocation LBraceLoc) {
15021   AdjustDeclIfTemplate(TagD);
15022   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15023 
15024   FieldCollector->StartClass();
15025 
15026   if (!Record->getIdentifier())
15027     return;
15028 
15029   if (FinalLoc.isValid())
15030     Record->addAttr(new (Context)
15031                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
15032 
15033   // C++ [class]p2:
15034   //   [...] The class-name is also inserted into the scope of the
15035   //   class itself; this is known as the injected-class-name. For
15036   //   purposes of access checking, the injected-class-name is treated
15037   //   as if it were a public member name.
15038   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15039       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
15040       Record->getLocation(), Record->getIdentifier(),
15041       /*PrevDecl=*/nullptr,
15042       /*DelayTypeCreation=*/true);
15043   Context.getTypeDeclType(InjectedClassName, Record);
15044   InjectedClassName->setImplicit();
15045   InjectedClassName->setAccess(AS_public);
15046   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15047       InjectedClassName->setDescribedClassTemplate(Template);
15048   PushOnScopeChains(InjectedClassName, S);
15049   assert(InjectedClassName->isInjectedClassName() &&
15050          "Broken injected-class-name");
15051 }
15052 
15053 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
15054                                     SourceRange BraceRange) {
15055   AdjustDeclIfTemplate(TagD);
15056   TagDecl *Tag = cast<TagDecl>(TagD);
15057   Tag->setBraceRange(BraceRange);
15058 
15059   // Make sure we "complete" the definition even it is invalid.
15060   if (Tag->isBeingDefined()) {
15061     assert(Tag->isInvalidDecl() && "We should already have completed it");
15062     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15063       RD->completeDefinition();
15064   }
15065 
15066   if (isa<CXXRecordDecl>(Tag)) {
15067     FieldCollector->FinishClass();
15068   }
15069 
15070   // Exit this scope of this tag's definition.
15071   PopDeclContext();
15072 
15073   if (getCurLexicalContext()->isObjCContainer() &&
15074       Tag->getDeclContext()->isFileContext())
15075     Tag->setTopLevelDeclInObjCContainer();
15076 
15077   // Notify the consumer that we've defined a tag.
15078   if (!Tag->isInvalidDecl())
15079     Consumer.HandleTagDeclDefinition(Tag);
15080 }
15081 
15082 void Sema::ActOnObjCContainerFinishDefinition() {
15083   // Exit this scope of this interface definition.
15084   PopDeclContext();
15085 }
15086 
15087 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15088   assert(DC == CurContext && "Mismatch of container contexts");
15089   OriginalLexicalContext = DC;
15090   ActOnObjCContainerFinishDefinition();
15091 }
15092 
15093 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15094   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15095   OriginalLexicalContext = nullptr;
15096 }
15097 
15098 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
15099   AdjustDeclIfTemplate(TagD);
15100   TagDecl *Tag = cast<TagDecl>(TagD);
15101   Tag->setInvalidDecl();
15102 
15103   // Make sure we "complete" the definition even it is invalid.
15104   if (Tag->isBeingDefined()) {
15105     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15106       RD->completeDefinition();
15107   }
15108 
15109   // We're undoing ActOnTagStartDefinition here, not
15110   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15111   // the FieldCollector.
15112 
15113   PopDeclContext();
15114 }
15115 
15116 // Note that FieldName may be null for anonymous bitfields.
15117 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15118                                 IdentifierInfo *FieldName,
15119                                 QualType FieldTy, bool IsMsStruct,
15120                                 Expr *BitWidth, bool *ZeroWidth) {
15121   // Default to true; that shouldn't confuse checks for emptiness
15122   if (ZeroWidth)
15123     *ZeroWidth = true;
15124 
15125   // C99 6.7.2.1p4 - verify the field type.
15126   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15127   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15128     // Handle incomplete types with specific error.
15129     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15130       return ExprError();
15131     if (FieldName)
15132       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15133         << FieldName << FieldTy << BitWidth->getSourceRange();
15134     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15135       << FieldTy << BitWidth->getSourceRange();
15136   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15137                                              UPPC_BitFieldWidth))
15138     return ExprError();
15139 
15140   // If the bit-width is type- or value-dependent, don't try to check
15141   // it now.
15142   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15143     return BitWidth;
15144 
15145   llvm::APSInt Value;
15146   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15147   if (ICE.isInvalid())
15148     return ICE;
15149   BitWidth = ICE.get();
15150 
15151   if (Value != 0 && ZeroWidth)
15152     *ZeroWidth = false;
15153 
15154   // Zero-width bitfield is ok for anonymous field.
15155   if (Value == 0 && FieldName)
15156     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15157 
15158   if (Value.isSigned() && Value.isNegative()) {
15159     if (FieldName)
15160       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15161                << FieldName << Value.toString(10);
15162     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15163       << Value.toString(10);
15164   }
15165 
15166   if (!FieldTy->isDependentType()) {
15167     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15168     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15169     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15170 
15171     // Over-wide bitfields are an error in C or when using the MSVC bitfield
15172     // ABI.
15173     bool CStdConstraintViolation =
15174         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15175     bool MSBitfieldViolation =
15176         Value.ugt(TypeStorageSize) &&
15177         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15178     if (CStdConstraintViolation || MSBitfieldViolation) {
15179       unsigned DiagWidth =
15180           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15181       if (FieldName)
15182         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15183                << FieldName << (unsigned)Value.getZExtValue()
15184                << !CStdConstraintViolation << DiagWidth;
15185 
15186       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15187              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15188              << DiagWidth;
15189     }
15190 
15191     // Warn on types where the user might conceivably expect to get all
15192     // specified bits as value bits: that's all integral types other than
15193     // 'bool'.
15194     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15195       if (FieldName)
15196         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15197             << FieldName << (unsigned)Value.getZExtValue()
15198             << (unsigned)TypeWidth;
15199       else
15200         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15201             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
15202     }
15203   }
15204 
15205   return BitWidth;
15206 }
15207 
15208 /// ActOnField - Each field of a C struct/union is passed into this in order
15209 /// to create a FieldDecl object for it.
15210 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
15211                        Declarator &D, Expr *BitfieldWidth) {
15212   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
15213                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
15214                                /*InitStyle=*/ICIS_NoInit, AS_public);
15215   return Res;
15216 }
15217 
15218 /// HandleField - Analyze a field of a C struct or a C++ data member.
15219 ///
15220 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
15221                              SourceLocation DeclStart,
15222                              Declarator &D, Expr *BitWidth,
15223                              InClassInitStyle InitStyle,
15224                              AccessSpecifier AS) {
15225   if (D.isDecompositionDeclarator()) {
15226     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
15227     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
15228       << Decomp.getSourceRange();
15229     return nullptr;
15230   }
15231 
15232   IdentifierInfo *II = D.getIdentifier();
15233   SourceLocation Loc = DeclStart;
15234   if (II) Loc = D.getIdentifierLoc();
15235 
15236   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15237   QualType T = TInfo->getType();
15238   if (getLangOpts().CPlusPlus) {
15239     CheckExtraCXXDefaultArguments(D);
15240 
15241     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15242                                         UPPC_DataMemberType)) {
15243       D.setInvalidType();
15244       T = Context.IntTy;
15245       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15246     }
15247   }
15248 
15249   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15250 
15251   if (D.getDeclSpec().isInlineSpecified())
15252     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15253         << getLangOpts().CPlusPlus17;
15254   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15255     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15256          diag::err_invalid_thread)
15257       << DeclSpec::getSpecifierName(TSCS);
15258 
15259   // Check to see if this name was declared as a member previously
15260   NamedDecl *PrevDecl = nullptr;
15261   LookupResult Previous(*this, II, Loc, LookupMemberName,
15262                         ForVisibleRedeclaration);
15263   LookupName(Previous, S);
15264   switch (Previous.getResultKind()) {
15265     case LookupResult::Found:
15266     case LookupResult::FoundUnresolvedValue:
15267       PrevDecl = Previous.getAsSingle<NamedDecl>();
15268       break;
15269 
15270     case LookupResult::FoundOverloaded:
15271       PrevDecl = Previous.getRepresentativeDecl();
15272       break;
15273 
15274     case LookupResult::NotFound:
15275     case LookupResult::NotFoundInCurrentInstantiation:
15276     case LookupResult::Ambiguous:
15277       break;
15278   }
15279   Previous.suppressDiagnostics();
15280 
15281   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15282     // Maybe we will complain about the shadowed template parameter.
15283     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15284     // Just pretend that we didn't see the previous declaration.
15285     PrevDecl = nullptr;
15286   }
15287 
15288   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15289     PrevDecl = nullptr;
15290 
15291   bool Mutable
15292     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
15293   SourceLocation TSSL = D.getBeginLoc();
15294   FieldDecl *NewFD
15295     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
15296                      TSSL, AS, PrevDecl, &D);
15297 
15298   if (NewFD->isInvalidDecl())
15299     Record->setInvalidDecl();
15300 
15301   if (D.getDeclSpec().isModulePrivateSpecified())
15302     NewFD->setModulePrivate();
15303 
15304   if (NewFD->isInvalidDecl() && PrevDecl) {
15305     // Don't introduce NewFD into scope; there's already something
15306     // with the same name in the same scope.
15307   } else if (II) {
15308     PushOnScopeChains(NewFD, S);
15309   } else
15310     Record->addDecl(NewFD);
15311 
15312   return NewFD;
15313 }
15314 
15315 /// Build a new FieldDecl and check its well-formedness.
15316 ///
15317 /// This routine builds a new FieldDecl given the fields name, type,
15318 /// record, etc. \p PrevDecl should refer to any previous declaration
15319 /// with the same name and in the same scope as the field to be
15320 /// created.
15321 ///
15322 /// \returns a new FieldDecl.
15323 ///
15324 /// \todo The Declarator argument is a hack. It will be removed once
15325 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
15326                                 TypeSourceInfo *TInfo,
15327                                 RecordDecl *Record, SourceLocation Loc,
15328                                 bool Mutable, Expr *BitWidth,
15329                                 InClassInitStyle InitStyle,
15330                                 SourceLocation TSSL,
15331                                 AccessSpecifier AS, NamedDecl *PrevDecl,
15332                                 Declarator *D) {
15333   IdentifierInfo *II = Name.getAsIdentifierInfo();
15334   bool InvalidDecl = false;
15335   if (D) InvalidDecl = D->isInvalidType();
15336 
15337   // If we receive a broken type, recover by assuming 'int' and
15338   // marking this declaration as invalid.
15339   if (T.isNull()) {
15340     InvalidDecl = true;
15341     T = Context.IntTy;
15342   }
15343 
15344   QualType EltTy = Context.getBaseElementType(T);
15345   if (!EltTy->isDependentType()) {
15346     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
15347       // Fields of incomplete type force their record to be invalid.
15348       Record->setInvalidDecl();
15349       InvalidDecl = true;
15350     } else {
15351       NamedDecl *Def;
15352       EltTy->isIncompleteType(&Def);
15353       if (Def && Def->isInvalidDecl()) {
15354         Record->setInvalidDecl();
15355         InvalidDecl = true;
15356       }
15357     }
15358   }
15359 
15360   // TR 18037 does not allow fields to be declared with address space
15361   if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() ||
15362       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
15363     Diag(Loc, diag::err_field_with_address_space);
15364     Record->setInvalidDecl();
15365     InvalidDecl = true;
15366   }
15367 
15368   if (LangOpts.OpenCL) {
15369     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
15370     // used as structure or union field: image, sampler, event or block types.
15371     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
15372         T->isBlockPointerType()) {
15373       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
15374       Record->setInvalidDecl();
15375       InvalidDecl = true;
15376     }
15377     // OpenCL v1.2 s6.9.c: bitfields are not supported.
15378     if (BitWidth) {
15379       Diag(Loc, diag::err_opencl_bitfields);
15380       InvalidDecl = true;
15381     }
15382   }
15383 
15384   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
15385   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
15386       T.hasQualifiers()) {
15387     InvalidDecl = true;
15388     Diag(Loc, diag::err_anon_bitfield_qualifiers);
15389   }
15390 
15391   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15392   // than a variably modified type.
15393   if (!InvalidDecl && T->isVariablyModifiedType()) {
15394     bool SizeIsNegative;
15395     llvm::APSInt Oversized;
15396 
15397     TypeSourceInfo *FixedTInfo =
15398       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
15399                                                     SizeIsNegative,
15400                                                     Oversized);
15401     if (FixedTInfo) {
15402       Diag(Loc, diag::warn_illegal_constant_array_size);
15403       TInfo = FixedTInfo;
15404       T = FixedTInfo->getType();
15405     } else {
15406       if (SizeIsNegative)
15407         Diag(Loc, diag::err_typecheck_negative_array_size);
15408       else if (Oversized.getBoolValue())
15409         Diag(Loc, diag::err_array_too_large)
15410           << Oversized.toString(10);
15411       else
15412         Diag(Loc, diag::err_typecheck_field_variable_size);
15413       InvalidDecl = true;
15414     }
15415   }
15416 
15417   // Fields can not have abstract class types
15418   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
15419                                              diag::err_abstract_type_in_decl,
15420                                              AbstractFieldType))
15421     InvalidDecl = true;
15422 
15423   bool ZeroWidth = false;
15424   if (InvalidDecl)
15425     BitWidth = nullptr;
15426   // If this is declared as a bit-field, check the bit-field.
15427   if (BitWidth) {
15428     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
15429                               &ZeroWidth).get();
15430     if (!BitWidth) {
15431       InvalidDecl = true;
15432       BitWidth = nullptr;
15433       ZeroWidth = false;
15434     }
15435   }
15436 
15437   // Check that 'mutable' is consistent with the type of the declaration.
15438   if (!InvalidDecl && Mutable) {
15439     unsigned DiagID = 0;
15440     if (T->isReferenceType())
15441       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
15442                                         : diag::err_mutable_reference;
15443     else if (T.isConstQualified())
15444       DiagID = diag::err_mutable_const;
15445 
15446     if (DiagID) {
15447       SourceLocation ErrLoc = Loc;
15448       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
15449         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
15450       Diag(ErrLoc, DiagID);
15451       if (DiagID != diag::ext_mutable_reference) {
15452         Mutable = false;
15453         InvalidDecl = true;
15454       }
15455     }
15456   }
15457 
15458   // C++11 [class.union]p8 (DR1460):
15459   //   At most one variant member of a union may have a
15460   //   brace-or-equal-initializer.
15461   if (InitStyle != ICIS_NoInit)
15462     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
15463 
15464   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
15465                                        BitWidth, Mutable, InitStyle);
15466   if (InvalidDecl)
15467     NewFD->setInvalidDecl();
15468 
15469   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
15470     Diag(Loc, diag::err_duplicate_member) << II;
15471     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15472     NewFD->setInvalidDecl();
15473   }
15474 
15475   if (!InvalidDecl && getLangOpts().CPlusPlus) {
15476     if (Record->isUnion()) {
15477       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15478         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
15479         if (RDecl->getDefinition()) {
15480           // C++ [class.union]p1: An object of a class with a non-trivial
15481           // constructor, a non-trivial copy constructor, a non-trivial
15482           // destructor, or a non-trivial copy assignment operator
15483           // cannot be a member of a union, nor can an array of such
15484           // objects.
15485           if (CheckNontrivialField(NewFD))
15486             NewFD->setInvalidDecl();
15487         }
15488       }
15489 
15490       // C++ [class.union]p1: If a union contains a member of reference type,
15491       // the program is ill-formed, except when compiling with MSVC extensions
15492       // enabled.
15493       if (EltTy->isReferenceType()) {
15494         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
15495                                     diag::ext_union_member_of_reference_type :
15496                                     diag::err_union_member_of_reference_type)
15497           << NewFD->getDeclName() << EltTy;
15498         if (!getLangOpts().MicrosoftExt)
15499           NewFD->setInvalidDecl();
15500       }
15501     }
15502   }
15503 
15504   // FIXME: We need to pass in the attributes given an AST
15505   // representation, not a parser representation.
15506   if (D) {
15507     // FIXME: The current scope is almost... but not entirely... correct here.
15508     ProcessDeclAttributes(getCurScope(), NewFD, *D);
15509 
15510     if (NewFD->hasAttrs())
15511       CheckAlignasUnderalignment(NewFD);
15512   }
15513 
15514   // In auto-retain/release, infer strong retension for fields of
15515   // retainable type.
15516   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
15517     NewFD->setInvalidDecl();
15518 
15519   if (T.isObjCGCWeak())
15520     Diag(Loc, diag::warn_attribute_weak_on_field);
15521 
15522   NewFD->setAccess(AS);
15523   return NewFD;
15524 }
15525 
15526 bool Sema::CheckNontrivialField(FieldDecl *FD) {
15527   assert(FD);
15528   assert(getLangOpts().CPlusPlus && "valid check only for C++");
15529 
15530   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
15531     return false;
15532 
15533   QualType EltTy = Context.getBaseElementType(FD->getType());
15534   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15535     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
15536     if (RDecl->getDefinition()) {
15537       // We check for copy constructors before constructors
15538       // because otherwise we'll never get complaints about
15539       // copy constructors.
15540 
15541       CXXSpecialMember member = CXXInvalid;
15542       // We're required to check for any non-trivial constructors. Since the
15543       // implicit default constructor is suppressed if there are any
15544       // user-declared constructors, we just need to check that there is a
15545       // trivial default constructor and a trivial copy constructor. (We don't
15546       // worry about move constructors here, since this is a C++98 check.)
15547       if (RDecl->hasNonTrivialCopyConstructor())
15548         member = CXXCopyConstructor;
15549       else if (!RDecl->hasTrivialDefaultConstructor())
15550         member = CXXDefaultConstructor;
15551       else if (RDecl->hasNonTrivialCopyAssignment())
15552         member = CXXCopyAssignment;
15553       else if (RDecl->hasNonTrivialDestructor())
15554         member = CXXDestructor;
15555 
15556       if (member != CXXInvalid) {
15557         if (!getLangOpts().CPlusPlus11 &&
15558             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
15559           // Objective-C++ ARC: it is an error to have a non-trivial field of
15560           // a union. However, system headers in Objective-C programs
15561           // occasionally have Objective-C lifetime objects within unions,
15562           // and rather than cause the program to fail, we make those
15563           // members unavailable.
15564           SourceLocation Loc = FD->getLocation();
15565           if (getSourceManager().isInSystemHeader(Loc)) {
15566             if (!FD->hasAttr<UnavailableAttr>())
15567               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15568                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
15569             return false;
15570           }
15571         }
15572 
15573         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
15574                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
15575                diag::err_illegal_union_or_anon_struct_member)
15576           << FD->getParent()->isUnion() << FD->getDeclName() << member;
15577         DiagnoseNontrivial(RDecl, member);
15578         return !getLangOpts().CPlusPlus11;
15579       }
15580     }
15581   }
15582 
15583   return false;
15584 }
15585 
15586 /// TranslateIvarVisibility - Translate visibility from a token ID to an
15587 ///  AST enum value.
15588 static ObjCIvarDecl::AccessControl
15589 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
15590   switch (ivarVisibility) {
15591   default: llvm_unreachable("Unknown visitibility kind");
15592   case tok::objc_private: return ObjCIvarDecl::Private;
15593   case tok::objc_public: return ObjCIvarDecl::Public;
15594   case tok::objc_protected: return ObjCIvarDecl::Protected;
15595   case tok::objc_package: return ObjCIvarDecl::Package;
15596   }
15597 }
15598 
15599 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
15600 /// in order to create an IvarDecl object for it.
15601 Decl *Sema::ActOnIvar(Scope *S,
15602                                 SourceLocation DeclStart,
15603                                 Declarator &D, Expr *BitfieldWidth,
15604                                 tok::ObjCKeywordKind Visibility) {
15605 
15606   IdentifierInfo *II = D.getIdentifier();
15607   Expr *BitWidth = (Expr*)BitfieldWidth;
15608   SourceLocation Loc = DeclStart;
15609   if (II) Loc = D.getIdentifierLoc();
15610 
15611   // FIXME: Unnamed fields can be handled in various different ways, for
15612   // example, unnamed unions inject all members into the struct namespace!
15613 
15614   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15615   QualType T = TInfo->getType();
15616 
15617   if (BitWidth) {
15618     // 6.7.2.1p3, 6.7.2.1p4
15619     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
15620     if (!BitWidth)
15621       D.setInvalidType();
15622   } else {
15623     // Not a bitfield.
15624 
15625     // validate II.
15626 
15627   }
15628   if (T->isReferenceType()) {
15629     Diag(Loc, diag::err_ivar_reference_type);
15630     D.setInvalidType();
15631   }
15632   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15633   // than a variably modified type.
15634   else if (T->isVariablyModifiedType()) {
15635     Diag(Loc, diag::err_typecheck_ivar_variable_size);
15636     D.setInvalidType();
15637   }
15638 
15639   // Get the visibility (access control) for this ivar.
15640   ObjCIvarDecl::AccessControl ac =
15641     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
15642                                         : ObjCIvarDecl::None;
15643   // Must set ivar's DeclContext to its enclosing interface.
15644   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
15645   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
15646     return nullptr;
15647   ObjCContainerDecl *EnclosingContext;
15648   if (ObjCImplementationDecl *IMPDecl =
15649       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15650     if (LangOpts.ObjCRuntime.isFragile()) {
15651     // Case of ivar declared in an implementation. Context is that of its class.
15652       EnclosingContext = IMPDecl->getClassInterface();
15653       assert(EnclosingContext && "Implementation has no class interface!");
15654     }
15655     else
15656       EnclosingContext = EnclosingDecl;
15657   } else {
15658     if (ObjCCategoryDecl *CDecl =
15659         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15660       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
15661         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
15662         return nullptr;
15663       }
15664     }
15665     EnclosingContext = EnclosingDecl;
15666   }
15667 
15668   // Construct the decl.
15669   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
15670                                              DeclStart, Loc, II, T,
15671                                              TInfo, ac, (Expr *)BitfieldWidth);
15672 
15673   if (II) {
15674     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
15675                                            ForVisibleRedeclaration);
15676     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
15677         && !isa<TagDecl>(PrevDecl)) {
15678       Diag(Loc, diag::err_duplicate_member) << II;
15679       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15680       NewID->setInvalidDecl();
15681     }
15682   }
15683 
15684   // Process attributes attached to the ivar.
15685   ProcessDeclAttributes(S, NewID, D);
15686 
15687   if (D.isInvalidType())
15688     NewID->setInvalidDecl();
15689 
15690   // In ARC, infer 'retaining' for ivars of retainable type.
15691   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
15692     NewID->setInvalidDecl();
15693 
15694   if (D.getDeclSpec().isModulePrivateSpecified())
15695     NewID->setModulePrivate();
15696 
15697   if (II) {
15698     // FIXME: When interfaces are DeclContexts, we'll need to add
15699     // these to the interface.
15700     S->AddDecl(NewID);
15701     IdResolver.AddDecl(NewID);
15702   }
15703 
15704   if (LangOpts.ObjCRuntime.isNonFragile() &&
15705       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
15706     Diag(Loc, diag::warn_ivars_in_interface);
15707 
15708   return NewID;
15709 }
15710 
15711 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
15712 /// class and class extensions. For every class \@interface and class
15713 /// extension \@interface, if the last ivar is a bitfield of any type,
15714 /// then add an implicit `char :0` ivar to the end of that interface.
15715 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
15716                              SmallVectorImpl<Decl *> &AllIvarDecls) {
15717   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
15718     return;
15719 
15720   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
15721   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
15722 
15723   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
15724     return;
15725   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
15726   if (!ID) {
15727     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
15728       if (!CD->IsClassExtension())
15729         return;
15730     }
15731     // No need to add this to end of @implementation.
15732     else
15733       return;
15734   }
15735   // All conditions are met. Add a new bitfield to the tail end of ivars.
15736   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
15737   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
15738 
15739   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
15740                               DeclLoc, DeclLoc, nullptr,
15741                               Context.CharTy,
15742                               Context.getTrivialTypeSourceInfo(Context.CharTy,
15743                                                                DeclLoc),
15744                               ObjCIvarDecl::Private, BW,
15745                               true);
15746   AllIvarDecls.push_back(Ivar);
15747 }
15748 
15749 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
15750                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
15751                        SourceLocation RBrac,
15752                        const ParsedAttributesView &Attrs) {
15753   assert(EnclosingDecl && "missing record or interface decl");
15754 
15755   // If this is an Objective-C @implementation or category and we have
15756   // new fields here we should reset the layout of the interface since
15757   // it will now change.
15758   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
15759     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
15760     switch (DC->getKind()) {
15761     default: break;
15762     case Decl::ObjCCategory:
15763       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
15764       break;
15765     case Decl::ObjCImplementation:
15766       Context.
15767         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
15768       break;
15769     }
15770   }
15771 
15772   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
15773   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
15774 
15775   // Start counting up the number of named members; make sure to include
15776   // members of anonymous structs and unions in the total.
15777   unsigned NumNamedMembers = 0;
15778   if (Record) {
15779     for (const auto *I : Record->decls()) {
15780       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
15781         if (IFD->getDeclName())
15782           ++NumNamedMembers;
15783     }
15784   }
15785 
15786   // Verify that all the fields are okay.
15787   SmallVector<FieldDecl*, 32> RecFields;
15788 
15789   bool ObjCFieldLifetimeErrReported = false;
15790   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
15791        i != end; ++i) {
15792     FieldDecl *FD = cast<FieldDecl>(*i);
15793 
15794     // Get the type for the field.
15795     const Type *FDTy = FD->getType().getTypePtr();
15796 
15797     if (!FD->isAnonymousStructOrUnion()) {
15798       // Remember all fields written by the user.
15799       RecFields.push_back(FD);
15800     }
15801 
15802     // If the field is already invalid for some reason, don't emit more
15803     // diagnostics about it.
15804     if (FD->isInvalidDecl()) {
15805       EnclosingDecl->setInvalidDecl();
15806       continue;
15807     }
15808 
15809     // C99 6.7.2.1p2:
15810     //   A structure or union shall not contain a member with
15811     //   incomplete or function type (hence, a structure shall not
15812     //   contain an instance of itself, but may contain a pointer to
15813     //   an instance of itself), except that the last member of a
15814     //   structure with more than one named member may have incomplete
15815     //   array type; such a structure (and any union containing,
15816     //   possibly recursively, a member that is such a structure)
15817     //   shall not be a member of a structure or an element of an
15818     //   array.
15819     bool IsLastField = (i + 1 == Fields.end());
15820     if (FDTy->isFunctionType()) {
15821       // Field declared as a function.
15822       Diag(FD->getLocation(), diag::err_field_declared_as_function)
15823         << FD->getDeclName();
15824       FD->setInvalidDecl();
15825       EnclosingDecl->setInvalidDecl();
15826       continue;
15827     } else if (FDTy->isIncompleteArrayType() &&
15828                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
15829       if (Record) {
15830         // Flexible array member.
15831         // Microsoft and g++ is more permissive regarding flexible array.
15832         // It will accept flexible array in union and also
15833         // as the sole element of a struct/class.
15834         unsigned DiagID = 0;
15835         if (!Record->isUnion() && !IsLastField) {
15836           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
15837             << FD->getDeclName() << FD->getType() << Record->getTagKind();
15838           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
15839           FD->setInvalidDecl();
15840           EnclosingDecl->setInvalidDecl();
15841           continue;
15842         } else if (Record->isUnion())
15843           DiagID = getLangOpts().MicrosoftExt
15844                        ? diag::ext_flexible_array_union_ms
15845                        : getLangOpts().CPlusPlus
15846                              ? diag::ext_flexible_array_union_gnu
15847                              : diag::err_flexible_array_union;
15848         else if (NumNamedMembers < 1)
15849           DiagID = getLangOpts().MicrosoftExt
15850                        ? diag::ext_flexible_array_empty_aggregate_ms
15851                        : getLangOpts().CPlusPlus
15852                              ? diag::ext_flexible_array_empty_aggregate_gnu
15853                              : diag::err_flexible_array_empty_aggregate;
15854 
15855         if (DiagID)
15856           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
15857                                           << Record->getTagKind();
15858         // While the layout of types that contain virtual bases is not specified
15859         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
15860         // virtual bases after the derived members.  This would make a flexible
15861         // array member declared at the end of an object not adjacent to the end
15862         // of the type.
15863         if (CXXRecord && CXXRecord->getNumVBases() != 0)
15864           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
15865               << FD->getDeclName() << Record->getTagKind();
15866         if (!getLangOpts().C99)
15867           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
15868             << FD->getDeclName() << Record->getTagKind();
15869 
15870         // If the element type has a non-trivial destructor, we would not
15871         // implicitly destroy the elements, so disallow it for now.
15872         //
15873         // FIXME: GCC allows this. We should probably either implicitly delete
15874         // the destructor of the containing class, or just allow this.
15875         QualType BaseElem = Context.getBaseElementType(FD->getType());
15876         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
15877           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
15878             << FD->getDeclName() << FD->getType();
15879           FD->setInvalidDecl();
15880           EnclosingDecl->setInvalidDecl();
15881           continue;
15882         }
15883         // Okay, we have a legal flexible array member at the end of the struct.
15884         Record->setHasFlexibleArrayMember(true);
15885       } else {
15886         // In ObjCContainerDecl ivars with incomplete array type are accepted,
15887         // unless they are followed by another ivar. That check is done
15888         // elsewhere, after synthesized ivars are known.
15889       }
15890     } else if (!FDTy->isDependentType() &&
15891                RequireCompleteType(FD->getLocation(), FD->getType(),
15892                                    diag::err_field_incomplete)) {
15893       // Incomplete type
15894       FD->setInvalidDecl();
15895       EnclosingDecl->setInvalidDecl();
15896       continue;
15897     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
15898       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
15899         // A type which contains a flexible array member is considered to be a
15900         // flexible array member.
15901         Record->setHasFlexibleArrayMember(true);
15902         if (!Record->isUnion()) {
15903           // If this is a struct/class and this is not the last element, reject
15904           // it.  Note that GCC supports variable sized arrays in the middle of
15905           // structures.
15906           if (!IsLastField)
15907             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
15908               << FD->getDeclName() << FD->getType();
15909           else {
15910             // We support flexible arrays at the end of structs in
15911             // other structs as an extension.
15912             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
15913               << FD->getDeclName();
15914           }
15915         }
15916       }
15917       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
15918           RequireNonAbstractType(FD->getLocation(), FD->getType(),
15919                                  diag::err_abstract_type_in_decl,
15920                                  AbstractIvarType)) {
15921         // Ivars can not have abstract class types
15922         FD->setInvalidDecl();
15923       }
15924       if (Record && FDTTy->getDecl()->hasObjectMember())
15925         Record->setHasObjectMember(true);
15926       if (Record && FDTTy->getDecl()->hasVolatileMember())
15927         Record->setHasVolatileMember(true);
15928       if (Record && Record->isUnion() &&
15929           FD->getType().isNonTrivialPrimitiveCType(Context))
15930         Diag(FD->getLocation(),
15931              diag::err_nontrivial_primitive_type_in_union);
15932     } else if (FDTy->isObjCObjectType()) {
15933       /// A field cannot be an Objective-c object
15934       Diag(FD->getLocation(), diag::err_statically_allocated_object)
15935         << FixItHint::CreateInsertion(FD->getLocation(), "*");
15936       QualType T = Context.getObjCObjectPointerType(FD->getType());
15937       FD->setType(T);
15938     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
15939                Record && !ObjCFieldLifetimeErrReported && Record->isUnion() &&
15940                !getLangOpts().CPlusPlus) {
15941       // It's an error in ARC or Weak if a field has lifetime.
15942       // We don't want to report this in a system header, though,
15943       // so we just make the field unavailable.
15944       // FIXME: that's really not sufficient; we need to make the type
15945       // itself invalid to, say, initialize or copy.
15946       QualType T = FD->getType();
15947       if (T.hasNonTrivialObjCLifetime()) {
15948         SourceLocation loc = FD->getLocation();
15949         if (getSourceManager().isInSystemHeader(loc)) {
15950           if (!FD->hasAttr<UnavailableAttr>()) {
15951             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15952                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
15953           }
15954         } else {
15955           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
15956             << T->isBlockPointerType() << Record->getTagKind();
15957         }
15958         ObjCFieldLifetimeErrReported = true;
15959       }
15960     } else if (getLangOpts().ObjC &&
15961                getLangOpts().getGC() != LangOptions::NonGC &&
15962                Record && !Record->hasObjectMember()) {
15963       if (FD->getType()->isObjCObjectPointerType() ||
15964           FD->getType().isObjCGCStrong())
15965         Record->setHasObjectMember(true);
15966       else if (Context.getAsArrayType(FD->getType())) {
15967         QualType BaseType = Context.getBaseElementType(FD->getType());
15968         if (BaseType->isRecordType() &&
15969             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
15970           Record->setHasObjectMember(true);
15971         else if (BaseType->isObjCObjectPointerType() ||
15972                  BaseType.isObjCGCStrong())
15973                Record->setHasObjectMember(true);
15974       }
15975     }
15976 
15977     if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
15978       QualType FT = FD->getType();
15979       if (FT.isNonTrivialToPrimitiveDefaultInitialize())
15980         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
15981       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
15982       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial)
15983         Record->setNonTrivialToPrimitiveCopy(true);
15984       if (FT.isDestructedType()) {
15985         Record->setNonTrivialToPrimitiveDestroy(true);
15986         Record->setParamDestroyedInCallee(true);
15987       }
15988 
15989       if (const auto *RT = FT->getAs<RecordType>()) {
15990         if (RT->getDecl()->getArgPassingRestrictions() ==
15991             RecordDecl::APK_CanNeverPassInRegs)
15992           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
15993       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
15994         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
15995     }
15996 
15997     if (Record && FD->getType().isVolatileQualified())
15998       Record->setHasVolatileMember(true);
15999     // Keep track of the number of named members.
16000     if (FD->getIdentifier())
16001       ++NumNamedMembers;
16002   }
16003 
16004   // Okay, we successfully defined 'Record'.
16005   if (Record) {
16006     bool Completed = false;
16007     if (CXXRecord) {
16008       if (!CXXRecord->isInvalidDecl()) {
16009         // Set access bits correctly on the directly-declared conversions.
16010         for (CXXRecordDecl::conversion_iterator
16011                I = CXXRecord->conversion_begin(),
16012                E = CXXRecord->conversion_end(); I != E; ++I)
16013           I.setAccess((*I)->getAccess());
16014       }
16015 
16016       if (!CXXRecord->isDependentType()) {
16017         // Add any implicitly-declared members to this class.
16018         AddImplicitlyDeclaredMembersToClass(CXXRecord);
16019 
16020         if (!CXXRecord->isInvalidDecl()) {
16021           // If we have virtual base classes, we may end up finding multiple
16022           // final overriders for a given virtual function. Check for this
16023           // problem now.
16024           if (CXXRecord->getNumVBases()) {
16025             CXXFinalOverriderMap FinalOverriders;
16026             CXXRecord->getFinalOverriders(FinalOverriders);
16027 
16028             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16029                                              MEnd = FinalOverriders.end();
16030                  M != MEnd; ++M) {
16031               for (OverridingMethods::iterator SO = M->second.begin(),
16032                                             SOEnd = M->second.end();
16033                    SO != SOEnd; ++SO) {
16034                 assert(SO->second.size() > 0 &&
16035                        "Virtual function without overriding functions?");
16036                 if (SO->second.size() == 1)
16037                   continue;
16038 
16039                 // C++ [class.virtual]p2:
16040                 //   In a derived class, if a virtual member function of a base
16041                 //   class subobject has more than one final overrider the
16042                 //   program is ill-formed.
16043                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16044                   << (const NamedDecl *)M->first << Record;
16045                 Diag(M->first->getLocation(),
16046                      diag::note_overridden_virtual_function);
16047                 for (OverridingMethods::overriding_iterator
16048                           OM = SO->second.begin(),
16049                        OMEnd = SO->second.end();
16050                      OM != OMEnd; ++OM)
16051                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
16052                     << (const NamedDecl *)M->first << OM->Method->getParent();
16053 
16054                 Record->setInvalidDecl();
16055               }
16056             }
16057             CXXRecord->completeDefinition(&FinalOverriders);
16058             Completed = true;
16059           }
16060         }
16061       }
16062     }
16063 
16064     if (!Completed)
16065       Record->completeDefinition();
16066 
16067     // Handle attributes before checking the layout.
16068     ProcessDeclAttributeList(S, Record, Attrs);
16069 
16070     // We may have deferred checking for a deleted destructor. Check now.
16071     if (CXXRecord) {
16072       auto *Dtor = CXXRecord->getDestructor();
16073       if (Dtor && Dtor->isImplicit() &&
16074           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16075         CXXRecord->setImplicitDestructorIsDeleted();
16076         SetDeclDeleted(Dtor, CXXRecord->getLocation());
16077       }
16078     }
16079 
16080     if (Record->hasAttrs()) {
16081       CheckAlignasUnderalignment(Record);
16082 
16083       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16084         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16085                                            IA->getRange(), IA->getBestCase(),
16086                                            IA->getSemanticSpelling());
16087     }
16088 
16089     // Check if the structure/union declaration is a type that can have zero
16090     // size in C. For C this is a language extension, for C++ it may cause
16091     // compatibility problems.
16092     bool CheckForZeroSize;
16093     if (!getLangOpts().CPlusPlus) {
16094       CheckForZeroSize = true;
16095     } else {
16096       // For C++ filter out types that cannot be referenced in C code.
16097       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16098       CheckForZeroSize =
16099           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16100           !CXXRecord->isDependentType() &&
16101           CXXRecord->isCLike();
16102     }
16103     if (CheckForZeroSize) {
16104       bool ZeroSize = true;
16105       bool IsEmpty = true;
16106       unsigned NonBitFields = 0;
16107       for (RecordDecl::field_iterator I = Record->field_begin(),
16108                                       E = Record->field_end();
16109            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16110         IsEmpty = false;
16111         if (I->isUnnamedBitfield()) {
16112           if (!I->isZeroLengthBitField(Context))
16113             ZeroSize = false;
16114         } else {
16115           ++NonBitFields;
16116           QualType FieldType = I->getType();
16117           if (FieldType->isIncompleteType() ||
16118               !Context.getTypeSizeInChars(FieldType).isZero())
16119             ZeroSize = false;
16120         }
16121       }
16122 
16123       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16124       // allowed in C++, but warn if its declaration is inside
16125       // extern "C" block.
16126       if (ZeroSize) {
16127         Diag(RecLoc, getLangOpts().CPlusPlus ?
16128                          diag::warn_zero_size_struct_union_in_extern_c :
16129                          diag::warn_zero_size_struct_union_compat)
16130           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16131       }
16132 
16133       // Structs without named members are extension in C (C99 6.7.2.1p7),
16134       // but are accepted by GCC.
16135       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16136         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16137                                diag::ext_no_named_members_in_struct_union)
16138           << Record->isUnion();
16139       }
16140     }
16141   } else {
16142     ObjCIvarDecl **ClsFields =
16143       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16144     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16145       ID->setEndOfDefinitionLoc(RBrac);
16146       // Add ivar's to class's DeclContext.
16147       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16148         ClsFields[i]->setLexicalDeclContext(ID);
16149         ID->addDecl(ClsFields[i]);
16150       }
16151       // Must enforce the rule that ivars in the base classes may not be
16152       // duplicates.
16153       if (ID->getSuperClass())
16154         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16155     } else if (ObjCImplementationDecl *IMPDecl =
16156                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16157       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16158       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16159         // Ivar declared in @implementation never belongs to the implementation.
16160         // Only it is in implementation's lexical context.
16161         ClsFields[I]->setLexicalDeclContext(IMPDecl);
16162       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16163       IMPDecl->setIvarLBraceLoc(LBrac);
16164       IMPDecl->setIvarRBraceLoc(RBrac);
16165     } else if (ObjCCategoryDecl *CDecl =
16166                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16167       // case of ivars in class extension; all other cases have been
16168       // reported as errors elsewhere.
16169       // FIXME. Class extension does not have a LocEnd field.
16170       // CDecl->setLocEnd(RBrac);
16171       // Add ivar's to class extension's DeclContext.
16172       // Diagnose redeclaration of private ivars.
16173       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16174       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16175         if (IDecl) {
16176           if (const ObjCIvarDecl *ClsIvar =
16177               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16178             Diag(ClsFields[i]->getLocation(),
16179                  diag::err_duplicate_ivar_declaration);
16180             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16181             continue;
16182           }
16183           for (const auto *Ext : IDecl->known_extensions()) {
16184             if (const ObjCIvarDecl *ClsExtIvar
16185                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16186               Diag(ClsFields[i]->getLocation(),
16187                    diag::err_duplicate_ivar_declaration);
16188               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16189               continue;
16190             }
16191           }
16192         }
16193         ClsFields[i]->setLexicalDeclContext(CDecl);
16194         CDecl->addDecl(ClsFields[i]);
16195       }
16196       CDecl->setIvarLBraceLoc(LBrac);
16197       CDecl->setIvarRBraceLoc(RBrac);
16198     }
16199   }
16200 }
16201 
16202 /// Determine whether the given integral value is representable within
16203 /// the given type T.
16204 static bool isRepresentableIntegerValue(ASTContext &Context,
16205                                         llvm::APSInt &Value,
16206                                         QualType T) {
16207   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
16208          "Integral type required!");
16209   unsigned BitWidth = Context.getIntWidth(T);
16210 
16211   if (Value.isUnsigned() || Value.isNonNegative()) {
16212     if (T->isSignedIntegerOrEnumerationType())
16213       --BitWidth;
16214     return Value.getActiveBits() <= BitWidth;
16215   }
16216   return Value.getMinSignedBits() <= BitWidth;
16217 }
16218 
16219 // Given an integral type, return the next larger integral type
16220 // (or a NULL type of no such type exists).
16221 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
16222   // FIXME: Int128/UInt128 support, which also needs to be introduced into
16223   // enum checking below.
16224   assert((T->isIntegralType(Context) ||
16225          T->isEnumeralType()) && "Integral type required!");
16226   const unsigned NumTypes = 4;
16227   QualType SignedIntegralTypes[NumTypes] = {
16228     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
16229   };
16230   QualType UnsignedIntegralTypes[NumTypes] = {
16231     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
16232     Context.UnsignedLongLongTy
16233   };
16234 
16235   unsigned BitWidth = Context.getTypeSize(T);
16236   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
16237                                                         : UnsignedIntegralTypes;
16238   for (unsigned I = 0; I != NumTypes; ++I)
16239     if (Context.getTypeSize(Types[I]) > BitWidth)
16240       return Types[I];
16241 
16242   return QualType();
16243 }
16244 
16245 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
16246                                           EnumConstantDecl *LastEnumConst,
16247                                           SourceLocation IdLoc,
16248                                           IdentifierInfo *Id,
16249                                           Expr *Val) {
16250   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16251   llvm::APSInt EnumVal(IntWidth);
16252   QualType EltTy;
16253 
16254   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
16255     Val = nullptr;
16256 
16257   if (Val)
16258     Val = DefaultLvalueConversion(Val).get();
16259 
16260   if (Val) {
16261     if (Enum->isDependentType() || Val->isTypeDependent())
16262       EltTy = Context.DependentTy;
16263     else {
16264       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
16265           !getLangOpts().MSVCCompat) {
16266         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
16267         // constant-expression in the enumerator-definition shall be a converted
16268         // constant expression of the underlying type.
16269         EltTy = Enum->getIntegerType();
16270         ExprResult Converted =
16271           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
16272                                            CCEK_Enumerator);
16273         if (Converted.isInvalid())
16274           Val = nullptr;
16275         else
16276           Val = Converted.get();
16277       } else if (!Val->isValueDependent() &&
16278                  !(Val = VerifyIntegerConstantExpression(Val,
16279                                                          &EnumVal).get())) {
16280         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
16281       } else {
16282         if (Enum->isComplete()) {
16283           EltTy = Enum->getIntegerType();
16284 
16285           // In Obj-C and Microsoft mode, require the enumeration value to be
16286           // representable in the underlying type of the enumeration. In C++11,
16287           // we perform a non-narrowing conversion as part of converted constant
16288           // expression checking.
16289           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16290             if (getLangOpts().MSVCCompat) {
16291               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
16292               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
16293             } else
16294               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
16295           } else
16296             Val = ImpCastExprToType(Val, EltTy,
16297                                     EltTy->isBooleanType() ?
16298                                     CK_IntegralToBoolean : CK_IntegralCast)
16299                     .get();
16300         } else if (getLangOpts().CPlusPlus) {
16301           // C++11 [dcl.enum]p5:
16302           //   If the underlying type is not fixed, the type of each enumerator
16303           //   is the type of its initializing value:
16304           //     - If an initializer is specified for an enumerator, the
16305           //       initializing value has the same type as the expression.
16306           EltTy = Val->getType();
16307         } else {
16308           // C99 6.7.2.2p2:
16309           //   The expression that defines the value of an enumeration constant
16310           //   shall be an integer constant expression that has a value
16311           //   representable as an int.
16312 
16313           // Complain if the value is not representable in an int.
16314           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
16315             Diag(IdLoc, diag::ext_enum_value_not_int)
16316               << EnumVal.toString(10) << Val->getSourceRange()
16317               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
16318           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
16319             // Force the type of the expression to 'int'.
16320             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
16321           }
16322           EltTy = Val->getType();
16323         }
16324       }
16325     }
16326   }
16327 
16328   if (!Val) {
16329     if (Enum->isDependentType())
16330       EltTy = Context.DependentTy;
16331     else if (!LastEnumConst) {
16332       // C++0x [dcl.enum]p5:
16333       //   If the underlying type is not fixed, the type of each enumerator
16334       //   is the type of its initializing value:
16335       //     - If no initializer is specified for the first enumerator, the
16336       //       initializing value has an unspecified integral type.
16337       //
16338       // GCC uses 'int' for its unspecified integral type, as does
16339       // C99 6.7.2.2p3.
16340       if (Enum->isFixed()) {
16341         EltTy = Enum->getIntegerType();
16342       }
16343       else {
16344         EltTy = Context.IntTy;
16345       }
16346     } else {
16347       // Assign the last value + 1.
16348       EnumVal = LastEnumConst->getInitVal();
16349       ++EnumVal;
16350       EltTy = LastEnumConst->getType();
16351 
16352       // Check for overflow on increment.
16353       if (EnumVal < LastEnumConst->getInitVal()) {
16354         // C++0x [dcl.enum]p5:
16355         //   If the underlying type is not fixed, the type of each enumerator
16356         //   is the type of its initializing value:
16357         //
16358         //     - Otherwise the type of the initializing value is the same as
16359         //       the type of the initializing value of the preceding enumerator
16360         //       unless the incremented value is not representable in that type,
16361         //       in which case the type is an unspecified integral type
16362         //       sufficient to contain the incremented value. If no such type
16363         //       exists, the program is ill-formed.
16364         QualType T = getNextLargerIntegralType(Context, EltTy);
16365         if (T.isNull() || Enum->isFixed()) {
16366           // There is no integral type larger enough to represent this
16367           // value. Complain, then allow the value to wrap around.
16368           EnumVal = LastEnumConst->getInitVal();
16369           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
16370           ++EnumVal;
16371           if (Enum->isFixed())
16372             // When the underlying type is fixed, this is ill-formed.
16373             Diag(IdLoc, diag::err_enumerator_wrapped)
16374               << EnumVal.toString(10)
16375               << EltTy;
16376           else
16377             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
16378               << EnumVal.toString(10);
16379         } else {
16380           EltTy = T;
16381         }
16382 
16383         // Retrieve the last enumerator's value, extent that type to the
16384         // type that is supposed to be large enough to represent the incremented
16385         // value, then increment.
16386         EnumVal = LastEnumConst->getInitVal();
16387         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16388         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
16389         ++EnumVal;
16390 
16391         // If we're not in C++, diagnose the overflow of enumerator values,
16392         // which in C99 means that the enumerator value is not representable in
16393         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
16394         // permits enumerator values that are representable in some larger
16395         // integral type.
16396         if (!getLangOpts().CPlusPlus && !T.isNull())
16397           Diag(IdLoc, diag::warn_enum_value_overflow);
16398       } else if (!getLangOpts().CPlusPlus &&
16399                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16400         // Enforce C99 6.7.2.2p2 even when we compute the next value.
16401         Diag(IdLoc, diag::ext_enum_value_not_int)
16402           << EnumVal.toString(10) << 1;
16403       }
16404     }
16405   }
16406 
16407   if (!EltTy->isDependentType()) {
16408     // Make the enumerator value match the signedness and size of the
16409     // enumerator's type.
16410     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
16411     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16412   }
16413 
16414   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
16415                                   Val, EnumVal);
16416 }
16417 
16418 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
16419                                                 SourceLocation IILoc) {
16420   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
16421       !getLangOpts().CPlusPlus)
16422     return SkipBodyInfo();
16423 
16424   // We have an anonymous enum definition. Look up the first enumerator to
16425   // determine if we should merge the definition with an existing one and
16426   // skip the body.
16427   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
16428                                          forRedeclarationInCurContext());
16429   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
16430   if (!PrevECD)
16431     return SkipBodyInfo();
16432 
16433   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
16434   NamedDecl *Hidden;
16435   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
16436     SkipBodyInfo Skip;
16437     Skip.Previous = Hidden;
16438     return Skip;
16439   }
16440 
16441   return SkipBodyInfo();
16442 }
16443 
16444 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
16445                               SourceLocation IdLoc, IdentifierInfo *Id,
16446                               const ParsedAttributesView &Attrs,
16447                               SourceLocation EqualLoc, Expr *Val) {
16448   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
16449   EnumConstantDecl *LastEnumConst =
16450     cast_or_null<EnumConstantDecl>(lastEnumConst);
16451 
16452   // The scope passed in may not be a decl scope.  Zip up the scope tree until
16453   // we find one that is.
16454   S = getNonFieldDeclScope(S);
16455 
16456   // Verify that there isn't already something declared with this name in this
16457   // scope.
16458   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
16459   LookupName(R, S);
16460   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
16461 
16462   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16463     // Maybe we will complain about the shadowed template parameter.
16464     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
16465     // Just pretend that we didn't see the previous declaration.
16466     PrevDecl = nullptr;
16467   }
16468 
16469   // C++ [class.mem]p15:
16470   // If T is the name of a class, then each of the following shall have a name
16471   // different from T:
16472   // - every enumerator of every member of class T that is an unscoped
16473   // enumerated type
16474   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
16475     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
16476                             DeclarationNameInfo(Id, IdLoc));
16477 
16478   EnumConstantDecl *New =
16479     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
16480   if (!New)
16481     return nullptr;
16482 
16483   if (PrevDecl) {
16484     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
16485       // Check for other kinds of shadowing not already handled.
16486       CheckShadow(New, PrevDecl, R);
16487     }
16488 
16489     // When in C++, we may get a TagDecl with the same name; in this case the
16490     // enum constant will 'hide' the tag.
16491     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
16492            "Received TagDecl when not in C++!");
16493     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
16494       if (isa<EnumConstantDecl>(PrevDecl))
16495         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
16496       else
16497         Diag(IdLoc, diag::err_redefinition) << Id;
16498       notePreviousDefinition(PrevDecl, IdLoc);
16499       return nullptr;
16500     }
16501   }
16502 
16503   // Process attributes.
16504   ProcessDeclAttributeList(S, New, Attrs);
16505   AddPragmaAttributes(S, New);
16506 
16507   // Register this decl in the current scope stack.
16508   New->setAccess(TheEnumDecl->getAccess());
16509   PushOnScopeChains(New, S);
16510 
16511   ActOnDocumentableDecl(New);
16512 
16513   return New;
16514 }
16515 
16516 // Returns true when the enum initial expression does not trigger the
16517 // duplicate enum warning.  A few common cases are exempted as follows:
16518 // Element2 = Element1
16519 // Element2 = Element1 + 1
16520 // Element2 = Element1 - 1
16521 // Where Element2 and Element1 are from the same enum.
16522 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
16523   Expr *InitExpr = ECD->getInitExpr();
16524   if (!InitExpr)
16525     return true;
16526   InitExpr = InitExpr->IgnoreImpCasts();
16527 
16528   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
16529     if (!BO->isAdditiveOp())
16530       return true;
16531     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
16532     if (!IL)
16533       return true;
16534     if (IL->getValue() != 1)
16535       return true;
16536 
16537     InitExpr = BO->getLHS();
16538   }
16539 
16540   // This checks if the elements are from the same enum.
16541   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
16542   if (!DRE)
16543     return true;
16544 
16545   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
16546   if (!EnumConstant)
16547     return true;
16548 
16549   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
16550       Enum)
16551     return true;
16552 
16553   return false;
16554 }
16555 
16556 // Emits a warning when an element is implicitly set a value that
16557 // a previous element has already been set to.
16558 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
16559                                         EnumDecl *Enum, QualType EnumType) {
16560   // Avoid anonymous enums
16561   if (!Enum->getIdentifier())
16562     return;
16563 
16564   // Only check for small enums.
16565   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
16566     return;
16567 
16568   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
16569     return;
16570 
16571   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
16572   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
16573 
16574   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
16575   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
16576 
16577   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
16578   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
16579     llvm::APSInt Val = D->getInitVal();
16580     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
16581   };
16582 
16583   DuplicatesVector DupVector;
16584   ValueToVectorMap EnumMap;
16585 
16586   // Populate the EnumMap with all values represented by enum constants without
16587   // an initializer.
16588   for (auto *Element : Elements) {
16589     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
16590 
16591     // Null EnumConstantDecl means a previous diagnostic has been emitted for
16592     // this constant.  Skip this enum since it may be ill-formed.
16593     if (!ECD) {
16594       return;
16595     }
16596 
16597     // Constants with initalizers are handled in the next loop.
16598     if (ECD->getInitExpr())
16599       continue;
16600 
16601     // Duplicate values are handled in the next loop.
16602     EnumMap.insert({EnumConstantToKey(ECD), ECD});
16603   }
16604 
16605   if (EnumMap.size() == 0)
16606     return;
16607 
16608   // Create vectors for any values that has duplicates.
16609   for (auto *Element : Elements) {
16610     // The last loop returned if any constant was null.
16611     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
16612     if (!ValidDuplicateEnum(ECD, Enum))
16613       continue;
16614 
16615     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
16616     if (Iter == EnumMap.end())
16617       continue;
16618 
16619     DeclOrVector& Entry = Iter->second;
16620     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
16621       // Ensure constants are different.
16622       if (D == ECD)
16623         continue;
16624 
16625       // Create new vector and push values onto it.
16626       auto Vec = llvm::make_unique<ECDVector>();
16627       Vec->push_back(D);
16628       Vec->push_back(ECD);
16629 
16630       // Update entry to point to the duplicates vector.
16631       Entry = Vec.get();
16632 
16633       // Store the vector somewhere we can consult later for quick emission of
16634       // diagnostics.
16635       DupVector.emplace_back(std::move(Vec));
16636       continue;
16637     }
16638 
16639     ECDVector *Vec = Entry.get<ECDVector*>();
16640     // Make sure constants are not added more than once.
16641     if (*Vec->begin() == ECD)
16642       continue;
16643 
16644     Vec->push_back(ECD);
16645   }
16646 
16647   // Emit diagnostics.
16648   for (const auto &Vec : DupVector) {
16649     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
16650 
16651     // Emit warning for one enum constant.
16652     auto *FirstECD = Vec->front();
16653     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
16654       << FirstECD << FirstECD->getInitVal().toString(10)
16655       << FirstECD->getSourceRange();
16656 
16657     // Emit one note for each of the remaining enum constants with
16658     // the same value.
16659     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
16660       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
16661         << ECD << ECD->getInitVal().toString(10)
16662         << ECD->getSourceRange();
16663   }
16664 }
16665 
16666 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
16667                              bool AllowMask) const {
16668   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
16669   assert(ED->isCompleteDefinition() && "expected enum definition");
16670 
16671   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
16672   llvm::APInt &FlagBits = R.first->second;
16673 
16674   if (R.second) {
16675     for (auto *E : ED->enumerators()) {
16676       const auto &EVal = E->getInitVal();
16677       // Only single-bit enumerators introduce new flag values.
16678       if (EVal.isPowerOf2())
16679         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
16680     }
16681   }
16682 
16683   // A value is in a flag enum if either its bits are a subset of the enum's
16684   // flag bits (the first condition) or we are allowing masks and the same is
16685   // true of its complement (the second condition). When masks are allowed, we
16686   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
16687   //
16688   // While it's true that any value could be used as a mask, the assumption is
16689   // that a mask will have all of the insignificant bits set. Anything else is
16690   // likely a logic error.
16691   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
16692   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
16693 }
16694 
16695 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
16696                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
16697                          const ParsedAttributesView &Attrs) {
16698   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
16699   QualType EnumType = Context.getTypeDeclType(Enum);
16700 
16701   ProcessDeclAttributeList(S, Enum, Attrs);
16702 
16703   if (Enum->isDependentType()) {
16704     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16705       EnumConstantDecl *ECD =
16706         cast_or_null<EnumConstantDecl>(Elements[i]);
16707       if (!ECD) continue;
16708 
16709       ECD->setType(EnumType);
16710     }
16711 
16712     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
16713     return;
16714   }
16715 
16716   // TODO: If the result value doesn't fit in an int, it must be a long or long
16717   // long value.  ISO C does not support this, but GCC does as an extension,
16718   // emit a warning.
16719   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16720   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
16721   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
16722 
16723   // Verify that all the values are okay, compute the size of the values, and
16724   // reverse the list.
16725   unsigned NumNegativeBits = 0;
16726   unsigned NumPositiveBits = 0;
16727 
16728   // Keep track of whether all elements have type int.
16729   bool AllElementsInt = true;
16730 
16731   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16732     EnumConstantDecl *ECD =
16733       cast_or_null<EnumConstantDecl>(Elements[i]);
16734     if (!ECD) continue;  // Already issued a diagnostic.
16735 
16736     const llvm::APSInt &InitVal = ECD->getInitVal();
16737 
16738     // Keep track of the size of positive and negative values.
16739     if (InitVal.isUnsigned() || InitVal.isNonNegative())
16740       NumPositiveBits = std::max(NumPositiveBits,
16741                                  (unsigned)InitVal.getActiveBits());
16742     else
16743       NumNegativeBits = std::max(NumNegativeBits,
16744                                  (unsigned)InitVal.getMinSignedBits());
16745 
16746     // Keep track of whether every enum element has type int (very common).
16747     if (AllElementsInt)
16748       AllElementsInt = ECD->getType() == Context.IntTy;
16749   }
16750 
16751   // Figure out the type that should be used for this enum.
16752   QualType BestType;
16753   unsigned BestWidth;
16754 
16755   // C++0x N3000 [conv.prom]p3:
16756   //   An rvalue of an unscoped enumeration type whose underlying
16757   //   type is not fixed can be converted to an rvalue of the first
16758   //   of the following types that can represent all the values of
16759   //   the enumeration: int, unsigned int, long int, unsigned long
16760   //   int, long long int, or unsigned long long int.
16761   // C99 6.4.4.3p2:
16762   //   An identifier declared as an enumeration constant has type int.
16763   // The C99 rule is modified by a gcc extension
16764   QualType BestPromotionType;
16765 
16766   bool Packed = Enum->hasAttr<PackedAttr>();
16767   // -fshort-enums is the equivalent to specifying the packed attribute on all
16768   // enum definitions.
16769   if (LangOpts.ShortEnums)
16770     Packed = true;
16771 
16772   // If the enum already has a type because it is fixed or dictated by the
16773   // target, promote that type instead of analyzing the enumerators.
16774   if (Enum->isComplete()) {
16775     BestType = Enum->getIntegerType();
16776     if (BestType->isPromotableIntegerType())
16777       BestPromotionType = Context.getPromotedIntegerType(BestType);
16778     else
16779       BestPromotionType = BestType;
16780 
16781     BestWidth = Context.getIntWidth(BestType);
16782   }
16783   else if (NumNegativeBits) {
16784     // If there is a negative value, figure out the smallest integer type (of
16785     // int/long/longlong) that fits.
16786     // If it's packed, check also if it fits a char or a short.
16787     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
16788       BestType = Context.SignedCharTy;
16789       BestWidth = CharWidth;
16790     } else if (Packed && NumNegativeBits <= ShortWidth &&
16791                NumPositiveBits < ShortWidth) {
16792       BestType = Context.ShortTy;
16793       BestWidth = ShortWidth;
16794     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
16795       BestType = Context.IntTy;
16796       BestWidth = IntWidth;
16797     } else {
16798       BestWidth = Context.getTargetInfo().getLongWidth();
16799 
16800       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
16801         BestType = Context.LongTy;
16802       } else {
16803         BestWidth = Context.getTargetInfo().getLongLongWidth();
16804 
16805         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
16806           Diag(Enum->getLocation(), diag::ext_enum_too_large);
16807         BestType = Context.LongLongTy;
16808       }
16809     }
16810     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
16811   } else {
16812     // If there is no negative value, figure out the smallest type that fits
16813     // all of the enumerator values.
16814     // If it's packed, check also if it fits a char or a short.
16815     if (Packed && NumPositiveBits <= CharWidth) {
16816       BestType = Context.UnsignedCharTy;
16817       BestPromotionType = Context.IntTy;
16818       BestWidth = CharWidth;
16819     } else if (Packed && NumPositiveBits <= ShortWidth) {
16820       BestType = Context.UnsignedShortTy;
16821       BestPromotionType = Context.IntTy;
16822       BestWidth = ShortWidth;
16823     } else if (NumPositiveBits <= IntWidth) {
16824       BestType = Context.UnsignedIntTy;
16825       BestWidth = IntWidth;
16826       BestPromotionType
16827         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16828                            ? Context.UnsignedIntTy : Context.IntTy;
16829     } else if (NumPositiveBits <=
16830                (BestWidth = Context.getTargetInfo().getLongWidth())) {
16831       BestType = Context.UnsignedLongTy;
16832       BestPromotionType
16833         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16834                            ? Context.UnsignedLongTy : Context.LongTy;
16835     } else {
16836       BestWidth = Context.getTargetInfo().getLongLongWidth();
16837       assert(NumPositiveBits <= BestWidth &&
16838              "How could an initializer get larger than ULL?");
16839       BestType = Context.UnsignedLongLongTy;
16840       BestPromotionType
16841         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16842                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
16843     }
16844   }
16845 
16846   // Loop over all of the enumerator constants, changing their types to match
16847   // the type of the enum if needed.
16848   for (auto *D : Elements) {
16849     auto *ECD = cast_or_null<EnumConstantDecl>(D);
16850     if (!ECD) continue;  // Already issued a diagnostic.
16851 
16852     // Standard C says the enumerators have int type, but we allow, as an
16853     // extension, the enumerators to be larger than int size.  If each
16854     // enumerator value fits in an int, type it as an int, otherwise type it the
16855     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
16856     // that X has type 'int', not 'unsigned'.
16857 
16858     // Determine whether the value fits into an int.
16859     llvm::APSInt InitVal = ECD->getInitVal();
16860 
16861     // If it fits into an integer type, force it.  Otherwise force it to match
16862     // the enum decl type.
16863     QualType NewTy;
16864     unsigned NewWidth;
16865     bool NewSign;
16866     if (!getLangOpts().CPlusPlus &&
16867         !Enum->isFixed() &&
16868         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
16869       NewTy = Context.IntTy;
16870       NewWidth = IntWidth;
16871       NewSign = true;
16872     } else if (ECD->getType() == BestType) {
16873       // Already the right type!
16874       if (getLangOpts().CPlusPlus)
16875         // C++ [dcl.enum]p4: Following the closing brace of an
16876         // enum-specifier, each enumerator has the type of its
16877         // enumeration.
16878         ECD->setType(EnumType);
16879       continue;
16880     } else {
16881       NewTy = BestType;
16882       NewWidth = BestWidth;
16883       NewSign = BestType->isSignedIntegerOrEnumerationType();
16884     }
16885 
16886     // Adjust the APSInt value.
16887     InitVal = InitVal.extOrTrunc(NewWidth);
16888     InitVal.setIsSigned(NewSign);
16889     ECD->setInitVal(InitVal);
16890 
16891     // Adjust the Expr initializer and type.
16892     if (ECD->getInitExpr() &&
16893         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
16894       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
16895                                                 CK_IntegralCast,
16896                                                 ECD->getInitExpr(),
16897                                                 /*base paths*/ nullptr,
16898                                                 VK_RValue));
16899     if (getLangOpts().CPlusPlus)
16900       // C++ [dcl.enum]p4: Following the closing brace of an
16901       // enum-specifier, each enumerator has the type of its
16902       // enumeration.
16903       ECD->setType(EnumType);
16904     else
16905       ECD->setType(NewTy);
16906   }
16907 
16908   Enum->completeDefinition(BestType, BestPromotionType,
16909                            NumPositiveBits, NumNegativeBits);
16910 
16911   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
16912 
16913   if (Enum->isClosedFlag()) {
16914     for (Decl *D : Elements) {
16915       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
16916       if (!ECD) continue;  // Already issued a diagnostic.
16917 
16918       llvm::APSInt InitVal = ECD->getInitVal();
16919       if (InitVal != 0 && !InitVal.isPowerOf2() &&
16920           !IsValueInFlagEnum(Enum, InitVal, true))
16921         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
16922           << ECD << Enum;
16923     }
16924   }
16925 
16926   // Now that the enum type is defined, ensure it's not been underaligned.
16927   if (Enum->hasAttrs())
16928     CheckAlignasUnderalignment(Enum);
16929 }
16930 
16931 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
16932                                   SourceLocation StartLoc,
16933                                   SourceLocation EndLoc) {
16934   StringLiteral *AsmString = cast<StringLiteral>(expr);
16935 
16936   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
16937                                                    AsmString, StartLoc,
16938                                                    EndLoc);
16939   CurContext->addDecl(New);
16940   return New;
16941 }
16942 
16943 static void checkModuleImportContext(Sema &S, Module *M,
16944                                      SourceLocation ImportLoc, DeclContext *DC,
16945                                      bool FromInclude = false) {
16946   SourceLocation ExternCLoc;
16947 
16948   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
16949     switch (LSD->getLanguage()) {
16950     case LinkageSpecDecl::lang_c:
16951       if (ExternCLoc.isInvalid())
16952         ExternCLoc = LSD->getBeginLoc();
16953       break;
16954     case LinkageSpecDecl::lang_cxx:
16955       break;
16956     }
16957     DC = LSD->getParent();
16958   }
16959 
16960   while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
16961     DC = DC->getParent();
16962 
16963   if (!isa<TranslationUnitDecl>(DC)) {
16964     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
16965                           ? diag::ext_module_import_not_at_top_level_noop
16966                           : diag::err_module_import_not_at_top_level_fatal)
16967         << M->getFullModuleName() << DC;
16968     S.Diag(cast<Decl>(DC)->getBeginLoc(),
16969            diag::note_module_import_not_at_top_level)
16970         << DC;
16971   } else if (!M->IsExternC && ExternCLoc.isValid()) {
16972     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
16973       << M->getFullModuleName();
16974     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
16975   }
16976 }
16977 
16978 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
16979                                            SourceLocation ModuleLoc,
16980                                            ModuleDeclKind MDK,
16981                                            ModuleIdPath Path) {
16982   assert(getLangOpts().ModulesTS &&
16983          "should only have module decl in modules TS");
16984 
16985   // A module implementation unit requires that we are not compiling a module
16986   // of any kind. A module interface unit requires that we are not compiling a
16987   // module map.
16988   switch (getLangOpts().getCompilingModule()) {
16989   case LangOptions::CMK_None:
16990     // It's OK to compile a module interface as a normal translation unit.
16991     break;
16992 
16993   case LangOptions::CMK_ModuleInterface:
16994     if (MDK != ModuleDeclKind::Implementation)
16995       break;
16996 
16997     // We were asked to compile a module interface unit but this is a module
16998     // implementation unit. That indicates the 'export' is missing.
16999     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
17000       << FixItHint::CreateInsertion(ModuleLoc, "export ");
17001     MDK = ModuleDeclKind::Interface;
17002     break;
17003 
17004   case LangOptions::CMK_ModuleMap:
17005     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
17006     return nullptr;
17007 
17008   case LangOptions::CMK_HeaderModule:
17009     Diag(ModuleLoc, diag::err_module_decl_in_header_module);
17010     return nullptr;
17011   }
17012 
17013   assert(ModuleScopes.size() == 1 && "expected to be at global module scope");
17014 
17015   // FIXME: Most of this work should be done by the preprocessor rather than
17016   // here, in order to support macro import.
17017 
17018   // Only one module-declaration is permitted per source file.
17019   if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) {
17020     Diag(ModuleLoc, diag::err_module_redeclaration);
17021     Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
17022          diag::note_prev_module_declaration);
17023     return nullptr;
17024   }
17025 
17026   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
17027   // modules, the dots here are just another character that can appear in a
17028   // module name.
17029   std::string ModuleName;
17030   for (auto &Piece : Path) {
17031     if (!ModuleName.empty())
17032       ModuleName += ".";
17033     ModuleName += Piece.first->getName();
17034   }
17035 
17036   // If a module name was explicitly specified on the command line, it must be
17037   // correct.
17038   if (!getLangOpts().CurrentModule.empty() &&
17039       getLangOpts().CurrentModule != ModuleName) {
17040     Diag(Path.front().second, diag::err_current_module_name_mismatch)
17041         << SourceRange(Path.front().second, Path.back().second)
17042         << getLangOpts().CurrentModule;
17043     return nullptr;
17044   }
17045   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
17046 
17047   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
17048   Module *Mod;
17049 
17050   switch (MDK) {
17051   case ModuleDeclKind::Interface: {
17052     // We can't have parsed or imported a definition of this module or parsed a
17053     // module map defining it already.
17054     if (auto *M = Map.findModule(ModuleName)) {
17055       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
17056       if (M->DefinitionLoc.isValid())
17057         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
17058       else if (const auto *FE = M->getASTFile())
17059         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
17060             << FE->getName();
17061       Mod = M;
17062       break;
17063     }
17064 
17065     // Create a Module for the module that we're defining.
17066     Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
17067                                            ModuleScopes.front().Module);
17068     assert(Mod && "module creation should not fail");
17069     break;
17070   }
17071 
17072   case ModuleDeclKind::Partition:
17073     // FIXME: Check we are in a submodule of the named module.
17074     return nullptr;
17075 
17076   case ModuleDeclKind::Implementation:
17077     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
17078         PP.getIdentifierInfo(ModuleName), Path[0].second);
17079     Mod = getModuleLoader().loadModule(ModuleLoc, {ModuleNameLoc},
17080                                        Module::AllVisible,
17081                                        /*IsIncludeDirective=*/false);
17082     if (!Mod) {
17083       Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
17084       // Create an empty module interface unit for error recovery.
17085       Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
17086                                              ModuleScopes.front().Module);
17087     }
17088     break;
17089   }
17090 
17091   // Switch from the global module to the named module.
17092   ModuleScopes.back().Module = Mod;
17093   ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
17094   VisibleModules.setVisible(Mod, ModuleLoc);
17095 
17096   // From now on, we have an owning module for all declarations we see.
17097   // However, those declarations are module-private unless explicitly
17098   // exported.
17099   auto *TU = Context.getTranslationUnitDecl();
17100   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
17101   TU->setLocalOwningModule(Mod);
17102 
17103   // FIXME: Create a ModuleDecl.
17104   return nullptr;
17105 }
17106 
17107 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
17108                                    SourceLocation ImportLoc,
17109                                    ModuleIdPath Path) {
17110   // Flatten the module path for a Modules TS module name.
17111   std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
17112   if (getLangOpts().ModulesTS) {
17113     std::string ModuleName;
17114     for (auto &Piece : Path) {
17115       if (!ModuleName.empty())
17116         ModuleName += ".";
17117       ModuleName += Piece.first->getName();
17118     }
17119     ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
17120     Path = ModuleIdPath(ModuleNameLoc);
17121   }
17122 
17123   Module *Mod =
17124       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
17125                                    /*IsIncludeDirective=*/false);
17126   if (!Mod)
17127     return true;
17128 
17129   VisibleModules.setVisible(Mod, ImportLoc);
17130 
17131   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
17132 
17133   // FIXME: we should support importing a submodule within a different submodule
17134   // of the same top-level module. Until we do, make it an error rather than
17135   // silently ignoring the import.
17136   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
17137   // warn on a redundant import of the current module?
17138   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
17139       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
17140     Diag(ImportLoc, getLangOpts().isCompilingModule()
17141                         ? diag::err_module_self_import
17142                         : diag::err_module_import_in_implementation)
17143         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
17144 
17145   SmallVector<SourceLocation, 2> IdentifierLocs;
17146   Module *ModCheck = Mod;
17147   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
17148     // If we've run out of module parents, just drop the remaining identifiers.
17149     // We need the length to be consistent.
17150     if (!ModCheck)
17151       break;
17152     ModCheck = ModCheck->Parent;
17153 
17154     IdentifierLocs.push_back(Path[I].second);
17155   }
17156 
17157   ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
17158                                           Mod, IdentifierLocs);
17159   if (!ModuleScopes.empty())
17160     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
17161   CurContext->addDecl(Import);
17162 
17163   // Re-export the module if needed.
17164   if (Import->isExported() &&
17165       !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface)
17166     getCurrentModule()->Exports.emplace_back(Mod, false);
17167 
17168   return Import;
17169 }
17170 
17171 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
17172   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
17173   BuildModuleInclude(DirectiveLoc, Mod);
17174 }
17175 
17176 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
17177   // Determine whether we're in the #include buffer for a module. The #includes
17178   // in that buffer do not qualify as module imports; they're just an
17179   // implementation detail of us building the module.
17180   //
17181   // FIXME: Should we even get ActOnModuleInclude calls for those?
17182   bool IsInModuleIncludes =
17183       TUKind == TU_Module &&
17184       getSourceManager().isWrittenInMainFile(DirectiveLoc);
17185 
17186   bool ShouldAddImport = !IsInModuleIncludes;
17187 
17188   // If this module import was due to an inclusion directive, create an
17189   // implicit import declaration to capture it in the AST.
17190   if (ShouldAddImport) {
17191     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
17192     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
17193                                                      DirectiveLoc, Mod,
17194                                                      DirectiveLoc);
17195     if (!ModuleScopes.empty())
17196       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
17197     TU->addDecl(ImportD);
17198     Consumer.HandleImplicitImportDecl(ImportD);
17199   }
17200 
17201   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
17202   VisibleModules.setVisible(Mod, DirectiveLoc);
17203 }
17204 
17205 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
17206   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
17207 
17208   ModuleScopes.push_back({});
17209   ModuleScopes.back().Module = Mod;
17210   if (getLangOpts().ModulesLocalVisibility)
17211     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
17212 
17213   VisibleModules.setVisible(Mod, DirectiveLoc);
17214 
17215   // The enclosing context is now part of this module.
17216   // FIXME: Consider creating a child DeclContext to hold the entities
17217   // lexically within the module.
17218   if (getLangOpts().trackLocalOwningModule()) {
17219     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
17220       cast<Decl>(DC)->setModuleOwnershipKind(
17221           getLangOpts().ModulesLocalVisibility
17222               ? Decl::ModuleOwnershipKind::VisibleWhenImported
17223               : Decl::ModuleOwnershipKind::Visible);
17224       cast<Decl>(DC)->setLocalOwningModule(Mod);
17225     }
17226   }
17227 }
17228 
17229 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
17230   if (getLangOpts().ModulesLocalVisibility) {
17231     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
17232     // Leaving a module hides namespace names, so our visible namespace cache
17233     // is now out of date.
17234     VisibleNamespaceCache.clear();
17235   }
17236 
17237   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
17238          "left the wrong module scope");
17239   ModuleScopes.pop_back();
17240 
17241   // We got to the end of processing a local module. Create an
17242   // ImportDecl as we would for an imported module.
17243   FileID File = getSourceManager().getFileID(EomLoc);
17244   SourceLocation DirectiveLoc;
17245   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
17246     // We reached the end of a #included module header. Use the #include loc.
17247     assert(File != getSourceManager().getMainFileID() &&
17248            "end of submodule in main source file");
17249     DirectiveLoc = getSourceManager().getIncludeLoc(File);
17250   } else {
17251     // We reached an EOM pragma. Use the pragma location.
17252     DirectiveLoc = EomLoc;
17253   }
17254   BuildModuleInclude(DirectiveLoc, Mod);
17255 
17256   // Any further declarations are in whatever module we returned to.
17257   if (getLangOpts().trackLocalOwningModule()) {
17258     // The parser guarantees that this is the same context that we entered
17259     // the module within.
17260     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
17261       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
17262       if (!getCurrentModule())
17263         cast<Decl>(DC)->setModuleOwnershipKind(
17264             Decl::ModuleOwnershipKind::Unowned);
17265     }
17266   }
17267 }
17268 
17269 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
17270                                                       Module *Mod) {
17271   // Bail if we're not allowed to implicitly import a module here.
17272   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
17273       VisibleModules.isVisible(Mod))
17274     return;
17275 
17276   // Create the implicit import declaration.
17277   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
17278   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
17279                                                    Loc, Mod, Loc);
17280   TU->addDecl(ImportD);
17281   Consumer.HandleImplicitImportDecl(ImportD);
17282 
17283   // Make the module visible.
17284   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
17285   VisibleModules.setVisible(Mod, Loc);
17286 }
17287 
17288 /// We have parsed the start of an export declaration, including the '{'
17289 /// (if present).
17290 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
17291                                  SourceLocation LBraceLoc) {
17292   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
17293 
17294   // C++ Modules TS draft:
17295   //   An export-declaration shall appear in the purview of a module other than
17296   //   the global module.
17297   if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface)
17298     Diag(ExportLoc, diag::err_export_not_in_module_interface);
17299 
17300   //   An export-declaration [...] shall not contain more than one
17301   //   export keyword.
17302   //
17303   // The intent here is that an export-declaration cannot appear within another
17304   // export-declaration.
17305   if (D->isExported())
17306     Diag(ExportLoc, diag::err_export_within_export);
17307 
17308   CurContext->addDecl(D);
17309   PushDeclContext(S, D);
17310   D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
17311   return D;
17312 }
17313 
17314 /// Complete the definition of an export declaration.
17315 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
17316   auto *ED = cast<ExportDecl>(D);
17317   if (RBraceLoc.isValid())
17318     ED->setRBraceLoc(RBraceLoc);
17319 
17320   // FIXME: Diagnose export of internal-linkage declaration (including
17321   // anonymous namespace).
17322 
17323   PopDeclContext();
17324   return D;
17325 }
17326 
17327 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17328                                       IdentifierInfo* AliasName,
17329                                       SourceLocation PragmaLoc,
17330                                       SourceLocation NameLoc,
17331                                       SourceLocation AliasNameLoc) {
17332   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17333                                          LookupOrdinaryName);
17334   AsmLabelAttr *Attr =
17335       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
17336 
17337   // If a declaration that:
17338   // 1) declares a function or a variable
17339   // 2) has external linkage
17340   // already exists, add a label attribute to it.
17341   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17342     if (isDeclExternC(PrevDecl))
17343       PrevDecl->addAttr(Attr);
17344     else
17345       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17346           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17347   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17348   } else
17349     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17350 }
17351 
17352 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17353                              SourceLocation PragmaLoc,
17354                              SourceLocation NameLoc) {
17355   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17356 
17357   if (PrevDecl) {
17358     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
17359   } else {
17360     (void)WeakUndeclaredIdentifiers.insert(
17361       std::pair<IdentifierInfo*,WeakInfo>
17362         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17363   }
17364 }
17365 
17366 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17367                                 IdentifierInfo* AliasName,
17368                                 SourceLocation PragmaLoc,
17369                                 SourceLocation NameLoc,
17370                                 SourceLocation AliasNameLoc) {
17371   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17372                                     LookupOrdinaryName);
17373   WeakInfo W = WeakInfo(Name, NameLoc);
17374 
17375   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17376     if (!PrevDecl->hasAttr<AliasAttr>())
17377       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17378         DeclApplyPragmaWeak(TUScope, ND, W);
17379   } else {
17380     (void)WeakUndeclaredIdentifiers.insert(
17381       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17382   }
17383 }
17384 
17385 Decl *Sema::getObjCDeclContext() const {
17386   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17387 }
17388