1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/CommentDiagnostic.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaInternal.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50 
51 using namespace clang;
52 using namespace sema;
53 
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59 
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62 
63 namespace {
64 
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66  public:
67    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
68                         bool AllowTemplates = false,
69                         bool AllowNonTemplates = true)
70        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
71          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
72      WantExpressionKeywords = false;
73      WantCXXNamedCasts = false;
74      WantRemainingKeywords = false;
75   }
76 
77   bool ValidateCandidate(const TypoCorrection &candidate) override {
78     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
79       if (!AllowInvalidDecl && ND->isInvalidDecl())
80         return false;
81 
82       if (getAsTypeTemplateDecl(ND))
83         return AllowTemplates;
84 
85       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
86       if (!IsType)
87         return false;
88 
89       if (AllowNonTemplates)
90         return true;
91 
92       // An injected-class-name of a class template (specialization) is valid
93       // as a template or as a non-template.
94       if (AllowTemplates) {
95         auto *RD = dyn_cast<CXXRecordDecl>(ND);
96         if (!RD || !RD->isInjectedClassName())
97           return false;
98         RD = cast<CXXRecordDecl>(RD->getDeclContext());
99         return RD->getDescribedClassTemplate() ||
100                isa<ClassTemplateSpecializationDecl>(RD);
101       }
102 
103       return false;
104     }
105 
106     return !WantClassName && candidate.isKeyword();
107   }
108 
109  private:
110   bool AllowInvalidDecl;
111   bool WantClassName;
112   bool AllowTemplates;
113   bool AllowNonTemplates;
114 };
115 
116 } // end anonymous namespace
117 
118 /// Determine whether the token kind starts a simple-type-specifier.
119 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
120   switch (Kind) {
121   // FIXME: Take into account the current language when deciding whether a
122   // token kind is a valid type specifier
123   case tok::kw_short:
124   case tok::kw_long:
125   case tok::kw___int64:
126   case tok::kw___int128:
127   case tok::kw_signed:
128   case tok::kw_unsigned:
129   case tok::kw_void:
130   case tok::kw_char:
131   case tok::kw_int:
132   case tok::kw_half:
133   case tok::kw_float:
134   case tok::kw_double:
135   case tok::kw__Float16:
136   case tok::kw___float128:
137   case tok::kw_wchar_t:
138   case tok::kw_bool:
139   case tok::kw___underlying_type:
140   case tok::kw___auto_type:
141     return true;
142 
143   case tok::annot_typename:
144   case tok::kw_char16_t:
145   case tok::kw_char32_t:
146   case tok::kw_typeof:
147   case tok::annot_decltype:
148   case tok::kw_decltype:
149     return getLangOpts().CPlusPlus;
150 
151   case tok::kw_char8_t:
152     return getLangOpts().Char8;
153 
154   default:
155     break;
156   }
157 
158   return false;
159 }
160 
161 namespace {
162 enum class UnqualifiedTypeNameLookupResult {
163   NotFound,
164   FoundNonType,
165   FoundType
166 };
167 } // end anonymous namespace
168 
169 /// Tries to perform unqualified lookup of the type decls in bases for
170 /// dependent class.
171 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
172 /// type decl, \a FoundType if only type decls are found.
173 static UnqualifiedTypeNameLookupResult
174 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
175                                 SourceLocation NameLoc,
176                                 const CXXRecordDecl *RD) {
177   if (!RD->hasDefinition())
178     return UnqualifiedTypeNameLookupResult::NotFound;
179   // Look for type decls in base classes.
180   UnqualifiedTypeNameLookupResult FoundTypeDecl =
181       UnqualifiedTypeNameLookupResult::NotFound;
182   for (const auto &Base : RD->bases()) {
183     const CXXRecordDecl *BaseRD = nullptr;
184     if (auto *BaseTT = Base.getType()->getAs<TagType>())
185       BaseRD = BaseTT->getAsCXXRecordDecl();
186     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
187       // Look for type decls in dependent base classes that have known primary
188       // templates.
189       if (!TST || !TST->isDependentType())
190         continue;
191       auto *TD = TST->getTemplateName().getAsTemplateDecl();
192       if (!TD)
193         continue;
194       if (auto *BasePrimaryTemplate =
195           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
196         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
197           BaseRD = BasePrimaryTemplate;
198         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
199           if (const ClassTemplatePartialSpecializationDecl *PS =
200                   CTD->findPartialSpecialization(Base.getType()))
201             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
202               BaseRD = PS;
203         }
204       }
205     }
206     if (BaseRD) {
207       for (NamedDecl *ND : BaseRD->lookup(&II)) {
208         if (!isa<TypeDecl>(ND))
209           return UnqualifiedTypeNameLookupResult::FoundNonType;
210         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
211       }
212       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
213         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
214         case UnqualifiedTypeNameLookupResult::FoundNonType:
215           return UnqualifiedTypeNameLookupResult::FoundNonType;
216         case UnqualifiedTypeNameLookupResult::FoundType:
217           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
218           break;
219         case UnqualifiedTypeNameLookupResult::NotFound:
220           break;
221         }
222       }
223     }
224   }
225 
226   return FoundTypeDecl;
227 }
228 
229 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
230                                                       const IdentifierInfo &II,
231                                                       SourceLocation NameLoc) {
232   // Lookup in the parent class template context, if any.
233   const CXXRecordDecl *RD = nullptr;
234   UnqualifiedTypeNameLookupResult FoundTypeDecl =
235       UnqualifiedTypeNameLookupResult::NotFound;
236   for (DeclContext *DC = S.CurContext;
237        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
238        DC = DC->getParent()) {
239     // Look for type decls in dependent base classes that have known primary
240     // templates.
241     RD = dyn_cast<CXXRecordDecl>(DC);
242     if (RD && RD->getDescribedClassTemplate())
243       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
244   }
245   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
246     return nullptr;
247 
248   // We found some types in dependent base classes.  Recover as if the user
249   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
250   // lookup during template instantiation.
251   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
252 
253   ASTContext &Context = S.Context;
254   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
255                                           cast<Type>(Context.getRecordType(RD)));
256   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
257 
258   CXXScopeSpec SS;
259   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
260 
261   TypeLocBuilder Builder;
262   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
263   DepTL.setNameLoc(NameLoc);
264   DepTL.setElaboratedKeywordLoc(SourceLocation());
265   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
266   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
267 }
268 
269 /// If the identifier refers to a type name within this scope,
270 /// return the declaration of that type.
271 ///
272 /// This routine performs ordinary name lookup of the identifier II
273 /// within the given scope, with optional C++ scope specifier SS, to
274 /// determine whether the name refers to a type. If so, returns an
275 /// opaque pointer (actually a QualType) corresponding to that
276 /// type. Otherwise, returns NULL.
277 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
278                              Scope *S, CXXScopeSpec *SS,
279                              bool isClassName, bool HasTrailingDot,
280                              ParsedType ObjectTypePtr,
281                              bool IsCtorOrDtorName,
282                              bool WantNontrivialTypeSourceInfo,
283                              bool IsClassTemplateDeductionContext,
284                              IdentifierInfo **CorrectedII) {
285   // FIXME: Consider allowing this outside C++1z mode as an extension.
286   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
287                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
288                               !isClassName && !HasTrailingDot;
289 
290   // Determine where we will perform name lookup.
291   DeclContext *LookupCtx = nullptr;
292   if (ObjectTypePtr) {
293     QualType ObjectType = ObjectTypePtr.get();
294     if (ObjectType->isRecordType())
295       LookupCtx = computeDeclContext(ObjectType);
296   } else if (SS && SS->isNotEmpty()) {
297     LookupCtx = computeDeclContext(*SS, false);
298 
299     if (!LookupCtx) {
300       if (isDependentScopeSpecifier(*SS)) {
301         // C++ [temp.res]p3:
302         //   A qualified-id that refers to a type and in which the
303         //   nested-name-specifier depends on a template-parameter (14.6.2)
304         //   shall be prefixed by the keyword typename to indicate that the
305         //   qualified-id denotes a type, forming an
306         //   elaborated-type-specifier (7.1.5.3).
307         //
308         // We therefore do not perform any name lookup if the result would
309         // refer to a member of an unknown specialization.
310         if (!isClassName && !IsCtorOrDtorName)
311           return nullptr;
312 
313         // We know from the grammar that this name refers to a type,
314         // so build a dependent node to describe the type.
315         if (WantNontrivialTypeSourceInfo)
316           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
317 
318         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
319         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
320                                        II, NameLoc);
321         return ParsedType::make(T);
322       }
323 
324       return nullptr;
325     }
326 
327     if (!LookupCtx->isDependentContext() &&
328         RequireCompleteDeclContext(*SS, LookupCtx))
329       return nullptr;
330   }
331 
332   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
333   // lookup for class-names.
334   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
335                                       LookupOrdinaryName;
336   LookupResult Result(*this, &II, NameLoc, Kind);
337   if (LookupCtx) {
338     // Perform "qualified" name lookup into the declaration context we
339     // computed, which is either the type of the base of a member access
340     // expression or the declaration context associated with a prior
341     // nested-name-specifier.
342     LookupQualifiedName(Result, LookupCtx);
343 
344     if (ObjectTypePtr && Result.empty()) {
345       // C++ [basic.lookup.classref]p3:
346       //   If the unqualified-id is ~type-name, the type-name is looked up
347       //   in the context of the entire postfix-expression. If the type T of
348       //   the object expression is of a class type C, the type-name is also
349       //   looked up in the scope of class C. At least one of the lookups shall
350       //   find a name that refers to (possibly cv-qualified) T.
351       LookupName(Result, S);
352     }
353   } else {
354     // Perform unqualified name lookup.
355     LookupName(Result, S);
356 
357     // For unqualified lookup in a class template in MSVC mode, look into
358     // dependent base classes where the primary class template is known.
359     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
360       if (ParsedType TypeInBase =
361               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
362         return TypeInBase;
363     }
364   }
365 
366   NamedDecl *IIDecl = nullptr;
367   switch (Result.getResultKind()) {
368   case LookupResult::NotFound:
369   case LookupResult::NotFoundInCurrentInstantiation:
370     if (CorrectedII) {
371       TypoCorrection Correction =
372           CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
373                       llvm::make_unique<TypeNameValidatorCCC>(
374                           true, isClassName, AllowDeducedTemplate),
375                       CTK_ErrorRecovery);
376       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
377       TemplateTy Template;
378       bool MemberOfUnknownSpecialization;
379       UnqualifiedId TemplateName;
380       TemplateName.setIdentifier(NewII, NameLoc);
381       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
382       CXXScopeSpec NewSS, *NewSSPtr = SS;
383       if (SS && NNS) {
384         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
385         NewSSPtr = &NewSS;
386       }
387       if (Correction && (NNS || NewII != &II) &&
388           // Ignore a correction to a template type as the to-be-corrected
389           // identifier is not a template (typo correction for template names
390           // is handled elsewhere).
391           !(getLangOpts().CPlusPlus && NewSSPtr &&
392             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
393                            Template, MemberOfUnknownSpecialization))) {
394         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
395                                     isClassName, HasTrailingDot, ObjectTypePtr,
396                                     IsCtorOrDtorName,
397                                     WantNontrivialTypeSourceInfo,
398                                     IsClassTemplateDeductionContext);
399         if (Ty) {
400           diagnoseTypo(Correction,
401                        PDiag(diag::err_unknown_type_or_class_name_suggest)
402                          << Result.getLookupName() << isClassName);
403           if (SS && NNS)
404             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
405           *CorrectedII = NewII;
406           return Ty;
407         }
408       }
409     }
410     // If typo correction failed or was not performed, fall through
411     LLVM_FALLTHROUGH;
412   case LookupResult::FoundOverloaded:
413   case LookupResult::FoundUnresolvedValue:
414     Result.suppressDiagnostics();
415     return nullptr;
416 
417   case LookupResult::Ambiguous:
418     // Recover from type-hiding ambiguities by hiding the type.  We'll
419     // do the lookup again when looking for an object, and we can
420     // diagnose the error then.  If we don't do this, then the error
421     // about hiding the type will be immediately followed by an error
422     // that only makes sense if the identifier was treated like a type.
423     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
424       Result.suppressDiagnostics();
425       return nullptr;
426     }
427 
428     // Look to see if we have a type anywhere in the list of results.
429     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
430          Res != ResEnd; ++Res) {
431       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
432           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
433         if (!IIDecl ||
434             (*Res)->getLocation().getRawEncoding() <
435               IIDecl->getLocation().getRawEncoding())
436           IIDecl = *Res;
437       }
438     }
439 
440     if (!IIDecl) {
441       // None of the entities we found is a type, so there is no way
442       // to even assume that the result is a type. In this case, don't
443       // complain about the ambiguity. The parser will either try to
444       // perform this lookup again (e.g., as an object name), which
445       // will produce the ambiguity, or will complain that it expected
446       // a type name.
447       Result.suppressDiagnostics();
448       return nullptr;
449     }
450 
451     // We found a type within the ambiguous lookup; diagnose the
452     // ambiguity and then return that type. This might be the right
453     // answer, or it might not be, but it suppresses any attempt to
454     // perform the name lookup again.
455     break;
456 
457   case LookupResult::Found:
458     IIDecl = Result.getFoundDecl();
459     break;
460   }
461 
462   assert(IIDecl && "Didn't find decl");
463 
464   QualType T;
465   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
466     // C++ [class.qual]p2: A lookup that would find the injected-class-name
467     // instead names the constructors of the class, except when naming a class.
468     // This is ill-formed when we're not actually forming a ctor or dtor name.
469     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
470     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
471     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
472         FoundRD->isInjectedClassName() &&
473         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
474       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
475           << &II << /*Type*/1;
476 
477     DiagnoseUseOfDecl(IIDecl, NameLoc);
478 
479     T = Context.getTypeDeclType(TD);
480     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
481   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
482     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
483     if (!HasTrailingDot)
484       T = Context.getObjCInterfaceType(IDecl);
485   } else if (AllowDeducedTemplate) {
486     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
487       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
488                                                        QualType(), false);
489   }
490 
491   if (T.isNull()) {
492     // If it's not plausibly a type, suppress diagnostics.
493     Result.suppressDiagnostics();
494     return nullptr;
495   }
496 
497   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
498   // constructor or destructor name (in such a case, the scope specifier
499   // will be attached to the enclosing Expr or Decl node).
500   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
501       !isa<ObjCInterfaceDecl>(IIDecl)) {
502     if (WantNontrivialTypeSourceInfo) {
503       // Construct a type with type-source information.
504       TypeLocBuilder Builder;
505       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
506 
507       T = getElaboratedType(ETK_None, *SS, T);
508       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
509       ElabTL.setElaboratedKeywordLoc(SourceLocation());
510       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
511       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
512     } else {
513       T = getElaboratedType(ETK_None, *SS, T);
514     }
515   }
516 
517   return ParsedType::make(T);
518 }
519 
520 // Builds a fake NNS for the given decl context.
521 static NestedNameSpecifier *
522 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
523   for (;; DC = DC->getLookupParent()) {
524     DC = DC->getPrimaryContext();
525     auto *ND = dyn_cast<NamespaceDecl>(DC);
526     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
527       return NestedNameSpecifier::Create(Context, nullptr, ND);
528     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
529       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
530                                          RD->getTypeForDecl());
531     else if (isa<TranslationUnitDecl>(DC))
532       return NestedNameSpecifier::GlobalSpecifier(Context);
533   }
534   llvm_unreachable("something isn't in TU scope?");
535 }
536 
537 /// Find the parent class with dependent bases of the innermost enclosing method
538 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
539 /// up allowing unqualified dependent type names at class-level, which MSVC
540 /// correctly rejects.
541 static const CXXRecordDecl *
542 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
543   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
544     DC = DC->getPrimaryContext();
545     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
546       if (MD->getParent()->hasAnyDependentBases())
547         return MD->getParent();
548   }
549   return nullptr;
550 }
551 
552 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
553                                           SourceLocation NameLoc,
554                                           bool IsTemplateTypeArg) {
555   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
556 
557   NestedNameSpecifier *NNS = nullptr;
558   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
559     // If we weren't able to parse a default template argument, delay lookup
560     // until instantiation time by making a non-dependent DependentTypeName. We
561     // pretend we saw a NestedNameSpecifier referring to the current scope, and
562     // lookup is retried.
563     // FIXME: This hurts our diagnostic quality, since we get errors like "no
564     // type named 'Foo' in 'current_namespace'" when the user didn't write any
565     // name specifiers.
566     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
567     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
568   } else if (const CXXRecordDecl *RD =
569                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
570     // Build a DependentNameType that will perform lookup into RD at
571     // instantiation time.
572     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
573                                       RD->getTypeForDecl());
574 
575     // Diagnose that this identifier was undeclared, and retry the lookup during
576     // template instantiation.
577     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
578                                                                       << RD;
579   } else {
580     // This is not a situation that we should recover from.
581     return ParsedType();
582   }
583 
584   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
585 
586   // Build type location information.  We synthesized the qualifier, so we have
587   // to build a fake NestedNameSpecifierLoc.
588   NestedNameSpecifierLocBuilder NNSLocBuilder;
589   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
590   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
591 
592   TypeLocBuilder Builder;
593   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
594   DepTL.setNameLoc(NameLoc);
595   DepTL.setElaboratedKeywordLoc(SourceLocation());
596   DepTL.setQualifierLoc(QualifierLoc);
597   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
598 }
599 
600 /// isTagName() - This method is called *for error recovery purposes only*
601 /// to determine if the specified name is a valid tag name ("struct foo").  If
602 /// so, this returns the TST for the tag corresponding to it (TST_enum,
603 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
604 /// cases in C where the user forgot to specify the tag.
605 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
606   // Do a tag name lookup in this scope.
607   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
608   LookupName(R, S, false);
609   R.suppressDiagnostics();
610   if (R.getResultKind() == LookupResult::Found)
611     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
612       switch (TD->getTagKind()) {
613       case TTK_Struct: return DeclSpec::TST_struct;
614       case TTK_Interface: return DeclSpec::TST_interface;
615       case TTK_Union:  return DeclSpec::TST_union;
616       case TTK_Class:  return DeclSpec::TST_class;
617       case TTK_Enum:   return DeclSpec::TST_enum;
618       }
619     }
620 
621   return DeclSpec::TST_unspecified;
622 }
623 
624 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
625 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
626 /// then downgrade the missing typename error to a warning.
627 /// This is needed for MSVC compatibility; Example:
628 /// @code
629 /// template<class T> class A {
630 /// public:
631 ///   typedef int TYPE;
632 /// };
633 /// template<class T> class B : public A<T> {
634 /// public:
635 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
636 /// };
637 /// @endcode
638 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
639   if (CurContext->isRecord()) {
640     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
641       return true;
642 
643     const Type *Ty = SS->getScopeRep()->getAsType();
644 
645     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
646     for (const auto &Base : RD->bases())
647       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
648         return true;
649     return S->isFunctionPrototypeScope();
650   }
651   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
652 }
653 
654 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
655                                    SourceLocation IILoc,
656                                    Scope *S,
657                                    CXXScopeSpec *SS,
658                                    ParsedType &SuggestedType,
659                                    bool IsTemplateName) {
660   // Don't report typename errors for editor placeholders.
661   if (II->isEditorPlaceholder())
662     return;
663   // We don't have anything to suggest (yet).
664   SuggestedType = nullptr;
665 
666   // There may have been a typo in the name of the type. Look up typo
667   // results, in case we have something that we can suggest.
668   if (TypoCorrection Corrected =
669           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
670                       llvm::make_unique<TypeNameValidatorCCC>(
671                           false, false, IsTemplateName, !IsTemplateName),
672                       CTK_ErrorRecovery)) {
673     // FIXME: Support error recovery for the template-name case.
674     bool CanRecover = !IsTemplateName;
675     if (Corrected.isKeyword()) {
676       // We corrected to a keyword.
677       diagnoseTypo(Corrected,
678                    PDiag(IsTemplateName ? diag::err_no_template_suggest
679                                         : diag::err_unknown_typename_suggest)
680                        << II);
681       II = Corrected.getCorrectionAsIdentifierInfo();
682     } else {
683       // We found a similarly-named type or interface; suggest that.
684       if (!SS || !SS->isSet()) {
685         diagnoseTypo(Corrected,
686                      PDiag(IsTemplateName ? diag::err_no_template_suggest
687                                           : diag::err_unknown_typename_suggest)
688                          << II, CanRecover);
689       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
690         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
691         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
692                                 II->getName().equals(CorrectedStr);
693         diagnoseTypo(Corrected,
694                      PDiag(IsTemplateName
695                                ? diag::err_no_member_template_suggest
696                                : diag::err_unknown_nested_typename_suggest)
697                          << II << DC << DroppedSpecifier << SS->getRange(),
698                      CanRecover);
699       } else {
700         llvm_unreachable("could not have corrected a typo here");
701       }
702 
703       if (!CanRecover)
704         return;
705 
706       CXXScopeSpec tmpSS;
707       if (Corrected.getCorrectionSpecifier())
708         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
709                           SourceRange(IILoc));
710       // FIXME: Support class template argument deduction here.
711       SuggestedType =
712           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
713                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
714                       /*IsCtorOrDtorName=*/false,
715                       /*NonTrivialTypeSourceInfo=*/true);
716     }
717     return;
718   }
719 
720   if (getLangOpts().CPlusPlus && !IsTemplateName) {
721     // See if II is a class template that the user forgot to pass arguments to.
722     UnqualifiedId Name;
723     Name.setIdentifier(II, IILoc);
724     CXXScopeSpec EmptySS;
725     TemplateTy TemplateResult;
726     bool MemberOfUnknownSpecialization;
727     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
728                        Name, nullptr, true, TemplateResult,
729                        MemberOfUnknownSpecialization) == TNK_Type_template) {
730       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
731       return;
732     }
733   }
734 
735   // FIXME: Should we move the logic that tries to recover from a missing tag
736   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
737 
738   if (!SS || (!SS->isSet() && !SS->isInvalid()))
739     Diag(IILoc, IsTemplateName ? diag::err_no_template
740                                : diag::err_unknown_typename)
741         << II;
742   else if (DeclContext *DC = computeDeclContext(*SS, false))
743     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
744                                : diag::err_typename_nested_not_found)
745         << II << DC << SS->getRange();
746   else if (isDependentScopeSpecifier(*SS)) {
747     unsigned DiagID = diag::err_typename_missing;
748     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
749       DiagID = diag::ext_typename_missing;
750 
751     Diag(SS->getRange().getBegin(), DiagID)
752       << SS->getScopeRep() << II->getName()
753       << SourceRange(SS->getRange().getBegin(), IILoc)
754       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
755     SuggestedType = ActOnTypenameType(S, SourceLocation(),
756                                       *SS, *II, IILoc).get();
757   } else {
758     assert(SS && SS->isInvalid() &&
759            "Invalid scope specifier has already been diagnosed");
760   }
761 }
762 
763 /// Determine whether the given result set contains either a type name
764 /// or
765 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
766   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
767                        NextToken.is(tok::less);
768 
769   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
770     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
771       return true;
772 
773     if (CheckTemplate && isa<TemplateDecl>(*I))
774       return true;
775   }
776 
777   return false;
778 }
779 
780 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
781                                     Scope *S, CXXScopeSpec &SS,
782                                     IdentifierInfo *&Name,
783                                     SourceLocation NameLoc) {
784   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
785   SemaRef.LookupParsedName(R, S, &SS);
786   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
787     StringRef FixItTagName;
788     switch (Tag->getTagKind()) {
789       case TTK_Class:
790         FixItTagName = "class ";
791         break;
792 
793       case TTK_Enum:
794         FixItTagName = "enum ";
795         break;
796 
797       case TTK_Struct:
798         FixItTagName = "struct ";
799         break;
800 
801       case TTK_Interface:
802         FixItTagName = "__interface ";
803         break;
804 
805       case TTK_Union:
806         FixItTagName = "union ";
807         break;
808     }
809 
810     StringRef TagName = FixItTagName.drop_back();
811     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
812       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
813       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
814 
815     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
816          I != IEnd; ++I)
817       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
818         << Name << TagName;
819 
820     // Replace lookup results with just the tag decl.
821     Result.clear(Sema::LookupTagName);
822     SemaRef.LookupParsedName(Result, S, &SS);
823     return true;
824   }
825 
826   return false;
827 }
828 
829 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
830 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
831                                   QualType T, SourceLocation NameLoc) {
832   ASTContext &Context = S.Context;
833 
834   TypeLocBuilder Builder;
835   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
836 
837   T = S.getElaboratedType(ETK_None, SS, T);
838   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
839   ElabTL.setElaboratedKeywordLoc(SourceLocation());
840   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
841   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
842 }
843 
844 Sema::NameClassification
845 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
846                    SourceLocation NameLoc, const Token &NextToken,
847                    bool IsAddressOfOperand,
848                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
849   DeclarationNameInfo NameInfo(Name, NameLoc);
850   ObjCMethodDecl *CurMethod = getCurMethodDecl();
851 
852   if (NextToken.is(tok::coloncolon)) {
853     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
854     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
855   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
856              isCurrentClassName(*Name, S, &SS)) {
857     // Per [class.qual]p2, this names the constructors of SS, not the
858     // injected-class-name. We don't have a classification for that.
859     // There's not much point caching this result, since the parser
860     // will reject it later.
861     return NameClassification::Unknown();
862   }
863 
864   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
865   LookupParsedName(Result, S, &SS, !CurMethod);
866 
867   // For unqualified lookup in a class template in MSVC mode, look into
868   // dependent base classes where the primary class template is known.
869   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
870     if (ParsedType TypeInBase =
871             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
872       return TypeInBase;
873   }
874 
875   // Perform lookup for Objective-C instance variables (including automatically
876   // synthesized instance variables), if we're in an Objective-C method.
877   // FIXME: This lookup really, really needs to be folded in to the normal
878   // unqualified lookup mechanism.
879   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
880     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
881     if (E.get() || E.isInvalid())
882       return E;
883   }
884 
885   bool SecondTry = false;
886   bool IsFilteredTemplateName = false;
887 
888 Corrected:
889   switch (Result.getResultKind()) {
890   case LookupResult::NotFound:
891     // If an unqualified-id is followed by a '(', then we have a function
892     // call.
893     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
894       // In C++, this is an ADL-only call.
895       // FIXME: Reference?
896       if (getLangOpts().CPlusPlus)
897         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
898 
899       // C90 6.3.2.2:
900       //   If the expression that precedes the parenthesized argument list in a
901       //   function call consists solely of an identifier, and if no
902       //   declaration is visible for this identifier, the identifier is
903       //   implicitly declared exactly as if, in the innermost block containing
904       //   the function call, the declaration
905       //
906       //     extern int identifier ();
907       //
908       //   appeared.
909       //
910       // We also allow this in C99 as an extension.
911       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
912         Result.addDecl(D);
913         Result.resolveKind();
914         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
915       }
916     }
917 
918     // In C, we first see whether there is a tag type by the same name, in
919     // which case it's likely that the user just forgot to write "enum",
920     // "struct", or "union".
921     if (!getLangOpts().CPlusPlus && !SecondTry &&
922         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
923       break;
924     }
925 
926     // Perform typo correction to determine if there is another name that is
927     // close to this name.
928     if (!SecondTry && CCC) {
929       SecondTry = true;
930       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
931                                                  Result.getLookupKind(), S,
932                                                  &SS, std::move(CCC),
933                                                  CTK_ErrorRecovery)) {
934         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
935         unsigned QualifiedDiag = diag::err_no_member_suggest;
936 
937         NamedDecl *FirstDecl = Corrected.getFoundDecl();
938         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
939         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
940             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
941           UnqualifiedDiag = diag::err_no_template_suggest;
942           QualifiedDiag = diag::err_no_member_template_suggest;
943         } else if (UnderlyingFirstDecl &&
944                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
945                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
946                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
947           UnqualifiedDiag = diag::err_unknown_typename_suggest;
948           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
949         }
950 
951         if (SS.isEmpty()) {
952           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
953         } else {// FIXME: is this even reachable? Test it.
954           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
955           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
956                                   Name->getName().equals(CorrectedStr);
957           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
958                                     << Name << computeDeclContext(SS, false)
959                                     << DroppedSpecifier << SS.getRange());
960         }
961 
962         // Update the name, so that the caller has the new name.
963         Name = Corrected.getCorrectionAsIdentifierInfo();
964 
965         // Typo correction corrected to a keyword.
966         if (Corrected.isKeyword())
967           return Name;
968 
969         // Also update the LookupResult...
970         // FIXME: This should probably go away at some point
971         Result.clear();
972         Result.setLookupName(Corrected.getCorrection());
973         if (FirstDecl)
974           Result.addDecl(FirstDecl);
975 
976         // If we found an Objective-C instance variable, let
977         // LookupInObjCMethod build the appropriate expression to
978         // reference the ivar.
979         // FIXME: This is a gross hack.
980         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
981           Result.clear();
982           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
983           return E;
984         }
985 
986         goto Corrected;
987       }
988     }
989 
990     // We failed to correct; just fall through and let the parser deal with it.
991     Result.suppressDiagnostics();
992     return NameClassification::Unknown();
993 
994   case LookupResult::NotFoundInCurrentInstantiation: {
995     // We performed name lookup into the current instantiation, and there were
996     // dependent bases, so we treat this result the same way as any other
997     // dependent nested-name-specifier.
998 
999     // C++ [temp.res]p2:
1000     //   A name used in a template declaration or definition and that is
1001     //   dependent on a template-parameter is assumed not to name a type
1002     //   unless the applicable name lookup finds a type name or the name is
1003     //   qualified by the keyword typename.
1004     //
1005     // FIXME: If the next token is '<', we might want to ask the parser to
1006     // perform some heroics to see if we actually have a
1007     // template-argument-list, which would indicate a missing 'template'
1008     // keyword here.
1009     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1010                                       NameInfo, IsAddressOfOperand,
1011                                       /*TemplateArgs=*/nullptr);
1012   }
1013 
1014   case LookupResult::Found:
1015   case LookupResult::FoundOverloaded:
1016   case LookupResult::FoundUnresolvedValue:
1017     break;
1018 
1019   case LookupResult::Ambiguous:
1020     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1021         hasAnyAcceptableTemplateNames(Result)) {
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 || hasAnyAcceptableTemplateNames(Result))) {
1046     // C++ [temp.names]p3:
1047     //   After name lookup (3.4) finds that a name is a template-name or that
1048     //   an operator-function-id or a literal- operator-id refers to a set of
1049     //   overloaded functions any member of which is a function template if
1050     //   this is followed by a <, the < is always taken as the delimiter of a
1051     //   template-argument-list and never as the less-than operator.
1052     if (!IsFilteredTemplateName)
1053       FilterAcceptableTemplateNames(Result);
1054 
1055     if (!Result.empty()) {
1056       bool IsFunctionTemplate;
1057       bool IsVarTemplate;
1058       TemplateName Template;
1059       if (Result.end() - Result.begin() > 1) {
1060         IsFunctionTemplate = true;
1061         Template = Context.getOverloadedTemplateName(Result.begin(),
1062                                                      Result.end());
1063       } else {
1064         TemplateDecl *TD
1065           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1066         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1067         IsVarTemplate = isa<VarTemplateDecl>(TD);
1068 
1069         if (SS.isSet() && !SS.isInvalid())
1070           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1071                                                     /*TemplateKeyword=*/false,
1072                                                       TD);
1073         else
1074           Template = TemplateName(TD);
1075       }
1076 
1077       if (IsFunctionTemplate) {
1078         // Function templates always go through overload resolution, at which
1079         // point we'll perform the various checks (e.g., accessibility) we need
1080         // to based on which function we selected.
1081         Result.suppressDiagnostics();
1082 
1083         return NameClassification::FunctionTemplate(Template);
1084       }
1085 
1086       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1087                            : NameClassification::TypeTemplate(Template);
1088     }
1089   }
1090 
1091   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1092   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1093     DiagnoseUseOfDecl(Type, NameLoc);
1094     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1095     QualType T = Context.getTypeDeclType(Type);
1096     if (SS.isNotEmpty())
1097       return buildNestedType(*this, SS, T, NameLoc);
1098     return ParsedType::make(T);
1099   }
1100 
1101   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1102   if (!Class) {
1103     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1104     if (ObjCCompatibleAliasDecl *Alias =
1105             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1106       Class = Alias->getClassInterface();
1107   }
1108 
1109   if (Class) {
1110     DiagnoseUseOfDecl(Class, NameLoc);
1111 
1112     if (NextToken.is(tok::period)) {
1113       // Interface. <something> is parsed as a property reference expression.
1114       // Just return "unknown" as a fall-through for now.
1115       Result.suppressDiagnostics();
1116       return NameClassification::Unknown();
1117     }
1118 
1119     QualType T = Context.getObjCInterfaceType(Class);
1120     return ParsedType::make(T);
1121   }
1122 
1123   // We can have a type template here if we're classifying a template argument.
1124   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1125       !isa<VarTemplateDecl>(FirstDecl))
1126     return NameClassification::TypeTemplate(
1127         TemplateName(cast<TemplateDecl>(FirstDecl)));
1128 
1129   // Check for a tag type hidden by a non-type decl in a few cases where it
1130   // seems likely a type is wanted instead of the non-type that was found.
1131   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1132   if ((NextToken.is(tok::identifier) ||
1133        (NextIsOp &&
1134         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1135       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1136     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1137     DiagnoseUseOfDecl(Type, NameLoc);
1138     QualType T = Context.getTypeDeclType(Type);
1139     if (SS.isNotEmpty())
1140       return buildNestedType(*this, SS, T, NameLoc);
1141     return ParsedType::make(T);
1142   }
1143 
1144   if (FirstDecl->isCXXClassMember())
1145     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1146                                            nullptr, S);
1147 
1148   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1149   return BuildDeclarationNameExpr(SS, Result, ADL);
1150 }
1151 
1152 Sema::TemplateNameKindForDiagnostics
1153 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1154   auto *TD = Name.getAsTemplateDecl();
1155   if (!TD)
1156     return TemplateNameKindForDiagnostics::DependentTemplate;
1157   if (isa<ClassTemplateDecl>(TD))
1158     return TemplateNameKindForDiagnostics::ClassTemplate;
1159   if (isa<FunctionTemplateDecl>(TD))
1160     return TemplateNameKindForDiagnostics::FunctionTemplate;
1161   if (isa<VarTemplateDecl>(TD))
1162     return TemplateNameKindForDiagnostics::VarTemplate;
1163   if (isa<TypeAliasTemplateDecl>(TD))
1164     return TemplateNameKindForDiagnostics::AliasTemplate;
1165   if (isa<TemplateTemplateParmDecl>(TD))
1166     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1167   return TemplateNameKindForDiagnostics::DependentTemplate;
1168 }
1169 
1170 // Determines the context to return to after temporarily entering a
1171 // context.  This depends in an unnecessarily complicated way on the
1172 // exact ordering of callbacks from the parser.
1173 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1174 
1175   // Functions defined inline within classes aren't parsed until we've
1176   // finished parsing the top-level class, so the top-level class is
1177   // the context we'll need to return to.
1178   // A Lambda call operator whose parent is a class must not be treated
1179   // as an inline member function.  A Lambda can be used legally
1180   // either as an in-class member initializer or a default argument.  These
1181   // are parsed once the class has been marked complete and so the containing
1182   // context would be the nested class (when the lambda is defined in one);
1183   // If the class is not complete, then the lambda is being used in an
1184   // ill-formed fashion (such as to specify the width of a bit-field, or
1185   // in an array-bound) - in which case we still want to return the
1186   // lexically containing DC (which could be a nested class).
1187   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1188     DC = DC->getLexicalParent();
1189 
1190     // A function not defined within a class will always return to its
1191     // lexical context.
1192     if (!isa<CXXRecordDecl>(DC))
1193       return DC;
1194 
1195     // A C++ inline method/friend is parsed *after* the topmost class
1196     // it was declared in is fully parsed ("complete");  the topmost
1197     // class is the context we need to return to.
1198     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1199       DC = RD;
1200 
1201     // Return the declaration context of the topmost class the inline method is
1202     // declared in.
1203     return DC;
1204   }
1205 
1206   return DC->getLexicalParent();
1207 }
1208 
1209 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1210   assert(getContainingDC(DC) == CurContext &&
1211       "The next DeclContext should be lexically contained in the current one.");
1212   CurContext = DC;
1213   S->setEntity(DC);
1214 }
1215 
1216 void Sema::PopDeclContext() {
1217   assert(CurContext && "DeclContext imbalance!");
1218 
1219   CurContext = getContainingDC(CurContext);
1220   assert(CurContext && "Popped translation unit!");
1221 }
1222 
1223 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1224                                                                     Decl *D) {
1225   // Unlike PushDeclContext, the context to which we return is not necessarily
1226   // the containing DC of TD, because the new context will be some pre-existing
1227   // TagDecl definition instead of a fresh one.
1228   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1229   CurContext = cast<TagDecl>(D)->getDefinition();
1230   assert(CurContext && "skipping definition of undefined tag");
1231   // Start lookups from the parent of the current context; we don't want to look
1232   // into the pre-existing complete definition.
1233   S->setEntity(CurContext->getLookupParent());
1234   return Result;
1235 }
1236 
1237 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1238   CurContext = static_cast<decltype(CurContext)>(Context);
1239 }
1240 
1241 /// EnterDeclaratorContext - Used when we must lookup names in the context
1242 /// of a declarator's nested name specifier.
1243 ///
1244 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1245   // C++0x [basic.lookup.unqual]p13:
1246   //   A name used in the definition of a static data member of class
1247   //   X (after the qualified-id of the static member) is looked up as
1248   //   if the name was used in a member function of X.
1249   // C++0x [basic.lookup.unqual]p14:
1250   //   If a variable member of a namespace is defined outside of the
1251   //   scope of its namespace then any name used in the definition of
1252   //   the variable member (after the declarator-id) is looked up as
1253   //   if the definition of the variable member occurred in its
1254   //   namespace.
1255   // Both of these imply that we should push a scope whose context
1256   // is the semantic context of the declaration.  We can't use
1257   // PushDeclContext here because that context is not necessarily
1258   // lexically contained in the current context.  Fortunately,
1259   // the containing scope should have the appropriate information.
1260 
1261   assert(!S->getEntity() && "scope already has entity");
1262 
1263 #ifndef NDEBUG
1264   Scope *Ancestor = S->getParent();
1265   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1266   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1267 #endif
1268 
1269   CurContext = DC;
1270   S->setEntity(DC);
1271 }
1272 
1273 void Sema::ExitDeclaratorContext(Scope *S) {
1274   assert(S->getEntity() == CurContext && "Context imbalance!");
1275 
1276   // Switch back to the lexical context.  The safety of this is
1277   // enforced by an assert in EnterDeclaratorContext.
1278   Scope *Ancestor = S->getParent();
1279   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1280   CurContext = Ancestor->getEntity();
1281 
1282   // We don't need to do anything with the scope, which is going to
1283   // disappear.
1284 }
1285 
1286 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1287   // We assume that the caller has already called
1288   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1289   FunctionDecl *FD = D->getAsFunction();
1290   if (!FD)
1291     return;
1292 
1293   // Same implementation as PushDeclContext, but enters the context
1294   // from the lexical parent, rather than the top-level class.
1295   assert(CurContext == FD->getLexicalParent() &&
1296     "The next DeclContext should be lexically contained in the current one.");
1297   CurContext = FD;
1298   S->setEntity(CurContext);
1299 
1300   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1301     ParmVarDecl *Param = FD->getParamDecl(P);
1302     // If the parameter has an identifier, then add it to the scope
1303     if (Param->getIdentifier()) {
1304       S->AddDecl(Param);
1305       IdResolver.AddDecl(Param);
1306     }
1307   }
1308 }
1309 
1310 void Sema::ActOnExitFunctionContext() {
1311   // Same implementation as PopDeclContext, but returns to the lexical parent,
1312   // rather than the top-level class.
1313   assert(CurContext && "DeclContext imbalance!");
1314   CurContext = CurContext->getLexicalParent();
1315   assert(CurContext && "Popped translation unit!");
1316 }
1317 
1318 /// Determine whether we allow overloading of the function
1319 /// PrevDecl with another declaration.
1320 ///
1321 /// This routine determines whether overloading is possible, not
1322 /// whether some new function is actually an overload. It will return
1323 /// true in C++ (where we can always provide overloads) or, as an
1324 /// extension, in C when the previous function is already an
1325 /// overloaded function declaration or has the "overloadable"
1326 /// attribute.
1327 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1328                                        ASTContext &Context,
1329                                        const FunctionDecl *New) {
1330   if (Context.getLangOpts().CPlusPlus)
1331     return true;
1332 
1333   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1334     return true;
1335 
1336   return Previous.getResultKind() == LookupResult::Found &&
1337          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1338           New->hasAttr<OverloadableAttr>());
1339 }
1340 
1341 /// Add this decl to the scope shadowed decl chains.
1342 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1343   // Move up the scope chain until we find the nearest enclosing
1344   // non-transparent context. The declaration will be introduced into this
1345   // scope.
1346   while (S->getEntity() && S->getEntity()->isTransparentContext())
1347     S = S->getParent();
1348 
1349   // Add scoped declarations into their context, so that they can be
1350   // found later. Declarations without a context won't be inserted
1351   // into any context.
1352   if (AddToContext)
1353     CurContext->addDecl(D);
1354 
1355   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1356   // are function-local declarations.
1357   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1358       !D->getDeclContext()->getRedeclContext()->Equals(
1359         D->getLexicalDeclContext()->getRedeclContext()) &&
1360       !D->getLexicalDeclContext()->isFunctionOrMethod())
1361     return;
1362 
1363   // Template instantiations should also not be pushed into scope.
1364   if (isa<FunctionDecl>(D) &&
1365       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1366     return;
1367 
1368   // If this replaces anything in the current scope,
1369   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1370                                IEnd = IdResolver.end();
1371   for (; I != IEnd; ++I) {
1372     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1373       S->RemoveDecl(*I);
1374       IdResolver.RemoveDecl(*I);
1375 
1376       // Should only need to replace one decl.
1377       break;
1378     }
1379   }
1380 
1381   S->AddDecl(D);
1382 
1383   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1384     // Implicitly-generated labels may end up getting generated in an order that
1385     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1386     // the label at the appropriate place in the identifier chain.
1387     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1388       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1389       if (IDC == CurContext) {
1390         if (!S->isDeclScope(*I))
1391           continue;
1392       } else if (IDC->Encloses(CurContext))
1393         break;
1394     }
1395 
1396     IdResolver.InsertDeclAfter(I, D);
1397   } else {
1398     IdResolver.AddDecl(D);
1399   }
1400 }
1401 
1402 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1403   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1404     TUScope->AddDecl(D);
1405 }
1406 
1407 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1408                          bool AllowInlineNamespace) {
1409   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1410 }
1411 
1412 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1413   DeclContext *TargetDC = DC->getPrimaryContext();
1414   do {
1415     if (DeclContext *ScopeDC = S->getEntity())
1416       if (ScopeDC->getPrimaryContext() == TargetDC)
1417         return S;
1418   } while ((S = S->getParent()));
1419 
1420   return nullptr;
1421 }
1422 
1423 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1424                                             DeclContext*,
1425                                             ASTContext&);
1426 
1427 /// Filters out lookup results that don't fall within the given scope
1428 /// as determined by isDeclInScope.
1429 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1430                                 bool ConsiderLinkage,
1431                                 bool AllowInlineNamespace) {
1432   LookupResult::Filter F = R.makeFilter();
1433   while (F.hasNext()) {
1434     NamedDecl *D = F.next();
1435 
1436     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1437       continue;
1438 
1439     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1440       continue;
1441 
1442     F.erase();
1443   }
1444 
1445   F.done();
1446 }
1447 
1448 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1449 /// have compatible owning modules.
1450 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1451   // FIXME: The Modules TS is not clear about how friend declarations are
1452   // to be treated. It's not meaningful to have different owning modules for
1453   // linkage in redeclarations of the same entity, so for now allow the
1454   // redeclaration and change the owning modules to match.
1455   if (New->getFriendObjectKind() &&
1456       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1457     New->setLocalOwningModule(Old->getOwningModule());
1458     makeMergedDefinitionVisible(New);
1459     return false;
1460   }
1461 
1462   Module *NewM = New->getOwningModule();
1463   Module *OldM = Old->getOwningModule();
1464   if (NewM == OldM)
1465     return false;
1466 
1467   // FIXME: Check proclaimed-ownership-declarations here too.
1468   bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit;
1469   bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit;
1470   if (NewIsModuleInterface || OldIsModuleInterface) {
1471     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1472     //   if a declaration of D [...] appears in the purview of a module, all
1473     //   other such declarations shall appear in the purview of the same module
1474     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1475       << New
1476       << NewIsModuleInterface
1477       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1478       << OldIsModuleInterface
1479       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1480     Diag(Old->getLocation(), diag::note_previous_declaration);
1481     New->setInvalidDecl();
1482     return true;
1483   }
1484 
1485   return false;
1486 }
1487 
1488 static bool isUsingDecl(NamedDecl *D) {
1489   return isa<UsingShadowDecl>(D) ||
1490          isa<UnresolvedUsingTypenameDecl>(D) ||
1491          isa<UnresolvedUsingValueDecl>(D);
1492 }
1493 
1494 /// Removes using shadow declarations from the lookup results.
1495 static void RemoveUsingDecls(LookupResult &R) {
1496   LookupResult::Filter F = R.makeFilter();
1497   while (F.hasNext())
1498     if (isUsingDecl(F.next()))
1499       F.erase();
1500 
1501   F.done();
1502 }
1503 
1504 /// Check for this common pattern:
1505 /// @code
1506 /// class S {
1507 ///   S(const S&); // DO NOT IMPLEMENT
1508 ///   void operator=(const S&); // DO NOT IMPLEMENT
1509 /// };
1510 /// @endcode
1511 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1512   // FIXME: Should check for private access too but access is set after we get
1513   // the decl here.
1514   if (D->doesThisDeclarationHaveABody())
1515     return false;
1516 
1517   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1518     return CD->isCopyConstructor();
1519   return D->isCopyAssignmentOperator();
1520 }
1521 
1522 // We need this to handle
1523 //
1524 // typedef struct {
1525 //   void *foo() { return 0; }
1526 // } A;
1527 //
1528 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1529 // for example. If 'A', foo will have external linkage. If we have '*A',
1530 // foo will have no linkage. Since we can't know until we get to the end
1531 // of the typedef, this function finds out if D might have non-external linkage.
1532 // Callers should verify at the end of the TU if it D has external linkage or
1533 // not.
1534 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1535   const DeclContext *DC = D->getDeclContext();
1536   while (!DC->isTranslationUnit()) {
1537     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1538       if (!RD->hasNameForLinkage())
1539         return true;
1540     }
1541     DC = DC->getParent();
1542   }
1543 
1544   return !D->isExternallyVisible();
1545 }
1546 
1547 // FIXME: This needs to be refactored; some other isInMainFile users want
1548 // these semantics.
1549 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1550   if (S.TUKind != TU_Complete)
1551     return false;
1552   return S.SourceMgr.isInMainFile(Loc);
1553 }
1554 
1555 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1556   assert(D);
1557 
1558   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1559     return false;
1560 
1561   // Ignore all entities declared within templates, and out-of-line definitions
1562   // of members of class templates.
1563   if (D->getDeclContext()->isDependentContext() ||
1564       D->getLexicalDeclContext()->isDependentContext())
1565     return false;
1566 
1567   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1568     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1569       return false;
1570     // A non-out-of-line declaration of a member specialization was implicitly
1571     // instantiated; it's the out-of-line declaration that we're interested in.
1572     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1573         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1574       return false;
1575 
1576     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1577       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1578         return false;
1579     } else {
1580       // 'static inline' functions are defined in headers; don't warn.
1581       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1582         return false;
1583     }
1584 
1585     if (FD->doesThisDeclarationHaveABody() &&
1586         Context.DeclMustBeEmitted(FD))
1587       return false;
1588   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1589     // Constants and utility variables are defined in headers with internal
1590     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1591     // like "inline".)
1592     if (!isMainFileLoc(*this, VD->getLocation()))
1593       return false;
1594 
1595     if (Context.DeclMustBeEmitted(VD))
1596       return false;
1597 
1598     if (VD->isStaticDataMember() &&
1599         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1600       return false;
1601     if (VD->isStaticDataMember() &&
1602         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1603         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1604       return false;
1605 
1606     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1607       return false;
1608   } else {
1609     return false;
1610   }
1611 
1612   // Only warn for unused decls internal to the translation unit.
1613   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1614   // for inline functions defined in the main source file, for instance.
1615   return mightHaveNonExternalLinkage(D);
1616 }
1617 
1618 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1619   if (!D)
1620     return;
1621 
1622   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1623     const FunctionDecl *First = FD->getFirstDecl();
1624     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1625       return; // First should already be in the vector.
1626   }
1627 
1628   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1629     const VarDecl *First = VD->getFirstDecl();
1630     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1631       return; // First should already be in the vector.
1632   }
1633 
1634   if (ShouldWarnIfUnusedFileScopedDecl(D))
1635     UnusedFileScopedDecls.push_back(D);
1636 }
1637 
1638 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1639   if (D->isInvalidDecl())
1640     return false;
1641 
1642   bool Referenced = false;
1643   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1644     // For a decomposition declaration, warn if none of the bindings are
1645     // referenced, instead of if the variable itself is referenced (which
1646     // it is, by the bindings' expressions).
1647     for (auto *BD : DD->bindings()) {
1648       if (BD->isReferenced()) {
1649         Referenced = true;
1650         break;
1651       }
1652     }
1653   } else if (!D->getDeclName()) {
1654     return false;
1655   } else if (D->isReferenced() || D->isUsed()) {
1656     Referenced = true;
1657   }
1658 
1659   if (Referenced || D->hasAttr<UnusedAttr>() ||
1660       D->hasAttr<ObjCPreciseLifetimeAttr>())
1661     return false;
1662 
1663   if (isa<LabelDecl>(D))
1664     return true;
1665 
1666   // Except for labels, we only care about unused decls that are local to
1667   // functions.
1668   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1669   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1670     // For dependent types, the diagnostic is deferred.
1671     WithinFunction =
1672         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1673   if (!WithinFunction)
1674     return false;
1675 
1676   if (isa<TypedefNameDecl>(D))
1677     return true;
1678 
1679   // White-list anything that isn't a local variable.
1680   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1681     return false;
1682 
1683   // Types of valid local variables should be complete, so this should succeed.
1684   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1685 
1686     // White-list anything with an __attribute__((unused)) type.
1687     const auto *Ty = VD->getType().getTypePtr();
1688 
1689     // Only look at the outermost level of typedef.
1690     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1691       if (TT->getDecl()->hasAttr<UnusedAttr>())
1692         return false;
1693     }
1694 
1695     // If we failed to complete the type for some reason, or if the type is
1696     // dependent, don't diagnose the variable.
1697     if (Ty->isIncompleteType() || Ty->isDependentType())
1698       return false;
1699 
1700     // Look at the element type to ensure that the warning behaviour is
1701     // consistent for both scalars and arrays.
1702     Ty = Ty->getBaseElementTypeUnsafe();
1703 
1704     if (const TagType *TT = Ty->getAs<TagType>()) {
1705       const TagDecl *Tag = TT->getDecl();
1706       if (Tag->hasAttr<UnusedAttr>())
1707         return false;
1708 
1709       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1710         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1711           return false;
1712 
1713         if (const Expr *Init = VD->getInit()) {
1714           if (const ExprWithCleanups *Cleanups =
1715                   dyn_cast<ExprWithCleanups>(Init))
1716             Init = Cleanups->getSubExpr();
1717           const CXXConstructExpr *Construct =
1718             dyn_cast<CXXConstructExpr>(Init);
1719           if (Construct && !Construct->isElidable()) {
1720             CXXConstructorDecl *CD = Construct->getConstructor();
1721             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1722                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1723               return false;
1724           }
1725         }
1726       }
1727     }
1728 
1729     // TODO: __attribute__((unused)) templates?
1730   }
1731 
1732   return true;
1733 }
1734 
1735 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1736                                      FixItHint &Hint) {
1737   if (isa<LabelDecl>(D)) {
1738     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1739                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1740     if (AfterColon.isInvalid())
1741       return;
1742     Hint = FixItHint::CreateRemoval(CharSourceRange::
1743                                     getCharRange(D->getLocStart(), AfterColon));
1744   }
1745 }
1746 
1747 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1748   if (D->getTypeForDecl()->isDependentType())
1749     return;
1750 
1751   for (auto *TmpD : D->decls()) {
1752     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1753       DiagnoseUnusedDecl(T);
1754     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1755       DiagnoseUnusedNestedTypedefs(R);
1756   }
1757 }
1758 
1759 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1760 /// unless they are marked attr(unused).
1761 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1762   if (!ShouldDiagnoseUnusedDecl(D))
1763     return;
1764 
1765   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1766     // typedefs can be referenced later on, so the diagnostics are emitted
1767     // at end-of-translation-unit.
1768     UnusedLocalTypedefNameCandidates.insert(TD);
1769     return;
1770   }
1771 
1772   FixItHint Hint;
1773   GenerateFixForUnusedDecl(D, Context, Hint);
1774 
1775   unsigned DiagID;
1776   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1777     DiagID = diag::warn_unused_exception_param;
1778   else if (isa<LabelDecl>(D))
1779     DiagID = diag::warn_unused_label;
1780   else
1781     DiagID = diag::warn_unused_variable;
1782 
1783   Diag(D->getLocation(), DiagID) << D << Hint;
1784 }
1785 
1786 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1787   // Verify that we have no forward references left.  If so, there was a goto
1788   // or address of a label taken, but no definition of it.  Label fwd
1789   // definitions are indicated with a null substmt which is also not a resolved
1790   // MS inline assembly label name.
1791   bool Diagnose = false;
1792   if (L->isMSAsmLabel())
1793     Diagnose = !L->isResolvedMSAsmLabel();
1794   else
1795     Diagnose = L->getStmt() == nullptr;
1796   if (Diagnose)
1797     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1798 }
1799 
1800 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1801   S->mergeNRVOIntoParent();
1802 
1803   if (S->decl_empty()) return;
1804   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1805          "Scope shouldn't contain decls!");
1806 
1807   for (auto *TmpD : S->decls()) {
1808     assert(TmpD && "This decl didn't get pushed??");
1809 
1810     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1811     NamedDecl *D = cast<NamedDecl>(TmpD);
1812 
1813     // Diagnose unused variables in this scope.
1814     if (!S->hasUnrecoverableErrorOccurred()) {
1815       DiagnoseUnusedDecl(D);
1816       if (const auto *RD = dyn_cast<RecordDecl>(D))
1817         DiagnoseUnusedNestedTypedefs(RD);
1818     }
1819 
1820     if (!D->getDeclName()) continue;
1821 
1822     // If this was a forward reference to a label, verify it was defined.
1823     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1824       CheckPoppedLabel(LD, *this);
1825 
1826     // Remove this name from our lexical scope, and warn on it if we haven't
1827     // already.
1828     IdResolver.RemoveDecl(D);
1829     auto ShadowI = ShadowingDecls.find(D);
1830     if (ShadowI != ShadowingDecls.end()) {
1831       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1832         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1833             << D << FD << FD->getParent();
1834         Diag(FD->getLocation(), diag::note_previous_declaration);
1835       }
1836       ShadowingDecls.erase(ShadowI);
1837     }
1838   }
1839 }
1840 
1841 /// Look for an Objective-C class in the translation unit.
1842 ///
1843 /// \param Id The name of the Objective-C class we're looking for. If
1844 /// typo-correction fixes this name, the Id will be updated
1845 /// to the fixed name.
1846 ///
1847 /// \param IdLoc The location of the name in the translation unit.
1848 ///
1849 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1850 /// if there is no class with the given name.
1851 ///
1852 /// \returns The declaration of the named Objective-C class, or NULL if the
1853 /// class could not be found.
1854 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1855                                               SourceLocation IdLoc,
1856                                               bool DoTypoCorrection) {
1857   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1858   // creation from this context.
1859   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1860 
1861   if (!IDecl && DoTypoCorrection) {
1862     // Perform typo correction at the given location, but only if we
1863     // find an Objective-C class name.
1864     if (TypoCorrection C = CorrectTypo(
1865             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1866             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1867             CTK_ErrorRecovery)) {
1868       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1869       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1870       Id = IDecl->getIdentifier();
1871     }
1872   }
1873   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1874   // This routine must always return a class definition, if any.
1875   if (Def && Def->getDefinition())
1876       Def = Def->getDefinition();
1877   return Def;
1878 }
1879 
1880 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1881 /// from S, where a non-field would be declared. This routine copes
1882 /// with the difference between C and C++ scoping rules in structs and
1883 /// unions. For example, the following code is well-formed in C but
1884 /// ill-formed in C++:
1885 /// @code
1886 /// struct S6 {
1887 ///   enum { BAR } e;
1888 /// };
1889 ///
1890 /// void test_S6() {
1891 ///   struct S6 a;
1892 ///   a.e = BAR;
1893 /// }
1894 /// @endcode
1895 /// For the declaration of BAR, this routine will return a different
1896 /// scope. The scope S will be the scope of the unnamed enumeration
1897 /// within S6. In C++, this routine will return the scope associated
1898 /// with S6, because the enumeration's scope is a transparent
1899 /// context but structures can contain non-field names. In C, this
1900 /// routine will return the translation unit scope, since the
1901 /// enumeration's scope is a transparent context and structures cannot
1902 /// contain non-field names.
1903 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1904   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1905          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1906          (S->isClassScope() && !getLangOpts().CPlusPlus))
1907     S = S->getParent();
1908   return S;
1909 }
1910 
1911 /// Looks up the declaration of "struct objc_super" and
1912 /// saves it for later use in building builtin declaration of
1913 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1914 /// pre-existing declaration exists no action takes place.
1915 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1916                                         IdentifierInfo *II) {
1917   if (!II->isStr("objc_msgSendSuper"))
1918     return;
1919   ASTContext &Context = ThisSema.Context;
1920 
1921   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1922                       SourceLocation(), Sema::LookupTagName);
1923   ThisSema.LookupName(Result, S);
1924   if (Result.getResultKind() == LookupResult::Found)
1925     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1926       Context.setObjCSuperType(Context.getTagDeclType(TD));
1927 }
1928 
1929 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1930   switch (Error) {
1931   case ASTContext::GE_None:
1932     return "";
1933   case ASTContext::GE_Missing_stdio:
1934     return "stdio.h";
1935   case ASTContext::GE_Missing_setjmp:
1936     return "setjmp.h";
1937   case ASTContext::GE_Missing_ucontext:
1938     return "ucontext.h";
1939   }
1940   llvm_unreachable("unhandled error kind");
1941 }
1942 
1943 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1944 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1945 /// if we're creating this built-in in anticipation of redeclaring the
1946 /// built-in.
1947 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1948                                      Scope *S, bool ForRedeclaration,
1949                                      SourceLocation Loc) {
1950   LookupPredefedObjCSuperType(*this, S, II);
1951 
1952   ASTContext::GetBuiltinTypeError Error;
1953   QualType R = Context.GetBuiltinType(ID, Error);
1954   if (Error) {
1955     if (ForRedeclaration)
1956       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1957           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1958     return nullptr;
1959   }
1960 
1961   if (!ForRedeclaration &&
1962       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1963        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1964     Diag(Loc, diag::ext_implicit_lib_function_decl)
1965         << Context.BuiltinInfo.getName(ID) << R;
1966     if (Context.BuiltinInfo.getHeaderName(ID) &&
1967         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1968       Diag(Loc, diag::note_include_header_or_declare)
1969           << Context.BuiltinInfo.getHeaderName(ID)
1970           << Context.BuiltinInfo.getName(ID);
1971   }
1972 
1973   if (R.isNull())
1974     return nullptr;
1975 
1976   DeclContext *Parent = Context.getTranslationUnitDecl();
1977   if (getLangOpts().CPlusPlus) {
1978     LinkageSpecDecl *CLinkageDecl =
1979         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1980                                 LinkageSpecDecl::lang_c, false);
1981     CLinkageDecl->setImplicit();
1982     Parent->addDecl(CLinkageDecl);
1983     Parent = CLinkageDecl;
1984   }
1985 
1986   FunctionDecl *New = FunctionDecl::Create(Context,
1987                                            Parent,
1988                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1989                                            SC_Extern,
1990                                            false,
1991                                            R->isFunctionProtoType());
1992   New->setImplicit();
1993 
1994   // Create Decl objects for each parameter, adding them to the
1995   // FunctionDecl.
1996   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1997     SmallVector<ParmVarDecl*, 16> Params;
1998     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1999       ParmVarDecl *parm =
2000           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2001                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2002                               SC_None, nullptr);
2003       parm->setScopeInfo(0, i);
2004       Params.push_back(parm);
2005     }
2006     New->setParams(Params);
2007   }
2008 
2009   AddKnownFunctionAttributes(New);
2010   RegisterLocallyScopedExternCDecl(New, S);
2011 
2012   // TUScope is the translation-unit scope to insert this function into.
2013   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2014   // relate Scopes to DeclContexts, and probably eliminate CurContext
2015   // entirely, but we're not there yet.
2016   DeclContext *SavedContext = CurContext;
2017   CurContext = Parent;
2018   PushOnScopeChains(New, TUScope);
2019   CurContext = SavedContext;
2020   return New;
2021 }
2022 
2023 /// Typedef declarations don't have linkage, but they still denote the same
2024 /// entity if their types are the same.
2025 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2026 /// isSameEntity.
2027 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2028                                                      TypedefNameDecl *Decl,
2029                                                      LookupResult &Previous) {
2030   // This is only interesting when modules are enabled.
2031   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2032     return;
2033 
2034   // Empty sets are uninteresting.
2035   if (Previous.empty())
2036     return;
2037 
2038   LookupResult::Filter Filter = Previous.makeFilter();
2039   while (Filter.hasNext()) {
2040     NamedDecl *Old = Filter.next();
2041 
2042     // Non-hidden declarations are never ignored.
2043     if (S.isVisible(Old))
2044       continue;
2045 
2046     // Declarations of the same entity are not ignored, even if they have
2047     // different linkages.
2048     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2049       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2050                                 Decl->getUnderlyingType()))
2051         continue;
2052 
2053       // If both declarations give a tag declaration a typedef name for linkage
2054       // purposes, then they declare the same entity.
2055       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2056           Decl->getAnonDeclWithTypedefName())
2057         continue;
2058     }
2059 
2060     Filter.erase();
2061   }
2062 
2063   Filter.done();
2064 }
2065 
2066 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2067   QualType OldType;
2068   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2069     OldType = OldTypedef->getUnderlyingType();
2070   else
2071     OldType = Context.getTypeDeclType(Old);
2072   QualType NewType = New->getUnderlyingType();
2073 
2074   if (NewType->isVariablyModifiedType()) {
2075     // Must not redefine a typedef with a variably-modified type.
2076     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2077     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2078       << Kind << NewType;
2079     if (Old->getLocation().isValid())
2080       notePreviousDefinition(Old, New->getLocation());
2081     New->setInvalidDecl();
2082     return true;
2083   }
2084 
2085   if (OldType != NewType &&
2086       !OldType->isDependentType() &&
2087       !NewType->isDependentType() &&
2088       !Context.hasSameType(OldType, NewType)) {
2089     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2090     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2091       << Kind << NewType << OldType;
2092     if (Old->getLocation().isValid())
2093       notePreviousDefinition(Old, New->getLocation());
2094     New->setInvalidDecl();
2095     return true;
2096   }
2097   return false;
2098 }
2099 
2100 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2101 /// same name and scope as a previous declaration 'Old'.  Figure out
2102 /// how to resolve this situation, merging decls or emitting
2103 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2104 ///
2105 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2106                                 LookupResult &OldDecls) {
2107   // If the new decl is known invalid already, don't bother doing any
2108   // merging checks.
2109   if (New->isInvalidDecl()) return;
2110 
2111   // Allow multiple definitions for ObjC built-in typedefs.
2112   // FIXME: Verify the underlying types are equivalent!
2113   if (getLangOpts().ObjC1) {
2114     const IdentifierInfo *TypeID = New->getIdentifier();
2115     switch (TypeID->getLength()) {
2116     default: break;
2117     case 2:
2118       {
2119         if (!TypeID->isStr("id"))
2120           break;
2121         QualType T = New->getUnderlyingType();
2122         if (!T->isPointerType())
2123           break;
2124         if (!T->isVoidPointerType()) {
2125           QualType PT = T->getAs<PointerType>()->getPointeeType();
2126           if (!PT->isStructureType())
2127             break;
2128         }
2129         Context.setObjCIdRedefinitionType(T);
2130         // Install the built-in type for 'id', ignoring the current definition.
2131         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2132         return;
2133       }
2134     case 5:
2135       if (!TypeID->isStr("Class"))
2136         break;
2137       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2138       // Install the built-in type for 'Class', ignoring the current definition.
2139       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2140       return;
2141     case 3:
2142       if (!TypeID->isStr("SEL"))
2143         break;
2144       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2145       // Install the built-in type for 'SEL', ignoring the current definition.
2146       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2147       return;
2148     }
2149     // Fall through - the typedef name was not a builtin type.
2150   }
2151 
2152   // Verify the old decl was also a type.
2153   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2154   if (!Old) {
2155     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2156       << New->getDeclName();
2157 
2158     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2159     if (OldD->getLocation().isValid())
2160       notePreviousDefinition(OldD, New->getLocation());
2161 
2162     return New->setInvalidDecl();
2163   }
2164 
2165   // If the old declaration is invalid, just give up here.
2166   if (Old->isInvalidDecl())
2167     return New->setInvalidDecl();
2168 
2169   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2170     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2171     auto *NewTag = New->getAnonDeclWithTypedefName();
2172     NamedDecl *Hidden = nullptr;
2173     if (OldTag && NewTag &&
2174         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2175         !hasVisibleDefinition(OldTag, &Hidden)) {
2176       // There is a definition of this tag, but it is not visible. Use it
2177       // instead of our tag.
2178       New->setTypeForDecl(OldTD->getTypeForDecl());
2179       if (OldTD->isModed())
2180         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2181                                     OldTD->getUnderlyingType());
2182       else
2183         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2184 
2185       // Make the old tag definition visible.
2186       makeMergedDefinitionVisible(Hidden);
2187 
2188       // If this was an unscoped enumeration, yank all of its enumerators
2189       // out of the scope.
2190       if (isa<EnumDecl>(NewTag)) {
2191         Scope *EnumScope = getNonFieldDeclScope(S);
2192         for (auto *D : NewTag->decls()) {
2193           auto *ED = cast<EnumConstantDecl>(D);
2194           assert(EnumScope->isDeclScope(ED));
2195           EnumScope->RemoveDecl(ED);
2196           IdResolver.RemoveDecl(ED);
2197           ED->getLexicalDeclContext()->removeDecl(ED);
2198         }
2199       }
2200     }
2201   }
2202 
2203   // If the typedef types are not identical, reject them in all languages and
2204   // with any extensions enabled.
2205   if (isIncompatibleTypedef(Old, New))
2206     return;
2207 
2208   // The types match.  Link up the redeclaration chain and merge attributes if
2209   // the old declaration was a typedef.
2210   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2211     New->setPreviousDecl(Typedef);
2212     mergeDeclAttributes(New, Old);
2213   }
2214 
2215   if (getLangOpts().MicrosoftExt)
2216     return;
2217 
2218   if (getLangOpts().CPlusPlus) {
2219     // C++ [dcl.typedef]p2:
2220     //   In a given non-class scope, a typedef specifier can be used to
2221     //   redefine the name of any type declared in that scope to refer
2222     //   to the type to which it already refers.
2223     if (!isa<CXXRecordDecl>(CurContext))
2224       return;
2225 
2226     // C++0x [dcl.typedef]p4:
2227     //   In a given class scope, a typedef specifier can be used to redefine
2228     //   any class-name declared in that scope that is not also a typedef-name
2229     //   to refer to the type to which it already refers.
2230     //
2231     // This wording came in via DR424, which was a correction to the
2232     // wording in DR56, which accidentally banned code like:
2233     //
2234     //   struct S {
2235     //     typedef struct A { } A;
2236     //   };
2237     //
2238     // in the C++03 standard. We implement the C++0x semantics, which
2239     // allow the above but disallow
2240     //
2241     //   struct S {
2242     //     typedef int I;
2243     //     typedef int I;
2244     //   };
2245     //
2246     // since that was the intent of DR56.
2247     if (!isa<TypedefNameDecl>(Old))
2248       return;
2249 
2250     Diag(New->getLocation(), diag::err_redefinition)
2251       << New->getDeclName();
2252     notePreviousDefinition(Old, New->getLocation());
2253     return New->setInvalidDecl();
2254   }
2255 
2256   // Modules always permit redefinition of typedefs, as does C11.
2257   if (getLangOpts().Modules || getLangOpts().C11)
2258     return;
2259 
2260   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2261   // is normally mapped to an error, but can be controlled with
2262   // -Wtypedef-redefinition.  If either the original or the redefinition is
2263   // in a system header, don't emit this for compatibility with GCC.
2264   if (getDiagnostics().getSuppressSystemWarnings() &&
2265       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2266       (Old->isImplicit() ||
2267        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2268        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2269     return;
2270 
2271   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2272     << New->getDeclName();
2273   notePreviousDefinition(Old, New->getLocation());
2274 }
2275 
2276 /// DeclhasAttr - returns true if decl Declaration already has the target
2277 /// attribute.
2278 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2279   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2280   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2281   for (const auto *i : D->attrs())
2282     if (i->getKind() == A->getKind()) {
2283       if (Ann) {
2284         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2285           return true;
2286         continue;
2287       }
2288       // FIXME: Don't hardcode this check
2289       if (OA && isa<OwnershipAttr>(i))
2290         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2291       return true;
2292     }
2293 
2294   return false;
2295 }
2296 
2297 static bool isAttributeTargetADefinition(Decl *D) {
2298   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2299     return VD->isThisDeclarationADefinition();
2300   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2301     return TD->isCompleteDefinition() || TD->isBeingDefined();
2302   return true;
2303 }
2304 
2305 /// Merge alignment attributes from \p Old to \p New, taking into account the
2306 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2307 ///
2308 /// \return \c true if any attributes were added to \p New.
2309 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2310   // Look for alignas attributes on Old, and pick out whichever attribute
2311   // specifies the strictest alignment requirement.
2312   AlignedAttr *OldAlignasAttr = nullptr;
2313   AlignedAttr *OldStrictestAlignAttr = nullptr;
2314   unsigned OldAlign = 0;
2315   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2316     // FIXME: We have no way of representing inherited dependent alignments
2317     // in a case like:
2318     //   template<int A, int B> struct alignas(A) X;
2319     //   template<int A, int B> struct alignas(B) X {};
2320     // For now, we just ignore any alignas attributes which are not on the
2321     // definition in such a case.
2322     if (I->isAlignmentDependent())
2323       return false;
2324 
2325     if (I->isAlignas())
2326       OldAlignasAttr = I;
2327 
2328     unsigned Align = I->getAlignment(S.Context);
2329     if (Align > OldAlign) {
2330       OldAlign = Align;
2331       OldStrictestAlignAttr = I;
2332     }
2333   }
2334 
2335   // Look for alignas attributes on New.
2336   AlignedAttr *NewAlignasAttr = nullptr;
2337   unsigned NewAlign = 0;
2338   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2339     if (I->isAlignmentDependent())
2340       return false;
2341 
2342     if (I->isAlignas())
2343       NewAlignasAttr = I;
2344 
2345     unsigned Align = I->getAlignment(S.Context);
2346     if (Align > NewAlign)
2347       NewAlign = Align;
2348   }
2349 
2350   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2351     // Both declarations have 'alignas' attributes. We require them to match.
2352     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2353     // fall short. (If two declarations both have alignas, they must both match
2354     // every definition, and so must match each other if there is a definition.)
2355 
2356     // If either declaration only contains 'alignas(0)' specifiers, then it
2357     // specifies the natural alignment for the type.
2358     if (OldAlign == 0 || NewAlign == 0) {
2359       QualType Ty;
2360       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2361         Ty = VD->getType();
2362       else
2363         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2364 
2365       if (OldAlign == 0)
2366         OldAlign = S.Context.getTypeAlign(Ty);
2367       if (NewAlign == 0)
2368         NewAlign = S.Context.getTypeAlign(Ty);
2369     }
2370 
2371     if (OldAlign != NewAlign) {
2372       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2373         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2374         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2375       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2376     }
2377   }
2378 
2379   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2380     // C++11 [dcl.align]p6:
2381     //   if any declaration of an entity has an alignment-specifier,
2382     //   every defining declaration of that entity shall specify an
2383     //   equivalent alignment.
2384     // C11 6.7.5/7:
2385     //   If the definition of an object does not have an alignment
2386     //   specifier, any other declaration of that object shall also
2387     //   have no alignment specifier.
2388     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2389       << OldAlignasAttr;
2390     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2391       << OldAlignasAttr;
2392   }
2393 
2394   bool AnyAdded = false;
2395 
2396   // Ensure we have an attribute representing the strictest alignment.
2397   if (OldAlign > NewAlign) {
2398     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2399     Clone->setInherited(true);
2400     New->addAttr(Clone);
2401     AnyAdded = true;
2402   }
2403 
2404   // Ensure we have an alignas attribute if the old declaration had one.
2405   if (OldAlignasAttr && !NewAlignasAttr &&
2406       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2407     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2408     Clone->setInherited(true);
2409     New->addAttr(Clone);
2410     AnyAdded = true;
2411   }
2412 
2413   return AnyAdded;
2414 }
2415 
2416 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2417                                const InheritableAttr *Attr,
2418                                Sema::AvailabilityMergeKind AMK) {
2419   // This function copies an attribute Attr from a previous declaration to the
2420   // new declaration D if the new declaration doesn't itself have that attribute
2421   // yet or if that attribute allows duplicates.
2422   // If you're adding a new attribute that requires logic different from
2423   // "use explicit attribute on decl if present, else use attribute from
2424   // previous decl", for example if the attribute needs to be consistent
2425   // between redeclarations, you need to call a custom merge function here.
2426   InheritableAttr *NewAttr = nullptr;
2427   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2428   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2429     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2430                                       AA->isImplicit(), AA->getIntroduced(),
2431                                       AA->getDeprecated(),
2432                                       AA->getObsoleted(), AA->getUnavailable(),
2433                                       AA->getMessage(), AA->getStrict(),
2434                                       AA->getReplacement(), AMK,
2435                                       AttrSpellingListIndex);
2436   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2437     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2438                                     AttrSpellingListIndex);
2439   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2440     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2441                                         AttrSpellingListIndex);
2442   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2443     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2444                                    AttrSpellingListIndex);
2445   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2446     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2447                                    AttrSpellingListIndex);
2448   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2449     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2450                                 FA->getFormatIdx(), FA->getFirstArg(),
2451                                 AttrSpellingListIndex);
2452   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2453     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2454                                  AttrSpellingListIndex);
2455   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2456     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2457                                        AttrSpellingListIndex,
2458                                        IA->getSemanticSpelling());
2459   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2460     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2461                                       &S.Context.Idents.get(AA->getSpelling()),
2462                                       AttrSpellingListIndex);
2463   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2464            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2465             isa<CUDAGlobalAttr>(Attr))) {
2466     // CUDA target attributes are part of function signature for
2467     // overloading purposes and must not be merged.
2468     return false;
2469   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2470     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2471   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2472     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2473   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2474     NewAttr = S.mergeInternalLinkageAttr(
2475         D, InternalLinkageA->getRange(),
2476         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2477         AttrSpellingListIndex);
2478   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2479     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2480                                 &S.Context.Idents.get(CommonA->getSpelling()),
2481                                 AttrSpellingListIndex);
2482   else if (isa<AlignedAttr>(Attr))
2483     // AlignedAttrs are handled separately, because we need to handle all
2484     // such attributes on a declaration at the same time.
2485     NewAttr = nullptr;
2486   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2487            (AMK == Sema::AMK_Override ||
2488             AMK == Sema::AMK_ProtocolImplementation))
2489     NewAttr = nullptr;
2490   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2491     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2492                               UA->getGuid());
2493   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2494     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2495 
2496   if (NewAttr) {
2497     NewAttr->setInherited(true);
2498     D->addAttr(NewAttr);
2499     if (isa<MSInheritanceAttr>(NewAttr))
2500       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2501     return true;
2502   }
2503 
2504   return false;
2505 }
2506 
2507 static const NamedDecl *getDefinition(const Decl *D) {
2508   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2509     return TD->getDefinition();
2510   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2511     const VarDecl *Def = VD->getDefinition();
2512     if (Def)
2513       return Def;
2514     return VD->getActingDefinition();
2515   }
2516   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2517     return FD->getDefinition();
2518   return nullptr;
2519 }
2520 
2521 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2522   for (const auto *Attribute : D->attrs())
2523     if (Attribute->getKind() == Kind)
2524       return true;
2525   return false;
2526 }
2527 
2528 /// checkNewAttributesAfterDef - If we already have a definition, check that
2529 /// there are no new attributes in this declaration.
2530 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2531   if (!New->hasAttrs())
2532     return;
2533 
2534   const NamedDecl *Def = getDefinition(Old);
2535   if (!Def || Def == New)
2536     return;
2537 
2538   AttrVec &NewAttributes = New->getAttrs();
2539   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2540     const Attr *NewAttribute = NewAttributes[I];
2541 
2542     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2543       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2544         Sema::SkipBodyInfo SkipBody;
2545         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2546 
2547         // If we're skipping this definition, drop the "alias" attribute.
2548         if (SkipBody.ShouldSkip) {
2549           NewAttributes.erase(NewAttributes.begin() + I);
2550           --E;
2551           continue;
2552         }
2553       } else {
2554         VarDecl *VD = cast<VarDecl>(New);
2555         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2556                                 VarDecl::TentativeDefinition
2557                             ? diag::err_alias_after_tentative
2558                             : diag::err_redefinition;
2559         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2560         if (Diag == diag::err_redefinition)
2561           S.notePreviousDefinition(Def, VD->getLocation());
2562         else
2563           S.Diag(Def->getLocation(), diag::note_previous_definition);
2564         VD->setInvalidDecl();
2565       }
2566       ++I;
2567       continue;
2568     }
2569 
2570     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2571       // Tentative definitions are only interesting for the alias check above.
2572       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2573         ++I;
2574         continue;
2575       }
2576     }
2577 
2578     if (hasAttribute(Def, NewAttribute->getKind())) {
2579       ++I;
2580       continue; // regular attr merging will take care of validating this.
2581     }
2582 
2583     if (isa<C11NoReturnAttr>(NewAttribute)) {
2584       // C's _Noreturn is allowed to be added to a function after it is defined.
2585       ++I;
2586       continue;
2587     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2588       if (AA->isAlignas()) {
2589         // C++11 [dcl.align]p6:
2590         //   if any declaration of an entity has an alignment-specifier,
2591         //   every defining declaration of that entity shall specify an
2592         //   equivalent alignment.
2593         // C11 6.7.5/7:
2594         //   If the definition of an object does not have an alignment
2595         //   specifier, any other declaration of that object shall also
2596         //   have no alignment specifier.
2597         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2598           << AA;
2599         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2600           << AA;
2601         NewAttributes.erase(NewAttributes.begin() + I);
2602         --E;
2603         continue;
2604       }
2605     }
2606 
2607     S.Diag(NewAttribute->getLocation(),
2608            diag::warn_attribute_precede_definition);
2609     S.Diag(Def->getLocation(), diag::note_previous_definition);
2610     NewAttributes.erase(NewAttributes.begin() + I);
2611     --E;
2612   }
2613 }
2614 
2615 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2616 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2617                                AvailabilityMergeKind AMK) {
2618   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2619     UsedAttr *NewAttr = OldAttr->clone(Context);
2620     NewAttr->setInherited(true);
2621     New->addAttr(NewAttr);
2622   }
2623 
2624   if (!Old->hasAttrs() && !New->hasAttrs())
2625     return;
2626 
2627   // Attributes declared post-definition are currently ignored.
2628   checkNewAttributesAfterDef(*this, New, Old);
2629 
2630   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2631     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2632       if (OldA->getLabel() != NewA->getLabel()) {
2633         // This redeclaration changes __asm__ label.
2634         Diag(New->getLocation(), diag::err_different_asm_label);
2635         Diag(OldA->getLocation(), diag::note_previous_declaration);
2636       }
2637     } else if (Old->isUsed()) {
2638       // This redeclaration adds an __asm__ label to a declaration that has
2639       // already been ODR-used.
2640       Diag(New->getLocation(), diag::err_late_asm_label_name)
2641         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2642     }
2643   }
2644 
2645   // Re-declaration cannot add abi_tag's.
2646   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2647     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2648       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2649         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2650                       NewTag) == OldAbiTagAttr->tags_end()) {
2651           Diag(NewAbiTagAttr->getLocation(),
2652                diag::err_new_abi_tag_on_redeclaration)
2653               << NewTag;
2654           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2655         }
2656       }
2657     } else {
2658       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2659       Diag(Old->getLocation(), diag::note_previous_declaration);
2660     }
2661   }
2662 
2663   // This redeclaration adds a section attribute.
2664   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2665     if (auto *VD = dyn_cast<VarDecl>(New)) {
2666       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2667         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2668         Diag(Old->getLocation(), diag::note_previous_declaration);
2669       }
2670     }
2671   }
2672 
2673   if (!Old->hasAttrs())
2674     return;
2675 
2676   bool foundAny = New->hasAttrs();
2677 
2678   // Ensure that any moving of objects within the allocated map is done before
2679   // we process them.
2680   if (!foundAny) New->setAttrs(AttrVec());
2681 
2682   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2683     // Ignore deprecated/unavailable/availability attributes if requested.
2684     AvailabilityMergeKind LocalAMK = AMK_None;
2685     if (isa<DeprecatedAttr>(I) ||
2686         isa<UnavailableAttr>(I) ||
2687         isa<AvailabilityAttr>(I)) {
2688       switch (AMK) {
2689       case AMK_None:
2690         continue;
2691 
2692       case AMK_Redeclaration:
2693       case AMK_Override:
2694       case AMK_ProtocolImplementation:
2695         LocalAMK = AMK;
2696         break;
2697       }
2698     }
2699 
2700     // Already handled.
2701     if (isa<UsedAttr>(I))
2702       continue;
2703 
2704     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2705       foundAny = true;
2706   }
2707 
2708   if (mergeAlignedAttrs(*this, New, Old))
2709     foundAny = true;
2710 
2711   if (!foundAny) New->dropAttrs();
2712 }
2713 
2714 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2715 /// to the new one.
2716 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2717                                      const ParmVarDecl *oldDecl,
2718                                      Sema &S) {
2719   // C++11 [dcl.attr.depend]p2:
2720   //   The first declaration of a function shall specify the
2721   //   carries_dependency attribute for its declarator-id if any declaration
2722   //   of the function specifies the carries_dependency attribute.
2723   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2724   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2725     S.Diag(CDA->getLocation(),
2726            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2727     // Find the first declaration of the parameter.
2728     // FIXME: Should we build redeclaration chains for function parameters?
2729     const FunctionDecl *FirstFD =
2730       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2731     const ParmVarDecl *FirstVD =
2732       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2733     S.Diag(FirstVD->getLocation(),
2734            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2735   }
2736 
2737   if (!oldDecl->hasAttrs())
2738     return;
2739 
2740   bool foundAny = newDecl->hasAttrs();
2741 
2742   // Ensure that any moving of objects within the allocated map is
2743   // done before we process them.
2744   if (!foundAny) newDecl->setAttrs(AttrVec());
2745 
2746   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2747     if (!DeclHasAttr(newDecl, I)) {
2748       InheritableAttr *newAttr =
2749         cast<InheritableParamAttr>(I->clone(S.Context));
2750       newAttr->setInherited(true);
2751       newDecl->addAttr(newAttr);
2752       foundAny = true;
2753     }
2754   }
2755 
2756   if (!foundAny) newDecl->dropAttrs();
2757 }
2758 
2759 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2760                                 const ParmVarDecl *OldParam,
2761                                 Sema &S) {
2762   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2763     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2764       if (*Oldnullability != *Newnullability) {
2765         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2766           << DiagNullabilityKind(
2767                *Newnullability,
2768                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2769                 != 0))
2770           << DiagNullabilityKind(
2771                *Oldnullability,
2772                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2773                 != 0));
2774         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2775       }
2776     } else {
2777       QualType NewT = NewParam->getType();
2778       NewT = S.Context.getAttributedType(
2779                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2780                          NewT, NewT);
2781       NewParam->setType(NewT);
2782     }
2783   }
2784 }
2785 
2786 namespace {
2787 
2788 /// Used in MergeFunctionDecl to keep track of function parameters in
2789 /// C.
2790 struct GNUCompatibleParamWarning {
2791   ParmVarDecl *OldParm;
2792   ParmVarDecl *NewParm;
2793   QualType PromotedType;
2794 };
2795 
2796 } // end anonymous namespace
2797 
2798 /// getSpecialMember - get the special member enum for a method.
2799 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2800   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2801     if (Ctor->isDefaultConstructor())
2802       return Sema::CXXDefaultConstructor;
2803 
2804     if (Ctor->isCopyConstructor())
2805       return Sema::CXXCopyConstructor;
2806 
2807     if (Ctor->isMoveConstructor())
2808       return Sema::CXXMoveConstructor;
2809   } else if (isa<CXXDestructorDecl>(MD)) {
2810     return Sema::CXXDestructor;
2811   } else if (MD->isCopyAssignmentOperator()) {
2812     return Sema::CXXCopyAssignment;
2813   } else if (MD->isMoveAssignmentOperator()) {
2814     return Sema::CXXMoveAssignment;
2815   }
2816 
2817   return Sema::CXXInvalid;
2818 }
2819 
2820 // Determine whether the previous declaration was a definition, implicit
2821 // declaration, or a declaration.
2822 template <typename T>
2823 static std::pair<diag::kind, SourceLocation>
2824 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2825   diag::kind PrevDiag;
2826   SourceLocation OldLocation = Old->getLocation();
2827   if (Old->isThisDeclarationADefinition())
2828     PrevDiag = diag::note_previous_definition;
2829   else if (Old->isImplicit()) {
2830     PrevDiag = diag::note_previous_implicit_declaration;
2831     if (OldLocation.isInvalid())
2832       OldLocation = New->getLocation();
2833   } else
2834     PrevDiag = diag::note_previous_declaration;
2835   return std::make_pair(PrevDiag, OldLocation);
2836 }
2837 
2838 /// canRedefineFunction - checks if a function can be redefined. Currently,
2839 /// only extern inline functions can be redefined, and even then only in
2840 /// GNU89 mode.
2841 static bool canRedefineFunction(const FunctionDecl *FD,
2842                                 const LangOptions& LangOpts) {
2843   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2844           !LangOpts.CPlusPlus &&
2845           FD->isInlineSpecified() &&
2846           FD->getStorageClass() == SC_Extern);
2847 }
2848 
2849 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2850   const AttributedType *AT = T->getAs<AttributedType>();
2851   while (AT && !AT->isCallingConv())
2852     AT = AT->getModifiedType()->getAs<AttributedType>();
2853   return AT;
2854 }
2855 
2856 template <typename T>
2857 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2858   const DeclContext *DC = Old->getDeclContext();
2859   if (DC->isRecord())
2860     return false;
2861 
2862   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2863   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2864     return true;
2865   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2866     return true;
2867   return false;
2868 }
2869 
2870 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2871 static bool isExternC(VarTemplateDecl *) { return false; }
2872 
2873 /// Check whether a redeclaration of an entity introduced by a
2874 /// using-declaration is valid, given that we know it's not an overload
2875 /// (nor a hidden tag declaration).
2876 template<typename ExpectedDecl>
2877 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2878                                    ExpectedDecl *New) {
2879   // C++11 [basic.scope.declarative]p4:
2880   //   Given a set of declarations in a single declarative region, each of
2881   //   which specifies the same unqualified name,
2882   //   -- they shall all refer to the same entity, or all refer to functions
2883   //      and function templates; or
2884   //   -- exactly one declaration shall declare a class name or enumeration
2885   //      name that is not a typedef name and the other declarations shall all
2886   //      refer to the same variable or enumerator, or all refer to functions
2887   //      and function templates; in this case the class name or enumeration
2888   //      name is hidden (3.3.10).
2889 
2890   // C++11 [namespace.udecl]p14:
2891   //   If a function declaration in namespace scope or block scope has the
2892   //   same name and the same parameter-type-list as a function introduced
2893   //   by a using-declaration, and the declarations do not declare the same
2894   //   function, the program is ill-formed.
2895 
2896   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2897   if (Old &&
2898       !Old->getDeclContext()->getRedeclContext()->Equals(
2899           New->getDeclContext()->getRedeclContext()) &&
2900       !(isExternC(Old) && isExternC(New)))
2901     Old = nullptr;
2902 
2903   if (!Old) {
2904     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2905     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2906     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2907     return true;
2908   }
2909   return false;
2910 }
2911 
2912 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2913                                             const FunctionDecl *B) {
2914   assert(A->getNumParams() == B->getNumParams());
2915 
2916   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2917     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2918     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2919     if (AttrA == AttrB)
2920       return true;
2921     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2922   };
2923 
2924   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2925 }
2926 
2927 /// If necessary, adjust the semantic declaration context for a qualified
2928 /// declaration to name the correct inline namespace within the qualifier.
2929 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
2930                                                DeclaratorDecl *OldD) {
2931   // The only case where we need to update the DeclContext is when
2932   // redeclaration lookup for a qualified name finds a declaration
2933   // in an inline namespace within the context named by the qualifier:
2934   //
2935   //   inline namespace N { int f(); }
2936   //   int ::f(); // Sema DC needs adjusting from :: to N::.
2937   //
2938   // For unqualified declarations, the semantic context *can* change
2939   // along the redeclaration chain (for local extern declarations,
2940   // extern "C" declarations, and friend declarations in particular).
2941   if (!NewD->getQualifier())
2942     return;
2943 
2944   // NewD is probably already in the right context.
2945   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
2946   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
2947   if (NamedDC->Equals(SemaDC))
2948     return;
2949 
2950   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
2951           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
2952          "unexpected context for redeclaration");
2953 
2954   auto *LexDC = NewD->getLexicalDeclContext();
2955   auto FixSemaDC = [=](NamedDecl *D) {
2956     if (!D)
2957       return;
2958     D->setDeclContext(SemaDC);
2959     D->setLexicalDeclContext(LexDC);
2960   };
2961 
2962   FixSemaDC(NewD);
2963   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
2964     FixSemaDC(FD->getDescribedFunctionTemplate());
2965   else if (auto *VD = dyn_cast<VarDecl>(NewD))
2966     FixSemaDC(VD->getDescribedVarTemplate());
2967 }
2968 
2969 /// MergeFunctionDecl - We just parsed a function 'New' from
2970 /// declarator D which has the same name and scope as a previous
2971 /// declaration 'Old'.  Figure out how to resolve this situation,
2972 /// merging decls or emitting diagnostics as appropriate.
2973 ///
2974 /// In C++, New and Old must be declarations that are not
2975 /// overloaded. Use IsOverload to determine whether New and Old are
2976 /// overloaded, and to select the Old declaration that New should be
2977 /// merged with.
2978 ///
2979 /// Returns true if there was an error, false otherwise.
2980 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2981                              Scope *S, bool MergeTypeWithOld) {
2982   // Verify the old decl was also a function.
2983   FunctionDecl *Old = OldD->getAsFunction();
2984   if (!Old) {
2985     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2986       if (New->getFriendObjectKind()) {
2987         Diag(New->getLocation(), diag::err_using_decl_friend);
2988         Diag(Shadow->getTargetDecl()->getLocation(),
2989              diag::note_using_decl_target);
2990         Diag(Shadow->getUsingDecl()->getLocation(),
2991              diag::note_using_decl) << 0;
2992         return true;
2993       }
2994 
2995       // Check whether the two declarations might declare the same function.
2996       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2997         return true;
2998       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2999     } else {
3000       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3001         << New->getDeclName();
3002       notePreviousDefinition(OldD, New->getLocation());
3003       return true;
3004     }
3005   }
3006 
3007   // If the old declaration is invalid, just give up here.
3008   if (Old->isInvalidDecl())
3009     return true;
3010 
3011   // Disallow redeclaration of some builtins.
3012   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3013     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3014     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3015         << Old << Old->getType();
3016     return true;
3017   }
3018 
3019   diag::kind PrevDiag;
3020   SourceLocation OldLocation;
3021   std::tie(PrevDiag, OldLocation) =
3022       getNoteDiagForInvalidRedeclaration(Old, New);
3023 
3024   // Don't complain about this if we're in GNU89 mode and the old function
3025   // is an extern inline function.
3026   // Don't complain about specializations. They are not supposed to have
3027   // storage classes.
3028   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3029       New->getStorageClass() == SC_Static &&
3030       Old->hasExternalFormalLinkage() &&
3031       !New->getTemplateSpecializationInfo() &&
3032       !canRedefineFunction(Old, getLangOpts())) {
3033     if (getLangOpts().MicrosoftExt) {
3034       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3035       Diag(OldLocation, PrevDiag);
3036     } else {
3037       Diag(New->getLocation(), diag::err_static_non_static) << New;
3038       Diag(OldLocation, PrevDiag);
3039       return true;
3040     }
3041   }
3042 
3043   if (New->hasAttr<InternalLinkageAttr>() &&
3044       !Old->hasAttr<InternalLinkageAttr>()) {
3045     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3046         << New->getDeclName();
3047     notePreviousDefinition(Old, New->getLocation());
3048     New->dropAttr<InternalLinkageAttr>();
3049   }
3050 
3051   if (CheckRedeclarationModuleOwnership(New, Old))
3052     return true;
3053 
3054   if (!getLangOpts().CPlusPlus) {
3055     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3056     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3057       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3058         << New << OldOvl;
3059 
3060       // Try our best to find a decl that actually has the overloadable
3061       // attribute for the note. In most cases (e.g. programs with only one
3062       // broken declaration/definition), this won't matter.
3063       //
3064       // FIXME: We could do this if we juggled some extra state in
3065       // OverloadableAttr, rather than just removing it.
3066       const Decl *DiagOld = Old;
3067       if (OldOvl) {
3068         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3069           const auto *A = D->getAttr<OverloadableAttr>();
3070           return A && !A->isImplicit();
3071         });
3072         // If we've implicitly added *all* of the overloadable attrs to this
3073         // chain, emitting a "previous redecl" note is pointless.
3074         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3075       }
3076 
3077       if (DiagOld)
3078         Diag(DiagOld->getLocation(),
3079              diag::note_attribute_overloadable_prev_overload)
3080           << OldOvl;
3081 
3082       if (OldOvl)
3083         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3084       else
3085         New->dropAttr<OverloadableAttr>();
3086     }
3087   }
3088 
3089   // If a function is first declared with a calling convention, but is later
3090   // declared or defined without one, all following decls assume the calling
3091   // convention of the first.
3092   //
3093   // It's OK if a function is first declared without a calling convention,
3094   // but is later declared or defined with the default calling convention.
3095   //
3096   // To test if either decl has an explicit calling convention, we look for
3097   // AttributedType sugar nodes on the type as written.  If they are missing or
3098   // were canonicalized away, we assume the calling convention was implicit.
3099   //
3100   // Note also that we DO NOT return at this point, because we still have
3101   // other tests to run.
3102   QualType OldQType = Context.getCanonicalType(Old->getType());
3103   QualType NewQType = Context.getCanonicalType(New->getType());
3104   const FunctionType *OldType = cast<FunctionType>(OldQType);
3105   const FunctionType *NewType = cast<FunctionType>(NewQType);
3106   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3107   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3108   bool RequiresAdjustment = false;
3109 
3110   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3111     FunctionDecl *First = Old->getFirstDecl();
3112     const FunctionType *FT =
3113         First->getType().getCanonicalType()->castAs<FunctionType>();
3114     FunctionType::ExtInfo FI = FT->getExtInfo();
3115     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3116     if (!NewCCExplicit) {
3117       // Inherit the CC from the previous declaration if it was specified
3118       // there but not here.
3119       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3120       RequiresAdjustment = true;
3121     } else {
3122       // Calling conventions aren't compatible, so complain.
3123       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3124       Diag(New->getLocation(), diag::err_cconv_change)
3125         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3126         << !FirstCCExplicit
3127         << (!FirstCCExplicit ? "" :
3128             FunctionType::getNameForCallConv(FI.getCC()));
3129 
3130       // Put the note on the first decl, since it is the one that matters.
3131       Diag(First->getLocation(), diag::note_previous_declaration);
3132       return true;
3133     }
3134   }
3135 
3136   // FIXME: diagnose the other way around?
3137   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3138     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3139     RequiresAdjustment = true;
3140   }
3141 
3142   // Merge regparm attribute.
3143   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3144       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3145     if (NewTypeInfo.getHasRegParm()) {
3146       Diag(New->getLocation(), diag::err_regparm_mismatch)
3147         << NewType->getRegParmType()
3148         << OldType->getRegParmType();
3149       Diag(OldLocation, diag::note_previous_declaration);
3150       return true;
3151     }
3152 
3153     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3154     RequiresAdjustment = true;
3155   }
3156 
3157   // Merge ns_returns_retained attribute.
3158   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3159     if (NewTypeInfo.getProducesResult()) {
3160       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3161           << "'ns_returns_retained'";
3162       Diag(OldLocation, diag::note_previous_declaration);
3163       return true;
3164     }
3165 
3166     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3167     RequiresAdjustment = true;
3168   }
3169 
3170   if (OldTypeInfo.getNoCallerSavedRegs() !=
3171       NewTypeInfo.getNoCallerSavedRegs()) {
3172     if (NewTypeInfo.getNoCallerSavedRegs()) {
3173       AnyX86NoCallerSavedRegistersAttr *Attr =
3174         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3175       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3176       Diag(OldLocation, diag::note_previous_declaration);
3177       return true;
3178     }
3179 
3180     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3181     RequiresAdjustment = true;
3182   }
3183 
3184   if (RequiresAdjustment) {
3185     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3186     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3187     New->setType(QualType(AdjustedType, 0));
3188     NewQType = Context.getCanonicalType(New->getType());
3189     NewType = cast<FunctionType>(NewQType);
3190   }
3191 
3192   // If this redeclaration makes the function inline, we may need to add it to
3193   // UndefinedButUsed.
3194   if (!Old->isInlined() && New->isInlined() &&
3195       !New->hasAttr<GNUInlineAttr>() &&
3196       !getLangOpts().GNUInline &&
3197       Old->isUsed(false) &&
3198       !Old->isDefined() && !New->isThisDeclarationADefinition())
3199     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3200                                            SourceLocation()));
3201 
3202   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3203   // about it.
3204   if (New->hasAttr<GNUInlineAttr>() &&
3205       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3206     UndefinedButUsed.erase(Old->getCanonicalDecl());
3207   }
3208 
3209   // If pass_object_size params don't match up perfectly, this isn't a valid
3210   // redeclaration.
3211   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3212       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3213     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3214         << New->getDeclName();
3215     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3216     return true;
3217   }
3218 
3219   if (getLangOpts().CPlusPlus) {
3220     // C++1z [over.load]p2
3221     //   Certain function declarations cannot be overloaded:
3222     //     -- Function declarations that differ only in the return type,
3223     //        the exception specification, or both cannot be overloaded.
3224 
3225     // Check the exception specifications match. This may recompute the type of
3226     // both Old and New if it resolved exception specifications, so grab the
3227     // types again after this. Because this updates the type, we do this before
3228     // any of the other checks below, which may update the "de facto" NewQType
3229     // but do not necessarily update the type of New.
3230     if (CheckEquivalentExceptionSpec(Old, New))
3231       return true;
3232     OldQType = Context.getCanonicalType(Old->getType());
3233     NewQType = Context.getCanonicalType(New->getType());
3234 
3235     // Go back to the type source info to compare the declared return types,
3236     // per C++1y [dcl.type.auto]p13:
3237     //   Redeclarations or specializations of a function or function template
3238     //   with a declared return type that uses a placeholder type shall also
3239     //   use that placeholder, not a deduced type.
3240     QualType OldDeclaredReturnType =
3241         (Old->getTypeSourceInfo()
3242              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3243              : OldType)->getReturnType();
3244     QualType NewDeclaredReturnType =
3245         (New->getTypeSourceInfo()
3246              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3247              : NewType)->getReturnType();
3248     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3249         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3250           New->isLocalExternDecl())) {
3251       QualType ResQT;
3252       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3253           OldDeclaredReturnType->isObjCObjectPointerType())
3254         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3255       if (ResQT.isNull()) {
3256         if (New->isCXXClassMember() && New->isOutOfLine())
3257           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3258               << New << New->getReturnTypeSourceRange();
3259         else
3260           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3261               << New->getReturnTypeSourceRange();
3262         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3263                                     << Old->getReturnTypeSourceRange();
3264         return true;
3265       }
3266       else
3267         NewQType = ResQT;
3268     }
3269 
3270     QualType OldReturnType = OldType->getReturnType();
3271     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3272     if (OldReturnType != NewReturnType) {
3273       // If this function has a deduced return type and has already been
3274       // defined, copy the deduced value from the old declaration.
3275       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3276       if (OldAT && OldAT->isDeduced()) {
3277         New->setType(
3278             SubstAutoType(New->getType(),
3279                           OldAT->isDependentType() ? Context.DependentTy
3280                                                    : OldAT->getDeducedType()));
3281         NewQType = Context.getCanonicalType(
3282             SubstAutoType(NewQType,
3283                           OldAT->isDependentType() ? Context.DependentTy
3284                                                    : OldAT->getDeducedType()));
3285       }
3286     }
3287 
3288     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3289     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3290     if (OldMethod && NewMethod) {
3291       // Preserve triviality.
3292       NewMethod->setTrivial(OldMethod->isTrivial());
3293 
3294       // MSVC allows explicit template specialization at class scope:
3295       // 2 CXXMethodDecls referring to the same function will be injected.
3296       // We don't want a redeclaration error.
3297       bool IsClassScopeExplicitSpecialization =
3298                               OldMethod->isFunctionTemplateSpecialization() &&
3299                               NewMethod->isFunctionTemplateSpecialization();
3300       bool isFriend = NewMethod->getFriendObjectKind();
3301 
3302       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3303           !IsClassScopeExplicitSpecialization) {
3304         //    -- Member function declarations with the same name and the
3305         //       same parameter types cannot be overloaded if any of them
3306         //       is a static member function declaration.
3307         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3308           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3309           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3310           return true;
3311         }
3312 
3313         // C++ [class.mem]p1:
3314         //   [...] A member shall not be declared twice in the
3315         //   member-specification, except that a nested class or member
3316         //   class template can be declared and then later defined.
3317         if (!inTemplateInstantiation()) {
3318           unsigned NewDiag;
3319           if (isa<CXXConstructorDecl>(OldMethod))
3320             NewDiag = diag::err_constructor_redeclared;
3321           else if (isa<CXXDestructorDecl>(NewMethod))
3322             NewDiag = diag::err_destructor_redeclared;
3323           else if (isa<CXXConversionDecl>(NewMethod))
3324             NewDiag = diag::err_conv_function_redeclared;
3325           else
3326             NewDiag = diag::err_member_redeclared;
3327 
3328           Diag(New->getLocation(), NewDiag);
3329         } else {
3330           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3331             << New << New->getType();
3332         }
3333         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3334         return true;
3335 
3336       // Complain if this is an explicit declaration of a special
3337       // member that was initially declared implicitly.
3338       //
3339       // As an exception, it's okay to befriend such methods in order
3340       // to permit the implicit constructor/destructor/operator calls.
3341       } else if (OldMethod->isImplicit()) {
3342         if (isFriend) {
3343           NewMethod->setImplicit();
3344         } else {
3345           Diag(NewMethod->getLocation(),
3346                diag::err_definition_of_implicitly_declared_member)
3347             << New << getSpecialMember(OldMethod);
3348           return true;
3349         }
3350       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3351         Diag(NewMethod->getLocation(),
3352              diag::err_definition_of_explicitly_defaulted_member)
3353           << getSpecialMember(OldMethod);
3354         return true;
3355       }
3356     }
3357 
3358     // C++11 [dcl.attr.noreturn]p1:
3359     //   The first declaration of a function shall specify the noreturn
3360     //   attribute if any declaration of that function specifies the noreturn
3361     //   attribute.
3362     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3363     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3364       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3365       Diag(Old->getFirstDecl()->getLocation(),
3366            diag::note_noreturn_missing_first_decl);
3367     }
3368 
3369     // C++11 [dcl.attr.depend]p2:
3370     //   The first declaration of a function shall specify the
3371     //   carries_dependency attribute for its declarator-id if any declaration
3372     //   of the function specifies the carries_dependency attribute.
3373     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3374     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3375       Diag(CDA->getLocation(),
3376            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3377       Diag(Old->getFirstDecl()->getLocation(),
3378            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3379     }
3380 
3381     // (C++98 8.3.5p3):
3382     //   All declarations for a function shall agree exactly in both the
3383     //   return type and the parameter-type-list.
3384     // We also want to respect all the extended bits except noreturn.
3385 
3386     // noreturn should now match unless the old type info didn't have it.
3387     QualType OldQTypeForComparison = OldQType;
3388     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3389       auto *OldType = OldQType->castAs<FunctionProtoType>();
3390       const FunctionType *OldTypeForComparison
3391         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3392       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3393       assert(OldQTypeForComparison.isCanonical());
3394     }
3395 
3396     if (haveIncompatibleLanguageLinkages(Old, New)) {
3397       // As a special case, retain the language linkage from previous
3398       // declarations of a friend function as an extension.
3399       //
3400       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3401       // and is useful because there's otherwise no way to specify language
3402       // linkage within class scope.
3403       //
3404       // Check cautiously as the friend object kind isn't yet complete.
3405       if (New->getFriendObjectKind() != Decl::FOK_None) {
3406         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3407         Diag(OldLocation, PrevDiag);
3408       } else {
3409         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3410         Diag(OldLocation, PrevDiag);
3411         return true;
3412       }
3413     }
3414 
3415     if (OldQTypeForComparison == NewQType)
3416       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3417 
3418     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3419         New->isLocalExternDecl()) {
3420       // It's OK if we couldn't merge types for a local function declaraton
3421       // if either the old or new type is dependent. We'll merge the types
3422       // when we instantiate the function.
3423       return false;
3424     }
3425 
3426     // Fall through for conflicting redeclarations and redefinitions.
3427   }
3428 
3429   // C: Function types need to be compatible, not identical. This handles
3430   // duplicate function decls like "void f(int); void f(enum X);" properly.
3431   if (!getLangOpts().CPlusPlus &&
3432       Context.typesAreCompatible(OldQType, NewQType)) {
3433     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3434     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3435     const FunctionProtoType *OldProto = nullptr;
3436     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3437         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3438       // The old declaration provided a function prototype, but the
3439       // new declaration does not. Merge in the prototype.
3440       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3441       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3442       NewQType =
3443           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3444                                   OldProto->getExtProtoInfo());
3445       New->setType(NewQType);
3446       New->setHasInheritedPrototype();
3447 
3448       // Synthesize parameters with the same types.
3449       SmallVector<ParmVarDecl*, 16> Params;
3450       for (const auto &ParamType : OldProto->param_types()) {
3451         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3452                                                  SourceLocation(), nullptr,
3453                                                  ParamType, /*TInfo=*/nullptr,
3454                                                  SC_None, nullptr);
3455         Param->setScopeInfo(0, Params.size());
3456         Param->setImplicit();
3457         Params.push_back(Param);
3458       }
3459 
3460       New->setParams(Params);
3461     }
3462 
3463     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3464   }
3465 
3466   // GNU C permits a K&R definition to follow a prototype declaration
3467   // if the declared types of the parameters in the K&R definition
3468   // match the types in the prototype declaration, even when the
3469   // promoted types of the parameters from the K&R definition differ
3470   // from the types in the prototype. GCC then keeps the types from
3471   // the prototype.
3472   //
3473   // If a variadic prototype is followed by a non-variadic K&R definition,
3474   // the K&R definition becomes variadic.  This is sort of an edge case, but
3475   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3476   // C99 6.9.1p8.
3477   if (!getLangOpts().CPlusPlus &&
3478       Old->hasPrototype() && !New->hasPrototype() &&
3479       New->getType()->getAs<FunctionProtoType>() &&
3480       Old->getNumParams() == New->getNumParams()) {
3481     SmallVector<QualType, 16> ArgTypes;
3482     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3483     const FunctionProtoType *OldProto
3484       = Old->getType()->getAs<FunctionProtoType>();
3485     const FunctionProtoType *NewProto
3486       = New->getType()->getAs<FunctionProtoType>();
3487 
3488     // Determine whether this is the GNU C extension.
3489     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3490                                                NewProto->getReturnType());
3491     bool LooseCompatible = !MergedReturn.isNull();
3492     for (unsigned Idx = 0, End = Old->getNumParams();
3493          LooseCompatible && Idx != End; ++Idx) {
3494       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3495       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3496       if (Context.typesAreCompatible(OldParm->getType(),
3497                                      NewProto->getParamType(Idx))) {
3498         ArgTypes.push_back(NewParm->getType());
3499       } else if (Context.typesAreCompatible(OldParm->getType(),
3500                                             NewParm->getType(),
3501                                             /*CompareUnqualified=*/true)) {
3502         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3503                                            NewProto->getParamType(Idx) };
3504         Warnings.push_back(Warn);
3505         ArgTypes.push_back(NewParm->getType());
3506       } else
3507         LooseCompatible = false;
3508     }
3509 
3510     if (LooseCompatible) {
3511       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3512         Diag(Warnings[Warn].NewParm->getLocation(),
3513              diag::ext_param_promoted_not_compatible_with_prototype)
3514           << Warnings[Warn].PromotedType
3515           << Warnings[Warn].OldParm->getType();
3516         if (Warnings[Warn].OldParm->getLocation().isValid())
3517           Diag(Warnings[Warn].OldParm->getLocation(),
3518                diag::note_previous_declaration);
3519       }
3520 
3521       if (MergeTypeWithOld)
3522         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3523                                              OldProto->getExtProtoInfo()));
3524       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3525     }
3526 
3527     // Fall through to diagnose conflicting types.
3528   }
3529 
3530   // A function that has already been declared has been redeclared or
3531   // defined with a different type; show an appropriate diagnostic.
3532 
3533   // If the previous declaration was an implicitly-generated builtin
3534   // declaration, then at the very least we should use a specialized note.
3535   unsigned BuiltinID;
3536   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3537     // If it's actually a library-defined builtin function like 'malloc'
3538     // or 'printf', just warn about the incompatible redeclaration.
3539     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3540       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3541       Diag(OldLocation, diag::note_previous_builtin_declaration)
3542         << Old << Old->getType();
3543 
3544       // If this is a global redeclaration, just forget hereafter
3545       // about the "builtin-ness" of the function.
3546       //
3547       // Doing this for local extern declarations is problematic.  If
3548       // the builtin declaration remains visible, a second invalid
3549       // local declaration will produce a hard error; if it doesn't
3550       // remain visible, a single bogus local redeclaration (which is
3551       // actually only a warning) could break all the downstream code.
3552       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3553         New->getIdentifier()->revertBuiltin();
3554 
3555       return false;
3556     }
3557 
3558     PrevDiag = diag::note_previous_builtin_declaration;
3559   }
3560 
3561   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3562   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3563   return true;
3564 }
3565 
3566 /// Completes the merge of two function declarations that are
3567 /// known to be compatible.
3568 ///
3569 /// This routine handles the merging of attributes and other
3570 /// properties of function declarations from the old declaration to
3571 /// the new declaration, once we know that New is in fact a
3572 /// redeclaration of Old.
3573 ///
3574 /// \returns false
3575 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3576                                         Scope *S, bool MergeTypeWithOld) {
3577   // Merge the attributes
3578   mergeDeclAttributes(New, Old);
3579 
3580   // Merge "pure" flag.
3581   if (Old->isPure())
3582     New->setPure();
3583 
3584   // Merge "used" flag.
3585   if (Old->getMostRecentDecl()->isUsed(false))
3586     New->setIsUsed();
3587 
3588   // Merge attributes from the parameters.  These can mismatch with K&R
3589   // declarations.
3590   if (New->getNumParams() == Old->getNumParams())
3591       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3592         ParmVarDecl *NewParam = New->getParamDecl(i);
3593         ParmVarDecl *OldParam = Old->getParamDecl(i);
3594         mergeParamDeclAttributes(NewParam, OldParam, *this);
3595         mergeParamDeclTypes(NewParam, OldParam, *this);
3596       }
3597 
3598   if (getLangOpts().CPlusPlus)
3599     return MergeCXXFunctionDecl(New, Old, S);
3600 
3601   // Merge the function types so the we get the composite types for the return
3602   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3603   // was visible.
3604   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3605   if (!Merged.isNull() && MergeTypeWithOld)
3606     New->setType(Merged);
3607 
3608   return false;
3609 }
3610 
3611 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3612                                 ObjCMethodDecl *oldMethod) {
3613   // Merge the attributes, including deprecated/unavailable
3614   AvailabilityMergeKind MergeKind =
3615     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3616       ? AMK_ProtocolImplementation
3617       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3618                                                        : AMK_Override;
3619 
3620   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3621 
3622   // Merge attributes from the parameters.
3623   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3624                                        oe = oldMethod->param_end();
3625   for (ObjCMethodDecl::param_iterator
3626          ni = newMethod->param_begin(), ne = newMethod->param_end();
3627        ni != ne && oi != oe; ++ni, ++oi)
3628     mergeParamDeclAttributes(*ni, *oi, *this);
3629 
3630   CheckObjCMethodOverride(newMethod, oldMethod);
3631 }
3632 
3633 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3634   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3635 
3636   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3637          ? diag::err_redefinition_different_type
3638          : diag::err_redeclaration_different_type)
3639     << New->getDeclName() << New->getType() << Old->getType();
3640 
3641   diag::kind PrevDiag;
3642   SourceLocation OldLocation;
3643   std::tie(PrevDiag, OldLocation)
3644     = getNoteDiagForInvalidRedeclaration(Old, New);
3645   S.Diag(OldLocation, PrevDiag);
3646   New->setInvalidDecl();
3647 }
3648 
3649 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3650 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3651 /// emitting diagnostics as appropriate.
3652 ///
3653 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3654 /// to here in AddInitializerToDecl. We can't check them before the initializer
3655 /// is attached.
3656 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3657                              bool MergeTypeWithOld) {
3658   if (New->isInvalidDecl() || Old->isInvalidDecl())
3659     return;
3660 
3661   QualType MergedT;
3662   if (getLangOpts().CPlusPlus) {
3663     if (New->getType()->isUndeducedType()) {
3664       // We don't know what the new type is until the initializer is attached.
3665       return;
3666     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3667       // These could still be something that needs exception specs checked.
3668       return MergeVarDeclExceptionSpecs(New, Old);
3669     }
3670     // C++ [basic.link]p10:
3671     //   [...] the types specified by all declarations referring to a given
3672     //   object or function shall be identical, except that declarations for an
3673     //   array object can specify array types that differ by the presence or
3674     //   absence of a major array bound (8.3.4).
3675     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3676       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3677       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3678 
3679       // We are merging a variable declaration New into Old. If it has an array
3680       // bound, and that bound differs from Old's bound, we should diagnose the
3681       // mismatch.
3682       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3683         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3684              PrevVD = PrevVD->getPreviousDecl()) {
3685           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3686           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3687             continue;
3688 
3689           if (!Context.hasSameType(NewArray, PrevVDTy))
3690             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3691         }
3692       }
3693 
3694       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3695         if (Context.hasSameType(OldArray->getElementType(),
3696                                 NewArray->getElementType()))
3697           MergedT = New->getType();
3698       }
3699       // FIXME: Check visibility. New is hidden but has a complete type. If New
3700       // has no array bound, it should not inherit one from Old, if Old is not
3701       // visible.
3702       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3703         if (Context.hasSameType(OldArray->getElementType(),
3704                                 NewArray->getElementType()))
3705           MergedT = Old->getType();
3706       }
3707     }
3708     else if (New->getType()->isObjCObjectPointerType() &&
3709                Old->getType()->isObjCObjectPointerType()) {
3710       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3711                                               Old->getType());
3712     }
3713   } else {
3714     // C 6.2.7p2:
3715     //   All declarations that refer to the same object or function shall have
3716     //   compatible type.
3717     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3718   }
3719   if (MergedT.isNull()) {
3720     // It's OK if we couldn't merge types if either type is dependent, for a
3721     // block-scope variable. In other cases (static data members of class
3722     // templates, variable templates, ...), we require the types to be
3723     // equivalent.
3724     // FIXME: The C++ standard doesn't say anything about this.
3725     if ((New->getType()->isDependentType() ||
3726          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3727       // If the old type was dependent, we can't merge with it, so the new type
3728       // becomes dependent for now. We'll reproduce the original type when we
3729       // instantiate the TypeSourceInfo for the variable.
3730       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3731         New->setType(Context.DependentTy);
3732       return;
3733     }
3734     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3735   }
3736 
3737   // Don't actually update the type on the new declaration if the old
3738   // declaration was an extern declaration in a different scope.
3739   if (MergeTypeWithOld)
3740     New->setType(MergedT);
3741 }
3742 
3743 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3744                                   LookupResult &Previous) {
3745   // C11 6.2.7p4:
3746   //   For an identifier with internal or external linkage declared
3747   //   in a scope in which a prior declaration of that identifier is
3748   //   visible, if the prior declaration specifies internal or
3749   //   external linkage, the type of the identifier at the later
3750   //   declaration becomes the composite type.
3751   //
3752   // If the variable isn't visible, we do not merge with its type.
3753   if (Previous.isShadowed())
3754     return false;
3755 
3756   if (S.getLangOpts().CPlusPlus) {
3757     // C++11 [dcl.array]p3:
3758     //   If there is a preceding declaration of the entity in the same
3759     //   scope in which the bound was specified, an omitted array bound
3760     //   is taken to be the same as in that earlier declaration.
3761     return NewVD->isPreviousDeclInSameBlockScope() ||
3762            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3763             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3764   } else {
3765     // If the old declaration was function-local, don't merge with its
3766     // type unless we're in the same function.
3767     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3768            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3769   }
3770 }
3771 
3772 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3773 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3774 /// situation, merging decls or emitting diagnostics as appropriate.
3775 ///
3776 /// Tentative definition rules (C99 6.9.2p2) are checked by
3777 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3778 /// definitions here, since the initializer hasn't been attached.
3779 ///
3780 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3781   // If the new decl is already invalid, don't do any other checking.
3782   if (New->isInvalidDecl())
3783     return;
3784 
3785   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3786     return;
3787 
3788   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3789 
3790   // Verify the old decl was also a variable or variable template.
3791   VarDecl *Old = nullptr;
3792   VarTemplateDecl *OldTemplate = nullptr;
3793   if (Previous.isSingleResult()) {
3794     if (NewTemplate) {
3795       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3796       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3797 
3798       if (auto *Shadow =
3799               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3800         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3801           return New->setInvalidDecl();
3802     } else {
3803       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3804 
3805       if (auto *Shadow =
3806               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3807         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3808           return New->setInvalidDecl();
3809     }
3810   }
3811   if (!Old) {
3812     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3813         << New->getDeclName();
3814     notePreviousDefinition(Previous.getRepresentativeDecl(),
3815                            New->getLocation());
3816     return New->setInvalidDecl();
3817   }
3818 
3819   // Ensure the template parameters are compatible.
3820   if (NewTemplate &&
3821       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3822                                       OldTemplate->getTemplateParameters(),
3823                                       /*Complain=*/true, TPL_TemplateMatch))
3824     return New->setInvalidDecl();
3825 
3826   // C++ [class.mem]p1:
3827   //   A member shall not be declared twice in the member-specification [...]
3828   //
3829   // Here, we need only consider static data members.
3830   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3831     Diag(New->getLocation(), diag::err_duplicate_member)
3832       << New->getIdentifier();
3833     Diag(Old->getLocation(), diag::note_previous_declaration);
3834     New->setInvalidDecl();
3835   }
3836 
3837   mergeDeclAttributes(New, Old);
3838   // Warn if an already-declared variable is made a weak_import in a subsequent
3839   // declaration
3840   if (New->hasAttr<WeakImportAttr>() &&
3841       Old->getStorageClass() == SC_None &&
3842       !Old->hasAttr<WeakImportAttr>()) {
3843     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3844     notePreviousDefinition(Old, New->getLocation());
3845     // Remove weak_import attribute on new declaration.
3846     New->dropAttr<WeakImportAttr>();
3847   }
3848 
3849   if (New->hasAttr<InternalLinkageAttr>() &&
3850       !Old->hasAttr<InternalLinkageAttr>()) {
3851     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3852         << New->getDeclName();
3853     notePreviousDefinition(Old, New->getLocation());
3854     New->dropAttr<InternalLinkageAttr>();
3855   }
3856 
3857   // Merge the types.
3858   VarDecl *MostRecent = Old->getMostRecentDecl();
3859   if (MostRecent != Old) {
3860     MergeVarDeclTypes(New, MostRecent,
3861                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3862     if (New->isInvalidDecl())
3863       return;
3864   }
3865 
3866   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3867   if (New->isInvalidDecl())
3868     return;
3869 
3870   diag::kind PrevDiag;
3871   SourceLocation OldLocation;
3872   std::tie(PrevDiag, OldLocation) =
3873       getNoteDiagForInvalidRedeclaration(Old, New);
3874 
3875   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3876   if (New->getStorageClass() == SC_Static &&
3877       !New->isStaticDataMember() &&
3878       Old->hasExternalFormalLinkage()) {
3879     if (getLangOpts().MicrosoftExt) {
3880       Diag(New->getLocation(), diag::ext_static_non_static)
3881           << New->getDeclName();
3882       Diag(OldLocation, PrevDiag);
3883     } else {
3884       Diag(New->getLocation(), diag::err_static_non_static)
3885           << New->getDeclName();
3886       Diag(OldLocation, PrevDiag);
3887       return New->setInvalidDecl();
3888     }
3889   }
3890   // C99 6.2.2p4:
3891   //   For an identifier declared with the storage-class specifier
3892   //   extern in a scope in which a prior declaration of that
3893   //   identifier is visible,23) if the prior declaration specifies
3894   //   internal or external linkage, the linkage of the identifier at
3895   //   the later declaration is the same as the linkage specified at
3896   //   the prior declaration. If no prior declaration is visible, or
3897   //   if the prior declaration specifies no linkage, then the
3898   //   identifier has external linkage.
3899   if (New->hasExternalStorage() && Old->hasLinkage())
3900     /* Okay */;
3901   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3902            !New->isStaticDataMember() &&
3903            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3904     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3905     Diag(OldLocation, PrevDiag);
3906     return New->setInvalidDecl();
3907   }
3908 
3909   // Check if extern is followed by non-extern and vice-versa.
3910   if (New->hasExternalStorage() &&
3911       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3912     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3913     Diag(OldLocation, PrevDiag);
3914     return New->setInvalidDecl();
3915   }
3916   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3917       !New->hasExternalStorage()) {
3918     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3919     Diag(OldLocation, PrevDiag);
3920     return New->setInvalidDecl();
3921   }
3922 
3923   if (CheckRedeclarationModuleOwnership(New, Old))
3924     return;
3925 
3926   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3927 
3928   // FIXME: The test for external storage here seems wrong? We still
3929   // need to check for mismatches.
3930   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3931       // Don't complain about out-of-line definitions of static members.
3932       !(Old->getLexicalDeclContext()->isRecord() &&
3933         !New->getLexicalDeclContext()->isRecord())) {
3934     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3935     Diag(OldLocation, PrevDiag);
3936     return New->setInvalidDecl();
3937   }
3938 
3939   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3940     if (VarDecl *Def = Old->getDefinition()) {
3941       // C++1z [dcl.fcn.spec]p4:
3942       //   If the definition of a variable appears in a translation unit before
3943       //   its first declaration as inline, the program is ill-formed.
3944       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3945       Diag(Def->getLocation(), diag::note_previous_definition);
3946     }
3947   }
3948 
3949   // If this redeclaration makes the variable inline, we may need to add it to
3950   // UndefinedButUsed.
3951   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3952       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3953     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3954                                            SourceLocation()));
3955 
3956   if (New->getTLSKind() != Old->getTLSKind()) {
3957     if (!Old->getTLSKind()) {
3958       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3959       Diag(OldLocation, PrevDiag);
3960     } else if (!New->getTLSKind()) {
3961       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3962       Diag(OldLocation, PrevDiag);
3963     } else {
3964       // Do not allow redeclaration to change the variable between requiring
3965       // static and dynamic initialization.
3966       // FIXME: GCC allows this, but uses the TLS keyword on the first
3967       // declaration to determine the kind. Do we need to be compatible here?
3968       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3969         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3970       Diag(OldLocation, PrevDiag);
3971     }
3972   }
3973 
3974   // C++ doesn't have tentative definitions, so go right ahead and check here.
3975   if (getLangOpts().CPlusPlus &&
3976       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3977     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3978         Old->getCanonicalDecl()->isConstexpr()) {
3979       // This definition won't be a definition any more once it's been merged.
3980       Diag(New->getLocation(),
3981            diag::warn_deprecated_redundant_constexpr_static_def);
3982     } else if (VarDecl *Def = Old->getDefinition()) {
3983       if (checkVarDeclRedefinition(Def, New))
3984         return;
3985     }
3986   }
3987 
3988   if (haveIncompatibleLanguageLinkages(Old, New)) {
3989     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3990     Diag(OldLocation, PrevDiag);
3991     New->setInvalidDecl();
3992     return;
3993   }
3994 
3995   // Merge "used" flag.
3996   if (Old->getMostRecentDecl()->isUsed(false))
3997     New->setIsUsed();
3998 
3999   // Keep a chain of previous declarations.
4000   New->setPreviousDecl(Old);
4001   if (NewTemplate)
4002     NewTemplate->setPreviousDecl(OldTemplate);
4003   adjustDeclContextForDeclaratorDecl(New, Old);
4004 
4005   // Inherit access appropriately.
4006   New->setAccess(Old->getAccess());
4007   if (NewTemplate)
4008     NewTemplate->setAccess(New->getAccess());
4009 
4010   if (Old->isInline())
4011     New->setImplicitlyInline();
4012 }
4013 
4014 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4015   SourceManager &SrcMgr = getSourceManager();
4016   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4017   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4018   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4019   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4020   auto &HSI = PP.getHeaderSearchInfo();
4021   StringRef HdrFilename =
4022       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4023 
4024   auto noteFromModuleOrInclude = [&](Module *Mod,
4025                                      SourceLocation IncLoc) -> bool {
4026     // Redefinition errors with modules are common with non modular mapped
4027     // headers, example: a non-modular header H in module A that also gets
4028     // included directly in a TU. Pointing twice to the same header/definition
4029     // is confusing, try to get better diagnostics when modules is on.
4030     if (IncLoc.isValid()) {
4031       if (Mod) {
4032         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4033             << HdrFilename.str() << Mod->getFullModuleName();
4034         if (!Mod->DefinitionLoc.isInvalid())
4035           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4036               << Mod->getFullModuleName();
4037       } else {
4038         Diag(IncLoc, diag::note_redefinition_include_same_file)
4039             << HdrFilename.str();
4040       }
4041       return true;
4042     }
4043 
4044     return false;
4045   };
4046 
4047   // Is it the same file and same offset? Provide more information on why
4048   // this leads to a redefinition error.
4049   bool EmittedDiag = false;
4050   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4051     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4052     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4053     EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4054     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4055 
4056     // If the header has no guards, emit a note suggesting one.
4057     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4058       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4059 
4060     if (EmittedDiag)
4061       return;
4062   }
4063 
4064   // Redefinition coming from different files or couldn't do better above.
4065   if (Old->getLocation().isValid())
4066     Diag(Old->getLocation(), diag::note_previous_definition);
4067 }
4068 
4069 /// We've just determined that \p Old and \p New both appear to be definitions
4070 /// of the same variable. Either diagnose or fix the problem.
4071 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4072   if (!hasVisibleDefinition(Old) &&
4073       (New->getFormalLinkage() == InternalLinkage ||
4074        New->isInline() ||
4075        New->getDescribedVarTemplate() ||
4076        New->getNumTemplateParameterLists() ||
4077        New->getDeclContext()->isDependentContext())) {
4078     // The previous definition is hidden, and multiple definitions are
4079     // permitted (in separate TUs). Demote this to a declaration.
4080     New->demoteThisDefinitionToDeclaration();
4081 
4082     // Make the canonical definition visible.
4083     if (auto *OldTD = Old->getDescribedVarTemplate())
4084       makeMergedDefinitionVisible(OldTD);
4085     makeMergedDefinitionVisible(Old);
4086     return false;
4087   } else {
4088     Diag(New->getLocation(), diag::err_redefinition) << New;
4089     notePreviousDefinition(Old, New->getLocation());
4090     New->setInvalidDecl();
4091     return true;
4092   }
4093 }
4094 
4095 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4096 /// no declarator (e.g. "struct foo;") is parsed.
4097 Decl *
4098 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4099                                  RecordDecl *&AnonRecord) {
4100   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4101                                     AnonRecord);
4102 }
4103 
4104 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4105 // disambiguate entities defined in different scopes.
4106 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4107 // compatibility.
4108 // We will pick our mangling number depending on which version of MSVC is being
4109 // targeted.
4110 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4111   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4112              ? S->getMSCurManglingNumber()
4113              : S->getMSLastManglingNumber();
4114 }
4115 
4116 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4117   if (!Context.getLangOpts().CPlusPlus)
4118     return;
4119 
4120   if (isa<CXXRecordDecl>(Tag->getParent())) {
4121     // If this tag is the direct child of a class, number it if
4122     // it is anonymous.
4123     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4124       return;
4125     MangleNumberingContext &MCtx =
4126         Context.getManglingNumberContext(Tag->getParent());
4127     Context.setManglingNumber(
4128         Tag, MCtx.getManglingNumber(
4129                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4130     return;
4131   }
4132 
4133   // If this tag isn't a direct child of a class, number it if it is local.
4134   Decl *ManglingContextDecl;
4135   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4136           Tag->getDeclContext(), ManglingContextDecl)) {
4137     Context.setManglingNumber(
4138         Tag, MCtx->getManglingNumber(
4139                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4140   }
4141 }
4142 
4143 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4144                                         TypedefNameDecl *NewTD) {
4145   if (TagFromDeclSpec->isInvalidDecl())
4146     return;
4147 
4148   // Do nothing if the tag already has a name for linkage purposes.
4149   if (TagFromDeclSpec->hasNameForLinkage())
4150     return;
4151 
4152   // A well-formed anonymous tag must always be a TUK_Definition.
4153   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4154 
4155   // The type must match the tag exactly;  no qualifiers allowed.
4156   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4157                            Context.getTagDeclType(TagFromDeclSpec))) {
4158     if (getLangOpts().CPlusPlus)
4159       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4160     return;
4161   }
4162 
4163   // If we've already computed linkage for the anonymous tag, then
4164   // adding a typedef name for the anonymous decl can change that
4165   // linkage, which might be a serious problem.  Diagnose this as
4166   // unsupported and ignore the typedef name.  TODO: we should
4167   // pursue this as a language defect and establish a formal rule
4168   // for how to handle it.
4169   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4170     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4171 
4172     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4173     tagLoc = getLocForEndOfToken(tagLoc);
4174 
4175     llvm::SmallString<40> textToInsert;
4176     textToInsert += ' ';
4177     textToInsert += NewTD->getIdentifier()->getName();
4178     Diag(tagLoc, diag::note_typedef_changes_linkage)
4179         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4180     return;
4181   }
4182 
4183   // Otherwise, set this is the anon-decl typedef for the tag.
4184   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4185 }
4186 
4187 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4188   switch (T) {
4189   case DeclSpec::TST_class:
4190     return 0;
4191   case DeclSpec::TST_struct:
4192     return 1;
4193   case DeclSpec::TST_interface:
4194     return 2;
4195   case DeclSpec::TST_union:
4196     return 3;
4197   case DeclSpec::TST_enum:
4198     return 4;
4199   default:
4200     llvm_unreachable("unexpected type specifier");
4201   }
4202 }
4203 
4204 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4205 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4206 /// parameters to cope with template friend declarations.
4207 Decl *
4208 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4209                                  MultiTemplateParamsArg TemplateParams,
4210                                  bool IsExplicitInstantiation,
4211                                  RecordDecl *&AnonRecord) {
4212   Decl *TagD = nullptr;
4213   TagDecl *Tag = nullptr;
4214   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4215       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4216       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4217       DS.getTypeSpecType() == DeclSpec::TST_union ||
4218       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4219     TagD = DS.getRepAsDecl();
4220 
4221     if (!TagD) // We probably had an error
4222       return nullptr;
4223 
4224     // Note that the above type specs guarantee that the
4225     // type rep is a Decl, whereas in many of the others
4226     // it's a Type.
4227     if (isa<TagDecl>(TagD))
4228       Tag = cast<TagDecl>(TagD);
4229     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4230       Tag = CTD->getTemplatedDecl();
4231   }
4232 
4233   if (Tag) {
4234     handleTagNumbering(Tag, S);
4235     Tag->setFreeStanding();
4236     if (Tag->isInvalidDecl())
4237       return Tag;
4238   }
4239 
4240   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4241     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4242     // or incomplete types shall not be restrict-qualified."
4243     if (TypeQuals & DeclSpec::TQ_restrict)
4244       Diag(DS.getRestrictSpecLoc(),
4245            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4246            << DS.getSourceRange();
4247   }
4248 
4249   if (DS.isInlineSpecified())
4250     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4251         << getLangOpts().CPlusPlus17;
4252 
4253   if (DS.isConstexprSpecified()) {
4254     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4255     // and definitions of functions and variables.
4256     if (Tag)
4257       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4258           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4259     else
4260       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4261     // Don't emit warnings after this error.
4262     return TagD;
4263   }
4264 
4265   DiagnoseFunctionSpecifiers(DS);
4266 
4267   if (DS.isFriendSpecified()) {
4268     // If we're dealing with a decl but not a TagDecl, assume that
4269     // whatever routines created it handled the friendship aspect.
4270     if (TagD && !Tag)
4271       return nullptr;
4272     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4273   }
4274 
4275   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4276   bool IsExplicitSpecialization =
4277     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4278   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4279       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4280       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4281     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4282     // nested-name-specifier unless it is an explicit instantiation
4283     // or an explicit specialization.
4284     //
4285     // FIXME: We allow class template partial specializations here too, per the
4286     // obvious intent of DR1819.
4287     //
4288     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4289     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4290         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4291     return nullptr;
4292   }
4293 
4294   // Track whether this decl-specifier declares anything.
4295   bool DeclaresAnything = true;
4296 
4297   // Handle anonymous struct definitions.
4298   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4299     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4300         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4301       if (getLangOpts().CPlusPlus ||
4302           Record->getDeclContext()->isRecord()) {
4303         // If CurContext is a DeclContext that can contain statements,
4304         // RecursiveASTVisitor won't visit the decls that
4305         // BuildAnonymousStructOrUnion() will put into CurContext.
4306         // Also store them here so that they can be part of the
4307         // DeclStmt that gets created in this case.
4308         // FIXME: Also return the IndirectFieldDecls created by
4309         // BuildAnonymousStructOr union, for the same reason?
4310         if (CurContext->isFunctionOrMethod())
4311           AnonRecord = Record;
4312         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4313                                            Context.getPrintingPolicy());
4314       }
4315 
4316       DeclaresAnything = false;
4317     }
4318   }
4319 
4320   // C11 6.7.2.1p2:
4321   //   A struct-declaration that does not declare an anonymous structure or
4322   //   anonymous union shall contain a struct-declarator-list.
4323   //
4324   // This rule also existed in C89 and C99; the grammar for struct-declaration
4325   // did not permit a struct-declaration without a struct-declarator-list.
4326   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4327       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4328     // Check for Microsoft C extension: anonymous struct/union member.
4329     // Handle 2 kinds of anonymous struct/union:
4330     //   struct STRUCT;
4331     //   union UNION;
4332     // and
4333     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4334     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4335     if ((Tag && Tag->getDeclName()) ||
4336         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4337       RecordDecl *Record = nullptr;
4338       if (Tag)
4339         Record = dyn_cast<RecordDecl>(Tag);
4340       else if (const RecordType *RT =
4341                    DS.getRepAsType().get()->getAsStructureType())
4342         Record = RT->getDecl();
4343       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4344         Record = UT->getDecl();
4345 
4346       if (Record && getLangOpts().MicrosoftExt) {
4347         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4348           << Record->isUnion() << DS.getSourceRange();
4349         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4350       }
4351 
4352       DeclaresAnything = false;
4353     }
4354   }
4355 
4356   // Skip all the checks below if we have a type error.
4357   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4358       (TagD && TagD->isInvalidDecl()))
4359     return TagD;
4360 
4361   if (getLangOpts().CPlusPlus &&
4362       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4363     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4364       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4365           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4366         DeclaresAnything = false;
4367 
4368   if (!DS.isMissingDeclaratorOk()) {
4369     // Customize diagnostic for a typedef missing a name.
4370     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4371       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4372         << DS.getSourceRange();
4373     else
4374       DeclaresAnything = false;
4375   }
4376 
4377   if (DS.isModulePrivateSpecified() &&
4378       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4379     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4380       << Tag->getTagKind()
4381       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4382 
4383   ActOnDocumentableDecl(TagD);
4384 
4385   // C 6.7/2:
4386   //   A declaration [...] shall declare at least a declarator [...], a tag,
4387   //   or the members of an enumeration.
4388   // C++ [dcl.dcl]p3:
4389   //   [If there are no declarators], and except for the declaration of an
4390   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4391   //   names into the program, or shall redeclare a name introduced by a
4392   //   previous declaration.
4393   if (!DeclaresAnything) {
4394     // In C, we allow this as a (popular) extension / bug. Don't bother
4395     // producing further diagnostics for redundant qualifiers after this.
4396     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4397     return TagD;
4398   }
4399 
4400   // C++ [dcl.stc]p1:
4401   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4402   //   init-declarator-list of the declaration shall not be empty.
4403   // C++ [dcl.fct.spec]p1:
4404   //   If a cv-qualifier appears in a decl-specifier-seq, the
4405   //   init-declarator-list of the declaration shall not be empty.
4406   //
4407   // Spurious qualifiers here appear to be valid in C.
4408   unsigned DiagID = diag::warn_standalone_specifier;
4409   if (getLangOpts().CPlusPlus)
4410     DiagID = diag::ext_standalone_specifier;
4411 
4412   // Note that a linkage-specification sets a storage class, but
4413   // 'extern "C" struct foo;' is actually valid and not theoretically
4414   // useless.
4415   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4416     if (SCS == DeclSpec::SCS_mutable)
4417       // Since mutable is not a viable storage class specifier in C, there is
4418       // no reason to treat it as an extension. Instead, diagnose as an error.
4419       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4420     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4421       Diag(DS.getStorageClassSpecLoc(), DiagID)
4422         << DeclSpec::getSpecifierName(SCS);
4423   }
4424 
4425   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4426     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4427       << DeclSpec::getSpecifierName(TSCS);
4428   if (DS.getTypeQualifiers()) {
4429     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4430       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4431     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4432       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4433     // Restrict is covered above.
4434     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4435       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4436     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4437       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4438   }
4439 
4440   // Warn about ignored type attributes, for example:
4441   // __attribute__((aligned)) struct A;
4442   // Attributes should be placed after tag to apply to type declaration.
4443   if (!DS.getAttributes().empty()) {
4444     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4445     if (TypeSpecType == DeclSpec::TST_class ||
4446         TypeSpecType == DeclSpec::TST_struct ||
4447         TypeSpecType == DeclSpec::TST_interface ||
4448         TypeSpecType == DeclSpec::TST_union ||
4449         TypeSpecType == DeclSpec::TST_enum) {
4450       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4451            attrs = attrs->getNext())
4452         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4453             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4454     }
4455   }
4456 
4457   return TagD;
4458 }
4459 
4460 /// We are trying to inject an anonymous member into the given scope;
4461 /// check if there's an existing declaration that can't be overloaded.
4462 ///
4463 /// \return true if this is a forbidden redeclaration
4464 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4465                                          Scope *S,
4466                                          DeclContext *Owner,
4467                                          DeclarationName Name,
4468                                          SourceLocation NameLoc,
4469                                          bool IsUnion) {
4470   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4471                  Sema::ForVisibleRedeclaration);
4472   if (!SemaRef.LookupName(R, S)) return false;
4473 
4474   // Pick a representative declaration.
4475   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4476   assert(PrevDecl && "Expected a non-null Decl");
4477 
4478   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4479     return false;
4480 
4481   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4482     << IsUnion << Name;
4483   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4484 
4485   return true;
4486 }
4487 
4488 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4489 /// anonymous struct or union AnonRecord into the owning context Owner
4490 /// and scope S. This routine will be invoked just after we realize
4491 /// that an unnamed union or struct is actually an anonymous union or
4492 /// struct, e.g.,
4493 ///
4494 /// @code
4495 /// union {
4496 ///   int i;
4497 ///   float f;
4498 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4499 ///    // f into the surrounding scope.x
4500 /// @endcode
4501 ///
4502 /// This routine is recursive, injecting the names of nested anonymous
4503 /// structs/unions into the owning context and scope as well.
4504 static bool
4505 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4506                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4507                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4508   bool Invalid = false;
4509 
4510   // Look every FieldDecl and IndirectFieldDecl with a name.
4511   for (auto *D : AnonRecord->decls()) {
4512     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4513         cast<NamedDecl>(D)->getDeclName()) {
4514       ValueDecl *VD = cast<ValueDecl>(D);
4515       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4516                                        VD->getLocation(),
4517                                        AnonRecord->isUnion())) {
4518         // C++ [class.union]p2:
4519         //   The names of the members of an anonymous union shall be
4520         //   distinct from the names of any other entity in the
4521         //   scope in which the anonymous union is declared.
4522         Invalid = true;
4523       } else {
4524         // C++ [class.union]p2:
4525         //   For the purpose of name lookup, after the anonymous union
4526         //   definition, the members of the anonymous union are
4527         //   considered to have been defined in the scope in which the
4528         //   anonymous union is declared.
4529         unsigned OldChainingSize = Chaining.size();
4530         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4531           Chaining.append(IF->chain_begin(), IF->chain_end());
4532         else
4533           Chaining.push_back(VD);
4534 
4535         assert(Chaining.size() >= 2);
4536         NamedDecl **NamedChain =
4537           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4538         for (unsigned i = 0; i < Chaining.size(); i++)
4539           NamedChain[i] = Chaining[i];
4540 
4541         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4542             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4543             VD->getType(), {NamedChain, Chaining.size()});
4544 
4545         for (const auto *Attr : VD->attrs())
4546           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4547 
4548         IndirectField->setAccess(AS);
4549         IndirectField->setImplicit();
4550         SemaRef.PushOnScopeChains(IndirectField, S);
4551 
4552         // That includes picking up the appropriate access specifier.
4553         if (AS != AS_none) IndirectField->setAccess(AS);
4554 
4555         Chaining.resize(OldChainingSize);
4556       }
4557     }
4558   }
4559 
4560   return Invalid;
4561 }
4562 
4563 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4564 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4565 /// illegal input values are mapped to SC_None.
4566 static StorageClass
4567 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4568   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4569   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4570          "Parser allowed 'typedef' as storage class VarDecl.");
4571   switch (StorageClassSpec) {
4572   case DeclSpec::SCS_unspecified:    return SC_None;
4573   case DeclSpec::SCS_extern:
4574     if (DS.isExternInLinkageSpec())
4575       return SC_None;
4576     return SC_Extern;
4577   case DeclSpec::SCS_static:         return SC_Static;
4578   case DeclSpec::SCS_auto:           return SC_Auto;
4579   case DeclSpec::SCS_register:       return SC_Register;
4580   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4581     // Illegal SCSs map to None: error reporting is up to the caller.
4582   case DeclSpec::SCS_mutable:        // Fall through.
4583   case DeclSpec::SCS_typedef:        return SC_None;
4584   }
4585   llvm_unreachable("unknown storage class specifier");
4586 }
4587 
4588 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4589   assert(Record->hasInClassInitializer());
4590 
4591   for (const auto *I : Record->decls()) {
4592     const auto *FD = dyn_cast<FieldDecl>(I);
4593     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4594       FD = IFD->getAnonField();
4595     if (FD && FD->hasInClassInitializer())
4596       return FD->getLocation();
4597   }
4598 
4599   llvm_unreachable("couldn't find in-class initializer");
4600 }
4601 
4602 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4603                                       SourceLocation DefaultInitLoc) {
4604   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4605     return;
4606 
4607   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4608   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4609 }
4610 
4611 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4612                                       CXXRecordDecl *AnonUnion) {
4613   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4614     return;
4615 
4616   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4617 }
4618 
4619 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4620 /// anonymous structure or union. Anonymous unions are a C++ feature
4621 /// (C++ [class.union]) and a C11 feature; anonymous structures
4622 /// are a C11 feature and GNU C++ extension.
4623 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4624                                         AccessSpecifier AS,
4625                                         RecordDecl *Record,
4626                                         const PrintingPolicy &Policy) {
4627   DeclContext *Owner = Record->getDeclContext();
4628 
4629   // Diagnose whether this anonymous struct/union is an extension.
4630   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4631     Diag(Record->getLocation(), diag::ext_anonymous_union);
4632   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4633     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4634   else if (!Record->isUnion() && !getLangOpts().C11)
4635     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4636 
4637   // C and C++ require different kinds of checks for anonymous
4638   // structs/unions.
4639   bool Invalid = false;
4640   if (getLangOpts().CPlusPlus) {
4641     const char *PrevSpec = nullptr;
4642     unsigned DiagID;
4643     if (Record->isUnion()) {
4644       // C++ [class.union]p6:
4645       // C++17 [class.union.anon]p2:
4646       //   Anonymous unions declared in a named namespace or in the
4647       //   global namespace shall be declared static.
4648       DeclContext *OwnerScope = Owner->getRedeclContext();
4649       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4650           (OwnerScope->isTranslationUnit() ||
4651            (OwnerScope->isNamespace() &&
4652             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4653         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4654           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4655 
4656         // Recover by adding 'static'.
4657         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4658                                PrevSpec, DiagID, Policy);
4659       }
4660       // C++ [class.union]p6:
4661       //   A storage class is not allowed in a declaration of an
4662       //   anonymous union in a class scope.
4663       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4664                isa<RecordDecl>(Owner)) {
4665         Diag(DS.getStorageClassSpecLoc(),
4666              diag::err_anonymous_union_with_storage_spec)
4667           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4668 
4669         // Recover by removing the storage specifier.
4670         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4671                                SourceLocation(),
4672                                PrevSpec, DiagID, Context.getPrintingPolicy());
4673       }
4674     }
4675 
4676     // Ignore const/volatile/restrict qualifiers.
4677     if (DS.getTypeQualifiers()) {
4678       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4679         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4680           << Record->isUnion() << "const"
4681           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4682       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4683         Diag(DS.getVolatileSpecLoc(),
4684              diag::ext_anonymous_struct_union_qualified)
4685           << Record->isUnion() << "volatile"
4686           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4687       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4688         Diag(DS.getRestrictSpecLoc(),
4689              diag::ext_anonymous_struct_union_qualified)
4690           << Record->isUnion() << "restrict"
4691           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4692       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4693         Diag(DS.getAtomicSpecLoc(),
4694              diag::ext_anonymous_struct_union_qualified)
4695           << Record->isUnion() << "_Atomic"
4696           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4697       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4698         Diag(DS.getUnalignedSpecLoc(),
4699              diag::ext_anonymous_struct_union_qualified)
4700           << Record->isUnion() << "__unaligned"
4701           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4702 
4703       DS.ClearTypeQualifiers();
4704     }
4705 
4706     // C++ [class.union]p2:
4707     //   The member-specification of an anonymous union shall only
4708     //   define non-static data members. [Note: nested types and
4709     //   functions cannot be declared within an anonymous union. ]
4710     for (auto *Mem : Record->decls()) {
4711       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4712         // C++ [class.union]p3:
4713         //   An anonymous union shall not have private or protected
4714         //   members (clause 11).
4715         assert(FD->getAccess() != AS_none);
4716         if (FD->getAccess() != AS_public) {
4717           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4718             << Record->isUnion() << (FD->getAccess() == AS_protected);
4719           Invalid = true;
4720         }
4721 
4722         // C++ [class.union]p1
4723         //   An object of a class with a non-trivial constructor, a non-trivial
4724         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4725         //   assignment operator cannot be a member of a union, nor can an
4726         //   array of such objects.
4727         if (CheckNontrivialField(FD))
4728           Invalid = true;
4729       } else if (Mem->isImplicit()) {
4730         // Any implicit members are fine.
4731       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4732         // This is a type that showed up in an
4733         // elaborated-type-specifier inside the anonymous struct or
4734         // union, but which actually declares a type outside of the
4735         // anonymous struct or union. It's okay.
4736       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4737         if (!MemRecord->isAnonymousStructOrUnion() &&
4738             MemRecord->getDeclName()) {
4739           // Visual C++ allows type definition in anonymous struct or union.
4740           if (getLangOpts().MicrosoftExt)
4741             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4742               << Record->isUnion();
4743           else {
4744             // This is a nested type declaration.
4745             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4746               << Record->isUnion();
4747             Invalid = true;
4748           }
4749         } else {
4750           // This is an anonymous type definition within another anonymous type.
4751           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4752           // not part of standard C++.
4753           Diag(MemRecord->getLocation(),
4754                diag::ext_anonymous_record_with_anonymous_type)
4755             << Record->isUnion();
4756         }
4757       } else if (isa<AccessSpecDecl>(Mem)) {
4758         // Any access specifier is fine.
4759       } else if (isa<StaticAssertDecl>(Mem)) {
4760         // In C++1z, static_assert declarations are also fine.
4761       } else {
4762         // We have something that isn't a non-static data
4763         // member. Complain about it.
4764         unsigned DK = diag::err_anonymous_record_bad_member;
4765         if (isa<TypeDecl>(Mem))
4766           DK = diag::err_anonymous_record_with_type;
4767         else if (isa<FunctionDecl>(Mem))
4768           DK = diag::err_anonymous_record_with_function;
4769         else if (isa<VarDecl>(Mem))
4770           DK = diag::err_anonymous_record_with_static;
4771 
4772         // Visual C++ allows type definition in anonymous struct or union.
4773         if (getLangOpts().MicrosoftExt &&
4774             DK == diag::err_anonymous_record_with_type)
4775           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4776             << Record->isUnion();
4777         else {
4778           Diag(Mem->getLocation(), DK) << Record->isUnion();
4779           Invalid = true;
4780         }
4781       }
4782     }
4783 
4784     // C++11 [class.union]p8 (DR1460):
4785     //   At most one variant member of a union may have a
4786     //   brace-or-equal-initializer.
4787     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4788         Owner->isRecord())
4789       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4790                                 cast<CXXRecordDecl>(Record));
4791   }
4792 
4793   if (!Record->isUnion() && !Owner->isRecord()) {
4794     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4795       << getLangOpts().CPlusPlus;
4796     Invalid = true;
4797   }
4798 
4799   // Mock up a declarator.
4800   Declarator Dc(DS, DeclaratorContext::MemberContext);
4801   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4802   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4803 
4804   // Create a declaration for this anonymous struct/union.
4805   NamedDecl *Anon = nullptr;
4806   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4807     Anon = FieldDecl::Create(Context, OwningClass,
4808                              DS.getLocStart(),
4809                              Record->getLocation(),
4810                              /*IdentifierInfo=*/nullptr,
4811                              Context.getTypeDeclType(Record),
4812                              TInfo,
4813                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4814                              /*InitStyle=*/ICIS_NoInit);
4815     Anon->setAccess(AS);
4816     if (getLangOpts().CPlusPlus)
4817       FieldCollector->Add(cast<FieldDecl>(Anon));
4818   } else {
4819     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4820     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4821     if (SCSpec == DeclSpec::SCS_mutable) {
4822       // mutable can only appear on non-static class members, so it's always
4823       // an error here
4824       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4825       Invalid = true;
4826       SC = SC_None;
4827     }
4828 
4829     Anon = VarDecl::Create(Context, Owner,
4830                            DS.getLocStart(),
4831                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4832                            Context.getTypeDeclType(Record),
4833                            TInfo, SC);
4834 
4835     // Default-initialize the implicit variable. This initialization will be
4836     // trivial in almost all cases, except if a union member has an in-class
4837     // initializer:
4838     //   union { int n = 0; };
4839     ActOnUninitializedDecl(Anon);
4840   }
4841   Anon->setImplicit();
4842 
4843   // Mark this as an anonymous struct/union type.
4844   Record->setAnonymousStructOrUnion(true);
4845 
4846   // Add the anonymous struct/union object to the current
4847   // context. We'll be referencing this object when we refer to one of
4848   // its members.
4849   Owner->addDecl(Anon);
4850 
4851   // Inject the members of the anonymous struct/union into the owning
4852   // context and into the identifier resolver chain for name lookup
4853   // purposes.
4854   SmallVector<NamedDecl*, 2> Chain;
4855   Chain.push_back(Anon);
4856 
4857   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4858     Invalid = true;
4859 
4860   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4861     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4862       Decl *ManglingContextDecl;
4863       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4864               NewVD->getDeclContext(), ManglingContextDecl)) {
4865         Context.setManglingNumber(
4866             NewVD, MCtx->getManglingNumber(
4867                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4868         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4869       }
4870     }
4871   }
4872 
4873   if (Invalid)
4874     Anon->setInvalidDecl();
4875 
4876   return Anon;
4877 }
4878 
4879 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4880 /// Microsoft C anonymous structure.
4881 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4882 /// Example:
4883 ///
4884 /// struct A { int a; };
4885 /// struct B { struct A; int b; };
4886 ///
4887 /// void foo() {
4888 ///   B var;
4889 ///   var.a = 3;
4890 /// }
4891 ///
4892 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4893                                            RecordDecl *Record) {
4894   assert(Record && "expected a record!");
4895 
4896   // Mock up a declarator.
4897   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
4898   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4899   assert(TInfo && "couldn't build declarator info for anonymous struct");
4900 
4901   auto *ParentDecl = cast<RecordDecl>(CurContext);
4902   QualType RecTy = Context.getTypeDeclType(Record);
4903 
4904   // Create a declaration for this anonymous struct.
4905   NamedDecl *Anon = FieldDecl::Create(Context,
4906                              ParentDecl,
4907                              DS.getLocStart(),
4908                              DS.getLocStart(),
4909                              /*IdentifierInfo=*/nullptr,
4910                              RecTy,
4911                              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     NameInfo.setLoc(Name.StartLocation);
4955     return NameInfo;
4956 
4957   case UnqualifiedIdKind::IK_DeductionGuideName: {
4958     // C++ [temp.deduct.guide]p3:
4959     //   The simple-template-id shall name a class template specialization.
4960     //   The template-name shall be the same identifier as the template-name
4961     //   of the simple-template-id.
4962     // These together intend to imply that the template-name shall name a
4963     // class template.
4964     // FIXME: template<typename T> struct X {};
4965     //        template<typename T> using Y = X<T>;
4966     //        Y(int) -> Y<int>;
4967     //   satisfies these rules but does not name a class template.
4968     TemplateName TN = Name.TemplateName.get().get();
4969     auto *Template = TN.getAsTemplateDecl();
4970     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4971       Diag(Name.StartLocation,
4972            diag::err_deduction_guide_name_not_class_template)
4973         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4974       if (Template)
4975         Diag(Template->getLocation(), diag::note_template_decl_here);
4976       return DeclarationNameInfo();
4977     }
4978 
4979     NameInfo.setName(
4980         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4981     NameInfo.setLoc(Name.StartLocation);
4982     return NameInfo;
4983   }
4984 
4985   case UnqualifiedIdKind::IK_OperatorFunctionId:
4986     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4987                                            Name.OperatorFunctionId.Operator));
4988     NameInfo.setLoc(Name.StartLocation);
4989     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4990       = Name.OperatorFunctionId.SymbolLocations[0];
4991     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4992       = Name.EndLocation.getRawEncoding();
4993     return NameInfo;
4994 
4995   case UnqualifiedIdKind::IK_LiteralOperatorId:
4996     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4997                                                            Name.Identifier));
4998     NameInfo.setLoc(Name.StartLocation);
4999     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5000     return NameInfo;
5001 
5002   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5003     TypeSourceInfo *TInfo;
5004     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5005     if (Ty.isNull())
5006       return DeclarationNameInfo();
5007     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5008                                                Context.getCanonicalType(Ty)));
5009     NameInfo.setLoc(Name.StartLocation);
5010     NameInfo.setNamedTypeInfo(TInfo);
5011     return NameInfo;
5012   }
5013 
5014   case UnqualifiedIdKind::IK_ConstructorName: {
5015     TypeSourceInfo *TInfo;
5016     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5017     if (Ty.isNull())
5018       return DeclarationNameInfo();
5019     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5020                                               Context.getCanonicalType(Ty)));
5021     NameInfo.setLoc(Name.StartLocation);
5022     NameInfo.setNamedTypeInfo(TInfo);
5023     return NameInfo;
5024   }
5025 
5026   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5027     // In well-formed code, we can only have a constructor
5028     // template-id that refers to the current context, so go there
5029     // to find the actual type being constructed.
5030     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5031     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5032       return DeclarationNameInfo();
5033 
5034     // Determine the type of the class being constructed.
5035     QualType CurClassType = Context.getTypeDeclType(CurClass);
5036 
5037     // FIXME: Check two things: that the template-id names the same type as
5038     // CurClassType, and that the template-id does not occur when the name
5039     // was qualified.
5040 
5041     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5042                                     Context.getCanonicalType(CurClassType)));
5043     NameInfo.setLoc(Name.StartLocation);
5044     // FIXME: should we retrieve TypeSourceInfo?
5045     NameInfo.setNamedTypeInfo(nullptr);
5046     return NameInfo;
5047   }
5048 
5049   case UnqualifiedIdKind::IK_DestructorName: {
5050     TypeSourceInfo *TInfo;
5051     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5052     if (Ty.isNull())
5053       return DeclarationNameInfo();
5054     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5055                                               Context.getCanonicalType(Ty)));
5056     NameInfo.setLoc(Name.StartLocation);
5057     NameInfo.setNamedTypeInfo(TInfo);
5058     return NameInfo;
5059   }
5060 
5061   case UnqualifiedIdKind::IK_TemplateId: {
5062     TemplateName TName = Name.TemplateId->Template.get();
5063     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5064     return Context.getNameForTemplate(TName, TNameLoc);
5065   }
5066 
5067   } // switch (Name.getKind())
5068 
5069   llvm_unreachable("Unknown name kind");
5070 }
5071 
5072 static QualType getCoreType(QualType Ty) {
5073   do {
5074     if (Ty->isPointerType() || Ty->isReferenceType())
5075       Ty = Ty->getPointeeType();
5076     else if (Ty->isArrayType())
5077       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5078     else
5079       return Ty.withoutLocalFastQualifiers();
5080   } while (true);
5081 }
5082 
5083 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5084 /// and Definition have "nearly" matching parameters. This heuristic is
5085 /// used to improve diagnostics in the case where an out-of-line function
5086 /// definition doesn't match any declaration within the class or namespace.
5087 /// Also sets Params to the list of indices to the parameters that differ
5088 /// between the declaration and the definition. If hasSimilarParameters
5089 /// returns true and Params is empty, then all of the parameters match.
5090 static bool hasSimilarParameters(ASTContext &Context,
5091                                      FunctionDecl *Declaration,
5092                                      FunctionDecl *Definition,
5093                                      SmallVectorImpl<unsigned> &Params) {
5094   Params.clear();
5095   if (Declaration->param_size() != Definition->param_size())
5096     return false;
5097   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5098     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5099     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5100 
5101     // The parameter types are identical
5102     if (Context.hasSameType(DefParamTy, DeclParamTy))
5103       continue;
5104 
5105     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5106     QualType DefParamBaseTy = getCoreType(DefParamTy);
5107     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5108     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5109 
5110     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5111         (DeclTyName && DeclTyName == DefTyName))
5112       Params.push_back(Idx);
5113     else  // The two parameters aren't even close
5114       return false;
5115   }
5116 
5117   return true;
5118 }
5119 
5120 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5121 /// declarator needs to be rebuilt in the current instantiation.
5122 /// Any bits of declarator which appear before the name are valid for
5123 /// consideration here.  That's specifically the type in the decl spec
5124 /// and the base type in any member-pointer chunks.
5125 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5126                                                     DeclarationName Name) {
5127   // The types we specifically need to rebuild are:
5128   //   - typenames, typeofs, and decltypes
5129   //   - types which will become injected class names
5130   // Of course, we also need to rebuild any type referencing such a
5131   // type.  It's safest to just say "dependent", but we call out a
5132   // few cases here.
5133 
5134   DeclSpec &DS = D.getMutableDeclSpec();
5135   switch (DS.getTypeSpecType()) {
5136   case DeclSpec::TST_typename:
5137   case DeclSpec::TST_typeofType:
5138   case DeclSpec::TST_underlyingType:
5139   case DeclSpec::TST_atomic: {
5140     // Grab the type from the parser.
5141     TypeSourceInfo *TSI = nullptr;
5142     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5143     if (T.isNull() || !T->isDependentType()) break;
5144 
5145     // Make sure there's a type source info.  This isn't really much
5146     // of a waste; most dependent types should have type source info
5147     // attached already.
5148     if (!TSI)
5149       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5150 
5151     // Rebuild the type in the current instantiation.
5152     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5153     if (!TSI) return true;
5154 
5155     // Store the new type back in the decl spec.
5156     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5157     DS.UpdateTypeRep(LocType);
5158     break;
5159   }
5160 
5161   case DeclSpec::TST_decltype:
5162   case DeclSpec::TST_typeofExpr: {
5163     Expr *E = DS.getRepAsExpr();
5164     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5165     if (Result.isInvalid()) return true;
5166     DS.UpdateExprRep(Result.get());
5167     break;
5168   }
5169 
5170   default:
5171     // Nothing to do for these decl specs.
5172     break;
5173   }
5174 
5175   // It doesn't matter what order we do this in.
5176   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5177     DeclaratorChunk &Chunk = D.getTypeObject(I);
5178 
5179     // The only type information in the declarator which can come
5180     // before the declaration name is the base type of a member
5181     // pointer.
5182     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5183       continue;
5184 
5185     // Rebuild the scope specifier in-place.
5186     CXXScopeSpec &SS = Chunk.Mem.Scope();
5187     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5188       return true;
5189   }
5190 
5191   return false;
5192 }
5193 
5194 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5195   D.setFunctionDefinitionKind(FDK_Declaration);
5196   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5197 
5198   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5199       Dcl && Dcl->getDeclContext()->isFileContext())
5200     Dcl->setTopLevelDeclInObjCContainer();
5201 
5202   if (getLangOpts().OpenCL)
5203     setCurrentOpenCLExtensionForDecl(Dcl);
5204 
5205   return Dcl;
5206 }
5207 
5208 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5209 ///   If T is the name of a class, then each of the following shall have a
5210 ///   name different from T:
5211 ///     - every static data member of class T;
5212 ///     - every member function of class T
5213 ///     - every member of class T that is itself a type;
5214 /// \returns true if the declaration name violates these rules.
5215 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5216                                    DeclarationNameInfo NameInfo) {
5217   DeclarationName Name = NameInfo.getName();
5218 
5219   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5220   while (Record && Record->isAnonymousStructOrUnion())
5221     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5222   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5223     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5224     return true;
5225   }
5226 
5227   return false;
5228 }
5229 
5230 /// Diagnose a declaration whose declarator-id has the given
5231 /// nested-name-specifier.
5232 ///
5233 /// \param SS The nested-name-specifier of the declarator-id.
5234 ///
5235 /// \param DC The declaration context to which the nested-name-specifier
5236 /// resolves.
5237 ///
5238 /// \param Name The name of the entity being declared.
5239 ///
5240 /// \param Loc The location of the name of the entity being declared.
5241 ///
5242 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5243 /// we're declaring an explicit / partial specialization / instantiation.
5244 ///
5245 /// \returns true if we cannot safely recover from this error, false otherwise.
5246 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5247                                         DeclarationName Name,
5248                                         SourceLocation Loc, bool IsTemplateId) {
5249   DeclContext *Cur = CurContext;
5250   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5251     Cur = Cur->getParent();
5252 
5253   // If the user provided a superfluous scope specifier that refers back to the
5254   // class in which the entity is already declared, diagnose and ignore it.
5255   //
5256   // class X {
5257   //   void X::f();
5258   // };
5259   //
5260   // Note, it was once ill-formed to give redundant qualification in all
5261   // contexts, but that rule was removed by DR482.
5262   if (Cur->Equals(DC)) {
5263     if (Cur->isRecord()) {
5264       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5265                                       : diag::err_member_extra_qualification)
5266         << Name << FixItHint::CreateRemoval(SS.getRange());
5267       SS.clear();
5268     } else {
5269       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5270     }
5271     return false;
5272   }
5273 
5274   // Check whether the qualifying scope encloses the scope of the original
5275   // declaration. For a template-id, we perform the checks in
5276   // CheckTemplateSpecializationScope.
5277   if (!Cur->Encloses(DC) && !IsTemplateId) {
5278     if (Cur->isRecord())
5279       Diag(Loc, diag::err_member_qualification)
5280         << Name << SS.getRange();
5281     else if (isa<TranslationUnitDecl>(DC))
5282       Diag(Loc, diag::err_invalid_declarator_global_scope)
5283         << Name << SS.getRange();
5284     else if (isa<FunctionDecl>(Cur))
5285       Diag(Loc, diag::err_invalid_declarator_in_function)
5286         << Name << SS.getRange();
5287     else if (isa<BlockDecl>(Cur))
5288       Diag(Loc, diag::err_invalid_declarator_in_block)
5289         << Name << SS.getRange();
5290     else
5291       Diag(Loc, diag::err_invalid_declarator_scope)
5292       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5293 
5294     return true;
5295   }
5296 
5297   if (Cur->isRecord()) {
5298     // Cannot qualify members within a class.
5299     Diag(Loc, diag::err_member_qualification)
5300       << Name << SS.getRange();
5301     SS.clear();
5302 
5303     // C++ constructors and destructors with incorrect scopes can break
5304     // our AST invariants by having the wrong underlying types. If
5305     // that's the case, then drop this declaration entirely.
5306     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5307          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5308         !Context.hasSameType(Name.getCXXNameType(),
5309                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5310       return true;
5311 
5312     return false;
5313   }
5314 
5315   // C++11 [dcl.meaning]p1:
5316   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5317   //   not begin with a decltype-specifer"
5318   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5319   while (SpecLoc.getPrefix())
5320     SpecLoc = SpecLoc.getPrefix();
5321   if (dyn_cast_or_null<DecltypeType>(
5322         SpecLoc.getNestedNameSpecifier()->getAsType()))
5323     Diag(Loc, diag::err_decltype_in_declarator)
5324       << SpecLoc.getTypeLoc().getSourceRange();
5325 
5326   return false;
5327 }
5328 
5329 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5330                                   MultiTemplateParamsArg TemplateParamLists) {
5331   // TODO: consider using NameInfo for diagnostic.
5332   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5333   DeclarationName Name = NameInfo.getName();
5334 
5335   // All of these full declarators require an identifier.  If it doesn't have
5336   // one, the ParsedFreeStandingDeclSpec action should be used.
5337   if (D.isDecompositionDeclarator()) {
5338     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5339   } else if (!Name) {
5340     if (!D.isInvalidType())  // Reject this if we think it is valid.
5341       Diag(D.getDeclSpec().getLocStart(),
5342            diag::err_declarator_need_ident)
5343         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5344     return nullptr;
5345   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5346     return nullptr;
5347 
5348   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5349   // we find one that is.
5350   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5351          (S->getFlags() & Scope::TemplateParamScope) != 0)
5352     S = S->getParent();
5353 
5354   DeclContext *DC = CurContext;
5355   if (D.getCXXScopeSpec().isInvalid())
5356     D.setInvalidType();
5357   else if (D.getCXXScopeSpec().isSet()) {
5358     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5359                                         UPPC_DeclarationQualifier))
5360       return nullptr;
5361 
5362     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5363     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5364     if (!DC || isa<EnumDecl>(DC)) {
5365       // If we could not compute the declaration context, it's because the
5366       // declaration context is dependent but does not refer to a class,
5367       // class template, or class template partial specialization. Complain
5368       // and return early, to avoid the coming semantic disaster.
5369       Diag(D.getIdentifierLoc(),
5370            diag::err_template_qualified_declarator_no_match)
5371         << D.getCXXScopeSpec().getScopeRep()
5372         << D.getCXXScopeSpec().getRange();
5373       return nullptr;
5374     }
5375     bool IsDependentContext = DC->isDependentContext();
5376 
5377     if (!IsDependentContext &&
5378         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5379       return nullptr;
5380 
5381     // If a class is incomplete, do not parse entities inside it.
5382     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5383       Diag(D.getIdentifierLoc(),
5384            diag::err_member_def_undefined_record)
5385         << Name << DC << D.getCXXScopeSpec().getRange();
5386       return nullptr;
5387     }
5388     if (!D.getDeclSpec().isFriendSpecified()) {
5389       if (diagnoseQualifiedDeclaration(
5390               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5391               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5392         if (DC->isRecord())
5393           return nullptr;
5394 
5395         D.setInvalidType();
5396       }
5397     }
5398 
5399     // Check whether we need to rebuild the type of the given
5400     // declaration in the current instantiation.
5401     if (EnteringContext && IsDependentContext &&
5402         TemplateParamLists.size() != 0) {
5403       ContextRAII SavedContext(*this, DC);
5404       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5405         D.setInvalidType();
5406     }
5407   }
5408 
5409   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5410   QualType R = TInfo->getType();
5411 
5412   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5413                                       UPPC_DeclarationType))
5414     D.setInvalidType();
5415 
5416   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5417                         forRedeclarationInCurContext());
5418 
5419   // See if this is a redefinition of a variable in the same scope.
5420   if (!D.getCXXScopeSpec().isSet()) {
5421     bool IsLinkageLookup = false;
5422     bool CreateBuiltins = false;
5423 
5424     // If the declaration we're planning to build will be a function
5425     // or object with linkage, then look for another declaration with
5426     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5427     //
5428     // If the declaration we're planning to build will be declared with
5429     // external linkage in the translation unit, create any builtin with
5430     // the same name.
5431     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5432       /* Do nothing*/;
5433     else if (CurContext->isFunctionOrMethod() &&
5434              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5435               R->isFunctionType())) {
5436       IsLinkageLookup = true;
5437       CreateBuiltins =
5438           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5439     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5440                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5441       CreateBuiltins = true;
5442 
5443     if (IsLinkageLookup) {
5444       Previous.clear(LookupRedeclarationWithLinkage);
5445       Previous.setRedeclarationKind(ForExternalRedeclaration);
5446     }
5447 
5448     LookupName(Previous, S, CreateBuiltins);
5449   } else { // Something like "int foo::x;"
5450     LookupQualifiedName(Previous, DC);
5451 
5452     // C++ [dcl.meaning]p1:
5453     //   When the declarator-id is qualified, the declaration shall refer to a
5454     //  previously declared member of the class or namespace to which the
5455     //  qualifier refers (or, in the case of a namespace, of an element of the
5456     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5457     //  thereof; [...]
5458     //
5459     // Note that we already checked the context above, and that we do not have
5460     // enough information to make sure that Previous contains the declaration
5461     // we want to match. For example, given:
5462     //
5463     //   class X {
5464     //     void f();
5465     //     void f(float);
5466     //   };
5467     //
5468     //   void X::f(int) { } // ill-formed
5469     //
5470     // In this case, Previous will point to the overload set
5471     // containing the two f's declared in X, but neither of them
5472     // matches.
5473 
5474     // C++ [dcl.meaning]p1:
5475     //   [...] the member shall not merely have been introduced by a
5476     //   using-declaration in the scope of the class or namespace nominated by
5477     //   the nested-name-specifier of the declarator-id.
5478     RemoveUsingDecls(Previous);
5479   }
5480 
5481   if (Previous.isSingleResult() &&
5482       Previous.getFoundDecl()->isTemplateParameter()) {
5483     // Maybe we will complain about the shadowed template parameter.
5484     if (!D.isInvalidType())
5485       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5486                                       Previous.getFoundDecl());
5487 
5488     // Just pretend that we didn't see the previous declaration.
5489     Previous.clear();
5490   }
5491 
5492   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5493     // Forget that the previous declaration is the injected-class-name.
5494     Previous.clear();
5495 
5496   // In C++, the previous declaration we find might be a tag type
5497   // (class or enum). In this case, the new declaration will hide the
5498   // tag type. Note that this applies to functions, function templates, and
5499   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5500   if (Previous.isSingleTagDecl() &&
5501       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5502       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5503     Previous.clear();
5504 
5505   // Check that there are no default arguments other than in the parameters
5506   // of a function declaration (C++ only).
5507   if (getLangOpts().CPlusPlus)
5508     CheckExtraCXXDefaultArguments(D);
5509 
5510   NamedDecl *New;
5511 
5512   bool AddToScope = true;
5513   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5514     if (TemplateParamLists.size()) {
5515       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5516       return nullptr;
5517     }
5518 
5519     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5520   } else if (R->isFunctionType()) {
5521     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5522                                   TemplateParamLists,
5523                                   AddToScope);
5524   } else {
5525     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5526                                   AddToScope);
5527   }
5528 
5529   if (!New)
5530     return nullptr;
5531 
5532   // If this has an identifier and is not a function template specialization,
5533   // add it to the scope stack.
5534   if (New->getDeclName() && AddToScope) {
5535     // Only make a locally-scoped extern declaration visible if it is the first
5536     // declaration of this entity. Qualified lookup for such an entity should
5537     // only find this declaration if there is no visible declaration of it.
5538     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5539     PushOnScopeChains(New, S, AddToContext);
5540     if (!AddToContext)
5541       CurContext->addHiddenDecl(New);
5542   }
5543 
5544   if (isInOpenMPDeclareTargetContext())
5545     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5546 
5547   return New;
5548 }
5549 
5550 /// Helper method to turn variable array types into constant array
5551 /// types in certain situations which would otherwise be errors (for
5552 /// GCC compatibility).
5553 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5554                                                     ASTContext &Context,
5555                                                     bool &SizeIsNegative,
5556                                                     llvm::APSInt &Oversized) {
5557   // This method tries to turn a variable array into a constant
5558   // array even when the size isn't an ICE.  This is necessary
5559   // for compatibility with code that depends on gcc's buggy
5560   // constant expression folding, like struct {char x[(int)(char*)2];}
5561   SizeIsNegative = false;
5562   Oversized = 0;
5563 
5564   if (T->isDependentType())
5565     return QualType();
5566 
5567   QualifierCollector Qs;
5568   const Type *Ty = Qs.strip(T);
5569 
5570   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5571     QualType Pointee = PTy->getPointeeType();
5572     QualType FixedType =
5573         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5574                                             Oversized);
5575     if (FixedType.isNull()) return FixedType;
5576     FixedType = Context.getPointerType(FixedType);
5577     return Qs.apply(Context, FixedType);
5578   }
5579   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5580     QualType Inner = PTy->getInnerType();
5581     QualType FixedType =
5582         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5583                                             Oversized);
5584     if (FixedType.isNull()) return FixedType;
5585     FixedType = Context.getParenType(FixedType);
5586     return Qs.apply(Context, FixedType);
5587   }
5588 
5589   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5590   if (!VLATy)
5591     return QualType();
5592   // FIXME: We should probably handle this case
5593   if (VLATy->getElementType()->isVariablyModifiedType())
5594     return QualType();
5595 
5596   llvm::APSInt Res;
5597   if (!VLATy->getSizeExpr() ||
5598       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5599     return QualType();
5600 
5601   // Check whether the array size is negative.
5602   if (Res.isSigned() && Res.isNegative()) {
5603     SizeIsNegative = true;
5604     return QualType();
5605   }
5606 
5607   // Check whether the array is too large to be addressed.
5608   unsigned ActiveSizeBits
5609     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5610                                               Res);
5611   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5612     Oversized = Res;
5613     return QualType();
5614   }
5615 
5616   return Context.getConstantArrayType(VLATy->getElementType(),
5617                                       Res, ArrayType::Normal, 0);
5618 }
5619 
5620 static void
5621 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5622   SrcTL = SrcTL.getUnqualifiedLoc();
5623   DstTL = DstTL.getUnqualifiedLoc();
5624   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5625     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5626     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5627                                       DstPTL.getPointeeLoc());
5628     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5629     return;
5630   }
5631   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5632     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5633     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5634                                       DstPTL.getInnerLoc());
5635     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5636     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5637     return;
5638   }
5639   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5640   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5641   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5642   TypeLoc DstElemTL = DstATL.getElementLoc();
5643   DstElemTL.initializeFullCopy(SrcElemTL);
5644   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5645   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5646   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5647 }
5648 
5649 /// Helper method to turn variable array types into constant array
5650 /// types in certain situations which would otherwise be errors (for
5651 /// GCC compatibility).
5652 static TypeSourceInfo*
5653 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5654                                               ASTContext &Context,
5655                                               bool &SizeIsNegative,
5656                                               llvm::APSInt &Oversized) {
5657   QualType FixedTy
5658     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5659                                           SizeIsNegative, Oversized);
5660   if (FixedTy.isNull())
5661     return nullptr;
5662   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5663   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5664                                     FixedTInfo->getTypeLoc());
5665   return FixedTInfo;
5666 }
5667 
5668 /// Register the given locally-scoped extern "C" declaration so
5669 /// that it can be found later for redeclarations. We include any extern "C"
5670 /// declaration that is not visible in the translation unit here, not just
5671 /// function-scope declarations.
5672 void
5673 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5674   if (!getLangOpts().CPlusPlus &&
5675       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5676     // Don't need to track declarations in the TU in C.
5677     return;
5678 
5679   // Note that we have a locally-scoped external with this name.
5680   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5681 }
5682 
5683 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5684   // FIXME: We can have multiple results via __attribute__((overloadable)).
5685   auto Result = Context.getExternCContextDecl()->lookup(Name);
5686   return Result.empty() ? nullptr : *Result.begin();
5687 }
5688 
5689 /// Diagnose function specifiers on a declaration of an identifier that
5690 /// does not identify a function.
5691 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5692   // FIXME: We should probably indicate the identifier in question to avoid
5693   // confusion for constructs like "virtual int a(), b;"
5694   if (DS.isVirtualSpecified())
5695     Diag(DS.getVirtualSpecLoc(),
5696          diag::err_virtual_non_function);
5697 
5698   if (DS.isExplicitSpecified())
5699     Diag(DS.getExplicitSpecLoc(),
5700          diag::err_explicit_non_function);
5701 
5702   if (DS.isNoreturnSpecified())
5703     Diag(DS.getNoreturnSpecLoc(),
5704          diag::err_noreturn_non_function);
5705 }
5706 
5707 NamedDecl*
5708 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5709                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5710   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5711   if (D.getCXXScopeSpec().isSet()) {
5712     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5713       << D.getCXXScopeSpec().getRange();
5714     D.setInvalidType();
5715     // Pretend we didn't see the scope specifier.
5716     DC = CurContext;
5717     Previous.clear();
5718   }
5719 
5720   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5721 
5722   if (D.getDeclSpec().isInlineSpecified())
5723     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5724         << getLangOpts().CPlusPlus17;
5725   if (D.getDeclSpec().isConstexprSpecified())
5726     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5727       << 1;
5728 
5729   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5730     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5731       Diag(D.getName().StartLocation,
5732            diag::err_deduction_guide_invalid_specifier)
5733           << "typedef";
5734     else
5735       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5736           << D.getName().getSourceRange();
5737     return nullptr;
5738   }
5739 
5740   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5741   if (!NewTD) return nullptr;
5742 
5743   // Handle attributes prior to checking for duplicates in MergeVarDecl
5744   ProcessDeclAttributes(S, NewTD, D);
5745 
5746   CheckTypedefForVariablyModifiedType(S, NewTD);
5747 
5748   bool Redeclaration = D.isRedeclaration();
5749   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5750   D.setRedeclaration(Redeclaration);
5751   return ND;
5752 }
5753 
5754 void
5755 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5756   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5757   // then it shall have block scope.
5758   // Note that variably modified types must be fixed before merging the decl so
5759   // that redeclarations will match.
5760   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5761   QualType T = TInfo->getType();
5762   if (T->isVariablyModifiedType()) {
5763     setFunctionHasBranchProtectedScope();
5764 
5765     if (S->getFnParent() == nullptr) {
5766       bool SizeIsNegative;
5767       llvm::APSInt Oversized;
5768       TypeSourceInfo *FixedTInfo =
5769         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5770                                                       SizeIsNegative,
5771                                                       Oversized);
5772       if (FixedTInfo) {
5773         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5774         NewTD->setTypeSourceInfo(FixedTInfo);
5775       } else {
5776         if (SizeIsNegative)
5777           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5778         else if (T->isVariableArrayType())
5779           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5780         else if (Oversized.getBoolValue())
5781           Diag(NewTD->getLocation(), diag::err_array_too_large)
5782             << Oversized.toString(10);
5783         else
5784           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5785         NewTD->setInvalidDecl();
5786       }
5787     }
5788   }
5789 }
5790 
5791 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5792 /// declares a typedef-name, either using the 'typedef' type specifier or via
5793 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5794 NamedDecl*
5795 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5796                            LookupResult &Previous, bool &Redeclaration) {
5797 
5798   // Find the shadowed declaration before filtering for scope.
5799   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5800 
5801   // Merge the decl with the existing one if appropriate. If the decl is
5802   // in an outer scope, it isn't the same thing.
5803   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5804                        /*AllowInlineNamespace*/false);
5805   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5806   if (!Previous.empty()) {
5807     Redeclaration = true;
5808     MergeTypedefNameDecl(S, NewTD, Previous);
5809   }
5810 
5811   if (ShadowedDecl && !Redeclaration)
5812     CheckShadow(NewTD, ShadowedDecl, Previous);
5813 
5814   // If this is the C FILE type, notify the AST context.
5815   if (IdentifierInfo *II = NewTD->getIdentifier())
5816     if (!NewTD->isInvalidDecl() &&
5817         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5818       if (II->isStr("FILE"))
5819         Context.setFILEDecl(NewTD);
5820       else if (II->isStr("jmp_buf"))
5821         Context.setjmp_bufDecl(NewTD);
5822       else if (II->isStr("sigjmp_buf"))
5823         Context.setsigjmp_bufDecl(NewTD);
5824       else if (II->isStr("ucontext_t"))
5825         Context.setucontext_tDecl(NewTD);
5826     }
5827 
5828   return NewTD;
5829 }
5830 
5831 /// Determines whether the given declaration is an out-of-scope
5832 /// previous declaration.
5833 ///
5834 /// This routine should be invoked when name lookup has found a
5835 /// previous declaration (PrevDecl) that is not in the scope where a
5836 /// new declaration by the same name is being introduced. If the new
5837 /// declaration occurs in a local scope, previous declarations with
5838 /// linkage may still be considered previous declarations (C99
5839 /// 6.2.2p4-5, C++ [basic.link]p6).
5840 ///
5841 /// \param PrevDecl the previous declaration found by name
5842 /// lookup
5843 ///
5844 /// \param DC the context in which the new declaration is being
5845 /// declared.
5846 ///
5847 /// \returns true if PrevDecl is an out-of-scope previous declaration
5848 /// for a new delcaration with the same name.
5849 static bool
5850 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5851                                 ASTContext &Context) {
5852   if (!PrevDecl)
5853     return false;
5854 
5855   if (!PrevDecl->hasLinkage())
5856     return false;
5857 
5858   if (Context.getLangOpts().CPlusPlus) {
5859     // C++ [basic.link]p6:
5860     //   If there is a visible declaration of an entity with linkage
5861     //   having the same name and type, ignoring entities declared
5862     //   outside the innermost enclosing namespace scope, the block
5863     //   scope declaration declares that same entity and receives the
5864     //   linkage of the previous declaration.
5865     DeclContext *OuterContext = DC->getRedeclContext();
5866     if (!OuterContext->isFunctionOrMethod())
5867       // This rule only applies to block-scope declarations.
5868       return false;
5869 
5870     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5871     if (PrevOuterContext->isRecord())
5872       // We found a member function: ignore it.
5873       return false;
5874 
5875     // Find the innermost enclosing namespace for the new and
5876     // previous declarations.
5877     OuterContext = OuterContext->getEnclosingNamespaceContext();
5878     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5879 
5880     // The previous declaration is in a different namespace, so it
5881     // isn't the same function.
5882     if (!OuterContext->Equals(PrevOuterContext))
5883       return false;
5884   }
5885 
5886   return true;
5887 }
5888 
5889 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5890   CXXScopeSpec &SS = D.getCXXScopeSpec();
5891   if (!SS.isSet()) return;
5892   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5893 }
5894 
5895 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5896   QualType type = decl->getType();
5897   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5898   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5899     // Various kinds of declaration aren't allowed to be __autoreleasing.
5900     unsigned kind = -1U;
5901     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5902       if (var->hasAttr<BlocksAttr>())
5903         kind = 0; // __block
5904       else if (!var->hasLocalStorage())
5905         kind = 1; // global
5906     } else if (isa<ObjCIvarDecl>(decl)) {
5907       kind = 3; // ivar
5908     } else if (isa<FieldDecl>(decl)) {
5909       kind = 2; // field
5910     }
5911 
5912     if (kind != -1U) {
5913       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5914         << kind;
5915     }
5916   } else if (lifetime == Qualifiers::OCL_None) {
5917     // Try to infer lifetime.
5918     if (!type->isObjCLifetimeType())
5919       return false;
5920 
5921     lifetime = type->getObjCARCImplicitLifetime();
5922     type = Context.getLifetimeQualifiedType(type, lifetime);
5923     decl->setType(type);
5924   }
5925 
5926   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5927     // Thread-local variables cannot have lifetime.
5928     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5929         var->getTLSKind()) {
5930       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5931         << var->getType();
5932       return true;
5933     }
5934   }
5935 
5936   return false;
5937 }
5938 
5939 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5940   // Ensure that an auto decl is deduced otherwise the checks below might cache
5941   // the wrong linkage.
5942   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5943 
5944   // 'weak' only applies to declarations with external linkage.
5945   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5946     if (!ND.isExternallyVisible()) {
5947       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5948       ND.dropAttr<WeakAttr>();
5949     }
5950   }
5951   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5952     if (ND.isExternallyVisible()) {
5953       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5954       ND.dropAttr<WeakRefAttr>();
5955       ND.dropAttr<AliasAttr>();
5956     }
5957   }
5958 
5959   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5960     if (VD->hasInit()) {
5961       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5962         assert(VD->isThisDeclarationADefinition() &&
5963                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5964         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5965         VD->dropAttr<AliasAttr>();
5966       }
5967     }
5968   }
5969 
5970   // 'selectany' only applies to externally visible variable declarations.
5971   // It does not apply to functions.
5972   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5973     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5974       S.Diag(Attr->getLocation(),
5975              diag::err_attribute_selectany_non_extern_data);
5976       ND.dropAttr<SelectAnyAttr>();
5977     }
5978   }
5979 
5980   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5981     // dll attributes require external linkage. Static locals may have external
5982     // linkage but still cannot be explicitly imported or exported.
5983     auto *VD = dyn_cast<VarDecl>(&ND);
5984     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5985       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5986         << &ND << Attr;
5987       ND.setInvalidDecl();
5988     }
5989   }
5990 
5991   // Virtual functions cannot be marked as 'notail'.
5992   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5993     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5994       if (MD->isVirtual()) {
5995         S.Diag(ND.getLocation(),
5996                diag::err_invalid_attribute_on_virtual_function)
5997             << Attr;
5998         ND.dropAttr<NotTailCalledAttr>();
5999       }
6000 }
6001 
6002 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6003                                            NamedDecl *NewDecl,
6004                                            bool IsSpecialization,
6005                                            bool IsDefinition) {
6006   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6007     return;
6008 
6009   bool IsTemplate = false;
6010   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6011     OldDecl = OldTD->getTemplatedDecl();
6012     IsTemplate = true;
6013     if (!IsSpecialization)
6014       IsDefinition = false;
6015   }
6016   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6017     NewDecl = NewTD->getTemplatedDecl();
6018     IsTemplate = true;
6019   }
6020 
6021   if (!OldDecl || !NewDecl)
6022     return;
6023 
6024   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6025   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6026   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6027   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6028 
6029   // dllimport and dllexport are inheritable attributes so we have to exclude
6030   // inherited attribute instances.
6031   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6032                     (NewExportAttr && !NewExportAttr->isInherited());
6033 
6034   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6035   // the only exception being explicit specializations.
6036   // Implicitly generated declarations are also excluded for now because there
6037   // is no other way to switch these to use dllimport or dllexport.
6038   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6039 
6040   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6041     // Allow with a warning for free functions and global variables.
6042     bool JustWarn = false;
6043     if (!OldDecl->isCXXClassMember()) {
6044       auto *VD = dyn_cast<VarDecl>(OldDecl);
6045       if (VD && !VD->getDescribedVarTemplate())
6046         JustWarn = true;
6047       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6048       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6049         JustWarn = true;
6050     }
6051 
6052     // We cannot change a declaration that's been used because IR has already
6053     // been emitted. Dllimported functions will still work though (modulo
6054     // address equality) as they can use the thunk.
6055     if (OldDecl->isUsed())
6056       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6057         JustWarn = false;
6058 
6059     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6060                                : diag::err_attribute_dll_redeclaration;
6061     S.Diag(NewDecl->getLocation(), DiagID)
6062         << NewDecl
6063         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6064     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6065     if (!JustWarn) {
6066       NewDecl->setInvalidDecl();
6067       return;
6068     }
6069   }
6070 
6071   // A redeclaration is not allowed to drop a dllimport attribute, the only
6072   // exceptions being inline function definitions (except for function
6073   // templates), local extern declarations, qualified friend declarations or
6074   // special MSVC extension: in the last case, the declaration is treated as if
6075   // it were marked dllexport.
6076   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6077   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6078   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6079     // Ignore static data because out-of-line definitions are diagnosed
6080     // separately.
6081     IsStaticDataMember = VD->isStaticDataMember();
6082     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6083                    VarDecl::DeclarationOnly;
6084   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6085     IsInline = FD->isInlined();
6086     IsQualifiedFriend = FD->getQualifier() &&
6087                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6088   }
6089 
6090   if (OldImportAttr && !HasNewAttr &&
6091       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6092       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6093     if (IsMicrosoft && IsDefinition) {
6094       S.Diag(NewDecl->getLocation(),
6095              diag::warn_redeclaration_without_import_attribute)
6096           << NewDecl;
6097       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6098       NewDecl->dropAttr<DLLImportAttr>();
6099       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6100           NewImportAttr->getRange(), S.Context,
6101           NewImportAttr->getSpellingListIndex()));
6102     } else {
6103       S.Diag(NewDecl->getLocation(),
6104              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6105           << NewDecl << OldImportAttr;
6106       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6107       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6108       OldDecl->dropAttr<DLLImportAttr>();
6109       NewDecl->dropAttr<DLLImportAttr>();
6110     }
6111   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6112     // In MinGW, seeing a function declared inline drops the dllimport
6113     // attribute.
6114     OldDecl->dropAttr<DLLImportAttr>();
6115     NewDecl->dropAttr<DLLImportAttr>();
6116     S.Diag(NewDecl->getLocation(),
6117            diag::warn_dllimport_dropped_from_inline_function)
6118         << NewDecl << OldImportAttr;
6119   }
6120 
6121   // A specialization of a class template member function is processed here
6122   // since it's a redeclaration. If the parent class is dllexport, the
6123   // specialization inherits that attribute. This doesn't happen automatically
6124   // since the parent class isn't instantiated until later.
6125   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6126     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6127         !NewImportAttr && !NewExportAttr) {
6128       if (const DLLExportAttr *ParentExportAttr =
6129               MD->getParent()->getAttr<DLLExportAttr>()) {
6130         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6131         NewAttr->setInherited(true);
6132         NewDecl->addAttr(NewAttr);
6133       }
6134     }
6135   }
6136 }
6137 
6138 /// Given that we are within the definition of the given function,
6139 /// will that definition behave like C99's 'inline', where the
6140 /// definition is discarded except for optimization purposes?
6141 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6142   // Try to avoid calling GetGVALinkageForFunction.
6143 
6144   // All cases of this require the 'inline' keyword.
6145   if (!FD->isInlined()) return false;
6146 
6147   // This is only possible in C++ with the gnu_inline attribute.
6148   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6149     return false;
6150 
6151   // Okay, go ahead and call the relatively-more-expensive function.
6152   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6153 }
6154 
6155 /// Determine whether a variable is extern "C" prior to attaching
6156 /// an initializer. We can't just call isExternC() here, because that
6157 /// will also compute and cache whether the declaration is externally
6158 /// visible, which might change when we attach the initializer.
6159 ///
6160 /// This can only be used if the declaration is known to not be a
6161 /// redeclaration of an internal linkage declaration.
6162 ///
6163 /// For instance:
6164 ///
6165 ///   auto x = []{};
6166 ///
6167 /// Attaching the initializer here makes this declaration not externally
6168 /// visible, because its type has internal linkage.
6169 ///
6170 /// FIXME: This is a hack.
6171 template<typename T>
6172 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6173   if (S.getLangOpts().CPlusPlus) {
6174     // In C++, the overloadable attribute negates the effects of extern "C".
6175     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6176       return false;
6177 
6178     // So do CUDA's host/device attributes.
6179     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6180                                  D->template hasAttr<CUDAHostAttr>()))
6181       return false;
6182   }
6183   return D->isExternC();
6184 }
6185 
6186 static bool shouldConsiderLinkage(const VarDecl *VD) {
6187   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6188   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
6189     return VD->hasExternalStorage();
6190   if (DC->isFileContext())
6191     return true;
6192   if (DC->isRecord())
6193     return false;
6194   llvm_unreachable("Unexpected context");
6195 }
6196 
6197 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6198   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6199   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6200       isa<OMPDeclareReductionDecl>(DC))
6201     return true;
6202   if (DC->isRecord())
6203     return false;
6204   llvm_unreachable("Unexpected context");
6205 }
6206 
6207 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
6208                           AttributeList::Kind Kind) {
6209   for (const AttributeList *L = AttrList; L; L = L->getNext())
6210     if (L->getKind() == Kind)
6211       return true;
6212   return false;
6213 }
6214 
6215 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6216                           AttributeList::Kind Kind) {
6217   // Check decl attributes on the DeclSpec.
6218   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
6219     return true;
6220 
6221   // Walk the declarator structure, checking decl attributes that were in a type
6222   // position to the decl itself.
6223   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6224     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
6225       return true;
6226   }
6227 
6228   // Finally, check attributes on the decl itself.
6229   return hasParsedAttr(S, PD.getAttributes(), Kind);
6230 }
6231 
6232 /// Adjust the \c DeclContext for a function or variable that might be a
6233 /// function-local external declaration.
6234 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6235   if (!DC->isFunctionOrMethod())
6236     return false;
6237 
6238   // If this is a local extern function or variable declared within a function
6239   // template, don't add it into the enclosing namespace scope until it is
6240   // instantiated; it might have a dependent type right now.
6241   if (DC->isDependentContext())
6242     return true;
6243 
6244   // C++11 [basic.link]p7:
6245   //   When a block scope declaration of an entity with linkage is not found to
6246   //   refer to some other declaration, then that entity is a member of the
6247   //   innermost enclosing namespace.
6248   //
6249   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6250   // semantically-enclosing namespace, not a lexically-enclosing one.
6251   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6252     DC = DC->getParent();
6253   return true;
6254 }
6255 
6256 /// Returns true if given declaration has external C language linkage.
6257 static bool isDeclExternC(const Decl *D) {
6258   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6259     return FD->isExternC();
6260   if (const auto *VD = dyn_cast<VarDecl>(D))
6261     return VD->isExternC();
6262 
6263   llvm_unreachable("Unknown type of decl!");
6264 }
6265 
6266 NamedDecl *Sema::ActOnVariableDeclarator(
6267     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6268     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6269     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6270   QualType R = TInfo->getType();
6271   DeclarationName Name = GetNameForDeclarator(D).getName();
6272 
6273   IdentifierInfo *II = Name.getAsIdentifierInfo();
6274 
6275   if (D.isDecompositionDeclarator()) {
6276     // Take the name of the first declarator as our name for diagnostic
6277     // purposes.
6278     auto &Decomp = D.getDecompositionDeclarator();
6279     if (!Decomp.bindings().empty()) {
6280       II = Decomp.bindings()[0].Name;
6281       Name = II;
6282     }
6283   } else if (!II) {
6284     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6285     return nullptr;
6286   }
6287 
6288   if (getLangOpts().OpenCL) {
6289     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6290     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6291     // argument.
6292     if (R->isImageType() || R->isPipeType()) {
6293       Diag(D.getIdentifierLoc(),
6294            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6295           << R;
6296       D.setInvalidType();
6297       return nullptr;
6298     }
6299 
6300     // OpenCL v1.2 s6.9.r:
6301     // The event type cannot be used to declare a program scope variable.
6302     // OpenCL v2.0 s6.9.q:
6303     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6304     if (NULL == S->getParent()) {
6305       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6306         Diag(D.getIdentifierLoc(),
6307              diag::err_invalid_type_for_program_scope_var) << R;
6308         D.setInvalidType();
6309         return nullptr;
6310       }
6311     }
6312 
6313     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6314     QualType NR = R;
6315     while (NR->isPointerType()) {
6316       if (NR->isFunctionPointerType()) {
6317         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6318         D.setInvalidType();
6319         break;
6320       }
6321       NR = NR->getPointeeType();
6322     }
6323 
6324     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6325       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6326       // half array type (unless the cl_khr_fp16 extension is enabled).
6327       if (Context.getBaseElementType(R)->isHalfType()) {
6328         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6329         D.setInvalidType();
6330       }
6331     }
6332 
6333     if (R->isSamplerT()) {
6334       // OpenCL v1.2 s6.9.b p4:
6335       // The sampler type cannot be used with the __local and __global address
6336       // space qualifiers.
6337       if (R.getAddressSpace() == LangAS::opencl_local ||
6338           R.getAddressSpace() == LangAS::opencl_global) {
6339         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6340       }
6341 
6342       // OpenCL v1.2 s6.12.14.1:
6343       // A global sampler must be declared with either the constant address
6344       // space qualifier or with the const qualifier.
6345       if (DC->isTranslationUnit() &&
6346           !(R.getAddressSpace() == LangAS::opencl_constant ||
6347           R.isConstQualified())) {
6348         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6349         D.setInvalidType();
6350       }
6351     }
6352 
6353     // OpenCL v1.2 s6.9.r:
6354     // The event type cannot be used with the __local, __constant and __global
6355     // address space qualifiers.
6356     if (R->isEventT()) {
6357       if (R.getAddressSpace() != LangAS::opencl_private) {
6358         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6359         D.setInvalidType();
6360       }
6361     }
6362 
6363     // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not
6364     // supported.  OpenCL C does not support thread_local either, and
6365     // also reject all other thread storage class specifiers.
6366     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6367     if (TSC != TSCS_unspecified) {
6368       bool IsCXX = getLangOpts().OpenCLCPlusPlus;
6369       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6370            diag::err_opencl_unknown_type_specifier)
6371           << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
6372           << DeclSpec::getSpecifierName(TSC) << 1;
6373       D.setInvalidType();
6374       return nullptr;
6375     }
6376   }
6377 
6378   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6379   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6380 
6381   // dllimport globals without explicit storage class are treated as extern. We
6382   // have to change the storage class this early to get the right DeclContext.
6383   if (SC == SC_None && !DC->isRecord() &&
6384       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
6385       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
6386     SC = SC_Extern;
6387 
6388   DeclContext *OriginalDC = DC;
6389   bool IsLocalExternDecl = SC == SC_Extern &&
6390                            adjustContextForLocalExternDecl(DC);
6391 
6392   if (SCSpec == DeclSpec::SCS_mutable) {
6393     // mutable can only appear on non-static class members, so it's always
6394     // an error here
6395     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6396     D.setInvalidType();
6397     SC = SC_None;
6398   }
6399 
6400   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6401       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6402                               D.getDeclSpec().getStorageClassSpecLoc())) {
6403     // In C++11, the 'register' storage class specifier is deprecated.
6404     // Suppress the warning in system macros, it's used in macros in some
6405     // popular C system headers, such as in glibc's htonl() macro.
6406     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6407          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6408                                    : diag::warn_deprecated_register)
6409       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6410   }
6411 
6412   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6413 
6414   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6415     // C99 6.9p2: The storage-class specifiers auto and register shall not
6416     // appear in the declaration specifiers in an external declaration.
6417     // Global Register+Asm is a GNU extension we support.
6418     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6419       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6420       D.setInvalidType();
6421     }
6422   }
6423 
6424   bool IsMemberSpecialization = false;
6425   bool IsVariableTemplateSpecialization = false;
6426   bool IsPartialSpecialization = false;
6427   bool IsVariableTemplate = false;
6428   VarDecl *NewVD = nullptr;
6429   VarTemplateDecl *NewTemplate = nullptr;
6430   TemplateParameterList *TemplateParams = nullptr;
6431   if (!getLangOpts().CPlusPlus) {
6432     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6433                             D.getIdentifierLoc(), II,
6434                             R, TInfo, SC);
6435 
6436     if (R->getContainedDeducedType())
6437       ParsingInitForAutoVars.insert(NewVD);
6438 
6439     if (D.isInvalidType())
6440       NewVD->setInvalidDecl();
6441   } else {
6442     bool Invalid = false;
6443 
6444     if (DC->isRecord() && !CurContext->isRecord()) {
6445       // This is an out-of-line definition of a static data member.
6446       switch (SC) {
6447       case SC_None:
6448         break;
6449       case SC_Static:
6450         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6451              diag::err_static_out_of_line)
6452           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6453         break;
6454       case SC_Auto:
6455       case SC_Register:
6456       case SC_Extern:
6457         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6458         // to names of variables declared in a block or to function parameters.
6459         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6460         // of class members
6461 
6462         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6463              diag::err_storage_class_for_static_member)
6464           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6465         break;
6466       case SC_PrivateExtern:
6467         llvm_unreachable("C storage class in c++!");
6468       }
6469     }
6470 
6471     if (SC == SC_Static && CurContext->isRecord()) {
6472       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6473         if (RD->isLocalClass())
6474           Diag(D.getIdentifierLoc(),
6475                diag::err_static_data_member_not_allowed_in_local_class)
6476             << Name << RD->getDeclName();
6477 
6478         // C++98 [class.union]p1: If a union contains a static data member,
6479         // the program is ill-formed. C++11 drops this restriction.
6480         if (RD->isUnion())
6481           Diag(D.getIdentifierLoc(),
6482                getLangOpts().CPlusPlus11
6483                  ? diag::warn_cxx98_compat_static_data_member_in_union
6484                  : diag::ext_static_data_member_in_union) << Name;
6485         // We conservatively disallow static data members in anonymous structs.
6486         else if (!RD->getDeclName())
6487           Diag(D.getIdentifierLoc(),
6488                diag::err_static_data_member_not_allowed_in_anon_struct)
6489             << Name << RD->isUnion();
6490       }
6491     }
6492 
6493     // Match up the template parameter lists with the scope specifier, then
6494     // determine whether we have a template or a template specialization.
6495     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6496         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6497         D.getCXXScopeSpec(),
6498         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6499             ? D.getName().TemplateId
6500             : nullptr,
6501         TemplateParamLists,
6502         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6503 
6504     if (TemplateParams) {
6505       if (!TemplateParams->size() &&
6506           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6507         // There is an extraneous 'template<>' for this variable. Complain
6508         // about it, but allow the declaration of the variable.
6509         Diag(TemplateParams->getTemplateLoc(),
6510              diag::err_template_variable_noparams)
6511           << II
6512           << SourceRange(TemplateParams->getTemplateLoc(),
6513                          TemplateParams->getRAngleLoc());
6514         TemplateParams = nullptr;
6515       } else {
6516         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6517           // This is an explicit specialization or a partial specialization.
6518           // FIXME: Check that we can declare a specialization here.
6519           IsVariableTemplateSpecialization = true;
6520           IsPartialSpecialization = TemplateParams->size() > 0;
6521         } else { // if (TemplateParams->size() > 0)
6522           // This is a template declaration.
6523           IsVariableTemplate = true;
6524 
6525           // Check that we can declare a template here.
6526           if (CheckTemplateDeclScope(S, TemplateParams))
6527             return nullptr;
6528 
6529           // Only C++1y supports variable templates (N3651).
6530           Diag(D.getIdentifierLoc(),
6531                getLangOpts().CPlusPlus14
6532                    ? diag::warn_cxx11_compat_variable_template
6533                    : diag::ext_variable_template);
6534         }
6535       }
6536     } else {
6537       assert((Invalid ||
6538               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6539              "should have a 'template<>' for this decl");
6540     }
6541 
6542     if (IsVariableTemplateSpecialization) {
6543       SourceLocation TemplateKWLoc =
6544           TemplateParamLists.size() > 0
6545               ? TemplateParamLists[0]->getTemplateLoc()
6546               : SourceLocation();
6547       DeclResult Res = ActOnVarTemplateSpecialization(
6548           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6549           IsPartialSpecialization);
6550       if (Res.isInvalid())
6551         return nullptr;
6552       NewVD = cast<VarDecl>(Res.get());
6553       AddToScope = false;
6554     } else if (D.isDecompositionDeclarator()) {
6555       NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6556                                         D.getIdentifierLoc(), R, TInfo, SC,
6557                                         Bindings);
6558     } else
6559       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6560                               D.getIdentifierLoc(), II, R, TInfo, SC);
6561 
6562     // If this is supposed to be a variable template, create it as such.
6563     if (IsVariableTemplate) {
6564       NewTemplate =
6565           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6566                                   TemplateParams, NewVD);
6567       NewVD->setDescribedVarTemplate(NewTemplate);
6568     }
6569 
6570     // If this decl has an auto type in need of deduction, make a note of the
6571     // Decl so we can diagnose uses of it in its own initializer.
6572     if (R->getContainedDeducedType())
6573       ParsingInitForAutoVars.insert(NewVD);
6574 
6575     if (D.isInvalidType() || Invalid) {
6576       NewVD->setInvalidDecl();
6577       if (NewTemplate)
6578         NewTemplate->setInvalidDecl();
6579     }
6580 
6581     SetNestedNameSpecifier(NewVD, D);
6582 
6583     // If we have any template parameter lists that don't directly belong to
6584     // the variable (matching the scope specifier), store them.
6585     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6586     if (TemplateParamLists.size() > VDTemplateParamLists)
6587       NewVD->setTemplateParameterListsInfo(
6588           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6589 
6590     if (D.getDeclSpec().isConstexprSpecified()) {
6591       NewVD->setConstexpr(true);
6592       // C++1z [dcl.spec.constexpr]p1:
6593       //   A static data member declared with the constexpr specifier is
6594       //   implicitly an inline variable.
6595       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
6596         NewVD->setImplicitlyInline();
6597     }
6598   }
6599 
6600   if (D.getDeclSpec().isInlineSpecified()) {
6601     if (!getLangOpts().CPlusPlus) {
6602       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6603           << 0;
6604     } else if (CurContext->isFunctionOrMethod()) {
6605       // 'inline' is not allowed on block scope variable declaration.
6606       Diag(D.getDeclSpec().getInlineSpecLoc(),
6607            diag::err_inline_declaration_block_scope) << Name
6608         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6609     } else {
6610       Diag(D.getDeclSpec().getInlineSpecLoc(),
6611            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6612                                      : diag::ext_inline_variable);
6613       NewVD->setInlineSpecified();
6614     }
6615   }
6616 
6617   // Set the lexical context. If the declarator has a C++ scope specifier, the
6618   // lexical context will be different from the semantic context.
6619   NewVD->setLexicalDeclContext(CurContext);
6620   if (NewTemplate)
6621     NewTemplate->setLexicalDeclContext(CurContext);
6622 
6623   if (IsLocalExternDecl) {
6624     if (D.isDecompositionDeclarator())
6625       for (auto *B : Bindings)
6626         B->setLocalExternDecl();
6627     else
6628       NewVD->setLocalExternDecl();
6629   }
6630 
6631   bool EmitTLSUnsupportedError = false;
6632   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6633     // C++11 [dcl.stc]p4:
6634     //   When thread_local is applied to a variable of block scope the
6635     //   storage-class-specifier static is implied if it does not appear
6636     //   explicitly.
6637     // Core issue: 'static' is not implied if the variable is declared
6638     //   'extern'.
6639     if (NewVD->hasLocalStorage() &&
6640         (SCSpec != DeclSpec::SCS_unspecified ||
6641          TSCS != DeclSpec::TSCS_thread_local ||
6642          !DC->isFunctionOrMethod()))
6643       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6644            diag::err_thread_non_global)
6645         << DeclSpec::getSpecifierName(TSCS);
6646     else if (!Context.getTargetInfo().isTLSSupported()) {
6647       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6648         // Postpone error emission until we've collected attributes required to
6649         // figure out whether it's a host or device variable and whether the
6650         // error should be ignored.
6651         EmitTLSUnsupportedError = true;
6652         // We still need to mark the variable as TLS so it shows up in AST with
6653         // proper storage class for other tools to use even if we're not going
6654         // to emit any code for it.
6655         NewVD->setTSCSpec(TSCS);
6656       } else
6657         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6658              diag::err_thread_unsupported);
6659     } else
6660       NewVD->setTSCSpec(TSCS);
6661   }
6662 
6663   // C99 6.7.4p3
6664   //   An inline definition of a function with external linkage shall
6665   //   not contain a definition of a modifiable object with static or
6666   //   thread storage duration...
6667   // We only apply this when the function is required to be defined
6668   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6669   // that a local variable with thread storage duration still has to
6670   // be marked 'static'.  Also note that it's possible to get these
6671   // semantics in C++ using __attribute__((gnu_inline)).
6672   if (SC == SC_Static && S->getFnParent() != nullptr &&
6673       !NewVD->getType().isConstQualified()) {
6674     FunctionDecl *CurFD = getCurFunctionDecl();
6675     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6676       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6677            diag::warn_static_local_in_extern_inline);
6678       MaybeSuggestAddingStaticToDecl(CurFD);
6679     }
6680   }
6681 
6682   if (D.getDeclSpec().isModulePrivateSpecified()) {
6683     if (IsVariableTemplateSpecialization)
6684       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6685           << (IsPartialSpecialization ? 1 : 0)
6686           << FixItHint::CreateRemoval(
6687                  D.getDeclSpec().getModulePrivateSpecLoc());
6688     else if (IsMemberSpecialization)
6689       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6690         << 2
6691         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6692     else if (NewVD->hasLocalStorage())
6693       Diag(NewVD->getLocation(), diag::err_module_private_local)
6694         << 0 << NewVD->getDeclName()
6695         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6696         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6697     else {
6698       NewVD->setModulePrivate();
6699       if (NewTemplate)
6700         NewTemplate->setModulePrivate();
6701       for (auto *B : Bindings)
6702         B->setModulePrivate();
6703     }
6704   }
6705 
6706   // Handle attributes prior to checking for duplicates in MergeVarDecl
6707   ProcessDeclAttributes(S, NewVD, D);
6708 
6709   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6710     if (EmitTLSUnsupportedError &&
6711         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6712          (getLangOpts().OpenMPIsDevice &&
6713           NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6714       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6715            diag::err_thread_unsupported);
6716     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6717     // storage [duration]."
6718     if (SC == SC_None && S->getFnParent() != nullptr &&
6719         (NewVD->hasAttr<CUDASharedAttr>() ||
6720          NewVD->hasAttr<CUDAConstantAttr>())) {
6721       NewVD->setStorageClass(SC_Static);
6722     }
6723   }
6724 
6725   // Ensure that dllimport globals without explicit storage class are treated as
6726   // extern. The storage class is set above using parsed attributes. Now we can
6727   // check the VarDecl itself.
6728   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6729          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6730          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6731 
6732   // In auto-retain/release, infer strong retension for variables of
6733   // retainable type.
6734   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6735     NewVD->setInvalidDecl();
6736 
6737   // Handle GNU asm-label extension (encoded as an attribute).
6738   if (Expr *E = (Expr*)D.getAsmLabel()) {
6739     // The parser guarantees this is a string.
6740     StringLiteral *SE = cast<StringLiteral>(E);
6741     StringRef Label = SE->getString();
6742     if (S->getFnParent() != nullptr) {
6743       switch (SC) {
6744       case SC_None:
6745       case SC_Auto:
6746         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6747         break;
6748       case SC_Register:
6749         // Local Named register
6750         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6751             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6752           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6753         break;
6754       case SC_Static:
6755       case SC_Extern:
6756       case SC_PrivateExtern:
6757         break;
6758       }
6759     } else if (SC == SC_Register) {
6760       // Global Named register
6761       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6762         const auto &TI = Context.getTargetInfo();
6763         bool HasSizeMismatch;
6764 
6765         if (!TI.isValidGCCRegisterName(Label))
6766           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6767         else if (!TI.validateGlobalRegisterVariable(Label,
6768                                                     Context.getTypeSize(R),
6769                                                     HasSizeMismatch))
6770           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6771         else if (HasSizeMismatch)
6772           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6773       }
6774 
6775       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6776         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6777         NewVD->setInvalidDecl(true);
6778       }
6779     }
6780 
6781     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6782                                                 Context, Label, 0));
6783   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6784     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6785       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6786     if (I != ExtnameUndeclaredIdentifiers.end()) {
6787       if (isDeclExternC(NewVD)) {
6788         NewVD->addAttr(I->second);
6789         ExtnameUndeclaredIdentifiers.erase(I);
6790       } else
6791         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6792             << /*Variable*/1 << NewVD;
6793     }
6794   }
6795 
6796   // Find the shadowed declaration before filtering for scope.
6797   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6798                                 ? getShadowedDeclaration(NewVD, Previous)
6799                                 : nullptr;
6800 
6801   // Don't consider existing declarations that are in a different
6802   // scope and are out-of-semantic-context declarations (if the new
6803   // declaration has linkage).
6804   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6805                        D.getCXXScopeSpec().isNotEmpty() ||
6806                        IsMemberSpecialization ||
6807                        IsVariableTemplateSpecialization);
6808 
6809   // Check whether the previous declaration is in the same block scope. This
6810   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6811   if (getLangOpts().CPlusPlus &&
6812       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6813     NewVD->setPreviousDeclInSameBlockScope(
6814         Previous.isSingleResult() && !Previous.isShadowed() &&
6815         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6816 
6817   if (!getLangOpts().CPlusPlus) {
6818     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6819   } else {
6820     // If this is an explicit specialization of a static data member, check it.
6821     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6822         CheckMemberSpecialization(NewVD, Previous))
6823       NewVD->setInvalidDecl();
6824 
6825     // Merge the decl with the existing one if appropriate.
6826     if (!Previous.empty()) {
6827       if (Previous.isSingleResult() &&
6828           isa<FieldDecl>(Previous.getFoundDecl()) &&
6829           D.getCXXScopeSpec().isSet()) {
6830         // The user tried to define a non-static data member
6831         // out-of-line (C++ [dcl.meaning]p1).
6832         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6833           << D.getCXXScopeSpec().getRange();
6834         Previous.clear();
6835         NewVD->setInvalidDecl();
6836       }
6837     } else if (D.getCXXScopeSpec().isSet()) {
6838       // No previous declaration in the qualifying scope.
6839       Diag(D.getIdentifierLoc(), diag::err_no_member)
6840         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6841         << D.getCXXScopeSpec().getRange();
6842       NewVD->setInvalidDecl();
6843     }
6844 
6845     if (!IsVariableTemplateSpecialization)
6846       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6847 
6848     if (NewTemplate) {
6849       VarTemplateDecl *PrevVarTemplate =
6850           NewVD->getPreviousDecl()
6851               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6852               : nullptr;
6853 
6854       // Check the template parameter list of this declaration, possibly
6855       // merging in the template parameter list from the previous variable
6856       // template declaration.
6857       if (CheckTemplateParameterList(
6858               TemplateParams,
6859               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6860                               : nullptr,
6861               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6862                DC->isDependentContext())
6863                   ? TPC_ClassTemplateMember
6864                   : TPC_VarTemplate))
6865         NewVD->setInvalidDecl();
6866 
6867       // If we are providing an explicit specialization of a static variable
6868       // template, make a note of that.
6869       if (PrevVarTemplate &&
6870           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6871         PrevVarTemplate->setMemberSpecialization();
6872     }
6873   }
6874 
6875   // Diagnose shadowed variables iff this isn't a redeclaration.
6876   if (ShadowedDecl && !D.isRedeclaration())
6877     CheckShadow(NewVD, ShadowedDecl, Previous);
6878 
6879   ProcessPragmaWeak(S, NewVD);
6880 
6881   // If this is the first declaration of an extern C variable, update
6882   // the map of such variables.
6883   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6884       isIncompleteDeclExternC(*this, NewVD))
6885     RegisterLocallyScopedExternCDecl(NewVD, S);
6886 
6887   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6888     Decl *ManglingContextDecl;
6889     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6890             NewVD->getDeclContext(), ManglingContextDecl)) {
6891       Context.setManglingNumber(
6892           NewVD, MCtx->getManglingNumber(
6893                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6894       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6895     }
6896   }
6897 
6898   // Special handling of variable named 'main'.
6899   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6900       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6901       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6902 
6903     // C++ [basic.start.main]p3
6904     // A program that declares a variable main at global scope is ill-formed.
6905     if (getLangOpts().CPlusPlus)
6906       Diag(D.getLocStart(), diag::err_main_global_variable);
6907 
6908     // In C, and external-linkage variable named main results in undefined
6909     // behavior.
6910     else if (NewVD->hasExternalFormalLinkage())
6911       Diag(D.getLocStart(), diag::warn_main_redefined);
6912   }
6913 
6914   if (D.isRedeclaration() && !Previous.empty()) {
6915     NamedDecl *Prev = Previous.getRepresentativeDecl();
6916     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
6917                                    D.isFunctionDefinition());
6918   }
6919 
6920   if (NewTemplate) {
6921     if (NewVD->isInvalidDecl())
6922       NewTemplate->setInvalidDecl();
6923     ActOnDocumentableDecl(NewTemplate);
6924     return NewTemplate;
6925   }
6926 
6927   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6928     CompleteMemberSpecialization(NewVD, Previous);
6929 
6930   return NewVD;
6931 }
6932 
6933 /// Enum describing the %select options in diag::warn_decl_shadow.
6934 enum ShadowedDeclKind {
6935   SDK_Local,
6936   SDK_Global,
6937   SDK_StaticMember,
6938   SDK_Field,
6939   SDK_Typedef,
6940   SDK_Using
6941 };
6942 
6943 /// Determine what kind of declaration we're shadowing.
6944 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6945                                                 const DeclContext *OldDC) {
6946   if (isa<TypeAliasDecl>(ShadowedDecl))
6947     return SDK_Using;
6948   else if (isa<TypedefDecl>(ShadowedDecl))
6949     return SDK_Typedef;
6950   else if (isa<RecordDecl>(OldDC))
6951     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6952 
6953   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6954 }
6955 
6956 /// Return the location of the capture if the given lambda captures the given
6957 /// variable \p VD, or an invalid source location otherwise.
6958 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6959                                          const VarDecl *VD) {
6960   for (const Capture &Capture : LSI->Captures) {
6961     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6962       return Capture.getLocation();
6963   }
6964   return SourceLocation();
6965 }
6966 
6967 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6968                                      const LookupResult &R) {
6969   // Only diagnose if we're shadowing an unambiguous field or variable.
6970   if (R.getResultKind() != LookupResult::Found)
6971     return false;
6972 
6973   // Return false if warning is ignored.
6974   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6975 }
6976 
6977 /// Return the declaration shadowed by the given variable \p D, or null
6978 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6979 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6980                                         const LookupResult &R) {
6981   if (!shouldWarnIfShadowedDecl(Diags, R))
6982     return nullptr;
6983 
6984   // Don't diagnose declarations at file scope.
6985   if (D->hasGlobalStorage())
6986     return nullptr;
6987 
6988   NamedDecl *ShadowedDecl = R.getFoundDecl();
6989   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6990              ? ShadowedDecl
6991              : nullptr;
6992 }
6993 
6994 /// Return the declaration shadowed by the given typedef \p D, or null
6995 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6996 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
6997                                         const LookupResult &R) {
6998   // Don't warn if typedef declaration is part of a class
6999   if (D->getDeclContext()->isRecord())
7000     return nullptr;
7001 
7002   if (!shouldWarnIfShadowedDecl(Diags, R))
7003     return nullptr;
7004 
7005   NamedDecl *ShadowedDecl = R.getFoundDecl();
7006   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7007 }
7008 
7009 /// Diagnose variable or built-in function shadowing.  Implements
7010 /// -Wshadow.
7011 ///
7012 /// This method is called whenever a VarDecl is added to a "useful"
7013 /// scope.
7014 ///
7015 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7016 /// \param R the lookup of the name
7017 ///
7018 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7019                        const LookupResult &R) {
7020   DeclContext *NewDC = D->getDeclContext();
7021 
7022   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7023     // Fields are not shadowed by variables in C++ static methods.
7024     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7025       if (MD->isStatic())
7026         return;
7027 
7028     // Fields shadowed by constructor parameters are a special case. Usually
7029     // the constructor initializes the field with the parameter.
7030     if (isa<CXXConstructorDecl>(NewDC))
7031       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7032         // Remember that this was shadowed so we can either warn about its
7033         // modification or its existence depending on warning settings.
7034         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7035         return;
7036       }
7037   }
7038 
7039   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7040     if (shadowedVar->isExternC()) {
7041       // For shadowing external vars, make sure that we point to the global
7042       // declaration, not a locally scoped extern declaration.
7043       for (auto I : shadowedVar->redecls())
7044         if (I->isFileVarDecl()) {
7045           ShadowedDecl = I;
7046           break;
7047         }
7048     }
7049 
7050   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7051 
7052   unsigned WarningDiag = diag::warn_decl_shadow;
7053   SourceLocation CaptureLoc;
7054   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7055       isa<CXXMethodDecl>(NewDC)) {
7056     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7057       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7058         if (RD->getLambdaCaptureDefault() == LCD_None) {
7059           // Try to avoid warnings for lambdas with an explicit capture list.
7060           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7061           // Warn only when the lambda captures the shadowed decl explicitly.
7062           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7063           if (CaptureLoc.isInvalid())
7064             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7065         } else {
7066           // Remember that this was shadowed so we can avoid the warning if the
7067           // shadowed decl isn't captured and the warning settings allow it.
7068           cast<LambdaScopeInfo>(getCurFunction())
7069               ->ShadowingDecls.push_back(
7070                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7071           return;
7072         }
7073       }
7074 
7075       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7076         // A variable can't shadow a local variable in an enclosing scope, if
7077         // they are separated by a non-capturing declaration context.
7078         for (DeclContext *ParentDC = NewDC;
7079              ParentDC && !ParentDC->Equals(OldDC);
7080              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7081           // Only block literals, captured statements, and lambda expressions
7082           // can capture; other scopes don't.
7083           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7084               !isLambdaCallOperator(ParentDC)) {
7085             return;
7086           }
7087         }
7088       }
7089     }
7090   }
7091 
7092   // Only warn about certain kinds of shadowing for class members.
7093   if (NewDC && NewDC->isRecord()) {
7094     // In particular, don't warn about shadowing non-class members.
7095     if (!OldDC->isRecord())
7096       return;
7097 
7098     // TODO: should we warn about static data members shadowing
7099     // static data members from base classes?
7100 
7101     // TODO: don't diagnose for inaccessible shadowed members.
7102     // This is hard to do perfectly because we might friend the
7103     // shadowing context, but that's just a false negative.
7104   }
7105 
7106 
7107   DeclarationName Name = R.getLookupName();
7108 
7109   // Emit warning and note.
7110   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7111     return;
7112   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7113   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7114   if (!CaptureLoc.isInvalid())
7115     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7116         << Name << /*explicitly*/ 1;
7117   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7118 }
7119 
7120 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7121 /// when these variables are captured by the lambda.
7122 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7123   for (const auto &Shadow : LSI->ShadowingDecls) {
7124     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7125     // Try to avoid the warning when the shadowed decl isn't captured.
7126     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7127     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7128     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7129                                        ? diag::warn_decl_shadow_uncaptured_local
7130                                        : diag::warn_decl_shadow)
7131         << Shadow.VD->getDeclName()
7132         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7133     if (!CaptureLoc.isInvalid())
7134       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7135           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7136     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7137   }
7138 }
7139 
7140 /// Check -Wshadow without the advantage of a previous lookup.
7141 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7142   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7143     return;
7144 
7145   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7146                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7147   LookupName(R, S);
7148   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7149     CheckShadow(D, ShadowedDecl, R);
7150 }
7151 
7152 /// Check if 'E', which is an expression that is about to be modified, refers
7153 /// to a constructor parameter that shadows a field.
7154 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7155   // Quickly ignore expressions that can't be shadowing ctor parameters.
7156   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7157     return;
7158   E = E->IgnoreParenImpCasts();
7159   auto *DRE = dyn_cast<DeclRefExpr>(E);
7160   if (!DRE)
7161     return;
7162   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7163   auto I = ShadowingDecls.find(D);
7164   if (I == ShadowingDecls.end())
7165     return;
7166   const NamedDecl *ShadowedDecl = I->second;
7167   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7168   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7169   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7170   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7171 
7172   // Avoid issuing multiple warnings about the same decl.
7173   ShadowingDecls.erase(I);
7174 }
7175 
7176 /// Check for conflict between this global or extern "C" declaration and
7177 /// previous global or extern "C" declarations. This is only used in C++.
7178 template<typename T>
7179 static bool checkGlobalOrExternCConflict(
7180     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7181   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7182   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7183 
7184   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7185     // The common case: this global doesn't conflict with any extern "C"
7186     // declaration.
7187     return false;
7188   }
7189 
7190   if (Prev) {
7191     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7192       // Both the old and new declarations have C language linkage. This is a
7193       // redeclaration.
7194       Previous.clear();
7195       Previous.addDecl(Prev);
7196       return true;
7197     }
7198 
7199     // This is a global, non-extern "C" declaration, and there is a previous
7200     // non-global extern "C" declaration. Diagnose if this is a variable
7201     // declaration.
7202     if (!isa<VarDecl>(ND))
7203       return false;
7204   } else {
7205     // The declaration is extern "C". Check for any declaration in the
7206     // translation unit which might conflict.
7207     if (IsGlobal) {
7208       // We have already performed the lookup into the translation unit.
7209       IsGlobal = false;
7210       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7211            I != E; ++I) {
7212         if (isa<VarDecl>(*I)) {
7213           Prev = *I;
7214           break;
7215         }
7216       }
7217     } else {
7218       DeclContext::lookup_result R =
7219           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7220       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7221            I != E; ++I) {
7222         if (isa<VarDecl>(*I)) {
7223           Prev = *I;
7224           break;
7225         }
7226         // FIXME: If we have any other entity with this name in global scope,
7227         // the declaration is ill-formed, but that is a defect: it breaks the
7228         // 'stat' hack, for instance. Only variables can have mangled name
7229         // clashes with extern "C" declarations, so only they deserve a
7230         // diagnostic.
7231       }
7232     }
7233 
7234     if (!Prev)
7235       return false;
7236   }
7237 
7238   // Use the first declaration's location to ensure we point at something which
7239   // is lexically inside an extern "C" linkage-spec.
7240   assert(Prev && "should have found a previous declaration to diagnose");
7241   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7242     Prev = FD->getFirstDecl();
7243   else
7244     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7245 
7246   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7247     << IsGlobal << ND;
7248   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7249     << IsGlobal;
7250   return false;
7251 }
7252 
7253 /// Apply special rules for handling extern "C" declarations. Returns \c true
7254 /// if we have found that this is a redeclaration of some prior entity.
7255 ///
7256 /// Per C++ [dcl.link]p6:
7257 ///   Two declarations [for a function or variable] with C language linkage
7258 ///   with the same name that appear in different scopes refer to the same
7259 ///   [entity]. An entity with C language linkage shall not be declared with
7260 ///   the same name as an entity in global scope.
7261 template<typename T>
7262 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7263                                                   LookupResult &Previous) {
7264   if (!S.getLangOpts().CPlusPlus) {
7265     // In C, when declaring a global variable, look for a corresponding 'extern'
7266     // variable declared in function scope. We don't need this in C++, because
7267     // we find local extern decls in the surrounding file-scope DeclContext.
7268     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7269       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7270         Previous.clear();
7271         Previous.addDecl(Prev);
7272         return true;
7273       }
7274     }
7275     return false;
7276   }
7277 
7278   // A declaration in the translation unit can conflict with an extern "C"
7279   // declaration.
7280   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7281     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7282 
7283   // An extern "C" declaration can conflict with a declaration in the
7284   // translation unit or can be a redeclaration of an extern "C" declaration
7285   // in another scope.
7286   if (isIncompleteDeclExternC(S,ND))
7287     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7288 
7289   // Neither global nor extern "C": nothing to do.
7290   return false;
7291 }
7292 
7293 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7294   // If the decl is already known invalid, don't check it.
7295   if (NewVD->isInvalidDecl())
7296     return;
7297 
7298   QualType T = NewVD->getType();
7299 
7300   // Defer checking an 'auto' type until its initializer is attached.
7301   if (T->isUndeducedType())
7302     return;
7303 
7304   if (NewVD->hasAttrs())
7305     CheckAlignasUnderalignment(NewVD);
7306 
7307   if (T->isObjCObjectType()) {
7308     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7309       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7310     T = Context.getObjCObjectPointerType(T);
7311     NewVD->setType(T);
7312   }
7313 
7314   // Emit an error if an address space was applied to decl with local storage.
7315   // This includes arrays of objects with address space qualifiers, but not
7316   // automatic variables that point to other address spaces.
7317   // ISO/IEC TR 18037 S5.1.2
7318   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7319       T.getAddressSpace() != LangAS::Default) {
7320     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7321     NewVD->setInvalidDecl();
7322     return;
7323   }
7324 
7325   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7326   // scope.
7327   if (getLangOpts().OpenCLVersion == 120 &&
7328       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7329       NewVD->isStaticLocal()) {
7330     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7331     NewVD->setInvalidDecl();
7332     return;
7333   }
7334 
7335   if (getLangOpts().OpenCL) {
7336     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7337     if (NewVD->hasAttr<BlocksAttr>()) {
7338       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7339       return;
7340     }
7341 
7342     if (T->isBlockPointerType()) {
7343       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7344       // can't use 'extern' storage class.
7345       if (!T.isConstQualified()) {
7346         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7347             << 0 /*const*/;
7348         NewVD->setInvalidDecl();
7349         return;
7350       }
7351       if (NewVD->hasExternalStorage()) {
7352         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7353         NewVD->setInvalidDecl();
7354         return;
7355       }
7356     }
7357     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7358     // __constant address space.
7359     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7360     // variables inside a function can also be declared in the global
7361     // address space.
7362     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7363         NewVD->hasExternalStorage()) {
7364       if (!T->isSamplerT() &&
7365           !(T.getAddressSpace() == LangAS::opencl_constant ||
7366             (T.getAddressSpace() == LangAS::opencl_global &&
7367              getLangOpts().OpenCLVersion == 200))) {
7368         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7369         if (getLangOpts().OpenCLVersion == 200)
7370           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7371               << Scope << "global or constant";
7372         else
7373           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7374               << Scope << "constant";
7375         NewVD->setInvalidDecl();
7376         return;
7377       }
7378     } else {
7379       if (T.getAddressSpace() == LangAS::opencl_global) {
7380         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7381             << 1 /*is any function*/ << "global";
7382         NewVD->setInvalidDecl();
7383         return;
7384       }
7385       if (T.getAddressSpace() == LangAS::opencl_constant ||
7386           T.getAddressSpace() == LangAS::opencl_local) {
7387         FunctionDecl *FD = getCurFunctionDecl();
7388         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7389         // in functions.
7390         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7391           if (T.getAddressSpace() == LangAS::opencl_constant)
7392             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7393                 << 0 /*non-kernel only*/ << "constant";
7394           else
7395             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7396                 << 0 /*non-kernel only*/ << "local";
7397           NewVD->setInvalidDecl();
7398           return;
7399         }
7400         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7401         // in the outermost scope of a kernel function.
7402         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7403           if (!getCurScope()->isFunctionScope()) {
7404             if (T.getAddressSpace() == LangAS::opencl_constant)
7405               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7406                   << "constant";
7407             else
7408               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7409                   << "local";
7410             NewVD->setInvalidDecl();
7411             return;
7412           }
7413         }
7414       } else if (T.getAddressSpace() != LangAS::opencl_private) {
7415         // Do not allow other address spaces on automatic variable.
7416         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7417         NewVD->setInvalidDecl();
7418         return;
7419       }
7420     }
7421   }
7422 
7423   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7424       && !NewVD->hasAttr<BlocksAttr>()) {
7425     if (getLangOpts().getGC() != LangOptions::NonGC)
7426       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7427     else {
7428       assert(!getLangOpts().ObjCAutoRefCount);
7429       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7430     }
7431   }
7432 
7433   bool isVM = T->isVariablyModifiedType();
7434   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7435       NewVD->hasAttr<BlocksAttr>())
7436     setFunctionHasBranchProtectedScope();
7437 
7438   if ((isVM && NewVD->hasLinkage()) ||
7439       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7440     bool SizeIsNegative;
7441     llvm::APSInt Oversized;
7442     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7443         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7444     QualType FixedT;
7445     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7446       FixedT = FixedTInfo->getType();
7447     else if (FixedTInfo) {
7448       // Type and type-as-written are canonically different. We need to fix up
7449       // both types separately.
7450       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7451                                                    Oversized);
7452     }
7453     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7454       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7455       // FIXME: This won't give the correct result for
7456       // int a[10][n];
7457       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7458 
7459       if (NewVD->isFileVarDecl())
7460         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7461         << SizeRange;
7462       else if (NewVD->isStaticLocal())
7463         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7464         << SizeRange;
7465       else
7466         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7467         << SizeRange;
7468       NewVD->setInvalidDecl();
7469       return;
7470     }
7471 
7472     if (!FixedTInfo) {
7473       if (NewVD->isFileVarDecl())
7474         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7475       else
7476         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7477       NewVD->setInvalidDecl();
7478       return;
7479     }
7480 
7481     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7482     NewVD->setType(FixedT);
7483     NewVD->setTypeSourceInfo(FixedTInfo);
7484   }
7485 
7486   if (T->isVoidType()) {
7487     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7488     //                    of objects and functions.
7489     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7490       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7491         << T;
7492       NewVD->setInvalidDecl();
7493       return;
7494     }
7495   }
7496 
7497   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7498     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7499     NewVD->setInvalidDecl();
7500     return;
7501   }
7502 
7503   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7504     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7505     NewVD->setInvalidDecl();
7506     return;
7507   }
7508 
7509   if (NewVD->isConstexpr() && !T->isDependentType() &&
7510       RequireLiteralType(NewVD->getLocation(), T,
7511                          diag::err_constexpr_var_non_literal)) {
7512     NewVD->setInvalidDecl();
7513     return;
7514   }
7515 }
7516 
7517 /// Perform semantic checking on a newly-created variable
7518 /// declaration.
7519 ///
7520 /// This routine performs all of the type-checking required for a
7521 /// variable declaration once it has been built. It is used both to
7522 /// check variables after they have been parsed and their declarators
7523 /// have been translated into a declaration, and to check variables
7524 /// that have been instantiated from a template.
7525 ///
7526 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7527 ///
7528 /// Returns true if the variable declaration is a redeclaration.
7529 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7530   CheckVariableDeclarationType(NewVD);
7531 
7532   // If the decl is already known invalid, don't check it.
7533   if (NewVD->isInvalidDecl())
7534     return false;
7535 
7536   // If we did not find anything by this name, look for a non-visible
7537   // extern "C" declaration with the same name.
7538   if (Previous.empty() &&
7539       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7540     Previous.setShadowed();
7541 
7542   if (!Previous.empty()) {
7543     MergeVarDecl(NewVD, Previous);
7544     return true;
7545   }
7546   return false;
7547 }
7548 
7549 namespace {
7550 struct FindOverriddenMethod {
7551   Sema *S;
7552   CXXMethodDecl *Method;
7553 
7554   /// Member lookup function that determines whether a given C++
7555   /// method overrides a method in a base class, to be used with
7556   /// CXXRecordDecl::lookupInBases().
7557   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7558     RecordDecl *BaseRecord =
7559         Specifier->getType()->getAs<RecordType>()->getDecl();
7560 
7561     DeclarationName Name = Method->getDeclName();
7562 
7563     // FIXME: Do we care about other names here too?
7564     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7565       // We really want to find the base class destructor here.
7566       QualType T = S->Context.getTypeDeclType(BaseRecord);
7567       CanQualType CT = S->Context.getCanonicalType(T);
7568 
7569       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7570     }
7571 
7572     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7573          Path.Decls = Path.Decls.slice(1)) {
7574       NamedDecl *D = Path.Decls.front();
7575       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7576         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7577           return true;
7578       }
7579     }
7580 
7581     return false;
7582   }
7583 };
7584 
7585 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7586 } // end anonymous namespace
7587 
7588 /// Report an error regarding overriding, along with any relevant
7589 /// overridden methods.
7590 ///
7591 /// \param DiagID the primary error to report.
7592 /// \param MD the overriding method.
7593 /// \param OEK which overrides to include as notes.
7594 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7595                             OverrideErrorKind OEK = OEK_All) {
7596   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7597   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7598     // This check (& the OEK parameter) could be replaced by a predicate, but
7599     // without lambdas that would be overkill. This is still nicer than writing
7600     // out the diag loop 3 times.
7601     if ((OEK == OEK_All) ||
7602         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7603         (OEK == OEK_Deleted && O->isDeleted()))
7604       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7605   }
7606 }
7607 
7608 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7609 /// and if so, check that it's a valid override and remember it.
7610 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7611   // Look for methods in base classes that this method might override.
7612   CXXBasePaths Paths;
7613   FindOverriddenMethod FOM;
7614   FOM.Method = MD;
7615   FOM.S = this;
7616   bool hasDeletedOverridenMethods = false;
7617   bool hasNonDeletedOverridenMethods = false;
7618   bool AddedAny = false;
7619   if (DC->lookupInBases(FOM, Paths)) {
7620     for (auto *I : Paths.found_decls()) {
7621       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7622         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7623         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7624             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7625             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7626             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7627           hasDeletedOverridenMethods |= OldMD->isDeleted();
7628           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7629           AddedAny = true;
7630         }
7631       }
7632     }
7633   }
7634 
7635   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7636     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7637   }
7638   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7639     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7640   }
7641 
7642   return AddedAny;
7643 }
7644 
7645 namespace {
7646   // Struct for holding all of the extra arguments needed by
7647   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7648   struct ActOnFDArgs {
7649     Scope *S;
7650     Declarator &D;
7651     MultiTemplateParamsArg TemplateParamLists;
7652     bool AddToScope;
7653   };
7654 } // end anonymous namespace
7655 
7656 namespace {
7657 
7658 // Callback to only accept typo corrections that have a non-zero edit distance.
7659 // Also only accept corrections that have the same parent decl.
7660 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7661  public:
7662   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7663                             CXXRecordDecl *Parent)
7664       : Context(Context), OriginalFD(TypoFD),
7665         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7666 
7667   bool ValidateCandidate(const TypoCorrection &candidate) override {
7668     if (candidate.getEditDistance() == 0)
7669       return false;
7670 
7671     SmallVector<unsigned, 1> MismatchedParams;
7672     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7673                                           CDeclEnd = candidate.end();
7674          CDecl != CDeclEnd; ++CDecl) {
7675       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7676 
7677       if (FD && !FD->hasBody() &&
7678           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7679         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7680           CXXRecordDecl *Parent = MD->getParent();
7681           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7682             return true;
7683         } else if (!ExpectedParent) {
7684           return true;
7685         }
7686       }
7687     }
7688 
7689     return false;
7690   }
7691 
7692  private:
7693   ASTContext &Context;
7694   FunctionDecl *OriginalFD;
7695   CXXRecordDecl *ExpectedParent;
7696 };
7697 
7698 } // end anonymous namespace
7699 
7700 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7701   TypoCorrectedFunctionDefinitions.insert(F);
7702 }
7703 
7704 /// Generate diagnostics for an invalid function redeclaration.
7705 ///
7706 /// This routine handles generating the diagnostic messages for an invalid
7707 /// function redeclaration, including finding possible similar declarations
7708 /// or performing typo correction if there are no previous declarations with
7709 /// the same name.
7710 ///
7711 /// Returns a NamedDecl iff typo correction was performed and substituting in
7712 /// the new declaration name does not cause new errors.
7713 static NamedDecl *DiagnoseInvalidRedeclaration(
7714     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7715     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7716   DeclarationName Name = NewFD->getDeclName();
7717   DeclContext *NewDC = NewFD->getDeclContext();
7718   SmallVector<unsigned, 1> MismatchedParams;
7719   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7720   TypoCorrection Correction;
7721   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7722   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7723                                    : diag::err_member_decl_does_not_match;
7724   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7725                     IsLocalFriend ? Sema::LookupLocalFriendName
7726                                   : Sema::LookupOrdinaryName,
7727                     Sema::ForVisibleRedeclaration);
7728 
7729   NewFD->setInvalidDecl();
7730   if (IsLocalFriend)
7731     SemaRef.LookupName(Prev, S);
7732   else
7733     SemaRef.LookupQualifiedName(Prev, NewDC);
7734   assert(!Prev.isAmbiguous() &&
7735          "Cannot have an ambiguity in previous-declaration lookup");
7736   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7737   if (!Prev.empty()) {
7738     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7739          Func != FuncEnd; ++Func) {
7740       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7741       if (FD &&
7742           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7743         // Add 1 to the index so that 0 can mean the mismatch didn't
7744         // involve a parameter
7745         unsigned ParamNum =
7746             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7747         NearMatches.push_back(std::make_pair(FD, ParamNum));
7748       }
7749     }
7750   // If the qualified name lookup yielded nothing, try typo correction
7751   } else if ((Correction = SemaRef.CorrectTypo(
7752                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7753                   &ExtraArgs.D.getCXXScopeSpec(),
7754                   llvm::make_unique<DifferentNameValidatorCCC>(
7755                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7756                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7757     // Set up everything for the call to ActOnFunctionDeclarator
7758     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7759                               ExtraArgs.D.getIdentifierLoc());
7760     Previous.clear();
7761     Previous.setLookupName(Correction.getCorrection());
7762     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7763                                     CDeclEnd = Correction.end();
7764          CDecl != CDeclEnd; ++CDecl) {
7765       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7766       if (FD && !FD->hasBody() &&
7767           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7768         Previous.addDecl(FD);
7769       }
7770     }
7771     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7772 
7773     NamedDecl *Result;
7774     // Retry building the function declaration with the new previous
7775     // declarations, and with errors suppressed.
7776     {
7777       // Trap errors.
7778       Sema::SFINAETrap Trap(SemaRef);
7779 
7780       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7781       // pieces need to verify the typo-corrected C++ declaration and hopefully
7782       // eliminate the need for the parameter pack ExtraArgs.
7783       Result = SemaRef.ActOnFunctionDeclarator(
7784           ExtraArgs.S, ExtraArgs.D,
7785           Correction.getCorrectionDecl()->getDeclContext(),
7786           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7787           ExtraArgs.AddToScope);
7788 
7789       if (Trap.hasErrorOccurred())
7790         Result = nullptr;
7791     }
7792 
7793     if (Result) {
7794       // Determine which correction we picked.
7795       Decl *Canonical = Result->getCanonicalDecl();
7796       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7797            I != E; ++I)
7798         if ((*I)->getCanonicalDecl() == Canonical)
7799           Correction.setCorrectionDecl(*I);
7800 
7801       // Let Sema know about the correction.
7802       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7803       SemaRef.diagnoseTypo(
7804           Correction,
7805           SemaRef.PDiag(IsLocalFriend
7806                           ? diag::err_no_matching_local_friend_suggest
7807                           : diag::err_member_decl_does_not_match_suggest)
7808             << Name << NewDC << IsDefinition);
7809       return Result;
7810     }
7811 
7812     // Pretend the typo correction never occurred
7813     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7814                               ExtraArgs.D.getIdentifierLoc());
7815     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7816     Previous.clear();
7817     Previous.setLookupName(Name);
7818   }
7819 
7820   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7821       << Name << NewDC << IsDefinition << NewFD->getLocation();
7822 
7823   bool NewFDisConst = false;
7824   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7825     NewFDisConst = NewMD->isConst();
7826 
7827   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7828        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7829        NearMatch != NearMatchEnd; ++NearMatch) {
7830     FunctionDecl *FD = NearMatch->first;
7831     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7832     bool FDisConst = MD && MD->isConst();
7833     bool IsMember = MD || !IsLocalFriend;
7834 
7835     // FIXME: These notes are poorly worded for the local friend case.
7836     if (unsigned Idx = NearMatch->second) {
7837       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7838       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7839       if (Loc.isInvalid()) Loc = FD->getLocation();
7840       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7841                                  : diag::note_local_decl_close_param_match)
7842         << Idx << FDParam->getType()
7843         << NewFD->getParamDecl(Idx - 1)->getType();
7844     } else if (FDisConst != NewFDisConst) {
7845       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7846           << NewFDisConst << FD->getSourceRange().getEnd();
7847     } else
7848       SemaRef.Diag(FD->getLocation(),
7849                    IsMember ? diag::note_member_def_close_match
7850                             : diag::note_local_decl_close_match);
7851   }
7852   return nullptr;
7853 }
7854 
7855 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7856   switch (D.getDeclSpec().getStorageClassSpec()) {
7857   default: llvm_unreachable("Unknown storage class!");
7858   case DeclSpec::SCS_auto:
7859   case DeclSpec::SCS_register:
7860   case DeclSpec::SCS_mutable:
7861     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7862                  diag::err_typecheck_sclass_func);
7863     D.getMutableDeclSpec().ClearStorageClassSpecs();
7864     D.setInvalidType();
7865     break;
7866   case DeclSpec::SCS_unspecified: break;
7867   case DeclSpec::SCS_extern:
7868     if (D.getDeclSpec().isExternInLinkageSpec())
7869       return SC_None;
7870     return SC_Extern;
7871   case DeclSpec::SCS_static: {
7872     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7873       // C99 6.7.1p5:
7874       //   The declaration of an identifier for a function that has
7875       //   block scope shall have no explicit storage-class specifier
7876       //   other than extern
7877       // See also (C++ [dcl.stc]p4).
7878       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7879                    diag::err_static_block_func);
7880       break;
7881     } else
7882       return SC_Static;
7883   }
7884   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7885   }
7886 
7887   // No explicit storage class has already been returned
7888   return SC_None;
7889 }
7890 
7891 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7892                                            DeclContext *DC, QualType &R,
7893                                            TypeSourceInfo *TInfo,
7894                                            StorageClass SC,
7895                                            bool &IsVirtualOkay) {
7896   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7897   DeclarationName Name = NameInfo.getName();
7898 
7899   FunctionDecl *NewFD = nullptr;
7900   bool isInline = D.getDeclSpec().isInlineSpecified();
7901 
7902   if (!SemaRef.getLangOpts().CPlusPlus) {
7903     // Determine whether the function was written with a
7904     // prototype. This true when:
7905     //   - there is a prototype in the declarator, or
7906     //   - the type R of the function is some kind of typedef or other non-
7907     //     attributed reference to a type name (which eventually refers to a
7908     //     function type).
7909     bool HasPrototype =
7910       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7911       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7912 
7913     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7914                                  D.getLocStart(), NameInfo, R,
7915                                  TInfo, SC, isInline,
7916                                  HasPrototype, false);
7917     if (D.isInvalidType())
7918       NewFD->setInvalidDecl();
7919 
7920     return NewFD;
7921   }
7922 
7923   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7924   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7925 
7926   // Check that the return type is not an abstract class type.
7927   // For record types, this is done by the AbstractClassUsageDiagnoser once
7928   // the class has been completely parsed.
7929   if (!DC->isRecord() &&
7930       SemaRef.RequireNonAbstractType(
7931           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7932           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7933     D.setInvalidType();
7934 
7935   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7936     // This is a C++ constructor declaration.
7937     assert(DC->isRecord() &&
7938            "Constructors can only be declared in a member context");
7939 
7940     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7941     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7942                                       D.getLocStart(), NameInfo,
7943                                       R, TInfo, isExplicit, isInline,
7944                                       /*isImplicitlyDeclared=*/false,
7945                                       isConstexpr);
7946 
7947   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7948     // This is a C++ destructor declaration.
7949     if (DC->isRecord()) {
7950       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7951       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7952       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7953                                         SemaRef.Context, Record,
7954                                         D.getLocStart(),
7955                                         NameInfo, R, TInfo, isInline,
7956                                         /*isImplicitlyDeclared=*/false);
7957 
7958       // If the class is complete, then we now create the implicit exception
7959       // specification. If the class is incomplete or dependent, we can't do
7960       // it yet.
7961       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7962           Record->getDefinition() && !Record->isBeingDefined() &&
7963           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7964         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7965       }
7966 
7967       IsVirtualOkay = true;
7968       return NewDD;
7969 
7970     } else {
7971       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7972       D.setInvalidType();
7973 
7974       // Create a FunctionDecl to satisfy the function definition parsing
7975       // code path.
7976       return FunctionDecl::Create(SemaRef.Context, DC,
7977                                   D.getLocStart(),
7978                                   D.getIdentifierLoc(), Name, R, TInfo,
7979                                   SC, isInline,
7980                                   /*hasPrototype=*/true, isConstexpr);
7981     }
7982 
7983   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7984     if (!DC->isRecord()) {
7985       SemaRef.Diag(D.getIdentifierLoc(),
7986            diag::err_conv_function_not_member);
7987       return nullptr;
7988     }
7989 
7990     SemaRef.CheckConversionDeclarator(D, R, SC);
7991     IsVirtualOkay = true;
7992     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7993                                      D.getLocStart(), NameInfo,
7994                                      R, TInfo, isInline, isExplicit,
7995                                      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.getLocStart(),
8001                                          isExplicit, NameInfo, R, TInfo,
8002                                          D.getLocEnd());
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(SemaRef.Context,
8018                                                cast<CXXRecordDecl>(DC),
8019                                                D.getLocStart(), NameInfo, R,
8020                                                TInfo, SC, isInline,
8021                                                isConstexpr, SourceLocation());
8022     IsVirtualOkay = !Ret->isStatic();
8023     return Ret;
8024   } else {
8025     bool isFriend =
8026         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8027     if (!isFriend && SemaRef.CurContext->isRecord())
8028       return nullptr;
8029 
8030     // Determine whether the function was written with a
8031     // prototype. This true when:
8032     //   - we're in C++ (where every function has a prototype),
8033     return FunctionDecl::Create(SemaRef.Context, DC,
8034                                 D.getLocStart(),
8035                                 NameInfo, R, TInfo, SC, isInline,
8036                                 true/*HasPrototype*/, isConstexpr);
8037   }
8038 }
8039 
8040 enum OpenCLParamType {
8041   ValidKernelParam,
8042   PtrPtrKernelParam,
8043   PtrKernelParam,
8044   InvalidAddrSpacePtrKernelParam,
8045   InvalidKernelParam,
8046   RecordKernelParam
8047 };
8048 
8049 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8050   if (PT->isPointerType()) {
8051     QualType PointeeType = PT->getPointeeType();
8052     if (PointeeType->isPointerType())
8053       return PtrPtrKernelParam;
8054     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8055         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8056         PointeeType.getAddressSpace() == LangAS::Default)
8057       return InvalidAddrSpacePtrKernelParam;
8058     return PtrKernelParam;
8059   }
8060 
8061   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
8062   // be used as builtin types.
8063 
8064   if (PT->isImageType())
8065     return PtrKernelParam;
8066 
8067   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8068     return InvalidKernelParam;
8069 
8070   // OpenCL extension spec v1.2 s9.5:
8071   // This extension adds support for half scalar and vector types as built-in
8072   // types that can be used for arithmetic operations, conversions etc.
8073   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8074     return InvalidKernelParam;
8075 
8076   if (PT->isRecordType())
8077     return RecordKernelParam;
8078 
8079   return ValidKernelParam;
8080 }
8081 
8082 static void checkIsValidOpenCLKernelParameter(
8083   Sema &S,
8084   Declarator &D,
8085   ParmVarDecl *Param,
8086   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8087   QualType PT = Param->getType();
8088 
8089   // Cache the valid types we encounter to avoid rechecking structs that are
8090   // used again
8091   if (ValidTypes.count(PT.getTypePtr()))
8092     return;
8093 
8094   switch (getOpenCLKernelParameterType(S, PT)) {
8095   case PtrPtrKernelParam:
8096     // OpenCL v1.2 s6.9.a:
8097     // A kernel function argument cannot be declared as a
8098     // pointer to a pointer type.
8099     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8100     D.setInvalidType();
8101     return;
8102 
8103   case InvalidAddrSpacePtrKernelParam:
8104     // OpenCL v1.0 s6.5:
8105     // __kernel function arguments declared to be a pointer of a type can point
8106     // to one of the following address spaces only : __global, __local or
8107     // __constant.
8108     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8109     D.setInvalidType();
8110     return;
8111 
8112     // OpenCL v1.2 s6.9.k:
8113     // Arguments to kernel functions in a program cannot be declared with the
8114     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8115     // uintptr_t or a struct and/or union that contain fields declared to be
8116     // one of these built-in scalar types.
8117 
8118   case InvalidKernelParam:
8119     // OpenCL v1.2 s6.8 n:
8120     // A kernel function argument cannot be declared
8121     // of event_t type.
8122     // Do not diagnose half type since it is diagnosed as invalid argument
8123     // type for any function elsewhere.
8124     if (!PT->isHalfType())
8125       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8126     D.setInvalidType();
8127     return;
8128 
8129   case PtrKernelParam:
8130   case ValidKernelParam:
8131     ValidTypes.insert(PT.getTypePtr());
8132     return;
8133 
8134   case RecordKernelParam:
8135     break;
8136   }
8137 
8138   // Track nested structs we will inspect
8139   SmallVector<const Decl *, 4> VisitStack;
8140 
8141   // Track where we are in the nested structs. Items will migrate from
8142   // VisitStack to HistoryStack as we do the DFS for bad field.
8143   SmallVector<const FieldDecl *, 4> HistoryStack;
8144   HistoryStack.push_back(nullptr);
8145 
8146   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
8147   VisitStack.push_back(PD);
8148 
8149   assert(VisitStack.back() && "First decl null?");
8150 
8151   do {
8152     const Decl *Next = VisitStack.pop_back_val();
8153     if (!Next) {
8154       assert(!HistoryStack.empty());
8155       // Found a marker, we have gone up a level
8156       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8157         ValidTypes.insert(Hist->getType().getTypePtr());
8158 
8159       continue;
8160     }
8161 
8162     // Adds everything except the original parameter declaration (which is not a
8163     // field itself) to the history stack.
8164     const RecordDecl *RD;
8165     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8166       HistoryStack.push_back(Field);
8167       RD = Field->getType()->castAs<RecordType>()->getDecl();
8168     } else {
8169       RD = cast<RecordDecl>(Next);
8170     }
8171 
8172     // Add a null marker so we know when we've gone back up a level
8173     VisitStack.push_back(nullptr);
8174 
8175     for (const auto *FD : RD->fields()) {
8176       QualType QT = FD->getType();
8177 
8178       if (ValidTypes.count(QT.getTypePtr()))
8179         continue;
8180 
8181       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8182       if (ParamType == ValidKernelParam)
8183         continue;
8184 
8185       if (ParamType == RecordKernelParam) {
8186         VisitStack.push_back(FD);
8187         continue;
8188       }
8189 
8190       // OpenCL v1.2 s6.9.p:
8191       // Arguments to kernel functions that are declared to be a struct or union
8192       // do not allow OpenCL objects to be passed as elements of the struct or
8193       // union.
8194       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8195           ParamType == InvalidAddrSpacePtrKernelParam) {
8196         S.Diag(Param->getLocation(),
8197                diag::err_record_with_pointers_kernel_param)
8198           << PT->isUnionType()
8199           << PT;
8200       } else {
8201         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8202       }
8203 
8204       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
8205         << PD->getDeclName();
8206 
8207       // We have an error, now let's go back up through history and show where
8208       // the offending field came from
8209       for (ArrayRef<const FieldDecl *>::const_iterator
8210                I = HistoryStack.begin() + 1,
8211                E = HistoryStack.end();
8212            I != E; ++I) {
8213         const FieldDecl *OuterField = *I;
8214         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8215           << OuterField->getType();
8216       }
8217 
8218       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8219         << QT->isPointerType()
8220         << QT;
8221       D.setInvalidType();
8222       return;
8223     }
8224   } while (!VisitStack.empty());
8225 }
8226 
8227 /// Find the DeclContext in which a tag is implicitly declared if we see an
8228 /// elaborated type specifier in the specified context, and lookup finds
8229 /// nothing.
8230 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8231   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8232     DC = DC->getParent();
8233   return DC;
8234 }
8235 
8236 /// Find the Scope in which a tag is implicitly declared if we see an
8237 /// elaborated type specifier in the specified context, and lookup finds
8238 /// nothing.
8239 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8240   while (S->isClassScope() ||
8241          (LangOpts.CPlusPlus &&
8242           S->isFunctionPrototypeScope()) ||
8243          ((S->getFlags() & Scope::DeclScope) == 0) ||
8244          (S->getEntity() && S->getEntity()->isTransparentContext()))
8245     S = S->getParent();
8246   return S;
8247 }
8248 
8249 NamedDecl*
8250 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8251                               TypeSourceInfo *TInfo, LookupResult &Previous,
8252                               MultiTemplateParamsArg TemplateParamLists,
8253                               bool &AddToScope) {
8254   QualType R = TInfo->getType();
8255 
8256   assert(R.getTypePtr()->isFunctionType());
8257 
8258   // TODO: consider using NameInfo for diagnostic.
8259   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8260   DeclarationName Name = NameInfo.getName();
8261   StorageClass SC = getFunctionStorageClass(*this, D);
8262 
8263   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8264     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8265          diag::err_invalid_thread)
8266       << DeclSpec::getSpecifierName(TSCS);
8267 
8268   if (D.isFirstDeclarationOfMember())
8269     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8270                            D.getIdentifierLoc());
8271 
8272   bool isFriend = false;
8273   FunctionTemplateDecl *FunctionTemplate = nullptr;
8274   bool isMemberSpecialization = false;
8275   bool isFunctionTemplateSpecialization = false;
8276 
8277   bool isDependentClassScopeExplicitSpecialization = false;
8278   bool HasExplicitTemplateArgs = false;
8279   TemplateArgumentListInfo TemplateArgs;
8280 
8281   bool isVirtualOkay = false;
8282 
8283   DeclContext *OriginalDC = DC;
8284   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8285 
8286   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8287                                               isVirtualOkay);
8288   if (!NewFD) return nullptr;
8289 
8290   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8291     NewFD->setTopLevelDeclInObjCContainer();
8292 
8293   // Set the lexical context. If this is a function-scope declaration, or has a
8294   // C++ scope specifier, or is the object of a friend declaration, the lexical
8295   // context will be different from the semantic context.
8296   NewFD->setLexicalDeclContext(CurContext);
8297 
8298   if (IsLocalExternDecl)
8299     NewFD->setLocalExternDecl();
8300 
8301   if (getLangOpts().CPlusPlus) {
8302     bool isInline = D.getDeclSpec().isInlineSpecified();
8303     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8304     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8305     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8306     isFriend = D.getDeclSpec().isFriendSpecified();
8307     if (isFriend && !isInline && D.isFunctionDefinition()) {
8308       // C++ [class.friend]p5
8309       //   A function can be defined in a friend declaration of a
8310       //   class . . . . Such a function is implicitly inline.
8311       NewFD->setImplicitlyInline();
8312     }
8313 
8314     // If this is a method defined in an __interface, and is not a constructor
8315     // or an overloaded operator, then set the pure flag (isVirtual will already
8316     // return true).
8317     if (const CXXRecordDecl *Parent =
8318           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8319       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8320         NewFD->setPure(true);
8321 
8322       // C++ [class.union]p2
8323       //   A union can have member functions, but not virtual functions.
8324       if (isVirtual && Parent->isUnion())
8325         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8326     }
8327 
8328     SetNestedNameSpecifier(NewFD, D);
8329     isMemberSpecialization = false;
8330     isFunctionTemplateSpecialization = false;
8331     if (D.isInvalidType())
8332       NewFD->setInvalidDecl();
8333 
8334     // Match up the template parameter lists with the scope specifier, then
8335     // determine whether we have a template or a template specialization.
8336     bool Invalid = false;
8337     if (TemplateParameterList *TemplateParams =
8338             MatchTemplateParametersToScopeSpecifier(
8339                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
8340                 D.getCXXScopeSpec(),
8341                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8342                     ? D.getName().TemplateId
8343                     : nullptr,
8344                 TemplateParamLists, isFriend, isMemberSpecialization,
8345                 Invalid)) {
8346       if (TemplateParams->size() > 0) {
8347         // This is a function template
8348 
8349         // Check that we can declare a template here.
8350         if (CheckTemplateDeclScope(S, TemplateParams))
8351           NewFD->setInvalidDecl();
8352 
8353         // A destructor cannot be a template.
8354         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8355           Diag(NewFD->getLocation(), diag::err_destructor_template);
8356           NewFD->setInvalidDecl();
8357         }
8358 
8359         // If we're adding a template to a dependent context, we may need to
8360         // rebuilding some of the types used within the template parameter list,
8361         // now that we know what the current instantiation is.
8362         if (DC->isDependentContext()) {
8363           ContextRAII SavedContext(*this, DC);
8364           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8365             Invalid = true;
8366         }
8367 
8368         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8369                                                         NewFD->getLocation(),
8370                                                         Name, TemplateParams,
8371                                                         NewFD);
8372         FunctionTemplate->setLexicalDeclContext(CurContext);
8373         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8374 
8375         // For source fidelity, store the other template param lists.
8376         if (TemplateParamLists.size() > 1) {
8377           NewFD->setTemplateParameterListsInfo(Context,
8378                                                TemplateParamLists.drop_back(1));
8379         }
8380       } else {
8381         // This is a function template specialization.
8382         isFunctionTemplateSpecialization = true;
8383         // For source fidelity, store all the template param lists.
8384         if (TemplateParamLists.size() > 0)
8385           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8386 
8387         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8388         if (isFriend) {
8389           // We want to remove the "template<>", found here.
8390           SourceRange RemoveRange = TemplateParams->getSourceRange();
8391 
8392           // If we remove the template<> and the name is not a
8393           // template-id, we're actually silently creating a problem:
8394           // the friend declaration will refer to an untemplated decl,
8395           // and clearly the user wants a template specialization.  So
8396           // we need to insert '<>' after the name.
8397           SourceLocation InsertLoc;
8398           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8399             InsertLoc = D.getName().getSourceRange().getEnd();
8400             InsertLoc = getLocForEndOfToken(InsertLoc);
8401           }
8402 
8403           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8404             << Name << RemoveRange
8405             << FixItHint::CreateRemoval(RemoveRange)
8406             << FixItHint::CreateInsertion(InsertLoc, "<>");
8407         }
8408       }
8409     }
8410     else {
8411       // All template param lists were matched against the scope specifier:
8412       // this is NOT (an explicit specialization of) a template.
8413       if (TemplateParamLists.size() > 0)
8414         // For source fidelity, store all the template param lists.
8415         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8416     }
8417 
8418     if (Invalid) {
8419       NewFD->setInvalidDecl();
8420       if (FunctionTemplate)
8421         FunctionTemplate->setInvalidDecl();
8422     }
8423 
8424     // C++ [dcl.fct.spec]p5:
8425     //   The virtual specifier shall only be used in declarations of
8426     //   nonstatic class member functions that appear within a
8427     //   member-specification of a class declaration; see 10.3.
8428     //
8429     if (isVirtual && !NewFD->isInvalidDecl()) {
8430       if (!isVirtualOkay) {
8431         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8432              diag::err_virtual_non_function);
8433       } else if (!CurContext->isRecord()) {
8434         // 'virtual' was specified outside of the class.
8435         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8436              diag::err_virtual_out_of_class)
8437           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8438       } else if (NewFD->getDescribedFunctionTemplate()) {
8439         // C++ [temp.mem]p3:
8440         //  A member function template shall not be virtual.
8441         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8442              diag::err_virtual_member_function_template)
8443           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8444       } else {
8445         // Okay: Add virtual to the method.
8446         NewFD->setVirtualAsWritten(true);
8447       }
8448 
8449       if (getLangOpts().CPlusPlus14 &&
8450           NewFD->getReturnType()->isUndeducedType())
8451         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8452     }
8453 
8454     if (getLangOpts().CPlusPlus14 &&
8455         (NewFD->isDependentContext() ||
8456          (isFriend && CurContext->isDependentContext())) &&
8457         NewFD->getReturnType()->isUndeducedType()) {
8458       // If the function template is referenced directly (for instance, as a
8459       // member of the current instantiation), pretend it has a dependent type.
8460       // This is not really justified by the standard, but is the only sane
8461       // thing to do.
8462       // FIXME: For a friend function, we have not marked the function as being
8463       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8464       const FunctionProtoType *FPT =
8465           NewFD->getType()->castAs<FunctionProtoType>();
8466       QualType Result =
8467           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8468       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8469                                              FPT->getExtProtoInfo()));
8470     }
8471 
8472     // C++ [dcl.fct.spec]p3:
8473     //  The inline specifier shall not appear on a block scope function
8474     //  declaration.
8475     if (isInline && !NewFD->isInvalidDecl()) {
8476       if (CurContext->isFunctionOrMethod()) {
8477         // 'inline' is not allowed on block scope function declaration.
8478         Diag(D.getDeclSpec().getInlineSpecLoc(),
8479              diag::err_inline_declaration_block_scope) << Name
8480           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8481       }
8482     }
8483 
8484     // C++ [dcl.fct.spec]p6:
8485     //  The explicit specifier shall be used only in the declaration of a
8486     //  constructor or conversion function within its class definition;
8487     //  see 12.3.1 and 12.3.2.
8488     if (isExplicit && !NewFD->isInvalidDecl() &&
8489         !isa<CXXDeductionGuideDecl>(NewFD)) {
8490       if (!CurContext->isRecord()) {
8491         // 'explicit' was specified outside of the class.
8492         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8493              diag::err_explicit_out_of_class)
8494           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8495       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8496                  !isa<CXXConversionDecl>(NewFD)) {
8497         // 'explicit' was specified on a function that wasn't a constructor
8498         // or conversion function.
8499         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8500              diag::err_explicit_non_ctor_or_conv_function)
8501           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8502       }
8503     }
8504 
8505     if (isConstexpr) {
8506       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8507       // are implicitly inline.
8508       NewFD->setImplicitlyInline();
8509 
8510       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8511       // be either constructors or to return a literal type. Therefore,
8512       // destructors cannot be declared constexpr.
8513       if (isa<CXXDestructorDecl>(NewFD))
8514         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8515     }
8516 
8517     // If __module_private__ was specified, mark the function accordingly.
8518     if (D.getDeclSpec().isModulePrivateSpecified()) {
8519       if (isFunctionTemplateSpecialization) {
8520         SourceLocation ModulePrivateLoc
8521           = D.getDeclSpec().getModulePrivateSpecLoc();
8522         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8523           << 0
8524           << FixItHint::CreateRemoval(ModulePrivateLoc);
8525       } else {
8526         NewFD->setModulePrivate();
8527         if (FunctionTemplate)
8528           FunctionTemplate->setModulePrivate();
8529       }
8530     }
8531 
8532     if (isFriend) {
8533       if (FunctionTemplate) {
8534         FunctionTemplate->setObjectOfFriendDecl();
8535         FunctionTemplate->setAccess(AS_public);
8536       }
8537       NewFD->setObjectOfFriendDecl();
8538       NewFD->setAccess(AS_public);
8539     }
8540 
8541     // If a function is defined as defaulted or deleted, mark it as such now.
8542     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8543     // definition kind to FDK_Definition.
8544     switch (D.getFunctionDefinitionKind()) {
8545       case FDK_Declaration:
8546       case FDK_Definition:
8547         break;
8548 
8549       case FDK_Defaulted:
8550         NewFD->setDefaulted();
8551         break;
8552 
8553       case FDK_Deleted:
8554         NewFD->setDeletedAsWritten();
8555         break;
8556     }
8557 
8558     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8559         D.isFunctionDefinition()) {
8560       // C++ [class.mfct]p2:
8561       //   A member function may be defined (8.4) in its class definition, in
8562       //   which case it is an inline member function (7.1.2)
8563       NewFD->setImplicitlyInline();
8564     }
8565 
8566     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8567         !CurContext->isRecord()) {
8568       // C++ [class.static]p1:
8569       //   A data or function member of a class may be declared static
8570       //   in a class definition, in which case it is a static member of
8571       //   the class.
8572 
8573       // Complain about the 'static' specifier if it's on an out-of-line
8574       // member function definition.
8575       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8576            diag::err_static_out_of_line)
8577         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8578     }
8579 
8580     // C++11 [except.spec]p15:
8581     //   A deallocation function with no exception-specification is treated
8582     //   as if it were specified with noexcept(true).
8583     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8584     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8585          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8586         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8587       NewFD->setType(Context.getFunctionType(
8588           FPT->getReturnType(), FPT->getParamTypes(),
8589           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8590   }
8591 
8592   // Filter out previous declarations that don't match the scope.
8593   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8594                        D.getCXXScopeSpec().isNotEmpty() ||
8595                        isMemberSpecialization ||
8596                        isFunctionTemplateSpecialization);
8597 
8598   // Handle GNU asm-label extension (encoded as an attribute).
8599   if (Expr *E = (Expr*) D.getAsmLabel()) {
8600     // The parser guarantees this is a string.
8601     StringLiteral *SE = cast<StringLiteral>(E);
8602     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8603                                                 SE->getString(), 0));
8604   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8605     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8606       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8607     if (I != ExtnameUndeclaredIdentifiers.end()) {
8608       if (isDeclExternC(NewFD)) {
8609         NewFD->addAttr(I->second);
8610         ExtnameUndeclaredIdentifiers.erase(I);
8611       } else
8612         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8613             << /*Variable*/0 << NewFD;
8614     }
8615   }
8616 
8617   // Copy the parameter declarations from the declarator D to the function
8618   // declaration NewFD, if they are available.  First scavenge them into Params.
8619   SmallVector<ParmVarDecl*, 16> Params;
8620   unsigned FTIIdx;
8621   if (D.isFunctionDeclarator(FTIIdx)) {
8622     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8623 
8624     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8625     // function that takes no arguments, not a function that takes a
8626     // single void argument.
8627     // We let through "const void" here because Sema::GetTypeForDeclarator
8628     // already checks for that case.
8629     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8630       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8631         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8632         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8633         Param->setDeclContext(NewFD);
8634         Params.push_back(Param);
8635 
8636         if (Param->isInvalidDecl())
8637           NewFD->setInvalidDecl();
8638       }
8639     }
8640 
8641     if (!getLangOpts().CPlusPlus) {
8642       // In C, find all the tag declarations from the prototype and move them
8643       // into the function DeclContext. Remove them from the surrounding tag
8644       // injection context of the function, which is typically but not always
8645       // the TU.
8646       DeclContext *PrototypeTagContext =
8647           getTagInjectionContext(NewFD->getLexicalDeclContext());
8648       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8649         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8650 
8651         // We don't want to reparent enumerators. Look at their parent enum
8652         // instead.
8653         if (!TD) {
8654           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8655             TD = cast<EnumDecl>(ECD->getDeclContext());
8656         }
8657         if (!TD)
8658           continue;
8659         DeclContext *TagDC = TD->getLexicalDeclContext();
8660         if (!TagDC->containsDecl(TD))
8661           continue;
8662         TagDC->removeDecl(TD);
8663         TD->setDeclContext(NewFD);
8664         NewFD->addDecl(TD);
8665 
8666         // Preserve the lexical DeclContext if it is not the surrounding tag
8667         // injection context of the FD. In this example, the semantic context of
8668         // E will be f and the lexical context will be S, while both the
8669         // semantic and lexical contexts of S will be f:
8670         //   void f(struct S { enum E { a } f; } s);
8671         if (TagDC != PrototypeTagContext)
8672           TD->setLexicalDeclContext(TagDC);
8673       }
8674     }
8675   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8676     // When we're declaring a function with a typedef, typeof, etc as in the
8677     // following example, we'll need to synthesize (unnamed)
8678     // parameters for use in the declaration.
8679     //
8680     // @code
8681     // typedef void fn(int);
8682     // fn f;
8683     // @endcode
8684 
8685     // Synthesize a parameter for each argument type.
8686     for (const auto &AI : FT->param_types()) {
8687       ParmVarDecl *Param =
8688           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8689       Param->setScopeInfo(0, Params.size());
8690       Params.push_back(Param);
8691     }
8692   } else {
8693     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8694            "Should not need args for typedef of non-prototype fn");
8695   }
8696 
8697   // Finally, we know we have the right number of parameters, install them.
8698   NewFD->setParams(Params);
8699 
8700   if (D.getDeclSpec().isNoreturnSpecified())
8701     NewFD->addAttr(
8702         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8703                                        Context, 0));
8704 
8705   // Functions returning a variably modified type violate C99 6.7.5.2p2
8706   // because all functions have linkage.
8707   if (!NewFD->isInvalidDecl() &&
8708       NewFD->getReturnType()->isVariablyModifiedType()) {
8709     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8710     NewFD->setInvalidDecl();
8711   }
8712 
8713   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8714   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8715       !NewFD->hasAttr<SectionAttr>()) {
8716     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8717                                                  PragmaClangTextSection.SectionName,
8718                                                  PragmaClangTextSection.PragmaLocation));
8719   }
8720 
8721   // Apply an implicit SectionAttr if #pragma code_seg is active.
8722   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8723       !NewFD->hasAttr<SectionAttr>()) {
8724     NewFD->addAttr(
8725         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8726                                     CodeSegStack.CurrentValue->getString(),
8727                                     CodeSegStack.CurrentPragmaLocation));
8728     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8729                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8730                          ASTContext::PSF_Read,
8731                      NewFD))
8732       NewFD->dropAttr<SectionAttr>();
8733   }
8734 
8735   // Handle attributes.
8736   ProcessDeclAttributes(S, NewFD, D);
8737 
8738   if (getLangOpts().OpenCL) {
8739     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8740     // type declaration will generate a compilation error.
8741     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
8742     if (AddressSpace != LangAS::Default) {
8743       Diag(NewFD->getLocation(),
8744            diag::err_opencl_return_value_with_address_space);
8745       NewFD->setInvalidDecl();
8746     }
8747   }
8748 
8749   if (!getLangOpts().CPlusPlus) {
8750     // Perform semantic checking on the function declaration.
8751     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8752       CheckMain(NewFD, D.getDeclSpec());
8753 
8754     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8755       CheckMSVCRTEntryPoint(NewFD);
8756 
8757     if (!NewFD->isInvalidDecl())
8758       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8759                                                   isMemberSpecialization));
8760     else if (!Previous.empty())
8761       // Recover gracefully from an invalid redeclaration.
8762       D.setRedeclaration(true);
8763     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8764             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8765            "previous declaration set still overloaded");
8766 
8767     // Diagnose no-prototype function declarations with calling conventions that
8768     // don't support variadic calls. Only do this in C and do it after merging
8769     // possibly prototyped redeclarations.
8770     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8771     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8772       CallingConv CC = FT->getExtInfo().getCC();
8773       if (!supportsVariadicCall(CC)) {
8774         // Windows system headers sometimes accidentally use stdcall without
8775         // (void) parameters, so we relax this to a warning.
8776         int DiagID =
8777             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8778         Diag(NewFD->getLocation(), DiagID)
8779             << FunctionType::getNameForCallConv(CC);
8780       }
8781     }
8782   } else {
8783     // C++11 [replacement.functions]p3:
8784     //  The program's definitions shall not be specified as inline.
8785     //
8786     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8787     //
8788     // Suppress the diagnostic if the function is __attribute__((used)), since
8789     // that forces an external definition to be emitted.
8790     if (D.getDeclSpec().isInlineSpecified() &&
8791         NewFD->isReplaceableGlobalAllocationFunction() &&
8792         !NewFD->hasAttr<UsedAttr>())
8793       Diag(D.getDeclSpec().getInlineSpecLoc(),
8794            diag::ext_operator_new_delete_declared_inline)
8795         << NewFD->getDeclName();
8796 
8797     // If the declarator is a template-id, translate the parser's template
8798     // argument list into our AST format.
8799     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
8800       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8801       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8802       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8803       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8804                                          TemplateId->NumArgs);
8805       translateTemplateArguments(TemplateArgsPtr,
8806                                  TemplateArgs);
8807 
8808       HasExplicitTemplateArgs = true;
8809 
8810       if (NewFD->isInvalidDecl()) {
8811         HasExplicitTemplateArgs = false;
8812       } else if (FunctionTemplate) {
8813         // Function template with explicit template arguments.
8814         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8815           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8816 
8817         HasExplicitTemplateArgs = false;
8818       } else {
8819         assert((isFunctionTemplateSpecialization ||
8820                 D.getDeclSpec().isFriendSpecified()) &&
8821                "should have a 'template<>' for this decl");
8822         // "friend void foo<>(int);" is an implicit specialization decl.
8823         isFunctionTemplateSpecialization = true;
8824       }
8825     } else if (isFriend && isFunctionTemplateSpecialization) {
8826       // This combination is only possible in a recovery case;  the user
8827       // wrote something like:
8828       //   template <> friend void foo(int);
8829       // which we're recovering from as if the user had written:
8830       //   friend void foo<>(int);
8831       // Go ahead and fake up a template id.
8832       HasExplicitTemplateArgs = true;
8833       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8834       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8835     }
8836 
8837     // We do not add HD attributes to specializations here because
8838     // they may have different constexpr-ness compared to their
8839     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8840     // may end up with different effective targets. Instead, a
8841     // specialization inherits its target attributes from its template
8842     // in the CheckFunctionTemplateSpecialization() call below.
8843     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8844       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8845 
8846     // If it's a friend (and only if it's a friend), it's possible
8847     // that either the specialized function type or the specialized
8848     // template is dependent, and therefore matching will fail.  In
8849     // this case, don't check the specialization yet.
8850     bool InstantiationDependent = false;
8851     if (isFunctionTemplateSpecialization && isFriend &&
8852         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8853          TemplateSpecializationType::anyDependentTemplateArguments(
8854             TemplateArgs,
8855             InstantiationDependent))) {
8856       assert(HasExplicitTemplateArgs &&
8857              "friend function specialization without template args");
8858       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8859                                                        Previous))
8860         NewFD->setInvalidDecl();
8861     } else if (isFunctionTemplateSpecialization) {
8862       if (CurContext->isDependentContext() && CurContext->isRecord()
8863           && !isFriend) {
8864         isDependentClassScopeExplicitSpecialization = true;
8865       } else if (!NewFD->isInvalidDecl() &&
8866                  CheckFunctionTemplateSpecialization(
8867                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
8868                      Previous))
8869         NewFD->setInvalidDecl();
8870 
8871       // C++ [dcl.stc]p1:
8872       //   A storage-class-specifier shall not be specified in an explicit
8873       //   specialization (14.7.3)
8874       FunctionTemplateSpecializationInfo *Info =
8875           NewFD->getTemplateSpecializationInfo();
8876       if (Info && SC != SC_None) {
8877         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8878           Diag(NewFD->getLocation(),
8879                diag::err_explicit_specialization_inconsistent_storage_class)
8880             << SC
8881             << FixItHint::CreateRemoval(
8882                                       D.getDeclSpec().getStorageClassSpecLoc());
8883 
8884         else
8885           Diag(NewFD->getLocation(),
8886                diag::ext_explicit_specialization_storage_class)
8887             << FixItHint::CreateRemoval(
8888                                       D.getDeclSpec().getStorageClassSpecLoc());
8889       }
8890     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8891       if (CheckMemberSpecialization(NewFD, Previous))
8892           NewFD->setInvalidDecl();
8893     }
8894 
8895     // Perform semantic checking on the function declaration.
8896     if (!isDependentClassScopeExplicitSpecialization) {
8897       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8898         CheckMain(NewFD, D.getDeclSpec());
8899 
8900       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8901         CheckMSVCRTEntryPoint(NewFD);
8902 
8903       if (!NewFD->isInvalidDecl())
8904         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8905                                                     isMemberSpecialization));
8906       else if (!Previous.empty())
8907         // Recover gracefully from an invalid redeclaration.
8908         D.setRedeclaration(true);
8909     }
8910 
8911     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8912             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8913            "previous declaration set still overloaded");
8914 
8915     NamedDecl *PrincipalDecl = (FunctionTemplate
8916                                 ? cast<NamedDecl>(FunctionTemplate)
8917                                 : NewFD);
8918 
8919     if (isFriend && NewFD->getPreviousDecl()) {
8920       AccessSpecifier Access = AS_public;
8921       if (!NewFD->isInvalidDecl())
8922         Access = NewFD->getPreviousDecl()->getAccess();
8923 
8924       NewFD->setAccess(Access);
8925       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8926     }
8927 
8928     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8929         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8930       PrincipalDecl->setNonMemberOperator();
8931 
8932     // If we have a function template, check the template parameter
8933     // list. This will check and merge default template arguments.
8934     if (FunctionTemplate) {
8935       FunctionTemplateDecl *PrevTemplate =
8936                                      FunctionTemplate->getPreviousDecl();
8937       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8938                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8939                                     : nullptr,
8940                             D.getDeclSpec().isFriendSpecified()
8941                               ? (D.isFunctionDefinition()
8942                                    ? TPC_FriendFunctionTemplateDefinition
8943                                    : TPC_FriendFunctionTemplate)
8944                               : (D.getCXXScopeSpec().isSet() &&
8945                                  DC && DC->isRecord() &&
8946                                  DC->isDependentContext())
8947                                   ? TPC_ClassTemplateMember
8948                                   : TPC_FunctionTemplate);
8949     }
8950 
8951     if (NewFD->isInvalidDecl()) {
8952       // Ignore all the rest of this.
8953     } else if (!D.isRedeclaration()) {
8954       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8955                                        AddToScope };
8956       // Fake up an access specifier if it's supposed to be a class member.
8957       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8958         NewFD->setAccess(AS_public);
8959 
8960       // Qualified decls generally require a previous declaration.
8961       if (D.getCXXScopeSpec().isSet()) {
8962         // ...with the major exception of templated-scope or
8963         // dependent-scope friend declarations.
8964 
8965         // TODO: we currently also suppress this check in dependent
8966         // contexts because (1) the parameter depth will be off when
8967         // matching friend templates and (2) we might actually be
8968         // selecting a friend based on a dependent factor.  But there
8969         // are situations where these conditions don't apply and we
8970         // can actually do this check immediately.
8971         if (isFriend &&
8972             (TemplateParamLists.size() ||
8973              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8974              CurContext->isDependentContext())) {
8975           // ignore these
8976         } else {
8977           // The user tried to provide an out-of-line definition for a
8978           // function that is a member of a class or namespace, but there
8979           // was no such member function declared (C++ [class.mfct]p2,
8980           // C++ [namespace.memdef]p2). For example:
8981           //
8982           // class X {
8983           //   void f() const;
8984           // };
8985           //
8986           // void X::f() { } // ill-formed
8987           //
8988           // Complain about this problem, and attempt to suggest close
8989           // matches (e.g., those that differ only in cv-qualifiers and
8990           // whether the parameter types are references).
8991 
8992           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8993                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8994             AddToScope = ExtraArgs.AddToScope;
8995             return Result;
8996           }
8997         }
8998 
8999         // Unqualified local friend declarations are required to resolve
9000         // to something.
9001       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9002         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9003                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9004           AddToScope = ExtraArgs.AddToScope;
9005           return Result;
9006         }
9007       }
9008     } else if (!D.isFunctionDefinition() &&
9009                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9010                !isFriend && !isFunctionTemplateSpecialization &&
9011                !isMemberSpecialization) {
9012       // An out-of-line member function declaration must also be a
9013       // definition (C++ [class.mfct]p2).
9014       // Note that this is not the case for explicit specializations of
9015       // function templates or member functions of class templates, per
9016       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9017       // extension for compatibility with old SWIG code which likes to
9018       // generate them.
9019       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9020         << D.getCXXScopeSpec().getRange();
9021     }
9022   }
9023 
9024   ProcessPragmaWeak(S, NewFD);
9025   checkAttributesAfterMerging(*this, *NewFD);
9026 
9027   AddKnownFunctionAttributes(NewFD);
9028 
9029   if (NewFD->hasAttr<OverloadableAttr>() &&
9030       !NewFD->getType()->getAs<FunctionProtoType>()) {
9031     Diag(NewFD->getLocation(),
9032          diag::err_attribute_overloadable_no_prototype)
9033       << NewFD;
9034 
9035     // Turn this into a variadic function with no parameters.
9036     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9037     FunctionProtoType::ExtProtoInfo EPI(
9038         Context.getDefaultCallingConvention(true, false));
9039     EPI.Variadic = true;
9040     EPI.ExtInfo = FT->getExtInfo();
9041 
9042     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9043     NewFD->setType(R);
9044   }
9045 
9046   // If there's a #pragma GCC visibility in scope, and this isn't a class
9047   // member, set the visibility of this function.
9048   if (!DC->isRecord() && NewFD->isExternallyVisible())
9049     AddPushedVisibilityAttribute(NewFD);
9050 
9051   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9052   // marking the function.
9053   AddCFAuditedAttribute(NewFD);
9054 
9055   // If this is a function definition, check if we have to apply optnone due to
9056   // a pragma.
9057   if(D.isFunctionDefinition())
9058     AddRangeBasedOptnone(NewFD);
9059 
9060   // If this is the first declaration of an extern C variable, update
9061   // the map of such variables.
9062   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9063       isIncompleteDeclExternC(*this, NewFD))
9064     RegisterLocallyScopedExternCDecl(NewFD, S);
9065 
9066   // Set this FunctionDecl's range up to the right paren.
9067   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9068 
9069   if (D.isRedeclaration() && !Previous.empty()) {
9070     NamedDecl *Prev = Previous.getRepresentativeDecl();
9071     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9072                                    isMemberSpecialization ||
9073                                        isFunctionTemplateSpecialization,
9074                                    D.isFunctionDefinition());
9075   }
9076 
9077   if (getLangOpts().CUDA) {
9078     IdentifierInfo *II = NewFD->getIdentifier();
9079     if (II &&
9080         II->isStr(getLangOpts().HIP ? "hipConfigureCall"
9081                                     : "cudaConfigureCall") &&
9082         !NewFD->isInvalidDecl() &&
9083         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9084       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9085         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
9086       Context.setcudaConfigureCallDecl(NewFD);
9087     }
9088 
9089     // Variadic functions, other than a *declaration* of printf, are not allowed
9090     // in device-side CUDA code, unless someone passed
9091     // -fcuda-allow-variadic-functions.
9092     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9093         (NewFD->hasAttr<CUDADeviceAttr>() ||
9094          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9095         !(II && II->isStr("printf") && NewFD->isExternC() &&
9096           !D.isFunctionDefinition())) {
9097       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9098     }
9099   }
9100 
9101   MarkUnusedFileScopedDecl(NewFD);
9102 
9103   if (getLangOpts().CPlusPlus) {
9104     if (FunctionTemplate) {
9105       if (NewFD->isInvalidDecl())
9106         FunctionTemplate->setInvalidDecl();
9107       return FunctionTemplate;
9108     }
9109 
9110     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9111       CompleteMemberSpecialization(NewFD, Previous);
9112   }
9113 
9114   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9115     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9116     if ((getLangOpts().OpenCLVersion >= 120)
9117         && (SC == SC_Static)) {
9118       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9119       D.setInvalidType();
9120     }
9121 
9122     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9123     if (!NewFD->getReturnType()->isVoidType()) {
9124       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9125       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9126           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9127                                 : FixItHint());
9128       D.setInvalidType();
9129     }
9130 
9131     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9132     for (auto Param : NewFD->parameters())
9133       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9134   }
9135   for (const ParmVarDecl *Param : NewFD->parameters()) {
9136     QualType PT = Param->getType();
9137 
9138     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9139     // types.
9140     if (getLangOpts().OpenCLVersion >= 200) {
9141       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9142         QualType ElemTy = PipeTy->getElementType();
9143           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9144             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9145             D.setInvalidType();
9146           }
9147       }
9148     }
9149   }
9150 
9151   // Here we have an function template explicit specialization at class scope.
9152   // The actual specialization will be postponed to template instatiation
9153   // time via the ClassScopeFunctionSpecializationDecl node.
9154   if (isDependentClassScopeExplicitSpecialization) {
9155     ClassScopeFunctionSpecializationDecl *NewSpec =
9156                          ClassScopeFunctionSpecializationDecl::Create(
9157                                 Context, CurContext, NewFD->getLocation(),
9158                                 cast<CXXMethodDecl>(NewFD),
9159                                 HasExplicitTemplateArgs, TemplateArgs);
9160     CurContext->addDecl(NewSpec);
9161     AddToScope = false;
9162   }
9163 
9164   // Diagnose availability attributes. Availability cannot be used on functions
9165   // that are run during load/unload.
9166   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9167     if (NewFD->hasAttr<ConstructorAttr>()) {
9168       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9169           << 1;
9170       NewFD->dropAttr<AvailabilityAttr>();
9171     }
9172     if (NewFD->hasAttr<DestructorAttr>()) {
9173       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9174           << 2;
9175       NewFD->dropAttr<AvailabilityAttr>();
9176     }
9177   }
9178 
9179   return NewFD;
9180 }
9181 
9182 /// Checks if the new declaration declared in dependent context must be
9183 /// put in the same redeclaration chain as the specified declaration.
9184 ///
9185 /// \param D Declaration that is checked.
9186 /// \param PrevDecl Previous declaration found with proper lookup method for the
9187 ///                 same declaration name.
9188 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9189 ///          belongs to.
9190 ///
9191 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9192   // Any declarations should be put into redeclaration chains except for
9193   // friend declaration in a dependent context that names a function in
9194   // namespace scope.
9195   //
9196   // This allows to compile code like:
9197   //
9198   //       void func();
9199   //       template<typename T> class C1 { friend void func() { } };
9200   //       template<typename T> class C2 { friend void func() { } };
9201   //
9202   // This code snippet is a valid code unless both templates are instantiated.
9203   return !(D->getLexicalDeclContext()->isDependentContext() &&
9204            D->getDeclContext()->isFileContext() &&
9205            D->getFriendObjectKind() != Decl::FOK_None);
9206 }
9207 
9208 /// Check the target attribute of the function for MultiVersion
9209 /// validity.
9210 ///
9211 /// Returns true if there was an error, false otherwise.
9212 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9213   const auto *TA = FD->getAttr<TargetAttr>();
9214   assert(TA && "MultiVersion Candidate requires a target attribute");
9215   TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9216   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9217   enum ErrType { Feature = 0, Architecture = 1 };
9218 
9219   if (!ParseInfo.Architecture.empty() &&
9220       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9221     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9222         << Architecture << ParseInfo.Architecture;
9223     return true;
9224   }
9225 
9226   for (const auto &Feat : ParseInfo.Features) {
9227     auto BareFeat = StringRef{Feat}.substr(1);
9228     if (Feat[0] == '-') {
9229       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9230           << Feature << ("no-" + BareFeat).str();
9231       return true;
9232     }
9233 
9234     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9235         !TargetInfo.isValidFeatureName(BareFeat)) {
9236       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9237           << Feature << BareFeat;
9238       return true;
9239     }
9240   }
9241   return false;
9242 }
9243 
9244 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9245                                              const FunctionDecl *NewFD,
9246                                              bool CausesMV) {
9247   enum DoesntSupport {
9248     FuncTemplates = 0,
9249     VirtFuncs = 1,
9250     DeducedReturn = 2,
9251     Constructors = 3,
9252     Destructors = 4,
9253     DeletedFuncs = 5,
9254     DefaultedFuncs = 6
9255   };
9256   enum Different {
9257     CallingConv = 0,
9258     ReturnType = 1,
9259     ConstexprSpec = 2,
9260     InlineSpec = 3,
9261     StorageClass = 4,
9262     Linkage = 5
9263   };
9264 
9265   // For now, disallow all other attributes.  These should be opt-in, but
9266   // an analysis of all of them is a future FIXME.
9267   if (CausesMV && OldFD &&
9268       std::distance(OldFD->attr_begin(), OldFD->attr_end()) != 1) {
9269     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs);
9270     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9271     return true;
9272   }
9273 
9274   if (std::distance(NewFD->attr_begin(), NewFD->attr_end()) != 1)
9275     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs);
9276 
9277   if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9278     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9279            << FuncTemplates;
9280 
9281   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9282     if (NewCXXFD->isVirtual())
9283       return S.Diag(NewCXXFD->getLocation(),
9284                     diag::err_multiversion_doesnt_support)
9285              << VirtFuncs;
9286 
9287     if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
9288       return S.Diag(NewCXXCtor->getLocation(),
9289                     diag::err_multiversion_doesnt_support)
9290              << Constructors;
9291 
9292     if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
9293       return S.Diag(NewCXXDtor->getLocation(),
9294                     diag::err_multiversion_doesnt_support)
9295              << Destructors;
9296   }
9297 
9298   if (NewFD->isDeleted())
9299     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9300            << DeletedFuncs;
9301 
9302   if (NewFD->isDefaulted())
9303     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9304            << DefaultedFuncs;
9305 
9306   QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
9307   const auto *NewType = cast<FunctionType>(NewQType);
9308   QualType NewReturnType = NewType->getReturnType();
9309 
9310   if (NewReturnType->isUndeducedType())
9311     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9312            << DeducedReturn;
9313 
9314   // Only allow transition to MultiVersion if it hasn't been used.
9315   if (OldFD && CausesMV && OldFD->isUsed(false))
9316     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9317 
9318   // Ensure the return type is identical.
9319   if (OldFD) {
9320     QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
9321     const auto *OldType = cast<FunctionType>(OldQType);
9322     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9323     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9324 
9325     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9326       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9327              << CallingConv;
9328 
9329     QualType OldReturnType = OldType->getReturnType();
9330 
9331     if (OldReturnType != NewReturnType)
9332       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9333              << ReturnType;
9334 
9335     if (OldFD->isConstexpr() != NewFD->isConstexpr())
9336       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9337              << ConstexprSpec;
9338 
9339     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9340       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9341              << InlineSpec;
9342 
9343     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9344       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9345              << StorageClass;
9346 
9347     if (OldFD->isExternC() != NewFD->isExternC())
9348       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9349              << Linkage;
9350 
9351     if (S.CheckEquivalentExceptionSpec(
9352             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9353             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9354       return true;
9355   }
9356   return false;
9357 }
9358 
9359 /// Check the validity of a mulitversion function declaration.
9360 /// Also sets the multiversion'ness' of the function itself.
9361 ///
9362 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9363 ///
9364 /// Returns true if there was an error, false otherwise.
9365 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
9366                                       bool &Redeclaration, NamedDecl *&OldDecl,
9367                                       bool &MergeTypeWithPrevious,
9368                                       LookupResult &Previous) {
9369   const auto *NewTA = NewFD->getAttr<TargetAttr>();
9370   if (NewFD->isMain()) {
9371     if (NewTA && NewTA->isDefaultVersion()) {
9372       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
9373       NewFD->setInvalidDecl();
9374       return true;
9375     }
9376     return false;
9377   }
9378 
9379   // If there is no matching previous decl, only 'default' can
9380   // cause MultiVersioning.
9381   if (!OldDecl) {
9382     if (NewTA && NewTA->isDefaultVersion()) {
9383       if (!NewFD->getType()->getAs<FunctionProtoType>()) {
9384         S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
9385         NewFD->setInvalidDecl();
9386         return true;
9387       }
9388       if (CheckMultiVersionAdditionalRules(S, nullptr, NewFD, true)) {
9389         NewFD->setInvalidDecl();
9390         return true;
9391       }
9392       if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9393         S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9394         NewFD->setInvalidDecl();
9395         return true;
9396       }
9397 
9398       NewFD->setIsMultiVersion();
9399     }
9400     return false;
9401   }
9402 
9403   if (OldDecl->getDeclContext()->getRedeclContext() !=
9404       NewFD->getDeclContext()->getRedeclContext())
9405     return false;
9406 
9407   FunctionDecl *OldFD = OldDecl->getAsFunction();
9408   // Unresolved 'using' statements (the other way OldDecl can be not a function)
9409   // likely cannot cause a problem here.
9410   if (!OldFD)
9411     return false;
9412 
9413   if (!OldFD->isMultiVersion() && !NewTA)
9414     return false;
9415 
9416   if (OldFD->isMultiVersion() && !NewTA) {
9417     S.Diag(NewFD->getLocation(), diag::err_target_required_in_redecl);
9418     NewFD->setInvalidDecl();
9419     return true;
9420   }
9421 
9422   TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9423   // Sort order doesn't matter, it just needs to be consistent.
9424   llvm::sort(NewParsed.Features.begin(), NewParsed.Features.end());
9425 
9426   const auto *OldTA = OldFD->getAttr<TargetAttr>();
9427   if (!OldFD->isMultiVersion()) {
9428     // If the old decl is NOT MultiVersioned yet, and we don't cause that
9429     // to change, this is a simple redeclaration.
9430     if (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())
9431       return false;
9432 
9433     // Otherwise, this decl causes MultiVersioning.
9434     if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9435       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9436       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9437       NewFD->setInvalidDecl();
9438       return true;
9439     }
9440 
9441     if (!OldFD->getType()->getAs<FunctionProtoType>()) {
9442       S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
9443       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9444       NewFD->setInvalidDecl();
9445       return true;
9446     }
9447 
9448     if (CheckMultiVersionValue(S, NewFD)) {
9449       NewFD->setInvalidDecl();
9450       return true;
9451     }
9452 
9453     if (CheckMultiVersionValue(S, OldFD)) {
9454       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9455       NewFD->setInvalidDecl();
9456       return true;
9457     }
9458 
9459     TargetAttr::ParsedTargetAttr OldParsed =
9460         OldTA->parse(std::less<std::string>());
9461 
9462     if (OldParsed == NewParsed) {
9463       S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9464       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9465       NewFD->setInvalidDecl();
9466       return true;
9467     }
9468 
9469     for (const auto *FD : OldFD->redecls()) {
9470       const auto *CurTA = FD->getAttr<TargetAttr>();
9471       if (!CurTA || CurTA->isInherited()) {
9472         S.Diag(FD->getLocation(), diag::err_target_required_in_redecl);
9473         S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9474         NewFD->setInvalidDecl();
9475         return true;
9476       }
9477     }
9478 
9479     if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true)) {
9480       NewFD->setInvalidDecl();
9481       return true;
9482     }
9483 
9484     OldFD->setIsMultiVersion();
9485     NewFD->setIsMultiVersion();
9486     Redeclaration = false;
9487     MergeTypeWithPrevious = false;
9488     OldDecl = nullptr;
9489     Previous.clear();
9490     return false;
9491   }
9492 
9493   bool UseMemberUsingDeclRules =
9494       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
9495 
9496   // Next, check ALL non-overloads to see if this is a redeclaration of a
9497   // previous member of the MultiVersion set.
9498   for (NamedDecl *ND : Previous) {
9499     FunctionDecl *CurFD = ND->getAsFunction();
9500     if (!CurFD)
9501       continue;
9502     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
9503       continue;
9504 
9505     const auto *CurTA = CurFD->getAttr<TargetAttr>();
9506     if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
9507       NewFD->setIsMultiVersion();
9508       Redeclaration = true;
9509       OldDecl = ND;
9510       return false;
9511     }
9512 
9513     TargetAttr::ParsedTargetAttr CurParsed =
9514         CurTA->parse(std::less<std::string>());
9515 
9516     if (CurParsed == NewParsed) {
9517       S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9518       S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9519       NewFD->setInvalidDecl();
9520       return true;
9521     }
9522   }
9523 
9524   // Else, this is simply a non-redecl case.
9525   if (CheckMultiVersionValue(S, NewFD)) {
9526     NewFD->setInvalidDecl();
9527     return true;
9528   }
9529 
9530   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, false)) {
9531     NewFD->setInvalidDecl();
9532     return true;
9533   }
9534 
9535   NewFD->setIsMultiVersion();
9536   Redeclaration = false;
9537   MergeTypeWithPrevious = false;
9538   OldDecl = nullptr;
9539   Previous.clear();
9540   return false;
9541 }
9542 
9543 /// Perform semantic checking of a new function declaration.
9544 ///
9545 /// Performs semantic analysis of the new function declaration
9546 /// NewFD. This routine performs all semantic checking that does not
9547 /// require the actual declarator involved in the declaration, and is
9548 /// used both for the declaration of functions as they are parsed
9549 /// (called via ActOnDeclarator) and for the declaration of functions
9550 /// that have been instantiated via C++ template instantiation (called
9551 /// via InstantiateDecl).
9552 ///
9553 /// \param IsMemberSpecialization whether this new function declaration is
9554 /// a member specialization (that replaces any definition provided by the
9555 /// previous declaration).
9556 ///
9557 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9558 ///
9559 /// \returns true if the function declaration is a redeclaration.
9560 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9561                                     LookupResult &Previous,
9562                                     bool IsMemberSpecialization) {
9563   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9564          "Variably modified return types are not handled here");
9565 
9566   // Determine whether the type of this function should be merged with
9567   // a previous visible declaration. This never happens for functions in C++,
9568   // and always happens in C if the previous declaration was visible.
9569   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9570                                !Previous.isShadowed();
9571 
9572   bool Redeclaration = false;
9573   NamedDecl *OldDecl = nullptr;
9574   bool MayNeedOverloadableChecks = false;
9575 
9576   // Merge or overload the declaration with an existing declaration of
9577   // the same name, if appropriate.
9578   if (!Previous.empty()) {
9579     // Determine whether NewFD is an overload of PrevDecl or
9580     // a declaration that requires merging. If it's an overload,
9581     // there's no more work to do here; we'll just add the new
9582     // function to the scope.
9583     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
9584       NamedDecl *Candidate = Previous.getRepresentativeDecl();
9585       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9586         Redeclaration = true;
9587         OldDecl = Candidate;
9588       }
9589     } else {
9590       MayNeedOverloadableChecks = true;
9591       switch (CheckOverload(S, NewFD, Previous, OldDecl,
9592                             /*NewIsUsingDecl*/ false)) {
9593       case Ovl_Match:
9594         Redeclaration = true;
9595         break;
9596 
9597       case Ovl_NonFunction:
9598         Redeclaration = true;
9599         break;
9600 
9601       case Ovl_Overload:
9602         Redeclaration = false;
9603         break;
9604       }
9605     }
9606   }
9607 
9608   // Check for a previous extern "C" declaration with this name.
9609   if (!Redeclaration &&
9610       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9611     if (!Previous.empty()) {
9612       // This is an extern "C" declaration with the same name as a previous
9613       // declaration, and thus redeclares that entity...
9614       Redeclaration = true;
9615       OldDecl = Previous.getFoundDecl();
9616       MergeTypeWithPrevious = false;
9617 
9618       // ... except in the presence of __attribute__((overloadable)).
9619       if (OldDecl->hasAttr<OverloadableAttr>() ||
9620           NewFD->hasAttr<OverloadableAttr>()) {
9621         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9622           MayNeedOverloadableChecks = true;
9623           Redeclaration = false;
9624           OldDecl = nullptr;
9625         }
9626       }
9627     }
9628   }
9629 
9630   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
9631                                 MergeTypeWithPrevious, Previous))
9632     return Redeclaration;
9633 
9634   // C++11 [dcl.constexpr]p8:
9635   //   A constexpr specifier for a non-static member function that is not
9636   //   a constructor declares that member function to be const.
9637   //
9638   // This needs to be delayed until we know whether this is an out-of-line
9639   // definition of a static member function.
9640   //
9641   // This rule is not present in C++1y, so we produce a backwards
9642   // compatibility warning whenever it happens in C++11.
9643   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9644   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9645       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9646       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9647     CXXMethodDecl *OldMD = nullptr;
9648     if (OldDecl)
9649       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9650     if (!OldMD || !OldMD->isStatic()) {
9651       const FunctionProtoType *FPT =
9652         MD->getType()->castAs<FunctionProtoType>();
9653       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9654       EPI.TypeQuals |= Qualifiers::Const;
9655       MD->setType(Context.getFunctionType(FPT->getReturnType(),
9656                                           FPT->getParamTypes(), EPI));
9657 
9658       // Warn that we did this, if we're not performing template instantiation.
9659       // In that case, we'll have warned already when the template was defined.
9660       if (!inTemplateInstantiation()) {
9661         SourceLocation AddConstLoc;
9662         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
9663                 .IgnoreParens().getAs<FunctionTypeLoc>())
9664           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
9665 
9666         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
9667           << FixItHint::CreateInsertion(AddConstLoc, " const");
9668       }
9669     }
9670   }
9671 
9672   if (Redeclaration) {
9673     // NewFD and OldDecl represent declarations that need to be
9674     // merged.
9675     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
9676       NewFD->setInvalidDecl();
9677       return Redeclaration;
9678     }
9679 
9680     Previous.clear();
9681     Previous.addDecl(OldDecl);
9682 
9683     if (FunctionTemplateDecl *OldTemplateDecl =
9684             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
9685       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
9686       NewFD->setPreviousDeclaration(OldFD);
9687       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
9688       FunctionTemplateDecl *NewTemplateDecl
9689         = NewFD->getDescribedFunctionTemplate();
9690       assert(NewTemplateDecl && "Template/non-template mismatch");
9691       if (NewFD->isCXXClassMember()) {
9692         NewFD->setAccess(OldTemplateDecl->getAccess());
9693         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
9694       }
9695 
9696       // If this is an explicit specialization of a member that is a function
9697       // template, mark it as a member specialization.
9698       if (IsMemberSpecialization &&
9699           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
9700         NewTemplateDecl->setMemberSpecialization();
9701         assert(OldTemplateDecl->isMemberSpecialization());
9702         // Explicit specializations of a member template do not inherit deleted
9703         // status from the parent member template that they are specializing.
9704         if (OldFD->isDeleted()) {
9705           // FIXME: This assert will not hold in the presence of modules.
9706           assert(OldFD->getCanonicalDecl() == OldFD);
9707           // FIXME: We need an update record for this AST mutation.
9708           OldFD->setDeletedAsWritten(false);
9709         }
9710       }
9711 
9712     } else {
9713       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9714         auto *OldFD = cast<FunctionDecl>(OldDecl);
9715         // This needs to happen first so that 'inline' propagates.
9716         NewFD->setPreviousDeclaration(OldFD);
9717         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
9718         if (NewFD->isCXXClassMember())
9719           NewFD->setAccess(OldFD->getAccess());
9720       }
9721     }
9722   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
9723              !NewFD->getAttr<OverloadableAttr>()) {
9724     assert((Previous.empty() ||
9725             llvm::any_of(Previous,
9726                          [](const NamedDecl *ND) {
9727                            return ND->hasAttr<OverloadableAttr>();
9728                          })) &&
9729            "Non-redecls shouldn't happen without overloadable present");
9730 
9731     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
9732       const auto *FD = dyn_cast<FunctionDecl>(ND);
9733       return FD && !FD->hasAttr<OverloadableAttr>();
9734     });
9735 
9736     if (OtherUnmarkedIter != Previous.end()) {
9737       Diag(NewFD->getLocation(),
9738            diag::err_attribute_overloadable_multiple_unmarked_overloads);
9739       Diag((*OtherUnmarkedIter)->getLocation(),
9740            diag::note_attribute_overloadable_prev_overload)
9741           << false;
9742 
9743       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9744     }
9745   }
9746 
9747   // Semantic checking for this function declaration (in isolation).
9748 
9749   if (getLangOpts().CPlusPlus) {
9750     // C++-specific checks.
9751     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9752       CheckConstructor(Constructor);
9753     } else if (CXXDestructorDecl *Destructor =
9754                 dyn_cast<CXXDestructorDecl>(NewFD)) {
9755       CXXRecordDecl *Record = Destructor->getParent();
9756       QualType ClassType = Context.getTypeDeclType(Record);
9757 
9758       // FIXME: Shouldn't we be able to perform this check even when the class
9759       // type is dependent? Both gcc and edg can handle that.
9760       if (!ClassType->isDependentType()) {
9761         DeclarationName Name
9762           = Context.DeclarationNames.getCXXDestructorName(
9763                                         Context.getCanonicalType(ClassType));
9764         if (NewFD->getDeclName() != Name) {
9765           Diag(NewFD->getLocation(), diag::err_destructor_name);
9766           NewFD->setInvalidDecl();
9767           return Redeclaration;
9768         }
9769       }
9770     } else if (CXXConversionDecl *Conversion
9771                = dyn_cast<CXXConversionDecl>(NewFD)) {
9772       ActOnConversionDeclarator(Conversion);
9773     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
9774       if (auto *TD = Guide->getDescribedFunctionTemplate())
9775         CheckDeductionGuideTemplate(TD);
9776 
9777       // A deduction guide is not on the list of entities that can be
9778       // explicitly specialized.
9779       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
9780         Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
9781             << /*explicit specialization*/ 1;
9782     }
9783 
9784     // Find any virtual functions that this function overrides.
9785     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9786       if (!Method->isFunctionTemplateSpecialization() &&
9787           !Method->getDescribedFunctionTemplate() &&
9788           Method->isCanonicalDecl()) {
9789         if (AddOverriddenMethods(Method->getParent(), Method)) {
9790           // If the function was marked as "static", we have a problem.
9791           if (NewFD->getStorageClass() == SC_Static) {
9792             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
9793           }
9794         }
9795       }
9796 
9797       if (Method->isStatic())
9798         checkThisInStaticMemberFunctionType(Method);
9799     }
9800 
9801     // Extra checking for C++ overloaded operators (C++ [over.oper]).
9802     if (NewFD->isOverloadedOperator() &&
9803         CheckOverloadedOperatorDeclaration(NewFD)) {
9804       NewFD->setInvalidDecl();
9805       return Redeclaration;
9806     }
9807 
9808     // Extra checking for C++0x literal operators (C++0x [over.literal]).
9809     if (NewFD->getLiteralIdentifier() &&
9810         CheckLiteralOperatorDeclaration(NewFD)) {
9811       NewFD->setInvalidDecl();
9812       return Redeclaration;
9813     }
9814 
9815     // In C++, check default arguments now that we have merged decls. Unless
9816     // the lexical context is the class, because in this case this is done
9817     // during delayed parsing anyway.
9818     if (!CurContext->isRecord())
9819       CheckCXXDefaultArguments(NewFD);
9820 
9821     // If this function declares a builtin function, check the type of this
9822     // declaration against the expected type for the builtin.
9823     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9824       ASTContext::GetBuiltinTypeError Error;
9825       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9826       QualType T = Context.GetBuiltinType(BuiltinID, Error);
9827       // If the type of the builtin differs only in its exception
9828       // specification, that's OK.
9829       // FIXME: If the types do differ in this way, it would be better to
9830       // retain the 'noexcept' form of the type.
9831       if (!T.isNull() &&
9832           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
9833                                                             NewFD->getType()))
9834         // The type of this function differs from the type of the builtin,
9835         // so forget about the builtin entirely.
9836         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9837     }
9838 
9839     // If this function is declared as being extern "C", then check to see if
9840     // the function returns a UDT (class, struct, or union type) that is not C
9841     // compatible, and if it does, warn the user.
9842     // But, issue any diagnostic on the first declaration only.
9843     if (Previous.empty() && NewFD->isExternC()) {
9844       QualType R = NewFD->getReturnType();
9845       if (R->isIncompleteType() && !R->isVoidType())
9846         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9847             << NewFD << R;
9848       else if (!R.isPODType(Context) && !R->isVoidType() &&
9849                !R->isObjCObjectPointerType())
9850         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9851     }
9852 
9853     // C++1z [dcl.fct]p6:
9854     //   [...] whether the function has a non-throwing exception-specification
9855     //   [is] part of the function type
9856     //
9857     // This results in an ABI break between C++14 and C++17 for functions whose
9858     // declared type includes an exception-specification in a parameter or
9859     // return type. (Exception specifications on the function itself are OK in
9860     // most cases, and exception specifications are not permitted in most other
9861     // contexts where they could make it into a mangling.)
9862     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
9863       auto HasNoexcept = [&](QualType T) -> bool {
9864         // Strip off declarator chunks that could be between us and a function
9865         // type. We don't need to look far, exception specifications are very
9866         // restricted prior to C++17.
9867         if (auto *RT = T->getAs<ReferenceType>())
9868           T = RT->getPointeeType();
9869         else if (T->isAnyPointerType())
9870           T = T->getPointeeType();
9871         else if (auto *MPT = T->getAs<MemberPointerType>())
9872           T = MPT->getPointeeType();
9873         if (auto *FPT = T->getAs<FunctionProtoType>())
9874           if (FPT->isNothrow())
9875             return true;
9876         return false;
9877       };
9878 
9879       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9880       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9881       for (QualType T : FPT->param_types())
9882         AnyNoexcept |= HasNoexcept(T);
9883       if (AnyNoexcept)
9884         Diag(NewFD->getLocation(),
9885              diag::warn_cxx17_compat_exception_spec_in_signature)
9886             << NewFD;
9887     }
9888 
9889     if (!Redeclaration && LangOpts.CUDA)
9890       checkCUDATargetOverload(NewFD, Previous);
9891   }
9892   return Redeclaration;
9893 }
9894 
9895 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9896   // C++11 [basic.start.main]p3:
9897   //   A program that [...] declares main to be inline, static or
9898   //   constexpr is ill-formed.
9899   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
9900   //   appear in a declaration of main.
9901   // static main is not an error under C99, but we should warn about it.
9902   // We accept _Noreturn main as an extension.
9903   if (FD->getStorageClass() == SC_Static)
9904     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9905          ? diag::err_static_main : diag::warn_static_main)
9906       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9907   if (FD->isInlineSpecified())
9908     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9909       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9910   if (DS.isNoreturnSpecified()) {
9911     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9912     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9913     Diag(NoreturnLoc, diag::ext_noreturn_main);
9914     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9915       << FixItHint::CreateRemoval(NoreturnRange);
9916   }
9917   if (FD->isConstexpr()) {
9918     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9919       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9920     FD->setConstexpr(false);
9921   }
9922 
9923   if (getLangOpts().OpenCL) {
9924     Diag(FD->getLocation(), diag::err_opencl_no_main)
9925         << FD->hasAttr<OpenCLKernelAttr>();
9926     FD->setInvalidDecl();
9927     return;
9928   }
9929 
9930   QualType T = FD->getType();
9931   assert(T->isFunctionType() && "function decl is not of function type");
9932   const FunctionType* FT = T->castAs<FunctionType>();
9933 
9934   // Set default calling convention for main()
9935   if (FT->getCallConv() != CC_C) {
9936     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
9937     FD->setType(QualType(FT, 0));
9938     T = Context.getCanonicalType(FD->getType());
9939   }
9940 
9941   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9942     // In C with GNU extensions we allow main() to have non-integer return
9943     // type, but we should warn about the extension, and we disable the
9944     // implicit-return-zero rule.
9945 
9946     // GCC in C mode accepts qualified 'int'.
9947     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9948       FD->setHasImplicitReturnZero(true);
9949     else {
9950       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9951       SourceRange RTRange = FD->getReturnTypeSourceRange();
9952       if (RTRange.isValid())
9953         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9954             << FixItHint::CreateReplacement(RTRange, "int");
9955     }
9956   } else {
9957     // In C and C++, main magically returns 0 if you fall off the end;
9958     // set the flag which tells us that.
9959     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9960 
9961     // All the standards say that main() should return 'int'.
9962     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9963       FD->setHasImplicitReturnZero(true);
9964     else {
9965       // Otherwise, this is just a flat-out error.
9966       SourceRange RTRange = FD->getReturnTypeSourceRange();
9967       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9968           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9969                                 : FixItHint());
9970       FD->setInvalidDecl(true);
9971     }
9972   }
9973 
9974   // Treat protoless main() as nullary.
9975   if (isa<FunctionNoProtoType>(FT)) return;
9976 
9977   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9978   unsigned nparams = FTP->getNumParams();
9979   assert(FD->getNumParams() == nparams);
9980 
9981   bool HasExtraParameters = (nparams > 3);
9982 
9983   if (FTP->isVariadic()) {
9984     Diag(FD->getLocation(), diag::ext_variadic_main);
9985     // FIXME: if we had information about the location of the ellipsis, we
9986     // could add a FixIt hint to remove it as a parameter.
9987   }
9988 
9989   // Darwin passes an undocumented fourth argument of type char**.  If
9990   // other platforms start sprouting these, the logic below will start
9991   // getting shifty.
9992   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9993     HasExtraParameters = false;
9994 
9995   if (HasExtraParameters) {
9996     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9997     FD->setInvalidDecl(true);
9998     nparams = 3;
9999   }
10000 
10001   // FIXME: a lot of the following diagnostics would be improved
10002   // if we had some location information about types.
10003 
10004   QualType CharPP =
10005     Context.getPointerType(Context.getPointerType(Context.CharTy));
10006   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10007 
10008   for (unsigned i = 0; i < nparams; ++i) {
10009     QualType AT = FTP->getParamType(i);
10010 
10011     bool mismatch = true;
10012 
10013     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10014       mismatch = false;
10015     else if (Expected[i] == CharPP) {
10016       // As an extension, the following forms are okay:
10017       //   char const **
10018       //   char const * const *
10019       //   char * const *
10020 
10021       QualifierCollector qs;
10022       const PointerType* PT;
10023       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10024           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10025           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10026                               Context.CharTy)) {
10027         qs.removeConst();
10028         mismatch = !qs.empty();
10029       }
10030     }
10031 
10032     if (mismatch) {
10033       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10034       // TODO: suggest replacing given type with expected type
10035       FD->setInvalidDecl(true);
10036     }
10037   }
10038 
10039   if (nparams == 1 && !FD->isInvalidDecl()) {
10040     Diag(FD->getLocation(), diag::warn_main_one_arg);
10041   }
10042 
10043   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10044     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10045     FD->setInvalidDecl();
10046   }
10047 }
10048 
10049 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10050   QualType T = FD->getType();
10051   assert(T->isFunctionType() && "function decl is not of function type");
10052   const FunctionType *FT = T->castAs<FunctionType>();
10053 
10054   // Set an implicit return of 'zero' if the function can return some integral,
10055   // enumeration, pointer or nullptr type.
10056   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10057       FT->getReturnType()->isAnyPointerType() ||
10058       FT->getReturnType()->isNullPtrType())
10059     // DllMain is exempt because a return value of zero means it failed.
10060     if (FD->getName() != "DllMain")
10061       FD->setHasImplicitReturnZero(true);
10062 
10063   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10064     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10065     FD->setInvalidDecl();
10066   }
10067 }
10068 
10069 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10070   // FIXME: Need strict checking.  In C89, we need to check for
10071   // any assignment, increment, decrement, function-calls, or
10072   // commas outside of a sizeof.  In C99, it's the same list,
10073   // except that the aforementioned are allowed in unevaluated
10074   // expressions.  Everything else falls under the
10075   // "may accept other forms of constant expressions" exception.
10076   // (We never end up here for C++, so the constant expression
10077   // rules there don't matter.)
10078   const Expr *Culprit;
10079   if (Init->isConstantInitializer(Context, false, &Culprit))
10080     return false;
10081   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10082     << Culprit->getSourceRange();
10083   return true;
10084 }
10085 
10086 namespace {
10087   // Visits an initialization expression to see if OrigDecl is evaluated in
10088   // its own initialization and throws a warning if it does.
10089   class SelfReferenceChecker
10090       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10091     Sema &S;
10092     Decl *OrigDecl;
10093     bool isRecordType;
10094     bool isPODType;
10095     bool isReferenceType;
10096 
10097     bool isInitList;
10098     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10099 
10100   public:
10101     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10102 
10103     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10104                                                     S(S), OrigDecl(OrigDecl) {
10105       isPODType = false;
10106       isRecordType = false;
10107       isReferenceType = false;
10108       isInitList = false;
10109       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10110         isPODType = VD->getType().isPODType(S.Context);
10111         isRecordType = VD->getType()->isRecordType();
10112         isReferenceType = VD->getType()->isReferenceType();
10113       }
10114     }
10115 
10116     // For most expressions, just call the visitor.  For initializer lists,
10117     // track the index of the field being initialized since fields are
10118     // initialized in order allowing use of previously initialized fields.
10119     void CheckExpr(Expr *E) {
10120       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10121       if (!InitList) {
10122         Visit(E);
10123         return;
10124       }
10125 
10126       // Track and increment the index here.
10127       isInitList = true;
10128       InitFieldIndex.push_back(0);
10129       for (auto Child : InitList->children()) {
10130         CheckExpr(cast<Expr>(Child));
10131         ++InitFieldIndex.back();
10132       }
10133       InitFieldIndex.pop_back();
10134     }
10135 
10136     // Returns true if MemberExpr is checked and no further checking is needed.
10137     // Returns false if additional checking is required.
10138     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10139       llvm::SmallVector<FieldDecl*, 4> Fields;
10140       Expr *Base = E;
10141       bool ReferenceField = false;
10142 
10143       // Get the field memebers used.
10144       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10145         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10146         if (!FD)
10147           return false;
10148         Fields.push_back(FD);
10149         if (FD->getType()->isReferenceType())
10150           ReferenceField = true;
10151         Base = ME->getBase()->IgnoreParenImpCasts();
10152       }
10153 
10154       // Keep checking only if the base Decl is the same.
10155       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10156       if (!DRE || DRE->getDecl() != OrigDecl)
10157         return false;
10158 
10159       // A reference field can be bound to an unininitialized field.
10160       if (CheckReference && !ReferenceField)
10161         return true;
10162 
10163       // Convert FieldDecls to their index number.
10164       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10165       for (const FieldDecl *I : llvm::reverse(Fields))
10166         UsedFieldIndex.push_back(I->getFieldIndex());
10167 
10168       // See if a warning is needed by checking the first difference in index
10169       // numbers.  If field being used has index less than the field being
10170       // initialized, then the use is safe.
10171       for (auto UsedIter = UsedFieldIndex.begin(),
10172                 UsedEnd = UsedFieldIndex.end(),
10173                 OrigIter = InitFieldIndex.begin(),
10174                 OrigEnd = InitFieldIndex.end();
10175            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10176         if (*UsedIter < *OrigIter)
10177           return true;
10178         if (*UsedIter > *OrigIter)
10179           break;
10180       }
10181 
10182       // TODO: Add a different warning which will print the field names.
10183       HandleDeclRefExpr(DRE);
10184       return true;
10185     }
10186 
10187     // For most expressions, the cast is directly above the DeclRefExpr.
10188     // For conditional operators, the cast can be outside the conditional
10189     // operator if both expressions are DeclRefExpr's.
10190     void HandleValue(Expr *E) {
10191       E = E->IgnoreParens();
10192       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10193         HandleDeclRefExpr(DRE);
10194         return;
10195       }
10196 
10197       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10198         Visit(CO->getCond());
10199         HandleValue(CO->getTrueExpr());
10200         HandleValue(CO->getFalseExpr());
10201         return;
10202       }
10203 
10204       if (BinaryConditionalOperator *BCO =
10205               dyn_cast<BinaryConditionalOperator>(E)) {
10206         Visit(BCO->getCond());
10207         HandleValue(BCO->getFalseExpr());
10208         return;
10209       }
10210 
10211       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10212         HandleValue(OVE->getSourceExpr());
10213         return;
10214       }
10215 
10216       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10217         if (BO->getOpcode() == BO_Comma) {
10218           Visit(BO->getLHS());
10219           HandleValue(BO->getRHS());
10220           return;
10221         }
10222       }
10223 
10224       if (isa<MemberExpr>(E)) {
10225         if (isInitList) {
10226           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10227                                       false /*CheckReference*/))
10228             return;
10229         }
10230 
10231         Expr *Base = E->IgnoreParenImpCasts();
10232         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10233           // Check for static member variables and don't warn on them.
10234           if (!isa<FieldDecl>(ME->getMemberDecl()))
10235             return;
10236           Base = ME->getBase()->IgnoreParenImpCasts();
10237         }
10238         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10239           HandleDeclRefExpr(DRE);
10240         return;
10241       }
10242 
10243       Visit(E);
10244     }
10245 
10246     // Reference types not handled in HandleValue are handled here since all
10247     // uses of references are bad, not just r-value uses.
10248     void VisitDeclRefExpr(DeclRefExpr *E) {
10249       if (isReferenceType)
10250         HandleDeclRefExpr(E);
10251     }
10252 
10253     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10254       if (E->getCastKind() == CK_LValueToRValue) {
10255         HandleValue(E->getSubExpr());
10256         return;
10257       }
10258 
10259       Inherited::VisitImplicitCastExpr(E);
10260     }
10261 
10262     void VisitMemberExpr(MemberExpr *E) {
10263       if (isInitList) {
10264         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
10265           return;
10266       }
10267 
10268       // Don't warn on arrays since they can be treated as pointers.
10269       if (E->getType()->canDecayToPointerType()) return;
10270 
10271       // Warn when a non-static method call is followed by non-static member
10272       // field accesses, which is followed by a DeclRefExpr.
10273       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10274       bool Warn = (MD && !MD->isStatic());
10275       Expr *Base = E->getBase()->IgnoreParenImpCasts();
10276       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10277         if (!isa<FieldDecl>(ME->getMemberDecl()))
10278           Warn = false;
10279         Base = ME->getBase()->IgnoreParenImpCasts();
10280       }
10281 
10282       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10283         if (Warn)
10284           HandleDeclRefExpr(DRE);
10285         return;
10286       }
10287 
10288       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10289       // Visit that expression.
10290       Visit(Base);
10291     }
10292 
10293     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10294       Expr *Callee = E->getCallee();
10295 
10296       if (isa<UnresolvedLookupExpr>(Callee))
10297         return Inherited::VisitCXXOperatorCallExpr(E);
10298 
10299       Visit(Callee);
10300       for (auto Arg: E->arguments())
10301         HandleValue(Arg->IgnoreParenImpCasts());
10302     }
10303 
10304     void VisitUnaryOperator(UnaryOperator *E) {
10305       // For POD record types, addresses of its own members are well-defined.
10306       if (E->getOpcode() == UO_AddrOf && isRecordType &&
10307           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
10308         if (!isPODType)
10309           HandleValue(E->getSubExpr());
10310         return;
10311       }
10312 
10313       if (E->isIncrementDecrementOp()) {
10314         HandleValue(E->getSubExpr());
10315         return;
10316       }
10317 
10318       Inherited::VisitUnaryOperator(E);
10319     }
10320 
10321     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
10322 
10323     void VisitCXXConstructExpr(CXXConstructExpr *E) {
10324       if (E->getConstructor()->isCopyConstructor()) {
10325         Expr *ArgExpr = E->getArg(0);
10326         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
10327           if (ILE->getNumInits() == 1)
10328             ArgExpr = ILE->getInit(0);
10329         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
10330           if (ICE->getCastKind() == CK_NoOp)
10331             ArgExpr = ICE->getSubExpr();
10332         HandleValue(ArgExpr);
10333         return;
10334       }
10335       Inherited::VisitCXXConstructExpr(E);
10336     }
10337 
10338     void VisitCallExpr(CallExpr *E) {
10339       // Treat std::move as a use.
10340       if (E->isCallToStdMove()) {
10341         HandleValue(E->getArg(0));
10342         return;
10343       }
10344 
10345       Inherited::VisitCallExpr(E);
10346     }
10347 
10348     void VisitBinaryOperator(BinaryOperator *E) {
10349       if (E->isCompoundAssignmentOp()) {
10350         HandleValue(E->getLHS());
10351         Visit(E->getRHS());
10352         return;
10353       }
10354 
10355       Inherited::VisitBinaryOperator(E);
10356     }
10357 
10358     // A custom visitor for BinaryConditionalOperator is needed because the
10359     // regular visitor would check the condition and true expression separately
10360     // but both point to the same place giving duplicate diagnostics.
10361     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10362       Visit(E->getCond());
10363       Visit(E->getFalseExpr());
10364     }
10365 
10366     void HandleDeclRefExpr(DeclRefExpr *DRE) {
10367       Decl* ReferenceDecl = DRE->getDecl();
10368       if (OrigDecl != ReferenceDecl) return;
10369       unsigned diag;
10370       if (isReferenceType) {
10371         diag = diag::warn_uninit_self_reference_in_reference_init;
10372       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10373         diag = diag::warn_static_self_reference_in_init;
10374       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10375                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10376                  DRE->getDecl()->getType()->isRecordType()) {
10377         diag = diag::warn_uninit_self_reference_in_init;
10378       } else {
10379         // Local variables will be handled by the CFG analysis.
10380         return;
10381       }
10382 
10383       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
10384                             S.PDiag(diag)
10385                               << DRE->getDecl()
10386                               << OrigDecl->getLocation()
10387                               << DRE->getSourceRange());
10388     }
10389   };
10390 
10391   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10392   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10393                                  bool DirectInit) {
10394     // Parameters arguments are occassionially constructed with itself,
10395     // for instance, in recursive functions.  Skip them.
10396     if (isa<ParmVarDecl>(OrigDecl))
10397       return;
10398 
10399     E = E->IgnoreParens();
10400 
10401     // Skip checking T a = a where T is not a record or reference type.
10402     // Doing so is a way to silence uninitialized warnings.
10403     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10404       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10405         if (ICE->getCastKind() == CK_LValueToRValue)
10406           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10407             if (DRE->getDecl() == OrigDecl)
10408               return;
10409 
10410     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10411   }
10412 } // end anonymous namespace
10413 
10414 namespace {
10415   // Simple wrapper to add the name of a variable or (if no variable is
10416   // available) a DeclarationName into a diagnostic.
10417   struct VarDeclOrName {
10418     VarDecl *VDecl;
10419     DeclarationName Name;
10420 
10421     friend const Sema::SemaDiagnosticBuilder &
10422     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10423       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10424     }
10425   };
10426 } // end anonymous namespace
10427 
10428 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10429                                             DeclarationName Name, QualType Type,
10430                                             TypeSourceInfo *TSI,
10431                                             SourceRange Range, bool DirectInit,
10432                                             Expr *Init) {
10433   bool IsInitCapture = !VDecl;
10434   assert((!VDecl || !VDecl->isInitCapture()) &&
10435          "init captures are expected to be deduced prior to initialization");
10436 
10437   VarDeclOrName VN{VDecl, Name};
10438 
10439   DeducedType *Deduced = Type->getContainedDeducedType();
10440   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10441 
10442   // C++11 [dcl.spec.auto]p3
10443   if (!Init) {
10444     assert(VDecl && "no init for init capture deduction?");
10445 
10446     // Except for class argument deduction, and then for an initializing
10447     // declaration only, i.e. no static at class scope or extern.
10448     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
10449         VDecl->hasExternalStorage() ||
10450         VDecl->isStaticDataMember()) {
10451       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10452         << VDecl->getDeclName() << Type;
10453       return QualType();
10454     }
10455   }
10456 
10457   ArrayRef<Expr*> DeduceInits;
10458   if (Init)
10459     DeduceInits = Init;
10460 
10461   if (DirectInit) {
10462     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10463       DeduceInits = PL->exprs();
10464   }
10465 
10466   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10467     assert(VDecl && "non-auto type for init capture deduction?");
10468     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10469     InitializationKind Kind = InitializationKind::CreateForInit(
10470         VDecl->getLocation(), DirectInit, Init);
10471     // FIXME: Initialization should not be taking a mutable list of inits.
10472     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10473     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10474                                                        InitsCopy);
10475   }
10476 
10477   if (DirectInit) {
10478     if (auto *IL = dyn_cast<InitListExpr>(Init))
10479       DeduceInits = IL->inits();
10480   }
10481 
10482   // Deduction only works if we have exactly one source expression.
10483   if (DeduceInits.empty()) {
10484     // It isn't possible to write this directly, but it is possible to
10485     // end up in this situation with "auto x(some_pack...);"
10486     Diag(Init->getLocStart(), IsInitCapture
10487                                   ? diag::err_init_capture_no_expression
10488                                   : diag::err_auto_var_init_no_expression)
10489         << VN << Type << Range;
10490     return QualType();
10491   }
10492 
10493   if (DeduceInits.size() > 1) {
10494     Diag(DeduceInits[1]->getLocStart(),
10495          IsInitCapture ? diag::err_init_capture_multiple_expressions
10496                        : diag::err_auto_var_init_multiple_expressions)
10497         << VN << Type << Range;
10498     return QualType();
10499   }
10500 
10501   Expr *DeduceInit = DeduceInits[0];
10502   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10503     Diag(Init->getLocStart(), IsInitCapture
10504                                   ? diag::err_init_capture_paren_braces
10505                                   : diag::err_auto_var_init_paren_braces)
10506         << isa<InitListExpr>(Init) << VN << Type << Range;
10507     return QualType();
10508   }
10509 
10510   // Expressions default to 'id' when we're in a debugger.
10511   bool DefaultedAnyToId = false;
10512   if (getLangOpts().DebuggerCastResultToId &&
10513       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10514     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10515     if (Result.isInvalid()) {
10516       return QualType();
10517     }
10518     Init = Result.get();
10519     DefaultedAnyToId = true;
10520   }
10521 
10522   // C++ [dcl.decomp]p1:
10523   //   If the assignment-expression [...] has array type A and no ref-qualifier
10524   //   is present, e has type cv A
10525   if (VDecl && isa<DecompositionDecl>(VDecl) &&
10526       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10527       DeduceInit->getType()->isConstantArrayType())
10528     return Context.getQualifiedType(DeduceInit->getType(),
10529                                     Type.getQualifiers());
10530 
10531   QualType DeducedType;
10532   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
10533     if (!IsInitCapture)
10534       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
10535     else if (isa<InitListExpr>(Init))
10536       Diag(Range.getBegin(),
10537            diag::err_init_capture_deduction_failure_from_init_list)
10538           << VN
10539           << (DeduceInit->getType().isNull() ? TSI->getType()
10540                                              : DeduceInit->getType())
10541           << DeduceInit->getSourceRange();
10542     else
10543       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10544           << VN << TSI->getType()
10545           << (DeduceInit->getType().isNull() ? TSI->getType()
10546                                              : DeduceInit->getType())
10547           << DeduceInit->getSourceRange();
10548   }
10549 
10550   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10551   // 'id' instead of a specific object type prevents most of our usual
10552   // checks.
10553   // We only want to warn outside of template instantiations, though:
10554   // inside a template, the 'id' could have come from a parameter.
10555   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10556       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10557     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10558     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10559   }
10560 
10561   return DeducedType;
10562 }
10563 
10564 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
10565                                          Expr *Init) {
10566   QualType DeducedType = deduceVarTypeFromInitializer(
10567       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10568       VDecl->getSourceRange(), DirectInit, Init);
10569   if (DeducedType.isNull()) {
10570     VDecl->setInvalidDecl();
10571     return true;
10572   }
10573 
10574   VDecl->setType(DeducedType);
10575   assert(VDecl->isLinkageValid());
10576 
10577   // In ARC, infer lifetime.
10578   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10579     VDecl->setInvalidDecl();
10580 
10581   // If this is a redeclaration, check that the type we just deduced matches
10582   // the previously declared type.
10583   if (VarDecl *Old = VDecl->getPreviousDecl()) {
10584     // We never need to merge the type, because we cannot form an incomplete
10585     // array of auto, nor deduce such a type.
10586     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
10587   }
10588 
10589   // Check the deduced type is valid for a variable declaration.
10590   CheckVariableDeclarationType(VDecl);
10591   return VDecl->isInvalidDecl();
10592 }
10593 
10594 /// AddInitializerToDecl - Adds the initializer Init to the
10595 /// declaration dcl. If DirectInit is true, this is C++ direct
10596 /// initialization rather than copy initialization.
10597 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10598   // If there is no declaration, there was an error parsing it.  Just ignore
10599   // the initializer.
10600   if (!RealDecl || RealDecl->isInvalidDecl()) {
10601     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10602     return;
10603   }
10604 
10605   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10606     // Pure-specifiers are handled in ActOnPureSpecifier.
10607     Diag(Method->getLocation(), diag::err_member_function_initialization)
10608       << Method->getDeclName() << Init->getSourceRange();
10609     Method->setInvalidDecl();
10610     return;
10611   }
10612 
10613   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
10614   if (!VDecl) {
10615     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
10616     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
10617     RealDecl->setInvalidDecl();
10618     return;
10619   }
10620 
10621   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
10622   if (VDecl->getType()->isUndeducedType()) {
10623     // Attempt typo correction early so that the type of the init expression can
10624     // be deduced based on the chosen correction if the original init contains a
10625     // TypoExpr.
10626     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
10627     if (!Res.isUsable()) {
10628       RealDecl->setInvalidDecl();
10629       return;
10630     }
10631     Init = Res.get();
10632 
10633     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
10634       return;
10635   }
10636 
10637   // dllimport cannot be used on variable definitions.
10638   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
10639     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
10640     VDecl->setInvalidDecl();
10641     return;
10642   }
10643 
10644   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
10645     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
10646     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
10647     VDecl->setInvalidDecl();
10648     return;
10649   }
10650 
10651   if (!VDecl->getType()->isDependentType()) {
10652     // A definition must end up with a complete type, which means it must be
10653     // complete with the restriction that an array type might be completed by
10654     // the initializer; note that later code assumes this restriction.
10655     QualType BaseDeclType = VDecl->getType();
10656     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
10657       BaseDeclType = Array->getElementType();
10658     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
10659                             diag::err_typecheck_decl_incomplete_type)) {
10660       RealDecl->setInvalidDecl();
10661       return;
10662     }
10663 
10664     // The variable can not have an abstract class type.
10665     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
10666                                diag::err_abstract_type_in_decl,
10667                                AbstractVariableType))
10668       VDecl->setInvalidDecl();
10669   }
10670 
10671   // If adding the initializer will turn this declaration into a definition,
10672   // and we already have a definition for this variable, diagnose or otherwise
10673   // handle the situation.
10674   VarDecl *Def;
10675   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
10676       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
10677       !VDecl->isThisDeclarationADemotedDefinition() &&
10678       checkVarDeclRedefinition(Def, VDecl))
10679     return;
10680 
10681   if (getLangOpts().CPlusPlus) {
10682     // C++ [class.static.data]p4
10683     //   If a static data member is of const integral or const
10684     //   enumeration type, its declaration in the class definition can
10685     //   specify a constant-initializer which shall be an integral
10686     //   constant expression (5.19). In that case, the member can appear
10687     //   in integral constant expressions. The member shall still be
10688     //   defined in a namespace scope if it is used in the program and the
10689     //   namespace scope definition shall not contain an initializer.
10690     //
10691     // We already performed a redefinition check above, but for static
10692     // data members we also need to check whether there was an in-class
10693     // declaration with an initializer.
10694     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
10695       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
10696           << VDecl->getDeclName();
10697       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
10698            diag::note_previous_initializer)
10699           << 0;
10700       return;
10701     }
10702 
10703     if (VDecl->hasLocalStorage())
10704       setFunctionHasBranchProtectedScope();
10705 
10706     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
10707       VDecl->setInvalidDecl();
10708       return;
10709     }
10710   }
10711 
10712   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
10713   // a kernel function cannot be initialized."
10714   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
10715     Diag(VDecl->getLocation(), diag::err_local_cant_init);
10716     VDecl->setInvalidDecl();
10717     return;
10718   }
10719 
10720   // Get the decls type and save a reference for later, since
10721   // CheckInitializerTypes may change it.
10722   QualType DclT = VDecl->getType(), SavT = DclT;
10723 
10724   // Expressions default to 'id' when we're in a debugger
10725   // and we are assigning it to a variable of Objective-C pointer type.
10726   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
10727       Init->getType() == Context.UnknownAnyTy) {
10728     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10729     if (Result.isInvalid()) {
10730       VDecl->setInvalidDecl();
10731       return;
10732     }
10733     Init = Result.get();
10734   }
10735 
10736   // Perform the initialization.
10737   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
10738   if (!VDecl->isInvalidDecl()) {
10739     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10740     InitializationKind Kind = InitializationKind::CreateForInit(
10741         VDecl->getLocation(), DirectInit, Init);
10742 
10743     MultiExprArg Args = Init;
10744     if (CXXDirectInit)
10745       Args = MultiExprArg(CXXDirectInit->getExprs(),
10746                           CXXDirectInit->getNumExprs());
10747 
10748     // Try to correct any TypoExprs in the initialization arguments.
10749     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
10750       ExprResult Res = CorrectDelayedTyposInExpr(
10751           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
10752             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
10753             return Init.Failed() ? ExprError() : E;
10754           });
10755       if (Res.isInvalid()) {
10756         VDecl->setInvalidDecl();
10757       } else if (Res.get() != Args[Idx]) {
10758         Args[Idx] = Res.get();
10759       }
10760     }
10761     if (VDecl->isInvalidDecl())
10762       return;
10763 
10764     InitializationSequence InitSeq(*this, Entity, Kind, Args,
10765                                    /*TopLevelOfInitList=*/false,
10766                                    /*TreatUnavailableAsInvalid=*/false);
10767     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
10768     if (Result.isInvalid()) {
10769       VDecl->setInvalidDecl();
10770       return;
10771     }
10772 
10773     Init = Result.getAs<Expr>();
10774   }
10775 
10776   // Check for self-references within variable initializers.
10777   // Variables declared within a function/method body (except for references)
10778   // are handled by a dataflow analysis.
10779   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
10780       VDecl->getType()->isReferenceType()) {
10781     CheckSelfReference(*this, RealDecl, Init, DirectInit);
10782   }
10783 
10784   // If the type changed, it means we had an incomplete type that was
10785   // completed by the initializer. For example:
10786   //   int ary[] = { 1, 3, 5 };
10787   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
10788   if (!VDecl->isInvalidDecl() && (DclT != SavT))
10789     VDecl->setType(DclT);
10790 
10791   if (!VDecl->isInvalidDecl()) {
10792     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
10793 
10794     if (VDecl->hasAttr<BlocksAttr>())
10795       checkRetainCycles(VDecl, Init);
10796 
10797     // It is safe to assign a weak reference into a strong variable.
10798     // Although this code can still have problems:
10799     //   id x = self.weakProp;
10800     //   id y = self.weakProp;
10801     // we do not warn to warn spuriously when 'x' and 'y' are on separate
10802     // paths through the function. This should be revisited if
10803     // -Wrepeated-use-of-weak is made flow-sensitive.
10804     if (FunctionScopeInfo *FSI = getCurFunction())
10805       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
10806            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
10807           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10808                            Init->getLocStart()))
10809         FSI->markSafeWeakUse(Init);
10810   }
10811 
10812   // The initialization is usually a full-expression.
10813   //
10814   // FIXME: If this is a braced initialization of an aggregate, it is not
10815   // an expression, and each individual field initializer is a separate
10816   // full-expression. For instance, in:
10817   //
10818   //   struct Temp { ~Temp(); };
10819   //   struct S { S(Temp); };
10820   //   struct T { S a, b; } t = { Temp(), Temp() }
10821   //
10822   // we should destroy the first Temp before constructing the second.
10823   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10824                                           false,
10825                                           VDecl->isConstexpr());
10826   if (Result.isInvalid()) {
10827     VDecl->setInvalidDecl();
10828     return;
10829   }
10830   Init = Result.get();
10831 
10832   // Attach the initializer to the decl.
10833   VDecl->setInit(Init);
10834 
10835   if (VDecl->isLocalVarDecl()) {
10836     // Don't check the initializer if the declaration is malformed.
10837     if (VDecl->isInvalidDecl()) {
10838       // do nothing
10839 
10840     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
10841     // This is true even in OpenCL C++.
10842     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
10843       CheckForConstantInitializer(Init, DclT);
10844 
10845     // Otherwise, C++ does not restrict the initializer.
10846     } else if (getLangOpts().CPlusPlus) {
10847       // do nothing
10848 
10849     // C99 6.7.8p4: All the expressions in an initializer for an object that has
10850     // static storage duration shall be constant expressions or string literals.
10851     } else if (VDecl->getStorageClass() == SC_Static) {
10852       CheckForConstantInitializer(Init, DclT);
10853 
10854     // C89 is stricter than C99 for aggregate initializers.
10855     // C89 6.5.7p3: All the expressions [...] in an initializer list
10856     // for an object that has aggregate or union type shall be
10857     // constant expressions.
10858     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10859                isa<InitListExpr>(Init)) {
10860       const Expr *Culprit;
10861       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
10862         Diag(Culprit->getExprLoc(),
10863              diag::ext_aggregate_init_not_constant)
10864           << Culprit->getSourceRange();
10865       }
10866     }
10867   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10868              VDecl->getLexicalDeclContext()->isRecord()) {
10869     // This is an in-class initialization for a static data member, e.g.,
10870     //
10871     // struct S {
10872     //   static const int value = 17;
10873     // };
10874 
10875     // C++ [class.mem]p4:
10876     //   A member-declarator can contain a constant-initializer only
10877     //   if it declares a static member (9.4) of const integral or
10878     //   const enumeration type, see 9.4.2.
10879     //
10880     // C++11 [class.static.data]p3:
10881     //   If a non-volatile non-inline const static data member is of integral
10882     //   or enumeration type, its declaration in the class definition can
10883     //   specify a brace-or-equal-initializer in which every initializer-clause
10884     //   that is an assignment-expression is a constant expression. A static
10885     //   data member of literal type can be declared in the class definition
10886     //   with the constexpr specifier; if so, its declaration shall specify a
10887     //   brace-or-equal-initializer in which every initializer-clause that is
10888     //   an assignment-expression is a constant expression.
10889 
10890     // Do nothing on dependent types.
10891     if (DclT->isDependentType()) {
10892 
10893     // Allow any 'static constexpr' members, whether or not they are of literal
10894     // type. We separately check that every constexpr variable is of literal
10895     // type.
10896     } else if (VDecl->isConstexpr()) {
10897 
10898     // Require constness.
10899     } else if (!DclT.isConstQualified()) {
10900       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10901         << Init->getSourceRange();
10902       VDecl->setInvalidDecl();
10903 
10904     // We allow integer constant expressions in all cases.
10905     } else if (DclT->isIntegralOrEnumerationType()) {
10906       // Check whether the expression is a constant expression.
10907       SourceLocation Loc;
10908       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10909         // In C++11, a non-constexpr const static data member with an
10910         // in-class initializer cannot be volatile.
10911         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10912       else if (Init->isValueDependent())
10913         ; // Nothing to check.
10914       else if (Init->isIntegerConstantExpr(Context, &Loc))
10915         ; // Ok, it's an ICE!
10916       else if (Init->isEvaluatable(Context)) {
10917         // If we can constant fold the initializer through heroics, accept it,
10918         // but report this as a use of an extension for -pedantic.
10919         Diag(Loc, diag::ext_in_class_initializer_non_constant)
10920           << Init->getSourceRange();
10921       } else {
10922         // Otherwise, this is some crazy unknown case.  Report the issue at the
10923         // location provided by the isIntegerConstantExpr failed check.
10924         Diag(Loc, diag::err_in_class_initializer_non_constant)
10925           << Init->getSourceRange();
10926         VDecl->setInvalidDecl();
10927       }
10928 
10929     // We allow foldable floating-point constants as an extension.
10930     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10931       // In C++98, this is a GNU extension. In C++11, it is not, but we support
10932       // it anyway and provide a fixit to add the 'constexpr'.
10933       if (getLangOpts().CPlusPlus11) {
10934         Diag(VDecl->getLocation(),
10935              diag::ext_in_class_initializer_float_type_cxx11)
10936             << DclT << Init->getSourceRange();
10937         Diag(VDecl->getLocStart(),
10938              diag::note_in_class_initializer_float_type_cxx11)
10939             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10940       } else {
10941         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10942           << DclT << Init->getSourceRange();
10943 
10944         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10945           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10946             << Init->getSourceRange();
10947           VDecl->setInvalidDecl();
10948         }
10949       }
10950 
10951     // Suggest adding 'constexpr' in C++11 for literal types.
10952     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10953       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10954         << DclT << Init->getSourceRange()
10955         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10956       VDecl->setConstexpr(true);
10957 
10958     } else {
10959       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10960         << DclT << Init->getSourceRange();
10961       VDecl->setInvalidDecl();
10962     }
10963   } else if (VDecl->isFileVarDecl()) {
10964     // In C, extern is typically used to avoid tentative definitions when
10965     // declaring variables in headers, but adding an intializer makes it a
10966     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
10967     // In C++, extern is often used to give implictly static const variables
10968     // external linkage, so don't warn in that case. If selectany is present,
10969     // this might be header code intended for C and C++ inclusion, so apply the
10970     // C++ rules.
10971     if (VDecl->getStorageClass() == SC_Extern &&
10972         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10973          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10974         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10975         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10976       Diag(VDecl->getLocation(), diag::warn_extern_init);
10977 
10978     // C99 6.7.8p4. All file scoped initializers need to be constant.
10979     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10980       CheckForConstantInitializer(Init, DclT);
10981   }
10982 
10983   // We will represent direct-initialization similarly to copy-initialization:
10984   //    int x(1);  -as-> int x = 1;
10985   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10986   //
10987   // Clients that want to distinguish between the two forms, can check for
10988   // direct initializer using VarDecl::getInitStyle().
10989   // A major benefit is that clients that don't particularly care about which
10990   // exactly form was it (like the CodeGen) can handle both cases without
10991   // special case code.
10992 
10993   // C++ 8.5p11:
10994   // The form of initialization (using parentheses or '=') is generally
10995   // insignificant, but does matter when the entity being initialized has a
10996   // class type.
10997   if (CXXDirectInit) {
10998     assert(DirectInit && "Call-style initializer must be direct init.");
10999     VDecl->setInitStyle(VarDecl::CallInit);
11000   } else if (DirectInit) {
11001     // This must be list-initialization. No other way is direct-initialization.
11002     VDecl->setInitStyle(VarDecl::ListInit);
11003   }
11004 
11005   CheckCompleteVariableDeclaration(VDecl);
11006 }
11007 
11008 /// ActOnInitializerError - Given that there was an error parsing an
11009 /// initializer for the given declaration, try to return to some form
11010 /// of sanity.
11011 void Sema::ActOnInitializerError(Decl *D) {
11012   // Our main concern here is re-establishing invariants like "a
11013   // variable's type is either dependent or complete".
11014   if (!D || D->isInvalidDecl()) return;
11015 
11016   VarDecl *VD = dyn_cast<VarDecl>(D);
11017   if (!VD) return;
11018 
11019   // Bindings are not usable if we can't make sense of the initializer.
11020   if (auto *DD = dyn_cast<DecompositionDecl>(D))
11021     for (auto *BD : DD->bindings())
11022       BD->setInvalidDecl();
11023 
11024   // Auto types are meaningless if we can't make sense of the initializer.
11025   if (ParsingInitForAutoVars.count(D)) {
11026     D->setInvalidDecl();
11027     return;
11028   }
11029 
11030   QualType Ty = VD->getType();
11031   if (Ty->isDependentType()) return;
11032 
11033   // Require a complete type.
11034   if (RequireCompleteType(VD->getLocation(),
11035                           Context.getBaseElementType(Ty),
11036                           diag::err_typecheck_decl_incomplete_type)) {
11037     VD->setInvalidDecl();
11038     return;
11039   }
11040 
11041   // Require a non-abstract type.
11042   if (RequireNonAbstractType(VD->getLocation(), Ty,
11043                              diag::err_abstract_type_in_decl,
11044                              AbstractVariableType)) {
11045     VD->setInvalidDecl();
11046     return;
11047   }
11048 
11049   // Don't bother complaining about constructors or destructors,
11050   // though.
11051 }
11052 
11053 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
11054   // If there is no declaration, there was an error parsing it. Just ignore it.
11055   if (!RealDecl)
11056     return;
11057 
11058   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
11059     QualType Type = Var->getType();
11060 
11061     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
11062     if (isa<DecompositionDecl>(RealDecl)) {
11063       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
11064       Var->setInvalidDecl();
11065       return;
11066     }
11067 
11068     if (Type->isUndeducedType() &&
11069         DeduceVariableDeclarationType(Var, false, nullptr))
11070       return;
11071 
11072     // C++11 [class.static.data]p3: A static data member can be declared with
11073     // the constexpr specifier; if so, its declaration shall specify
11074     // a brace-or-equal-initializer.
11075     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
11076     // the definition of a variable [...] or the declaration of a static data
11077     // member.
11078     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
11079         !Var->isThisDeclarationADemotedDefinition()) {
11080       if (Var->isStaticDataMember()) {
11081         // C++1z removes the relevant rule; the in-class declaration is always
11082         // a definition there.
11083         if (!getLangOpts().CPlusPlus17) {
11084           Diag(Var->getLocation(),
11085                diag::err_constexpr_static_mem_var_requires_init)
11086             << Var->getDeclName();
11087           Var->setInvalidDecl();
11088           return;
11089         }
11090       } else {
11091         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
11092         Var->setInvalidDecl();
11093         return;
11094       }
11095     }
11096 
11097     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
11098     // be initialized.
11099     if (!Var->isInvalidDecl() &&
11100         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
11101         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
11102       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
11103       Var->setInvalidDecl();
11104       return;
11105     }
11106 
11107     switch (Var->isThisDeclarationADefinition()) {
11108     case VarDecl::Definition:
11109       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
11110         break;
11111 
11112       // We have an out-of-line definition of a static data member
11113       // that has an in-class initializer, so we type-check this like
11114       // a declaration.
11115       //
11116       LLVM_FALLTHROUGH;
11117 
11118     case VarDecl::DeclarationOnly:
11119       // It's only a declaration.
11120 
11121       // Block scope. C99 6.7p7: If an identifier for an object is
11122       // declared with no linkage (C99 6.2.2p6), the type for the
11123       // object shall be complete.
11124       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
11125           !Var->hasLinkage() && !Var->isInvalidDecl() &&
11126           RequireCompleteType(Var->getLocation(), Type,
11127                               diag::err_typecheck_decl_incomplete_type))
11128         Var->setInvalidDecl();
11129 
11130       // Make sure that the type is not abstract.
11131       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11132           RequireNonAbstractType(Var->getLocation(), Type,
11133                                  diag::err_abstract_type_in_decl,
11134                                  AbstractVariableType))
11135         Var->setInvalidDecl();
11136       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11137           Var->getStorageClass() == SC_PrivateExtern) {
11138         Diag(Var->getLocation(), diag::warn_private_extern);
11139         Diag(Var->getLocation(), diag::note_private_extern);
11140       }
11141 
11142       return;
11143 
11144     case VarDecl::TentativeDefinition:
11145       // File scope. C99 6.9.2p2: A declaration of an identifier for an
11146       // object that has file scope without an initializer, and without a
11147       // storage-class specifier or with the storage-class specifier "static",
11148       // constitutes a tentative definition. Note: A tentative definition with
11149       // external linkage is valid (C99 6.2.2p5).
11150       if (!Var->isInvalidDecl()) {
11151         if (const IncompleteArrayType *ArrayT
11152                                     = Context.getAsIncompleteArrayType(Type)) {
11153           if (RequireCompleteType(Var->getLocation(),
11154                                   ArrayT->getElementType(),
11155                                   diag::err_illegal_decl_array_incomplete_type))
11156             Var->setInvalidDecl();
11157         } else if (Var->getStorageClass() == SC_Static) {
11158           // C99 6.9.2p3: If the declaration of an identifier for an object is
11159           // a tentative definition and has internal linkage (C99 6.2.2p3), the
11160           // declared type shall not be an incomplete type.
11161           // NOTE: code such as the following
11162           //     static struct s;
11163           //     struct s { int a; };
11164           // is accepted by gcc. Hence here we issue a warning instead of
11165           // an error and we do not invalidate the static declaration.
11166           // NOTE: to avoid multiple warnings, only check the first declaration.
11167           if (Var->isFirstDecl())
11168             RequireCompleteType(Var->getLocation(), Type,
11169                                 diag::ext_typecheck_decl_incomplete_type);
11170         }
11171       }
11172 
11173       // Record the tentative definition; we're done.
11174       if (!Var->isInvalidDecl())
11175         TentativeDefinitions.push_back(Var);
11176       return;
11177     }
11178 
11179     // Provide a specific diagnostic for uninitialized variable
11180     // definitions with incomplete array type.
11181     if (Type->isIncompleteArrayType()) {
11182       Diag(Var->getLocation(),
11183            diag::err_typecheck_incomplete_array_needs_initializer);
11184       Var->setInvalidDecl();
11185       return;
11186     }
11187 
11188     // Provide a specific diagnostic for uninitialized variable
11189     // definitions with reference type.
11190     if (Type->isReferenceType()) {
11191       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
11192         << Var->getDeclName()
11193         << SourceRange(Var->getLocation(), Var->getLocation());
11194       Var->setInvalidDecl();
11195       return;
11196     }
11197 
11198     // Do not attempt to type-check the default initializer for a
11199     // variable with dependent type.
11200     if (Type->isDependentType())
11201       return;
11202 
11203     if (Var->isInvalidDecl())
11204       return;
11205 
11206     if (!Var->hasAttr<AliasAttr>()) {
11207       if (RequireCompleteType(Var->getLocation(),
11208                               Context.getBaseElementType(Type),
11209                               diag::err_typecheck_decl_incomplete_type)) {
11210         Var->setInvalidDecl();
11211         return;
11212       }
11213     } else {
11214       return;
11215     }
11216 
11217     // The variable can not have an abstract class type.
11218     if (RequireNonAbstractType(Var->getLocation(), Type,
11219                                diag::err_abstract_type_in_decl,
11220                                AbstractVariableType)) {
11221       Var->setInvalidDecl();
11222       return;
11223     }
11224 
11225     // Check for jumps past the implicit initializer.  C++0x
11226     // clarifies that this applies to a "variable with automatic
11227     // storage duration", not a "local variable".
11228     // C++11 [stmt.dcl]p3
11229     //   A program that jumps from a point where a variable with automatic
11230     //   storage duration is not in scope to a point where it is in scope is
11231     //   ill-formed unless the variable has scalar type, class type with a
11232     //   trivial default constructor and a trivial destructor, a cv-qualified
11233     //   version of one of these types, or an array of one of the preceding
11234     //   types and is declared without an initializer.
11235     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
11236       if (const RecordType *Record
11237             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
11238         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
11239         // Mark the function (if we're in one) for further checking even if the
11240         // looser rules of C++11 do not require such checks, so that we can
11241         // diagnose incompatibilities with C++98.
11242         if (!CXXRecord->isPOD())
11243           setFunctionHasBranchProtectedScope();
11244       }
11245     }
11246 
11247     // C++03 [dcl.init]p9:
11248     //   If no initializer is specified for an object, and the
11249     //   object is of (possibly cv-qualified) non-POD class type (or
11250     //   array thereof), the object shall be default-initialized; if
11251     //   the object is of const-qualified type, the underlying class
11252     //   type shall have a user-declared default
11253     //   constructor. Otherwise, if no initializer is specified for
11254     //   a non- static object, the object and its subobjects, if
11255     //   any, have an indeterminate initial value); if the object
11256     //   or any of its subobjects are of const-qualified type, the
11257     //   program is ill-formed.
11258     // C++0x [dcl.init]p11:
11259     //   If no initializer is specified for an object, the object is
11260     //   default-initialized; [...].
11261     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
11262     InitializationKind Kind
11263       = InitializationKind::CreateDefault(Var->getLocation());
11264 
11265     InitializationSequence InitSeq(*this, Entity, Kind, None);
11266     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
11267     if (Init.isInvalid())
11268       Var->setInvalidDecl();
11269     else if (Init.get()) {
11270       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
11271       // This is important for template substitution.
11272       Var->setInitStyle(VarDecl::CallInit);
11273     }
11274 
11275     CheckCompleteVariableDeclaration(Var);
11276   }
11277 }
11278 
11279 void Sema::ActOnCXXForRangeDecl(Decl *D) {
11280   // If there is no declaration, there was an error parsing it. Ignore it.
11281   if (!D)
11282     return;
11283 
11284   VarDecl *VD = dyn_cast<VarDecl>(D);
11285   if (!VD) {
11286     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
11287     D->setInvalidDecl();
11288     return;
11289   }
11290 
11291   VD->setCXXForRangeDecl(true);
11292 
11293   // for-range-declaration cannot be given a storage class specifier.
11294   int Error = -1;
11295   switch (VD->getStorageClass()) {
11296   case SC_None:
11297     break;
11298   case SC_Extern:
11299     Error = 0;
11300     break;
11301   case SC_Static:
11302     Error = 1;
11303     break;
11304   case SC_PrivateExtern:
11305     Error = 2;
11306     break;
11307   case SC_Auto:
11308     Error = 3;
11309     break;
11310   case SC_Register:
11311     Error = 4;
11312     break;
11313   }
11314   if (Error != -1) {
11315     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
11316       << VD->getDeclName() << Error;
11317     D->setInvalidDecl();
11318   }
11319 }
11320 
11321 StmtResult
11322 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
11323                                  IdentifierInfo *Ident,
11324                                  ParsedAttributes &Attrs,
11325                                  SourceLocation AttrEnd) {
11326   // C++1y [stmt.iter]p1:
11327   //   A range-based for statement of the form
11328   //      for ( for-range-identifier : for-range-initializer ) statement
11329   //   is equivalent to
11330   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
11331   DeclSpec DS(Attrs.getPool().getFactory());
11332 
11333   const char *PrevSpec;
11334   unsigned DiagID;
11335   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
11336                      getPrintingPolicy());
11337 
11338   Declarator D(DS, DeclaratorContext::ForContext);
11339   D.SetIdentifier(Ident, IdentLoc);
11340   D.takeAttributes(Attrs, AttrEnd);
11341 
11342   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
11343   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
11344                 EmptyAttrs, IdentLoc);
11345   Decl *Var = ActOnDeclarator(S, D);
11346   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
11347   FinalizeDeclaration(Var);
11348   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
11349                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
11350 }
11351 
11352 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
11353   if (var->isInvalidDecl()) return;
11354 
11355   if (getLangOpts().OpenCL) {
11356     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
11357     // initialiser
11358     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
11359         !var->hasInit()) {
11360       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
11361           << 1 /*Init*/;
11362       var->setInvalidDecl();
11363       return;
11364     }
11365   }
11366 
11367   // In Objective-C, don't allow jumps past the implicit initialization of a
11368   // local retaining variable.
11369   if (getLangOpts().ObjC1 &&
11370       var->hasLocalStorage()) {
11371     switch (var->getType().getObjCLifetime()) {
11372     case Qualifiers::OCL_None:
11373     case Qualifiers::OCL_ExplicitNone:
11374     case Qualifiers::OCL_Autoreleasing:
11375       break;
11376 
11377     case Qualifiers::OCL_Weak:
11378     case Qualifiers::OCL_Strong:
11379       setFunctionHasBranchProtectedScope();
11380       break;
11381     }
11382   }
11383 
11384   if (var->hasLocalStorage() &&
11385       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
11386     setFunctionHasBranchProtectedScope();
11387 
11388   // Warn about externally-visible variables being defined without a
11389   // prior declaration.  We only want to do this for global
11390   // declarations, but we also specifically need to avoid doing it for
11391   // class members because the linkage of an anonymous class can
11392   // change if it's later given a typedef name.
11393   if (var->isThisDeclarationADefinition() &&
11394       var->getDeclContext()->getRedeclContext()->isFileContext() &&
11395       var->isExternallyVisible() && var->hasLinkage() &&
11396       !var->isInline() && !var->getDescribedVarTemplate() &&
11397       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
11398       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11399                                   var->getLocation())) {
11400     // Find a previous declaration that's not a definition.
11401     VarDecl *prev = var->getPreviousDecl();
11402     while (prev && prev->isThisDeclarationADefinition())
11403       prev = prev->getPreviousDecl();
11404 
11405     if (!prev)
11406       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11407   }
11408 
11409   // Cache the result of checking for constant initialization.
11410   Optional<bool> CacheHasConstInit;
11411   const Expr *CacheCulprit;
11412   auto checkConstInit = [&]() mutable {
11413     if (!CacheHasConstInit)
11414       CacheHasConstInit = var->getInit()->isConstantInitializer(
11415             Context, var->getType()->isReferenceType(), &CacheCulprit);
11416     return *CacheHasConstInit;
11417   };
11418 
11419   if (var->getTLSKind() == VarDecl::TLS_Static) {
11420     if (var->getType().isDestructedType()) {
11421       // GNU C++98 edits for __thread, [basic.start.term]p3:
11422       //   The type of an object with thread storage duration shall not
11423       //   have a non-trivial destructor.
11424       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11425       if (getLangOpts().CPlusPlus11)
11426         Diag(var->getLocation(), diag::note_use_thread_local);
11427     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11428       if (!checkConstInit()) {
11429         // GNU C++98 edits for __thread, [basic.start.init]p4:
11430         //   An object of thread storage duration shall not require dynamic
11431         //   initialization.
11432         // FIXME: Need strict checking here.
11433         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11434           << CacheCulprit->getSourceRange();
11435         if (getLangOpts().CPlusPlus11)
11436           Diag(var->getLocation(), diag::note_use_thread_local);
11437       }
11438     }
11439   }
11440 
11441   // Apply section attributes and pragmas to global variables.
11442   bool GlobalStorage = var->hasGlobalStorage();
11443   if (GlobalStorage && var->isThisDeclarationADefinition() &&
11444       !inTemplateInstantiation()) {
11445     PragmaStack<StringLiteral *> *Stack = nullptr;
11446     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11447     if (var->getType().isConstQualified())
11448       Stack = &ConstSegStack;
11449     else if (!var->getInit()) {
11450       Stack = &BSSSegStack;
11451       SectionFlags |= ASTContext::PSF_Write;
11452     } else {
11453       Stack = &DataSegStack;
11454       SectionFlags |= ASTContext::PSF_Write;
11455     }
11456     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11457       var->addAttr(SectionAttr::CreateImplicit(
11458           Context, SectionAttr::Declspec_allocate,
11459           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11460     }
11461     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11462       if (UnifySection(SA->getName(), SectionFlags, var))
11463         var->dropAttr<SectionAttr>();
11464 
11465     // Apply the init_seg attribute if this has an initializer.  If the
11466     // initializer turns out to not be dynamic, we'll end up ignoring this
11467     // attribute.
11468     if (CurInitSeg && var->getInit())
11469       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11470                                                CurInitSegLoc));
11471   }
11472 
11473   // All the following checks are C++ only.
11474   if (!getLangOpts().CPlusPlus) {
11475       // If this variable must be emitted, add it as an initializer for the
11476       // current module.
11477      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11478        Context.addModuleInitializer(ModuleScopes.back().Module, var);
11479      return;
11480   }
11481 
11482   if (auto *DD = dyn_cast<DecompositionDecl>(var))
11483     CheckCompleteDecompositionDeclaration(DD);
11484 
11485   QualType type = var->getType();
11486   if (type->isDependentType()) return;
11487 
11488   // __block variables might require us to capture a copy-initializer.
11489   if (var->hasAttr<BlocksAttr>()) {
11490     // It's currently invalid to ever have a __block variable with an
11491     // array type; should we diagnose that here?
11492 
11493     // Regardless, we don't want to ignore array nesting when
11494     // constructing this copy.
11495     if (type->isStructureOrClassType()) {
11496       EnterExpressionEvaluationContext scope(
11497           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
11498       SourceLocation poi = var->getLocation();
11499       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
11500       ExprResult result
11501         = PerformMoveOrCopyInitialization(
11502             InitializedEntity::InitializeBlock(poi, type, false),
11503             var, var->getType(), varRef, /*AllowNRVO=*/true);
11504       if (!result.isInvalid()) {
11505         result = MaybeCreateExprWithCleanups(result);
11506         Expr *init = result.getAs<Expr>();
11507         Context.setBlockVarCopyInits(var, init);
11508       }
11509     }
11510   }
11511 
11512   Expr *Init = var->getInit();
11513   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11514   QualType baseType = Context.getBaseElementType(type);
11515 
11516   if (Init && !Init->isValueDependent()) {
11517     if (var->isConstexpr()) {
11518       SmallVector<PartialDiagnosticAt, 8> Notes;
11519       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11520         SourceLocation DiagLoc = var->getLocation();
11521         // If the note doesn't add any useful information other than a source
11522         // location, fold it into the primary diagnostic.
11523         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11524               diag::note_invalid_subexpr_in_const_expr) {
11525           DiagLoc = Notes[0].first;
11526           Notes.clear();
11527         }
11528         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11529           << var << Init->getSourceRange();
11530         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11531           Diag(Notes[I].first, Notes[I].second);
11532       }
11533     } else if (var->isUsableInConstantExpressions(Context)) {
11534       // Check whether the initializer of a const variable of integral or
11535       // enumeration type is an ICE now, since we can't tell whether it was
11536       // initialized by a constant expression if we check later.
11537       var->checkInitIsICE();
11538     }
11539 
11540     // Don't emit further diagnostics about constexpr globals since they
11541     // were just diagnosed.
11542     if (!var->isConstexpr() && GlobalStorage &&
11543             var->hasAttr<RequireConstantInitAttr>()) {
11544       // FIXME: Need strict checking in C++03 here.
11545       bool DiagErr = getLangOpts().CPlusPlus11
11546           ? !var->checkInitIsICE() : !checkConstInit();
11547       if (DiagErr) {
11548         auto attr = var->getAttr<RequireConstantInitAttr>();
11549         Diag(var->getLocation(), diag::err_require_constant_init_failed)
11550           << Init->getSourceRange();
11551         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11552           << attr->getRange();
11553         if (getLangOpts().CPlusPlus11) {
11554           APValue Value;
11555           SmallVector<PartialDiagnosticAt, 8> Notes;
11556           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11557           for (auto &it : Notes)
11558             Diag(it.first, it.second);
11559         } else {
11560           Diag(CacheCulprit->getExprLoc(),
11561                diag::note_invalid_subexpr_in_const_expr)
11562               << CacheCulprit->getSourceRange();
11563         }
11564       }
11565     }
11566     else if (!var->isConstexpr() && IsGlobal &&
11567              !getDiagnostics().isIgnored(diag::warn_global_constructor,
11568                                     var->getLocation())) {
11569       // Warn about globals which don't have a constant initializer.  Don't
11570       // warn about globals with a non-trivial destructor because we already
11571       // warned about them.
11572       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11573       if (!(RD && !RD->hasTrivialDestructor())) {
11574         if (!checkConstInit())
11575           Diag(var->getLocation(), diag::warn_global_constructor)
11576             << Init->getSourceRange();
11577       }
11578     }
11579   }
11580 
11581   // Require the destructor.
11582   if (const RecordType *recordType = baseType->getAs<RecordType>())
11583     FinalizeVarWithDestructor(var, recordType);
11584 
11585   // If this variable must be emitted, add it as an initializer for the current
11586   // module.
11587   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11588     Context.addModuleInitializer(ModuleScopes.back().Module, var);
11589 }
11590 
11591 /// Determines if a variable's alignment is dependent.
11592 static bool hasDependentAlignment(VarDecl *VD) {
11593   if (VD->getType()->isDependentType())
11594     return true;
11595   for (auto *I : VD->specific_attrs<AlignedAttr>())
11596     if (I->isAlignmentDependent())
11597       return true;
11598   return false;
11599 }
11600 
11601 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
11602 /// any semantic actions necessary after any initializer has been attached.
11603 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
11604   // Note that we are no longer parsing the initializer for this declaration.
11605   ParsingInitForAutoVars.erase(ThisDecl);
11606 
11607   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
11608   if (!VD)
11609     return;
11610 
11611   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
11612   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
11613       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
11614     if (PragmaClangBSSSection.Valid)
11615       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
11616                                                             PragmaClangBSSSection.SectionName,
11617                                                             PragmaClangBSSSection.PragmaLocation));
11618     if (PragmaClangDataSection.Valid)
11619       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
11620                                                              PragmaClangDataSection.SectionName,
11621                                                              PragmaClangDataSection.PragmaLocation));
11622     if (PragmaClangRodataSection.Valid)
11623       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
11624                                                                PragmaClangRodataSection.SectionName,
11625                                                                PragmaClangRodataSection.PragmaLocation));
11626   }
11627 
11628   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
11629     for (auto *BD : DD->bindings()) {
11630       FinalizeDeclaration(BD);
11631     }
11632   }
11633 
11634   checkAttributesAfterMerging(*this, *VD);
11635 
11636   // Perform TLS alignment check here after attributes attached to the variable
11637   // which may affect the alignment have been processed. Only perform the check
11638   // if the target has a maximum TLS alignment (zero means no constraints).
11639   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
11640     // Protect the check so that it's not performed on dependent types and
11641     // dependent alignments (we can't determine the alignment in that case).
11642     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
11643         !VD->isInvalidDecl()) {
11644       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
11645       if (Context.getDeclAlign(VD) > MaxAlignChars) {
11646         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
11647           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
11648           << (unsigned)MaxAlignChars.getQuantity();
11649       }
11650     }
11651   }
11652 
11653   if (VD->isStaticLocal()) {
11654     if (FunctionDecl *FD =
11655             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
11656       // Static locals inherit dll attributes from their function.
11657       if (Attr *A = getDLLAttr(FD)) {
11658         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11659         NewAttr->setInherited(true);
11660         VD->addAttr(NewAttr);
11661       }
11662       // CUDA E.2.9.4: Within the body of a __device__ or __global__
11663       // function, only __shared__ variables may be declared with
11664       // static storage class.
11665       if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
11666           CUDADiagIfDeviceCode(VD->getLocation(),
11667                                diag::err_device_static_local_var)
11668               << CurrentCUDATarget())
11669         VD->setInvalidDecl();
11670     }
11671   }
11672 
11673   // Perform check for initializers of device-side global variables.
11674   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
11675   // 7.5). We must also apply the same checks to all __shared__
11676   // variables whether they are local or not. CUDA also allows
11677   // constant initializers for __constant__ and __device__ variables.
11678   if (getLangOpts().CUDA)
11679     checkAllowedCUDAInitializer(VD);
11680 
11681   // Grab the dllimport or dllexport attribute off of the VarDecl.
11682   const InheritableAttr *DLLAttr = getDLLAttr(VD);
11683 
11684   // Imported static data members cannot be defined out-of-line.
11685   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
11686     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
11687         VD->isThisDeclarationADefinition()) {
11688       // We allow definitions of dllimport class template static data members
11689       // with a warning.
11690       CXXRecordDecl *Context =
11691         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
11692       bool IsClassTemplateMember =
11693           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
11694           Context->getDescribedClassTemplate();
11695 
11696       Diag(VD->getLocation(),
11697            IsClassTemplateMember
11698                ? diag::warn_attribute_dllimport_static_field_definition
11699                : diag::err_attribute_dllimport_static_field_definition);
11700       Diag(IA->getLocation(), diag::note_attribute);
11701       if (!IsClassTemplateMember)
11702         VD->setInvalidDecl();
11703     }
11704   }
11705 
11706   // dllimport/dllexport variables cannot be thread local, their TLS index
11707   // isn't exported with the variable.
11708   if (DLLAttr && VD->getTLSKind()) {
11709     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11710     if (F && getDLLAttr(F)) {
11711       assert(VD->isStaticLocal());
11712       // But if this is a static local in a dlimport/dllexport function, the
11713       // function will never be inlined, which means the var would never be
11714       // imported, so having it marked import/export is safe.
11715     } else {
11716       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
11717                                                                     << DLLAttr;
11718       VD->setInvalidDecl();
11719     }
11720   }
11721 
11722   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
11723     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
11724       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11725       VD->dropAttr<UsedAttr>();
11726     }
11727   }
11728 
11729   const DeclContext *DC = VD->getDeclContext();
11730   // If there's a #pragma GCC visibility in scope, and this isn't a class
11731   // member, set the visibility of this variable.
11732   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11733     AddPushedVisibilityAttribute(VD);
11734 
11735   // FIXME: Warn on unused var template partial specializations.
11736   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
11737     MarkUnusedFileScopedDecl(VD);
11738 
11739   // Now we have parsed the initializer and can update the table of magic
11740   // tag values.
11741   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11742       !VD->getType()->isIntegralOrEnumerationType())
11743     return;
11744 
11745   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11746     const Expr *MagicValueExpr = VD->getInit();
11747     if (!MagicValueExpr) {
11748       continue;
11749     }
11750     llvm::APSInt MagicValueInt;
11751     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11752       Diag(I->getRange().getBegin(),
11753            diag::err_type_tag_for_datatype_not_ice)
11754         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11755       continue;
11756     }
11757     if (MagicValueInt.getActiveBits() > 64) {
11758       Diag(I->getRange().getBegin(),
11759            diag::err_type_tag_for_datatype_too_large)
11760         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11761       continue;
11762     }
11763     uint64_t MagicValue = MagicValueInt.getZExtValue();
11764     RegisterTypeTagForDatatype(I->getArgumentKind(),
11765                                MagicValue,
11766                                I->getMatchingCType(),
11767                                I->getLayoutCompatible(),
11768                                I->getMustBeNull());
11769   }
11770 }
11771 
11772 static bool hasDeducedAuto(DeclaratorDecl *DD) {
11773   auto *VD = dyn_cast<VarDecl>(DD);
11774   return VD && !VD->getType()->hasAutoForTrailingReturnType();
11775 }
11776 
11777 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
11778                                                    ArrayRef<Decl *> Group) {
11779   SmallVector<Decl*, 8> Decls;
11780 
11781   if (DS.isTypeSpecOwned())
11782     Decls.push_back(DS.getRepAsDecl());
11783 
11784   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11785   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11786   bool DiagnosedMultipleDecomps = false;
11787   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
11788   bool DiagnosedNonDeducedAuto = false;
11789 
11790   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11791     if (Decl *D = Group[i]) {
11792       // For declarators, there are some additional syntactic-ish checks we need
11793       // to perform.
11794       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11795         if (!FirstDeclaratorInGroup)
11796           FirstDeclaratorInGroup = DD;
11797         if (!FirstDecompDeclaratorInGroup)
11798           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
11799         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
11800             !hasDeducedAuto(DD))
11801           FirstNonDeducedAutoInGroup = DD;
11802 
11803         if (FirstDeclaratorInGroup != DD) {
11804           // A decomposition declaration cannot be combined with any other
11805           // declaration in the same group.
11806           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
11807             Diag(FirstDecompDeclaratorInGroup->getLocation(),
11808                  diag::err_decomp_decl_not_alone)
11809                 << FirstDeclaratorInGroup->getSourceRange()
11810                 << DD->getSourceRange();
11811             DiagnosedMultipleDecomps = true;
11812           }
11813 
11814           // A declarator that uses 'auto' in any way other than to declare a
11815           // variable with a deduced type cannot be combined with any other
11816           // declarator in the same group.
11817           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
11818             Diag(FirstNonDeducedAutoInGroup->getLocation(),
11819                  diag::err_auto_non_deduced_not_alone)
11820                 << FirstNonDeducedAutoInGroup->getType()
11821                        ->hasAutoForTrailingReturnType()
11822                 << FirstDeclaratorInGroup->getSourceRange()
11823                 << DD->getSourceRange();
11824             DiagnosedNonDeducedAuto = true;
11825           }
11826         }
11827       }
11828 
11829       Decls.push_back(D);
11830     }
11831   }
11832 
11833   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11834     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11835       handleTagNumbering(Tag, S);
11836       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11837           getLangOpts().CPlusPlus)
11838         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11839     }
11840   }
11841 
11842   return BuildDeclaratorGroup(Decls);
11843 }
11844 
11845 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11846 /// group, performing any necessary semantic checking.
11847 Sema::DeclGroupPtrTy
11848 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
11849   // C++14 [dcl.spec.auto]p7: (DR1347)
11850   //   If the type that replaces the placeholder type is not the same in each
11851   //   deduction, the program is ill-formed.
11852   if (Group.size() > 1) {
11853     QualType Deduced;
11854     VarDecl *DeducedDecl = nullptr;
11855     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11856       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
11857       if (!D || D->isInvalidDecl())
11858         break;
11859       DeducedType *DT = D->getType()->getContainedDeducedType();
11860       if (!DT || DT->getDeducedType().isNull())
11861         continue;
11862       if (Deduced.isNull()) {
11863         Deduced = DT->getDeducedType();
11864         DeducedDecl = D;
11865       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
11866         auto *AT = dyn_cast<AutoType>(DT);
11867         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11868              diag::err_auto_different_deductions)
11869           << (AT ? (unsigned)AT->getKeyword() : 3)
11870           << Deduced << DeducedDecl->getDeclName()
11871           << DT->getDeducedType() << D->getDeclName()
11872           << DeducedDecl->getInit()->getSourceRange()
11873           << D->getInit()->getSourceRange();
11874         D->setInvalidDecl();
11875         break;
11876       }
11877     }
11878   }
11879 
11880   ActOnDocumentableDecls(Group);
11881 
11882   return DeclGroupPtrTy::make(
11883       DeclGroupRef::Create(Context, Group.data(), Group.size()));
11884 }
11885 
11886 void Sema::ActOnDocumentableDecl(Decl *D) {
11887   ActOnDocumentableDecls(D);
11888 }
11889 
11890 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11891   // Don't parse the comment if Doxygen diagnostics are ignored.
11892   if (Group.empty() || !Group[0])
11893     return;
11894 
11895   if (Diags.isIgnored(diag::warn_doc_param_not_found,
11896                       Group[0]->getLocation()) &&
11897       Diags.isIgnored(diag::warn_unknown_comment_command_name,
11898                       Group[0]->getLocation()))
11899     return;
11900 
11901   if (Group.size() >= 2) {
11902     // This is a decl group.  Normally it will contain only declarations
11903     // produced from declarator list.  But in case we have any definitions or
11904     // additional declaration references:
11905     //   'typedef struct S {} S;'
11906     //   'typedef struct S *S;'
11907     //   'struct S *pS;'
11908     // FinalizeDeclaratorGroup adds these as separate declarations.
11909     Decl *MaybeTagDecl = Group[0];
11910     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11911       Group = Group.slice(1);
11912     }
11913   }
11914 
11915   // See if there are any new comments that are not attached to a decl.
11916   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11917   if (!Comments.empty() &&
11918       !Comments.back()->isAttached()) {
11919     // There is at least one comment that not attached to a decl.
11920     // Maybe it should be attached to one of these decls?
11921     //
11922     // Note that this way we pick up not only comments that precede the
11923     // declaration, but also comments that *follow* the declaration -- thanks to
11924     // the lookahead in the lexer: we've consumed the semicolon and looked
11925     // ahead through comments.
11926     for (unsigned i = 0, e = Group.size(); i != e; ++i)
11927       Context.getCommentForDecl(Group[i], &PP);
11928   }
11929 }
11930 
11931 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11932 /// to introduce parameters into function prototype scope.
11933 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11934   const DeclSpec &DS = D.getDeclSpec();
11935 
11936   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11937 
11938   // C++03 [dcl.stc]p2 also permits 'auto'.
11939   StorageClass SC = SC_None;
11940   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11941     SC = SC_Register;
11942     // In C++11, the 'register' storage class specifier is deprecated.
11943     // In C++17, it is not allowed, but we tolerate it as an extension.
11944     if (getLangOpts().CPlusPlus11) {
11945       Diag(DS.getStorageClassSpecLoc(),
11946            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
11947                                      : diag::warn_deprecated_register)
11948         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11949     }
11950   } else if (getLangOpts().CPlusPlus &&
11951              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11952     SC = SC_Auto;
11953   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11954     Diag(DS.getStorageClassSpecLoc(),
11955          diag::err_invalid_storage_class_in_func_decl);
11956     D.getMutableDeclSpec().ClearStorageClassSpecs();
11957   }
11958 
11959   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11960     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11961       << DeclSpec::getSpecifierName(TSCS);
11962   if (DS.isInlineSpecified())
11963     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11964         << getLangOpts().CPlusPlus17;
11965   if (DS.isConstexprSpecified())
11966     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11967       << 0;
11968 
11969   DiagnoseFunctionSpecifiers(DS);
11970 
11971   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11972   QualType parmDeclType = TInfo->getType();
11973 
11974   if (getLangOpts().CPlusPlus) {
11975     // Check that there are no default arguments inside the type of this
11976     // parameter.
11977     CheckExtraCXXDefaultArguments(D);
11978 
11979     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11980     if (D.getCXXScopeSpec().isSet()) {
11981       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11982         << D.getCXXScopeSpec().getRange();
11983       D.getCXXScopeSpec().clear();
11984     }
11985   }
11986 
11987   // Ensure we have a valid name
11988   IdentifierInfo *II = nullptr;
11989   if (D.hasName()) {
11990     II = D.getIdentifier();
11991     if (!II) {
11992       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11993         << GetNameForDeclarator(D).getName();
11994       D.setInvalidType(true);
11995     }
11996   }
11997 
11998   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11999   if (II) {
12000     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
12001                    ForVisibleRedeclaration);
12002     LookupName(R, S);
12003     if (R.isSingleResult()) {
12004       NamedDecl *PrevDecl = R.getFoundDecl();
12005       if (PrevDecl->isTemplateParameter()) {
12006         // Maybe we will complain about the shadowed template parameter.
12007         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12008         // Just pretend that we didn't see the previous declaration.
12009         PrevDecl = nullptr;
12010       } else if (S->isDeclScope(PrevDecl)) {
12011         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
12012         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12013 
12014         // Recover by removing the name
12015         II = nullptr;
12016         D.SetIdentifier(nullptr, D.getIdentifierLoc());
12017         D.setInvalidType(true);
12018       }
12019     }
12020   }
12021 
12022   // Temporarily put parameter variables in the translation unit, not
12023   // the enclosing context.  This prevents them from accidentally
12024   // looking like class members in C++.
12025   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
12026                                     D.getLocStart(),
12027                                     D.getIdentifierLoc(), II,
12028                                     parmDeclType, TInfo,
12029                                     SC);
12030 
12031   if (D.isInvalidType())
12032     New->setInvalidDecl();
12033 
12034   assert(S->isFunctionPrototypeScope());
12035   assert(S->getFunctionPrototypeDepth() >= 1);
12036   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
12037                     S->getNextFunctionPrototypeIndex());
12038 
12039   // Add the parameter declaration into this scope.
12040   S->AddDecl(New);
12041   if (II)
12042     IdResolver.AddDecl(New);
12043 
12044   ProcessDeclAttributes(S, New, D);
12045 
12046   if (D.getDeclSpec().isModulePrivateSpecified())
12047     Diag(New->getLocation(), diag::err_module_private_local)
12048       << 1 << New->getDeclName()
12049       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12050       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12051 
12052   if (New->hasAttr<BlocksAttr>()) {
12053     Diag(New->getLocation(), diag::err_block_on_nonlocal);
12054   }
12055   return New;
12056 }
12057 
12058 /// Synthesizes a variable for a parameter arising from a
12059 /// typedef.
12060 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
12061                                               SourceLocation Loc,
12062                                               QualType T) {
12063   /* FIXME: setting StartLoc == Loc.
12064      Would it be worth to modify callers so as to provide proper source
12065      location for the unnamed parameters, embedding the parameter's type? */
12066   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
12067                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
12068                                            SC_None, nullptr);
12069   Param->setImplicit();
12070   return Param;
12071 }
12072 
12073 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
12074   // Don't diagnose unused-parameter errors in template instantiations; we
12075   // will already have done so in the template itself.
12076   if (inTemplateInstantiation())
12077     return;
12078 
12079   for (const ParmVarDecl *Parameter : Parameters) {
12080     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
12081         !Parameter->hasAttr<UnusedAttr>()) {
12082       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
12083         << Parameter->getDeclName();
12084     }
12085   }
12086 }
12087 
12088 void Sema::DiagnoseSizeOfParametersAndReturnValue(
12089     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
12090   if (LangOpts.NumLargeByValueCopy == 0) // No check.
12091     return;
12092 
12093   // Warn if the return value is pass-by-value and larger than the specified
12094   // threshold.
12095   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
12096     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
12097     if (Size > LangOpts.NumLargeByValueCopy)
12098       Diag(D->getLocation(), diag::warn_return_value_size)
12099           << D->getDeclName() << Size;
12100   }
12101 
12102   // Warn if any parameter is pass-by-value and larger than the specified
12103   // threshold.
12104   for (const ParmVarDecl *Parameter : Parameters) {
12105     QualType T = Parameter->getType();
12106     if (T->isDependentType() || !T.isPODType(Context))
12107       continue;
12108     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
12109     if (Size > LangOpts.NumLargeByValueCopy)
12110       Diag(Parameter->getLocation(), diag::warn_parameter_size)
12111           << Parameter->getDeclName() << Size;
12112   }
12113 }
12114 
12115 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
12116                                   SourceLocation NameLoc, IdentifierInfo *Name,
12117                                   QualType T, TypeSourceInfo *TSInfo,
12118                                   StorageClass SC) {
12119   // In ARC, infer a lifetime qualifier for appropriate parameter types.
12120   if (getLangOpts().ObjCAutoRefCount &&
12121       T.getObjCLifetime() == Qualifiers::OCL_None &&
12122       T->isObjCLifetimeType()) {
12123 
12124     Qualifiers::ObjCLifetime lifetime;
12125 
12126     // Special cases for arrays:
12127     //   - if it's const, use __unsafe_unretained
12128     //   - otherwise, it's an error
12129     if (T->isArrayType()) {
12130       if (!T.isConstQualified()) {
12131         DelayedDiagnostics.add(
12132             sema::DelayedDiagnostic::makeForbiddenType(
12133             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
12134       }
12135       lifetime = Qualifiers::OCL_ExplicitNone;
12136     } else {
12137       lifetime = T->getObjCARCImplicitLifetime();
12138     }
12139     T = Context.getLifetimeQualifiedType(T, lifetime);
12140   }
12141 
12142   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
12143                                          Context.getAdjustedParameterType(T),
12144                                          TSInfo, SC, nullptr);
12145 
12146   // Parameters can not be abstract class types.
12147   // For record types, this is done by the AbstractClassUsageDiagnoser once
12148   // the class has been completely parsed.
12149   if (!CurContext->isRecord() &&
12150       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
12151                              AbstractParamType))
12152     New->setInvalidDecl();
12153 
12154   // Parameter declarators cannot be interface types. All ObjC objects are
12155   // passed by reference.
12156   if (T->isObjCObjectType()) {
12157     SourceLocation TypeEndLoc =
12158         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
12159     Diag(NameLoc,
12160          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
12161       << FixItHint::CreateInsertion(TypeEndLoc, "*");
12162     T = Context.getObjCObjectPointerType(T);
12163     New->setType(T);
12164   }
12165 
12166   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
12167   // duration shall not be qualified by an address-space qualifier."
12168   // Since all parameters have automatic store duration, they can not have
12169   // an address space.
12170   if (T.getAddressSpace() != LangAS::Default &&
12171       // OpenCL allows function arguments declared to be an array of a type
12172       // to be qualified with an address space.
12173       !(getLangOpts().OpenCL &&
12174         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
12175     Diag(NameLoc, diag::err_arg_with_address_space);
12176     New->setInvalidDecl();
12177   }
12178 
12179   return New;
12180 }
12181 
12182 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
12183                                            SourceLocation LocAfterDecls) {
12184   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
12185 
12186   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
12187   // for a K&R function.
12188   if (!FTI.hasPrototype) {
12189     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
12190       --i;
12191       if (FTI.Params[i].Param == nullptr) {
12192         SmallString<256> Code;
12193         llvm::raw_svector_ostream(Code)
12194             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
12195         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
12196             << FTI.Params[i].Ident
12197             << FixItHint::CreateInsertion(LocAfterDecls, Code);
12198 
12199         // Implicitly declare the argument as type 'int' for lack of a better
12200         // type.
12201         AttributeFactory attrs;
12202         DeclSpec DS(attrs);
12203         const char* PrevSpec; // unused
12204         unsigned DiagID; // unused
12205         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
12206                            DiagID, Context.getPrintingPolicy());
12207         // Use the identifier location for the type source range.
12208         DS.SetRangeStart(FTI.Params[i].IdentLoc);
12209         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
12210         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
12211         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
12212         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
12213       }
12214     }
12215   }
12216 }
12217 
12218 Decl *
12219 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
12220                               MultiTemplateParamsArg TemplateParameterLists,
12221                               SkipBodyInfo *SkipBody) {
12222   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
12223   assert(D.isFunctionDeclarator() && "Not a function declarator!");
12224   Scope *ParentScope = FnBodyScope->getParent();
12225 
12226   D.setFunctionDefinitionKind(FDK_Definition);
12227   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
12228   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
12229 }
12230 
12231 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
12232   Consumer.HandleInlineFunctionDefinition(D);
12233 }
12234 
12235 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
12236                              const FunctionDecl*& PossibleZeroParamPrototype) {
12237   // Don't warn about invalid declarations.
12238   if (FD->isInvalidDecl())
12239     return false;
12240 
12241   // Or declarations that aren't global.
12242   if (!FD->isGlobal())
12243     return false;
12244 
12245   // Don't warn about C++ member functions.
12246   if (isa<CXXMethodDecl>(FD))
12247     return false;
12248 
12249   // Don't warn about 'main'.
12250   if (FD->isMain())
12251     return false;
12252 
12253   // Don't warn about inline functions.
12254   if (FD->isInlined())
12255     return false;
12256 
12257   // Don't warn about function templates.
12258   if (FD->getDescribedFunctionTemplate())
12259     return false;
12260 
12261   // Don't warn about function template specializations.
12262   if (FD->isFunctionTemplateSpecialization())
12263     return false;
12264 
12265   // Don't warn for OpenCL kernels.
12266   if (FD->hasAttr<OpenCLKernelAttr>())
12267     return false;
12268 
12269   // Don't warn on explicitly deleted functions.
12270   if (FD->isDeleted())
12271     return false;
12272 
12273   bool MissingPrototype = true;
12274   for (const FunctionDecl *Prev = FD->getPreviousDecl();
12275        Prev; Prev = Prev->getPreviousDecl()) {
12276     // Ignore any declarations that occur in function or method
12277     // scope, because they aren't visible from the header.
12278     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
12279       continue;
12280 
12281     MissingPrototype = !Prev->getType()->isFunctionProtoType();
12282     if (FD->getNumParams() == 0)
12283       PossibleZeroParamPrototype = Prev;
12284     break;
12285   }
12286 
12287   return MissingPrototype;
12288 }
12289 
12290 void
12291 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
12292                                    const FunctionDecl *EffectiveDefinition,
12293                                    SkipBodyInfo *SkipBody) {
12294   const FunctionDecl *Definition = EffectiveDefinition;
12295   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
12296     // If this is a friend function defined in a class template, it does not
12297     // have a body until it is used, nevertheless it is a definition, see
12298     // [temp.inst]p2:
12299     //
12300     // ... for the purpose of determining whether an instantiated redeclaration
12301     // is valid according to [basic.def.odr] and [class.mem], a declaration that
12302     // corresponds to a definition in the template is considered to be a
12303     // definition.
12304     //
12305     // The following code must produce redefinition error:
12306     //
12307     //     template<typename T> struct C20 { friend void func_20() {} };
12308     //     C20<int> c20i;
12309     //     void func_20() {}
12310     //
12311     for (auto I : FD->redecls()) {
12312       if (I != FD && !I->isInvalidDecl() &&
12313           I->getFriendObjectKind() != Decl::FOK_None) {
12314         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
12315           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
12316             // A merged copy of the same function, instantiated as a member of
12317             // the same class, is OK.
12318             if (declaresSameEntity(OrigFD, Original) &&
12319                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
12320                                    cast<Decl>(FD->getLexicalDeclContext())))
12321               continue;
12322           }
12323 
12324           if (Original->isThisDeclarationADefinition()) {
12325             Definition = I;
12326             break;
12327           }
12328         }
12329       }
12330     }
12331   }
12332   if (!Definition)
12333     return;
12334 
12335   if (canRedefineFunction(Definition, getLangOpts()))
12336     return;
12337 
12338   // Don't emit an error when this is redefinition of a typo-corrected
12339   // definition.
12340   if (TypoCorrectedFunctionDefinitions.count(Definition))
12341     return;
12342 
12343   // If we don't have a visible definition of the function, and it's inline or
12344   // a template, skip the new definition.
12345   if (SkipBody && !hasVisibleDefinition(Definition) &&
12346       (Definition->getFormalLinkage() == InternalLinkage ||
12347        Definition->isInlined() ||
12348        Definition->getDescribedFunctionTemplate() ||
12349        Definition->getNumTemplateParameterLists())) {
12350     SkipBody->ShouldSkip = true;
12351     if (auto *TD = Definition->getDescribedFunctionTemplate())
12352       makeMergedDefinitionVisible(TD);
12353     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
12354     return;
12355   }
12356 
12357   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
12358       Definition->getStorageClass() == SC_Extern)
12359     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
12360         << FD->getDeclName() << getLangOpts().CPlusPlus;
12361   else
12362     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12363 
12364   Diag(Definition->getLocation(), diag::note_previous_definition);
12365   FD->setInvalidDecl();
12366 }
12367 
12368 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12369                                    Sema &S) {
12370   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12371 
12372   LambdaScopeInfo *LSI = S.PushLambdaScope();
12373   LSI->CallOperator = CallOperator;
12374   LSI->Lambda = LambdaClass;
12375   LSI->ReturnType = CallOperator->getReturnType();
12376   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12377 
12378   if (LCD == LCD_None)
12379     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12380   else if (LCD == LCD_ByCopy)
12381     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12382   else if (LCD == LCD_ByRef)
12383     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12384   DeclarationNameInfo DNI = CallOperator->getNameInfo();
12385 
12386   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12387   LSI->Mutable = !CallOperator->isConst();
12388 
12389   // Add the captures to the LSI so they can be noted as already
12390   // captured within tryCaptureVar.
12391   auto I = LambdaClass->field_begin();
12392   for (const auto &C : LambdaClass->captures()) {
12393     if (C.capturesVariable()) {
12394       VarDecl *VD = C.getCapturedVar();
12395       if (VD->isInitCapture())
12396         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12397       QualType CaptureType = VD->getType();
12398       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12399       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12400           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12401           /*EllipsisLoc*/C.isPackExpansion()
12402                          ? C.getEllipsisLoc() : SourceLocation(),
12403           CaptureType, /*Expr*/ nullptr);
12404 
12405     } else if (C.capturesThis()) {
12406       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
12407                               /*Expr*/ nullptr,
12408                               C.getCaptureKind() == LCK_StarThis);
12409     } else {
12410       LSI->addVLATypeCapture(C.getLocation(), I->getType());
12411     }
12412     ++I;
12413   }
12414 }
12415 
12416 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12417                                     SkipBodyInfo *SkipBody) {
12418   if (!D) {
12419     // Parsing the function declaration failed in some way. Push on a fake scope
12420     // anyway so we can try to parse the function body.
12421     PushFunctionScope();
12422     return D;
12423   }
12424 
12425   FunctionDecl *FD = nullptr;
12426 
12427   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
12428     FD = FunTmpl->getTemplatedDecl();
12429   else
12430     FD = cast<FunctionDecl>(D);
12431 
12432   // Check for defining attributes before the check for redefinition.
12433   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
12434     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
12435     FD->dropAttr<AliasAttr>();
12436     FD->setInvalidDecl();
12437   }
12438   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12439     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12440     FD->dropAttr<IFuncAttr>();
12441     FD->setInvalidDecl();
12442   }
12443 
12444   // See if this is a redefinition. If 'will have body' is already set, then
12445   // these checks were already performed when it was set.
12446   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
12447     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
12448 
12449     // If we're skipping the body, we're done. Don't enter the scope.
12450     if (SkipBody && SkipBody->ShouldSkip)
12451       return D;
12452   }
12453 
12454   // Mark this function as "will have a body eventually".  This lets users to
12455   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12456   // this function.
12457   FD->setWillHaveBody();
12458 
12459   // If we are instantiating a generic lambda call operator, push
12460   // a LambdaScopeInfo onto the function stack.  But use the information
12461   // that's already been calculated (ActOnLambdaExpr) to prime the current
12462   // LambdaScopeInfo.
12463   // When the template operator is being specialized, the LambdaScopeInfo,
12464   // has to be properly restored so that tryCaptureVariable doesn't try
12465   // and capture any new variables. In addition when calculating potential
12466   // captures during transformation of nested lambdas, it is necessary to
12467   // have the LSI properly restored.
12468   if (isGenericLambdaCallOperatorSpecialization(FD)) {
12469     assert(inTemplateInstantiation() &&
12470            "There should be an active template instantiation on the stack "
12471            "when instantiating a generic lambda!");
12472     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12473   } else {
12474     // Enter a new function scope
12475     PushFunctionScope();
12476   }
12477 
12478   // Builtin functions cannot be defined.
12479   if (unsigned BuiltinID = FD->getBuiltinID()) {
12480     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12481         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12482       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12483       FD->setInvalidDecl();
12484     }
12485   }
12486 
12487   // The return type of a function definition must be complete
12488   // (C99 6.9.1p3, C++ [dcl.fct]p6).
12489   QualType ResultType = FD->getReturnType();
12490   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12491       !FD->isInvalidDecl() &&
12492       RequireCompleteType(FD->getLocation(), ResultType,
12493                           diag::err_func_def_incomplete_result))
12494     FD->setInvalidDecl();
12495 
12496   if (FnBodyScope)
12497     PushDeclContext(FnBodyScope, FD);
12498 
12499   // Check the validity of our function parameters
12500   CheckParmsForFunctionDef(FD->parameters(),
12501                            /*CheckParameterNames=*/true);
12502 
12503   // Add non-parameter declarations already in the function to the current
12504   // scope.
12505   if (FnBodyScope) {
12506     for (Decl *NPD : FD->decls()) {
12507       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
12508       if (!NonParmDecl)
12509         continue;
12510       assert(!isa<ParmVarDecl>(NonParmDecl) &&
12511              "parameters should not be in newly created FD yet");
12512 
12513       // If the decl has a name, make it accessible in the current scope.
12514       if (NonParmDecl->getDeclName())
12515         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
12516 
12517       // Similarly, dive into enums and fish their constants out, making them
12518       // accessible in this scope.
12519       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
12520         for (auto *EI : ED->enumerators())
12521           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
12522       }
12523     }
12524   }
12525 
12526   // Introduce our parameters into the function scope
12527   for (auto Param : FD->parameters()) {
12528     Param->setOwningFunction(FD);
12529 
12530     // If this has an identifier, add it to the scope stack.
12531     if (Param->getIdentifier() && FnBodyScope) {
12532       CheckShadow(FnBodyScope, Param);
12533 
12534       PushOnScopeChains(Param, FnBodyScope);
12535     }
12536   }
12537 
12538   // Ensure that the function's exception specification is instantiated.
12539   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
12540     ResolveExceptionSpec(D->getLocation(), FPT);
12541 
12542   // dllimport cannot be applied to non-inline function definitions.
12543   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
12544       !FD->isTemplateInstantiation()) {
12545     assert(!FD->hasAttr<DLLExportAttr>());
12546     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
12547     FD->setInvalidDecl();
12548     return D;
12549   }
12550   // We want to attach documentation to original Decl (which might be
12551   // a function template).
12552   ActOnDocumentableDecl(D);
12553   if (getCurLexicalContext()->isObjCContainer() &&
12554       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
12555       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
12556     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
12557 
12558   return D;
12559 }
12560 
12561 /// Given the set of return statements within a function body,
12562 /// compute the variables that are subject to the named return value
12563 /// optimization.
12564 ///
12565 /// Each of the variables that is subject to the named return value
12566 /// optimization will be marked as NRVO variables in the AST, and any
12567 /// return statement that has a marked NRVO variable as its NRVO candidate can
12568 /// use the named return value optimization.
12569 ///
12570 /// This function applies a very simplistic algorithm for NRVO: if every return
12571 /// statement in the scope of a variable has the same NRVO candidate, that
12572 /// candidate is an NRVO variable.
12573 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
12574   ReturnStmt **Returns = Scope->Returns.data();
12575 
12576   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
12577     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
12578       if (!NRVOCandidate->isNRVOVariable())
12579         Returns[I]->setNRVOCandidate(nullptr);
12580     }
12581   }
12582 }
12583 
12584 bool Sema::canDelayFunctionBody(const Declarator &D) {
12585   // We can't delay parsing the body of a constexpr function template (yet).
12586   if (D.getDeclSpec().isConstexprSpecified())
12587     return false;
12588 
12589   // We can't delay parsing the body of a function template with a deduced
12590   // return type (yet).
12591   if (D.getDeclSpec().hasAutoTypeSpec()) {
12592     // If the placeholder introduces a non-deduced trailing return type,
12593     // we can still delay parsing it.
12594     if (D.getNumTypeObjects()) {
12595       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
12596       if (Outer.Kind == DeclaratorChunk::Function &&
12597           Outer.Fun.hasTrailingReturnType()) {
12598         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
12599         return Ty.isNull() || !Ty->isUndeducedType();
12600       }
12601     }
12602     return false;
12603   }
12604 
12605   return true;
12606 }
12607 
12608 bool Sema::canSkipFunctionBody(Decl *D) {
12609   // We cannot skip the body of a function (or function template) which is
12610   // constexpr, since we may need to evaluate its body in order to parse the
12611   // rest of the file.
12612   // We cannot skip the body of a function with an undeduced return type,
12613   // because any callers of that function need to know the type.
12614   if (const FunctionDecl *FD = D->getAsFunction()) {
12615     if (FD->isConstexpr())
12616       return false;
12617     // We can't simply call Type::isUndeducedType here, because inside template
12618     // auto can be deduced to a dependent type, which is not considered
12619     // "undeduced".
12620     if (FD->getReturnType()->getContainedDeducedType())
12621       return false;
12622   }
12623   return Consumer.shouldSkipFunctionBody(D);
12624 }
12625 
12626 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
12627   if (!Decl)
12628     return nullptr;
12629   if (FunctionDecl *FD = Decl->getAsFunction())
12630     FD->setHasSkippedBody();
12631   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
12632     MD->setHasSkippedBody();
12633   return Decl;
12634 }
12635 
12636 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
12637   return ActOnFinishFunctionBody(D, BodyArg, false);
12638 }
12639 
12640 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
12641                                     bool IsInstantiation) {
12642   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
12643 
12644   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12645   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
12646 
12647   if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
12648     CheckCompletedCoroutineBody(FD, Body);
12649 
12650   if (FD) {
12651     FD->setBody(Body);
12652     FD->setWillHaveBody(false);
12653 
12654     if (getLangOpts().CPlusPlus14) {
12655       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
12656           FD->getReturnType()->isUndeducedType()) {
12657         // If the function has a deduced result type but contains no 'return'
12658         // statements, the result type as written must be exactly 'auto', and
12659         // the deduced result type is 'void'.
12660         if (!FD->getReturnType()->getAs<AutoType>()) {
12661           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
12662               << FD->getReturnType();
12663           FD->setInvalidDecl();
12664         } else {
12665           // Substitute 'void' for the 'auto' in the type.
12666           TypeLoc ResultType = getReturnTypeLoc(FD);
12667           Context.adjustDeducedFunctionResultType(
12668               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
12669         }
12670       }
12671     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
12672       // In C++11, we don't use 'auto' deduction rules for lambda call
12673       // operators because we don't support return type deduction.
12674       auto *LSI = getCurLambda();
12675       if (LSI->HasImplicitReturnType) {
12676         deduceClosureReturnType(*LSI);
12677 
12678         // C++11 [expr.prim.lambda]p4:
12679         //   [...] if there are no return statements in the compound-statement
12680         //   [the deduced type is] the type void
12681         QualType RetType =
12682             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
12683 
12684         // Update the return type to the deduced type.
12685         const FunctionProtoType *Proto =
12686             FD->getType()->getAs<FunctionProtoType>();
12687         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
12688                                             Proto->getExtProtoInfo()));
12689       }
12690     }
12691 
12692     // If the function implicitly returns zero (like 'main') or is naked,
12693     // don't complain about missing return statements.
12694     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
12695       WP.disableCheckFallThrough();
12696 
12697     // MSVC permits the use of pure specifier (=0) on function definition,
12698     // defined at class scope, warn about this non-standard construct.
12699     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
12700       Diag(FD->getLocation(), diag::ext_pure_function_definition);
12701 
12702     if (!FD->isInvalidDecl()) {
12703       // Don't diagnose unused parameters of defaulted or deleted functions.
12704       if (!FD->isDeleted() && !FD->isDefaulted())
12705         DiagnoseUnusedParameters(FD->parameters());
12706       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
12707                                              FD->getReturnType(), FD);
12708 
12709       // If this is a structor, we need a vtable.
12710       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
12711         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
12712       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
12713         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
12714 
12715       // Try to apply the named return value optimization. We have to check
12716       // if we can do this here because lambdas keep return statements around
12717       // to deduce an implicit return type.
12718       if (FD->getReturnType()->isRecordType() &&
12719           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
12720         computeNRVO(Body, getCurFunction());
12721     }
12722 
12723     // GNU warning -Wmissing-prototypes:
12724     //   Warn if a global function is defined without a previous
12725     //   prototype declaration. This warning is issued even if the
12726     //   definition itself provides a prototype. The aim is to detect
12727     //   global functions that fail to be declared in header files.
12728     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
12729     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
12730       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
12731 
12732       if (PossibleZeroParamPrototype) {
12733         // We found a declaration that is not a prototype,
12734         // but that could be a zero-parameter prototype
12735         if (TypeSourceInfo *TI =
12736                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
12737           TypeLoc TL = TI->getTypeLoc();
12738           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
12739             Diag(PossibleZeroParamPrototype->getLocation(),
12740                  diag::note_declaration_not_a_prototype)
12741                 << PossibleZeroParamPrototype
12742                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
12743         }
12744       }
12745 
12746       // GNU warning -Wstrict-prototypes
12747       //   Warn if K&R function is defined without a previous declaration.
12748       //   This warning is issued only if the definition itself does not provide
12749       //   a prototype. Only K&R definitions do not provide a prototype.
12750       //   An empty list in a function declarator that is part of a definition
12751       //   of that function specifies that the function has no parameters
12752       //   (C99 6.7.5.3p14)
12753       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
12754           !LangOpts.CPlusPlus) {
12755         TypeSourceInfo *TI = FD->getTypeSourceInfo();
12756         TypeLoc TL = TI->getTypeLoc();
12757         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
12758         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
12759       }
12760     }
12761 
12762     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12763       const CXXMethodDecl *KeyFunction;
12764       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
12765           MD->isVirtual() &&
12766           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
12767           MD == KeyFunction->getCanonicalDecl()) {
12768         // Update the key-function state if necessary for this ABI.
12769         if (FD->isInlined() &&
12770             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12771           Context.setNonKeyFunction(MD);
12772 
12773           // If the newly-chosen key function is already defined, then we
12774           // need to mark the vtable as used retroactively.
12775           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
12776           const FunctionDecl *Definition;
12777           if (KeyFunction && KeyFunction->isDefined(Definition))
12778             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
12779         } else {
12780           // We just defined they key function; mark the vtable as used.
12781           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
12782         }
12783       }
12784     }
12785 
12786     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
12787            "Function parsing confused");
12788   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
12789     assert(MD == getCurMethodDecl() && "Method parsing confused");
12790     MD->setBody(Body);
12791     if (!MD->isInvalidDecl()) {
12792       DiagnoseUnusedParameters(MD->parameters());
12793       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
12794                                              MD->getReturnType(), MD);
12795 
12796       if (Body)
12797         computeNRVO(Body, getCurFunction());
12798     }
12799     if (getCurFunction()->ObjCShouldCallSuper) {
12800       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
12801         << MD->getSelector().getAsString();
12802       getCurFunction()->ObjCShouldCallSuper = false;
12803     }
12804     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12805       const ObjCMethodDecl *InitMethod = nullptr;
12806       bool isDesignated =
12807           MD->isDesignatedInitializerForTheInterface(&InitMethod);
12808       assert(isDesignated && InitMethod);
12809       (void)isDesignated;
12810 
12811       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12812         auto IFace = MD->getClassInterface();
12813         if (!IFace)
12814           return false;
12815         auto SuperD = IFace->getSuperClass();
12816         if (!SuperD)
12817           return false;
12818         return SuperD->getIdentifier() ==
12819             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12820       };
12821       // Don't issue this warning for unavailable inits or direct subclasses
12822       // of NSObject.
12823       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12824         Diag(MD->getLocation(),
12825              diag::warn_objc_designated_init_missing_super_call);
12826         Diag(InitMethod->getLocation(),
12827              diag::note_objc_designated_init_marked_here);
12828       }
12829       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12830     }
12831     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12832       // Don't issue this warning for unavaialable inits.
12833       if (!MD->isUnavailable())
12834         Diag(MD->getLocation(),
12835              diag::warn_objc_secondary_init_missing_init_call);
12836       getCurFunction()->ObjCWarnForNoInitDelegation = false;
12837     }
12838   } else {
12839     // Parsing the function declaration failed in some way. Pop the fake scope
12840     // we pushed on.
12841     PopFunctionScopeInfo(ActivePolicy, dcl);
12842     return nullptr;
12843   }
12844 
12845   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12846     DiagnoseUnguardedAvailabilityViolations(dcl);
12847 
12848   assert(!getCurFunction()->ObjCShouldCallSuper &&
12849          "This should only be set for ObjC methods, which should have been "
12850          "handled in the block above.");
12851 
12852   // Verify and clean out per-function state.
12853   if (Body && (!FD || !FD->isDefaulted())) {
12854     // C++ constructors that have function-try-blocks can't have return
12855     // statements in the handlers of that block. (C++ [except.handle]p14)
12856     // Verify this.
12857     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12858       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12859 
12860     // Verify that gotos and switch cases don't jump into scopes illegally.
12861     if (getCurFunction()->NeedsScopeChecking() &&
12862         !PP.isCodeCompletionEnabled())
12863       DiagnoseInvalidJumps(Body);
12864 
12865     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12866       if (!Destructor->getParent()->isDependentType())
12867         CheckDestructor(Destructor);
12868 
12869       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12870                                              Destructor->getParent());
12871     }
12872 
12873     // If any errors have occurred, clear out any temporaries that may have
12874     // been leftover. This ensures that these temporaries won't be picked up for
12875     // deletion in some later function.
12876     if (getDiagnostics().hasErrorOccurred() ||
12877         getDiagnostics().getSuppressAllDiagnostics()) {
12878       DiscardCleanupsInEvaluationContext();
12879     }
12880     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12881         !isa<FunctionTemplateDecl>(dcl)) {
12882       // Since the body is valid, issue any analysis-based warnings that are
12883       // enabled.
12884       ActivePolicy = &WP;
12885     }
12886 
12887     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12888         (!CheckConstexprFunctionDecl(FD) ||
12889          !CheckConstexprFunctionBody(FD, Body)))
12890       FD->setInvalidDecl();
12891 
12892     if (FD && FD->hasAttr<NakedAttr>()) {
12893       for (const Stmt *S : Body->children()) {
12894         // Allow local register variables without initializer as they don't
12895         // require prologue.
12896         bool RegisterVariables = false;
12897         if (auto *DS = dyn_cast<DeclStmt>(S)) {
12898           for (const auto *Decl : DS->decls()) {
12899             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12900               RegisterVariables =
12901                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12902               if (!RegisterVariables)
12903                 break;
12904             }
12905           }
12906         }
12907         if (RegisterVariables)
12908           continue;
12909         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12910           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12911           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12912           FD->setInvalidDecl();
12913           break;
12914         }
12915       }
12916     }
12917 
12918     assert(ExprCleanupObjects.size() ==
12919                ExprEvalContexts.back().NumCleanupObjects &&
12920            "Leftover temporaries in function");
12921     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12922     assert(MaybeODRUseExprs.empty() &&
12923            "Leftover expressions for odr-use checking");
12924   }
12925 
12926   if (!IsInstantiation)
12927     PopDeclContext();
12928 
12929   PopFunctionScopeInfo(ActivePolicy, dcl);
12930   // If any errors have occurred, clear out any temporaries that may have
12931   // been leftover. This ensures that these temporaries won't be picked up for
12932   // deletion in some later function.
12933   if (getDiagnostics().hasErrorOccurred()) {
12934     DiscardCleanupsInEvaluationContext();
12935   }
12936 
12937   return dcl;
12938 }
12939 
12940 /// When we finish delayed parsing of an attribute, we must attach it to the
12941 /// relevant Decl.
12942 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12943                                        ParsedAttributes &Attrs) {
12944   // Always attach attributes to the underlying decl.
12945   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12946     D = TD->getTemplatedDecl();
12947   ProcessDeclAttributeList(S, D, Attrs.getList());
12948 
12949   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12950     if (Method->isStatic())
12951       checkThisInStaticMemberFunctionAttributes(Method);
12952 }
12953 
12954 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12955 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12956 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12957                                           IdentifierInfo &II, Scope *S) {
12958   // Find the scope in which the identifier is injected and the corresponding
12959   // DeclContext.
12960   // FIXME: C89 does not say what happens if there is no enclosing block scope.
12961   // In that case, we inject the declaration into the translation unit scope
12962   // instead.
12963   Scope *BlockScope = S;
12964   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
12965     BlockScope = BlockScope->getParent();
12966 
12967   Scope *ContextScope = BlockScope;
12968   while (!ContextScope->getEntity())
12969     ContextScope = ContextScope->getParent();
12970   ContextRAII SavedContext(*this, ContextScope->getEntity());
12971 
12972   // Before we produce a declaration for an implicitly defined
12973   // function, see whether there was a locally-scoped declaration of
12974   // this name as a function or variable. If so, use that
12975   // (non-visible) declaration, and complain about it.
12976   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
12977   if (ExternCPrev) {
12978     // We still need to inject the function into the enclosing block scope so
12979     // that later (non-call) uses can see it.
12980     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
12981 
12982     // C89 footnote 38:
12983     //   If in fact it is not defined as having type "function returning int",
12984     //   the behavior is undefined.
12985     if (!isa<FunctionDecl>(ExternCPrev) ||
12986         !Context.typesAreCompatible(
12987             cast<FunctionDecl>(ExternCPrev)->getType(),
12988             Context.getFunctionNoProtoType(Context.IntTy))) {
12989       Diag(Loc, diag::ext_use_out_of_scope_declaration)
12990           << ExternCPrev << !getLangOpts().C99;
12991       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12992       return ExternCPrev;
12993     }
12994   }
12995 
12996   // Extension in C99.  Legal in C90, but warn about it.
12997   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
12998   unsigned diag_id;
12999   if (II.getName().startswith("__builtin_"))
13000     diag_id = diag::warn_builtin_unknown;
13001   else if (getLangOpts().C99 || getLangOpts().OpenCL)
13002     diag_id = diag::ext_implicit_function_decl;
13003   else
13004     diag_id = diag::warn_implicit_function_decl;
13005   Diag(Loc, diag_id) << &II << getLangOpts().OpenCL;
13006 
13007   // If we found a prior declaration of this function, don't bother building
13008   // another one. We've already pushed that one into scope, so there's nothing
13009   // more to do.
13010   if (ExternCPrev)
13011     return ExternCPrev;
13012 
13013   // Because typo correction is expensive, only do it if the implicit
13014   // function declaration is going to be treated as an error.
13015   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
13016     TypoCorrection Corrected;
13017     if (S &&
13018         (Corrected = CorrectTypo(
13019              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
13020              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
13021       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
13022                    /*ErrorRecovery*/false);
13023   }
13024 
13025   // Set a Declarator for the implicit definition: int foo();
13026   const char *Dummy;
13027   AttributeFactory attrFactory;
13028   DeclSpec DS(attrFactory);
13029   unsigned DiagID;
13030   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
13031                                   Context.getPrintingPolicy());
13032   (void)Error; // Silence warning.
13033   assert(!Error && "Error setting up implicit decl!");
13034   SourceLocation NoLoc;
13035   Declarator D(DS, DeclaratorContext::BlockContext);
13036   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
13037                                              /*IsAmbiguous=*/false,
13038                                              /*LParenLoc=*/NoLoc,
13039                                              /*Params=*/nullptr,
13040                                              /*NumParams=*/0,
13041                                              /*EllipsisLoc=*/NoLoc,
13042                                              /*RParenLoc=*/NoLoc,
13043                                              /*TypeQuals=*/0,
13044                                              /*RefQualifierIsLvalueRef=*/true,
13045                                              /*RefQualifierLoc=*/NoLoc,
13046                                              /*ConstQualifierLoc=*/NoLoc,
13047                                              /*VolatileQualifierLoc=*/NoLoc,
13048                                              /*RestrictQualifierLoc=*/NoLoc,
13049                                              /*MutableLoc=*/NoLoc,
13050                                              EST_None,
13051                                              /*ESpecRange=*/SourceRange(),
13052                                              /*Exceptions=*/nullptr,
13053                                              /*ExceptionRanges=*/nullptr,
13054                                              /*NumExceptions=*/0,
13055                                              /*NoexceptExpr=*/nullptr,
13056                                              /*ExceptionSpecTokens=*/nullptr,
13057                                              /*DeclsInPrototype=*/None,
13058                                              Loc, Loc, D),
13059                 DS.getAttributes(),
13060                 SourceLocation());
13061   D.SetIdentifier(&II, Loc);
13062 
13063   // Insert this function into the enclosing block scope.
13064   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
13065   FD->setImplicit();
13066 
13067   AddKnownFunctionAttributes(FD);
13068 
13069   return FD;
13070 }
13071 
13072 /// Adds any function attributes that we know a priori based on
13073 /// the declaration of this function.
13074 ///
13075 /// These attributes can apply both to implicitly-declared builtins
13076 /// (like __builtin___printf_chk) or to library-declared functions
13077 /// like NSLog or printf.
13078 ///
13079 /// We need to check for duplicate attributes both here and where user-written
13080 /// attributes are applied to declarations.
13081 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
13082   if (FD->isInvalidDecl())
13083     return;
13084 
13085   // If this is a built-in function, map its builtin attributes to
13086   // actual attributes.
13087   if (unsigned BuiltinID = FD->getBuiltinID()) {
13088     // Handle printf-formatting attributes.
13089     unsigned FormatIdx;
13090     bool HasVAListArg;
13091     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
13092       if (!FD->hasAttr<FormatAttr>()) {
13093         const char *fmt = "printf";
13094         unsigned int NumParams = FD->getNumParams();
13095         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
13096             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
13097           fmt = "NSString";
13098         FD->addAttr(FormatAttr::CreateImplicit(Context,
13099                                                &Context.Idents.get(fmt),
13100                                                FormatIdx+1,
13101                                                HasVAListArg ? 0 : FormatIdx+2,
13102                                                FD->getLocation()));
13103       }
13104     }
13105     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
13106                                              HasVAListArg)) {
13107      if (!FD->hasAttr<FormatAttr>())
13108        FD->addAttr(FormatAttr::CreateImplicit(Context,
13109                                               &Context.Idents.get("scanf"),
13110                                               FormatIdx+1,
13111                                               HasVAListArg ? 0 : FormatIdx+2,
13112                                               FD->getLocation()));
13113     }
13114 
13115     // Mark const if we don't care about errno and that is the only thing
13116     // preventing the function from being const. This allows IRgen to use LLVM
13117     // intrinsics for such functions.
13118     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
13119         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
13120       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13121 
13122     // We make "fma" on some platforms const because we know it does not set
13123     // errno in those environments even though it could set errno based on the
13124     // C standard.
13125     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
13126     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
13127         !FD->hasAttr<ConstAttr>()) {
13128       switch (BuiltinID) {
13129       case Builtin::BI__builtin_fma:
13130       case Builtin::BI__builtin_fmaf:
13131       case Builtin::BI__builtin_fmal:
13132       case Builtin::BIfma:
13133       case Builtin::BIfmaf:
13134       case Builtin::BIfmal:
13135         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13136         break;
13137       default:
13138         break;
13139       }
13140     }
13141 
13142     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
13143         !FD->hasAttr<ReturnsTwiceAttr>())
13144       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
13145                                          FD->getLocation()));
13146     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
13147       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13148     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
13149       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
13150     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
13151       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13152     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
13153         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
13154       // Add the appropriate attribute, depending on the CUDA compilation mode
13155       // and which target the builtin belongs to. For example, during host
13156       // compilation, aux builtins are __device__, while the rest are __host__.
13157       if (getLangOpts().CUDAIsDevice !=
13158           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
13159         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
13160       else
13161         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
13162     }
13163   }
13164 
13165   // If C++ exceptions are enabled but we are told extern "C" functions cannot
13166   // throw, add an implicit nothrow attribute to any extern "C" function we come
13167   // across.
13168   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
13169       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
13170     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
13171     if (!FPT || FPT->getExceptionSpecType() == EST_None)
13172       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13173   }
13174 
13175   IdentifierInfo *Name = FD->getIdentifier();
13176   if (!Name)
13177     return;
13178   if ((!getLangOpts().CPlusPlus &&
13179        FD->getDeclContext()->isTranslationUnit()) ||
13180       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
13181        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
13182        LinkageSpecDecl::lang_c)) {
13183     // Okay: this could be a libc/libm/Objective-C function we know
13184     // about.
13185   } else
13186     return;
13187 
13188   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
13189     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
13190     // target-specific builtins, perhaps?
13191     if (!FD->hasAttr<FormatAttr>())
13192       FD->addAttr(FormatAttr::CreateImplicit(Context,
13193                                              &Context.Idents.get("printf"), 2,
13194                                              Name->isStr("vasprintf") ? 0 : 3,
13195                                              FD->getLocation()));
13196   }
13197 
13198   if (Name->isStr("__CFStringMakeConstantString")) {
13199     // We already have a __builtin___CFStringMakeConstantString,
13200     // but builds that use -fno-constant-cfstrings don't go through that.
13201     if (!FD->hasAttr<FormatArgAttr>())
13202       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
13203                                                 FD->getLocation()));
13204   }
13205 }
13206 
13207 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
13208                                     TypeSourceInfo *TInfo) {
13209   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
13210   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
13211 
13212   if (!TInfo) {
13213     assert(D.isInvalidType() && "no declarator info for valid type");
13214     TInfo = Context.getTrivialTypeSourceInfo(T);
13215   }
13216 
13217   // Scope manipulation handled by caller.
13218   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
13219                                            D.getLocStart(),
13220                                            D.getIdentifierLoc(),
13221                                            D.getIdentifier(),
13222                                            TInfo);
13223 
13224   // Bail out immediately if we have an invalid declaration.
13225   if (D.isInvalidType()) {
13226     NewTD->setInvalidDecl();
13227     return NewTD;
13228   }
13229 
13230   if (D.getDeclSpec().isModulePrivateSpecified()) {
13231     if (CurContext->isFunctionOrMethod())
13232       Diag(NewTD->getLocation(), diag::err_module_private_local)
13233         << 2 << NewTD->getDeclName()
13234         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13235         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13236     else
13237       NewTD->setModulePrivate();
13238   }
13239 
13240   // C++ [dcl.typedef]p8:
13241   //   If the typedef declaration defines an unnamed class (or
13242   //   enum), the first typedef-name declared by the declaration
13243   //   to be that class type (or enum type) is used to denote the
13244   //   class type (or enum type) for linkage purposes only.
13245   // We need to check whether the type was declared in the declaration.
13246   switch (D.getDeclSpec().getTypeSpecType()) {
13247   case TST_enum:
13248   case TST_struct:
13249   case TST_interface:
13250   case TST_union:
13251   case TST_class: {
13252     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
13253     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
13254     break;
13255   }
13256 
13257   default:
13258     break;
13259   }
13260 
13261   return NewTD;
13262 }
13263 
13264 /// Check that this is a valid underlying type for an enum declaration.
13265 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
13266   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
13267   QualType T = TI->getType();
13268 
13269   if (T->isDependentType())
13270     return false;
13271 
13272   if (const BuiltinType *BT = T->getAs<BuiltinType>())
13273     if (BT->isInteger())
13274       return false;
13275 
13276   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
13277   return true;
13278 }
13279 
13280 /// Check whether this is a valid redeclaration of a previous enumeration.
13281 /// \return true if the redeclaration was invalid.
13282 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
13283                                   QualType EnumUnderlyingTy, bool IsFixed,
13284                                   const EnumDecl *Prev) {
13285   if (IsScoped != Prev->isScoped()) {
13286     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
13287       << Prev->isScoped();
13288     Diag(Prev->getLocation(), diag::note_previous_declaration);
13289     return true;
13290   }
13291 
13292   if (IsFixed && Prev->isFixed()) {
13293     if (!EnumUnderlyingTy->isDependentType() &&
13294         !Prev->getIntegerType()->isDependentType() &&
13295         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
13296                                         Prev->getIntegerType())) {
13297       // TODO: Highlight the underlying type of the redeclaration.
13298       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
13299         << EnumUnderlyingTy << Prev->getIntegerType();
13300       Diag(Prev->getLocation(), diag::note_previous_declaration)
13301           << Prev->getIntegerTypeRange();
13302       return true;
13303     }
13304   } else if (IsFixed != Prev->isFixed()) {
13305     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
13306       << Prev->isFixed();
13307     Diag(Prev->getLocation(), diag::note_previous_declaration);
13308     return true;
13309   }
13310 
13311   return false;
13312 }
13313 
13314 /// Get diagnostic %select index for tag kind for
13315 /// redeclaration diagnostic message.
13316 /// WARNING: Indexes apply to particular diagnostics only!
13317 ///
13318 /// \returns diagnostic %select index.
13319 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
13320   switch (Tag) {
13321   case TTK_Struct: return 0;
13322   case TTK_Interface: return 1;
13323   case TTK_Class:  return 2;
13324   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
13325   }
13326 }
13327 
13328 /// Determine if tag kind is a class-key compatible with
13329 /// class for redeclaration (class, struct, or __interface).
13330 ///
13331 /// \returns true iff the tag kind is compatible.
13332 static bool isClassCompatTagKind(TagTypeKind Tag)
13333 {
13334   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
13335 }
13336 
13337 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
13338                                              TagTypeKind TTK) {
13339   if (isa<TypedefDecl>(PrevDecl))
13340     return NTK_Typedef;
13341   else if (isa<TypeAliasDecl>(PrevDecl))
13342     return NTK_TypeAlias;
13343   else if (isa<ClassTemplateDecl>(PrevDecl))
13344     return NTK_Template;
13345   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
13346     return NTK_TypeAliasTemplate;
13347   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
13348     return NTK_TemplateTemplateArgument;
13349   switch (TTK) {
13350   case TTK_Struct:
13351   case TTK_Interface:
13352   case TTK_Class:
13353     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
13354   case TTK_Union:
13355     return NTK_NonUnion;
13356   case TTK_Enum:
13357     return NTK_NonEnum;
13358   }
13359   llvm_unreachable("invalid TTK");
13360 }
13361 
13362 /// Determine whether a tag with a given kind is acceptable
13363 /// as a redeclaration of the given tag declaration.
13364 ///
13365 /// \returns true if the new tag kind is acceptable, false otherwise.
13366 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
13367                                         TagTypeKind NewTag, bool isDefinition,
13368                                         SourceLocation NewTagLoc,
13369                                         const IdentifierInfo *Name) {
13370   // C++ [dcl.type.elab]p3:
13371   //   The class-key or enum keyword present in the
13372   //   elaborated-type-specifier shall agree in kind with the
13373   //   declaration to which the name in the elaborated-type-specifier
13374   //   refers. This rule also applies to the form of
13375   //   elaborated-type-specifier that declares a class-name or
13376   //   friend class since it can be construed as referring to the
13377   //   definition of the class. Thus, in any
13378   //   elaborated-type-specifier, the enum keyword shall be used to
13379   //   refer to an enumeration (7.2), the union class-key shall be
13380   //   used to refer to a union (clause 9), and either the class or
13381   //   struct class-key shall be used to refer to a class (clause 9)
13382   //   declared using the class or struct class-key.
13383   TagTypeKind OldTag = Previous->getTagKind();
13384   if (!isDefinition || !isClassCompatTagKind(NewTag))
13385     if (OldTag == NewTag)
13386       return true;
13387 
13388   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
13389     // Warn about the struct/class tag mismatch.
13390     bool isTemplate = false;
13391     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
13392       isTemplate = Record->getDescribedClassTemplate();
13393 
13394     if (inTemplateInstantiation()) {
13395       // In a template instantiation, do not offer fix-its for tag mismatches
13396       // since they usually mess up the template instead of fixing the problem.
13397       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13398         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13399         << getRedeclDiagFromTagKind(OldTag);
13400       return true;
13401     }
13402 
13403     if (isDefinition) {
13404       // On definitions, check previous tags and issue a fix-it for each
13405       // one that doesn't match the current tag.
13406       if (Previous->getDefinition()) {
13407         // Don't suggest fix-its for redefinitions.
13408         return true;
13409       }
13410 
13411       bool previousMismatch = false;
13412       for (auto I : Previous->redecls()) {
13413         if (I->getTagKind() != NewTag) {
13414           if (!previousMismatch) {
13415             previousMismatch = true;
13416             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
13417               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13418               << getRedeclDiagFromTagKind(I->getTagKind());
13419           }
13420           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
13421             << getRedeclDiagFromTagKind(NewTag)
13422             << FixItHint::CreateReplacement(I->getInnerLocStart(),
13423                  TypeWithKeyword::getTagTypeKindName(NewTag));
13424         }
13425       }
13426       return true;
13427     }
13428 
13429     // Check for a previous definition.  If current tag and definition
13430     // are same type, do nothing.  If no definition, but disagree with
13431     // with previous tag type, give a warning, but no fix-it.
13432     const TagDecl *Redecl = Previous->getDefinition() ?
13433                             Previous->getDefinition() : Previous;
13434     if (Redecl->getTagKind() == NewTag) {
13435       return true;
13436     }
13437 
13438     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13439       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13440       << getRedeclDiagFromTagKind(OldTag);
13441     Diag(Redecl->getLocation(), diag::note_previous_use);
13442 
13443     // If there is a previous definition, suggest a fix-it.
13444     if (Previous->getDefinition()) {
13445         Diag(NewTagLoc, diag::note_struct_class_suggestion)
13446           << getRedeclDiagFromTagKind(Redecl->getTagKind())
13447           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
13448                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
13449     }
13450 
13451     return true;
13452   }
13453   return false;
13454 }
13455 
13456 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
13457 /// from an outer enclosing namespace or file scope inside a friend declaration.
13458 /// This should provide the commented out code in the following snippet:
13459 ///   namespace N {
13460 ///     struct X;
13461 ///     namespace M {
13462 ///       struct Y { friend struct /*N::*/ X; };
13463 ///     }
13464 ///   }
13465 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
13466                                          SourceLocation NameLoc) {
13467   // While the decl is in a namespace, do repeated lookup of that name and see
13468   // if we get the same namespace back.  If we do not, continue until
13469   // translation unit scope, at which point we have a fully qualified NNS.
13470   SmallVector<IdentifierInfo *, 4> Namespaces;
13471   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13472   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
13473     // This tag should be declared in a namespace, which can only be enclosed by
13474     // other namespaces.  Bail if there's an anonymous namespace in the chain.
13475     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
13476     if (!Namespace || Namespace->isAnonymousNamespace())
13477       return FixItHint();
13478     IdentifierInfo *II = Namespace->getIdentifier();
13479     Namespaces.push_back(II);
13480     NamedDecl *Lookup = SemaRef.LookupSingleName(
13481         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
13482     if (Lookup == Namespace)
13483       break;
13484   }
13485 
13486   // Once we have all the namespaces, reverse them to go outermost first, and
13487   // build an NNS.
13488   SmallString<64> Insertion;
13489   llvm::raw_svector_ostream OS(Insertion);
13490   if (DC->isTranslationUnit())
13491     OS << "::";
13492   std::reverse(Namespaces.begin(), Namespaces.end());
13493   for (auto *II : Namespaces)
13494     OS << II->getName() << "::";
13495   return FixItHint::CreateInsertion(NameLoc, Insertion);
13496 }
13497 
13498 /// Determine whether a tag originally declared in context \p OldDC can
13499 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
13500 /// found a declaration in \p OldDC as a previous decl, perhaps through a
13501 /// using-declaration).
13502 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
13503                                          DeclContext *NewDC) {
13504   OldDC = OldDC->getRedeclContext();
13505   NewDC = NewDC->getRedeclContext();
13506 
13507   if (OldDC->Equals(NewDC))
13508     return true;
13509 
13510   // In MSVC mode, we allow a redeclaration if the contexts are related (either
13511   // encloses the other).
13512   if (S.getLangOpts().MSVCCompat &&
13513       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
13514     return true;
13515 
13516   return false;
13517 }
13518 
13519 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
13520 /// former case, Name will be non-null.  In the later case, Name will be null.
13521 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
13522 /// reference/declaration/definition of a tag.
13523 ///
13524 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
13525 /// trailing-type-specifier) other than one in an alias-declaration.
13526 ///
13527 /// \param SkipBody If non-null, will be set to indicate if the caller should
13528 /// skip the definition of this tag and treat it as if it were a declaration.
13529 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
13530                      SourceLocation KWLoc, CXXScopeSpec &SS,
13531                      IdentifierInfo *Name, SourceLocation NameLoc,
13532                      AttributeList *Attr, AccessSpecifier AS,
13533                      SourceLocation ModulePrivateLoc,
13534                      MultiTemplateParamsArg TemplateParameterLists,
13535                      bool &OwnedDecl, bool &IsDependent,
13536                      SourceLocation ScopedEnumKWLoc,
13537                      bool ScopedEnumUsesClassTag,
13538                      TypeResult UnderlyingType,
13539                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
13540                      SkipBodyInfo *SkipBody) {
13541   // If this is not a definition, it must have a name.
13542   IdentifierInfo *OrigName = Name;
13543   assert((Name != nullptr || TUK == TUK_Definition) &&
13544          "Nameless record must be a definition!");
13545   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
13546 
13547   OwnedDecl = false;
13548   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13549   bool ScopedEnum = ScopedEnumKWLoc.isValid();
13550 
13551   // FIXME: Check member specializations more carefully.
13552   bool isMemberSpecialization = false;
13553   bool Invalid = false;
13554 
13555   // We only need to do this matching if we have template parameters
13556   // or a scope specifier, which also conveniently avoids this work
13557   // for non-C++ cases.
13558   if (TemplateParameterLists.size() > 0 ||
13559       (SS.isNotEmpty() && TUK != TUK_Reference)) {
13560     if (TemplateParameterList *TemplateParams =
13561             MatchTemplateParametersToScopeSpecifier(
13562                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
13563                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
13564       if (Kind == TTK_Enum) {
13565         Diag(KWLoc, diag::err_enum_template);
13566         return nullptr;
13567       }
13568 
13569       if (TemplateParams->size() > 0) {
13570         // This is a declaration or definition of a class template (which may
13571         // be a member of another template).
13572 
13573         if (Invalid)
13574           return nullptr;
13575 
13576         OwnedDecl = false;
13577         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
13578                                                SS, Name, NameLoc, Attr,
13579                                                TemplateParams, AS,
13580                                                ModulePrivateLoc,
13581                                                /*FriendLoc*/SourceLocation(),
13582                                                TemplateParameterLists.size()-1,
13583                                                TemplateParameterLists.data(),
13584                                                SkipBody);
13585         return Result.get();
13586       } else {
13587         // The "template<>" header is extraneous.
13588         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13589           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13590         isMemberSpecialization = true;
13591       }
13592     }
13593   }
13594 
13595   // Figure out the underlying type if this a enum declaration. We need to do
13596   // this early, because it's needed to detect if this is an incompatible
13597   // redeclaration.
13598   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
13599   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
13600 
13601   if (Kind == TTK_Enum) {
13602     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
13603       // No underlying type explicitly specified, or we failed to parse the
13604       // type, default to int.
13605       EnumUnderlying = Context.IntTy.getTypePtr();
13606     } else if (UnderlyingType.get()) {
13607       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
13608       // integral type; any cv-qualification is ignored.
13609       TypeSourceInfo *TI = nullptr;
13610       GetTypeFromParser(UnderlyingType.get(), &TI);
13611       EnumUnderlying = TI;
13612 
13613       if (CheckEnumUnderlyingType(TI))
13614         // Recover by falling back to int.
13615         EnumUnderlying = Context.IntTy.getTypePtr();
13616 
13617       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
13618                                           UPPC_FixedUnderlyingType))
13619         EnumUnderlying = Context.IntTy.getTypePtr();
13620 
13621     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13622       // For MSVC ABI compatibility, unfixed enums must use an underlying type
13623       // of 'int'. However, if this is an unfixed forward declaration, don't set
13624       // the underlying type unless the user enables -fms-compatibility. This
13625       // makes unfixed forward declared enums incomplete and is more conforming.
13626       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
13627         EnumUnderlying = Context.IntTy.getTypePtr();
13628     }
13629   }
13630 
13631   DeclContext *SearchDC = CurContext;
13632   DeclContext *DC = CurContext;
13633   bool isStdBadAlloc = false;
13634   bool isStdAlignValT = false;
13635 
13636   RedeclarationKind Redecl = forRedeclarationInCurContext();
13637   if (TUK == TUK_Friend || TUK == TUK_Reference)
13638     Redecl = NotForRedeclaration;
13639 
13640   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
13641   /// implemented asks for structural equivalence checking, the returned decl
13642   /// here is passed back to the parser, allowing the tag body to be parsed.
13643   auto createTagFromNewDecl = [&]() -> TagDecl * {
13644     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
13645     // If there is an identifier, use the location of the identifier as the
13646     // location of the decl, otherwise use the location of the struct/union
13647     // keyword.
13648     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13649     TagDecl *New = nullptr;
13650 
13651     if (Kind == TTK_Enum) {
13652       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
13653                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
13654       // If this is an undefined enum, bail.
13655       if (TUK != TUK_Definition && !Invalid)
13656         return nullptr;
13657       if (EnumUnderlying) {
13658         EnumDecl *ED = cast<EnumDecl>(New);
13659         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
13660           ED->setIntegerTypeSourceInfo(TI);
13661         else
13662           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
13663         ED->setPromotionType(ED->getIntegerType());
13664       }
13665     } else { // struct/union
13666       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13667                                nullptr);
13668     }
13669 
13670     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13671       // Add alignment attributes if necessary; these attributes are checked
13672       // when the ASTContext lays out the structure.
13673       //
13674       // It is important for implementing the correct semantics that this
13675       // happen here (in ActOnTag). The #pragma pack stack is
13676       // maintained as a result of parser callbacks which can occur at
13677       // many points during the parsing of a struct declaration (because
13678       // the #pragma tokens are effectively skipped over during the
13679       // parsing of the struct).
13680       if (TUK == TUK_Definition) {
13681         AddAlignmentAttributesForRecord(RD);
13682         AddMsStructLayoutForRecord(RD);
13683       }
13684     }
13685     New->setLexicalDeclContext(CurContext);
13686     return New;
13687   };
13688 
13689   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
13690   if (Name && SS.isNotEmpty()) {
13691     // We have a nested-name tag ('struct foo::bar').
13692 
13693     // Check for invalid 'foo::'.
13694     if (SS.isInvalid()) {
13695       Name = nullptr;
13696       goto CreateNewDecl;
13697     }
13698 
13699     // If this is a friend or a reference to a class in a dependent
13700     // context, don't try to make a decl for it.
13701     if (TUK == TUK_Friend || TUK == TUK_Reference) {
13702       DC = computeDeclContext(SS, false);
13703       if (!DC) {
13704         IsDependent = true;
13705         return nullptr;
13706       }
13707     } else {
13708       DC = computeDeclContext(SS, true);
13709       if (!DC) {
13710         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
13711           << SS.getRange();
13712         return nullptr;
13713       }
13714     }
13715 
13716     if (RequireCompleteDeclContext(SS, DC))
13717       return nullptr;
13718 
13719     SearchDC = DC;
13720     // Look-up name inside 'foo::'.
13721     LookupQualifiedName(Previous, DC);
13722 
13723     if (Previous.isAmbiguous())
13724       return nullptr;
13725 
13726     if (Previous.empty()) {
13727       // Name lookup did not find anything. However, if the
13728       // nested-name-specifier refers to the current instantiation,
13729       // and that current instantiation has any dependent base
13730       // classes, we might find something at instantiation time: treat
13731       // this as a dependent elaborated-type-specifier.
13732       // But this only makes any sense for reference-like lookups.
13733       if (Previous.wasNotFoundInCurrentInstantiation() &&
13734           (TUK == TUK_Reference || TUK == TUK_Friend)) {
13735         IsDependent = true;
13736         return nullptr;
13737       }
13738 
13739       // A tag 'foo::bar' must already exist.
13740       Diag(NameLoc, diag::err_not_tag_in_scope)
13741         << Kind << Name << DC << SS.getRange();
13742       Name = nullptr;
13743       Invalid = true;
13744       goto CreateNewDecl;
13745     }
13746   } else if (Name) {
13747     // C++14 [class.mem]p14:
13748     //   If T is the name of a class, then each of the following shall have a
13749     //   name different from T:
13750     //    -- every member of class T that is itself a type
13751     if (TUK != TUK_Reference && TUK != TUK_Friend &&
13752         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
13753       return nullptr;
13754 
13755     // If this is a named struct, check to see if there was a previous forward
13756     // declaration or definition.
13757     // FIXME: We're looking into outer scopes here, even when we
13758     // shouldn't be. Doing so can result in ambiguities that we
13759     // shouldn't be diagnosing.
13760     LookupName(Previous, S);
13761 
13762     // When declaring or defining a tag, ignore ambiguities introduced
13763     // by types using'ed into this scope.
13764     if (Previous.isAmbiguous() &&
13765         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
13766       LookupResult::Filter F = Previous.makeFilter();
13767       while (F.hasNext()) {
13768         NamedDecl *ND = F.next();
13769         if (!ND->getDeclContext()->getRedeclContext()->Equals(
13770                 SearchDC->getRedeclContext()))
13771           F.erase();
13772       }
13773       F.done();
13774     }
13775 
13776     // C++11 [namespace.memdef]p3:
13777     //   If the name in a friend declaration is neither qualified nor
13778     //   a template-id and the declaration is a function or an
13779     //   elaborated-type-specifier, the lookup to determine whether
13780     //   the entity has been previously declared shall not consider
13781     //   any scopes outside the innermost enclosing namespace.
13782     //
13783     // MSVC doesn't implement the above rule for types, so a friend tag
13784     // declaration may be a redeclaration of a type declared in an enclosing
13785     // scope.  They do implement this rule for friend functions.
13786     //
13787     // Does it matter that this should be by scope instead of by
13788     // semantic context?
13789     if (!Previous.empty() && TUK == TUK_Friend) {
13790       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
13791       LookupResult::Filter F = Previous.makeFilter();
13792       bool FriendSawTagOutsideEnclosingNamespace = false;
13793       while (F.hasNext()) {
13794         NamedDecl *ND = F.next();
13795         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13796         if (DC->isFileContext() &&
13797             !EnclosingNS->Encloses(ND->getDeclContext())) {
13798           if (getLangOpts().MSVCCompat)
13799             FriendSawTagOutsideEnclosingNamespace = true;
13800           else
13801             F.erase();
13802         }
13803       }
13804       F.done();
13805 
13806       // Diagnose this MSVC extension in the easy case where lookup would have
13807       // unambiguously found something outside the enclosing namespace.
13808       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
13809         NamedDecl *ND = Previous.getFoundDecl();
13810         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
13811             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
13812       }
13813     }
13814 
13815     // Note:  there used to be some attempt at recovery here.
13816     if (Previous.isAmbiguous())
13817       return nullptr;
13818 
13819     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
13820       // FIXME: This makes sure that we ignore the contexts associated
13821       // with C structs, unions, and enums when looking for a matching
13822       // tag declaration or definition. See the similar lookup tweak
13823       // in Sema::LookupName; is there a better way to deal with this?
13824       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
13825         SearchDC = SearchDC->getParent();
13826     }
13827   }
13828 
13829   if (Previous.isSingleResult() &&
13830       Previous.getFoundDecl()->isTemplateParameter()) {
13831     // Maybe we will complain about the shadowed template parameter.
13832     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
13833     // Just pretend that we didn't see the previous declaration.
13834     Previous.clear();
13835   }
13836 
13837   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
13838       DC->Equals(getStdNamespace())) {
13839     if (Name->isStr("bad_alloc")) {
13840       // This is a declaration of or a reference to "std::bad_alloc".
13841       isStdBadAlloc = true;
13842 
13843       // If std::bad_alloc has been implicitly declared (but made invisible to
13844       // name lookup), fill in this implicit declaration as the previous
13845       // declaration, so that the declarations get chained appropriately.
13846       if (Previous.empty() && StdBadAlloc)
13847         Previous.addDecl(getStdBadAlloc());
13848     } else if (Name->isStr("align_val_t")) {
13849       isStdAlignValT = true;
13850       if (Previous.empty() && StdAlignValT)
13851         Previous.addDecl(getStdAlignValT());
13852     }
13853   }
13854 
13855   // If we didn't find a previous declaration, and this is a reference
13856   // (or friend reference), move to the correct scope.  In C++, we
13857   // also need to do a redeclaration lookup there, just in case
13858   // there's a shadow friend decl.
13859   if (Name && Previous.empty() &&
13860       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
13861     if (Invalid) goto CreateNewDecl;
13862     assert(SS.isEmpty());
13863 
13864     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
13865       // C++ [basic.scope.pdecl]p5:
13866       //   -- for an elaborated-type-specifier of the form
13867       //
13868       //          class-key identifier
13869       //
13870       //      if the elaborated-type-specifier is used in the
13871       //      decl-specifier-seq or parameter-declaration-clause of a
13872       //      function defined in namespace scope, the identifier is
13873       //      declared as a class-name in the namespace that contains
13874       //      the declaration; otherwise, except as a friend
13875       //      declaration, the identifier is declared in the smallest
13876       //      non-class, non-function-prototype scope that contains the
13877       //      declaration.
13878       //
13879       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
13880       // C structs and unions.
13881       //
13882       // It is an error in C++ to declare (rather than define) an enum
13883       // type, including via an elaborated type specifier.  We'll
13884       // diagnose that later; for now, declare the enum in the same
13885       // scope as we would have picked for any other tag type.
13886       //
13887       // GNU C also supports this behavior as part of its incomplete
13888       // enum types extension, while GNU C++ does not.
13889       //
13890       // Find the context where we'll be declaring the tag.
13891       // FIXME: We would like to maintain the current DeclContext as the
13892       // lexical context,
13893       SearchDC = getTagInjectionContext(SearchDC);
13894 
13895       // Find the scope where we'll be declaring the tag.
13896       S = getTagInjectionScope(S, getLangOpts());
13897     } else {
13898       assert(TUK == TUK_Friend);
13899       // C++ [namespace.memdef]p3:
13900       //   If a friend declaration in a non-local class first declares a
13901       //   class or function, the friend class or function is a member of
13902       //   the innermost enclosing namespace.
13903       SearchDC = SearchDC->getEnclosingNamespaceContext();
13904     }
13905 
13906     // In C++, we need to do a redeclaration lookup to properly
13907     // diagnose some problems.
13908     // FIXME: redeclaration lookup is also used (with and without C++) to find a
13909     // hidden declaration so that we don't get ambiguity errors when using a
13910     // type declared by an elaborated-type-specifier.  In C that is not correct
13911     // and we should instead merge compatible types found by lookup.
13912     if (getLangOpts().CPlusPlus) {
13913       Previous.setRedeclarationKind(forRedeclarationInCurContext());
13914       LookupQualifiedName(Previous, SearchDC);
13915     } else {
13916       Previous.setRedeclarationKind(forRedeclarationInCurContext());
13917       LookupName(Previous, S);
13918     }
13919   }
13920 
13921   // If we have a known previous declaration to use, then use it.
13922   if (Previous.empty() && SkipBody && SkipBody->Previous)
13923     Previous.addDecl(SkipBody->Previous);
13924 
13925   if (!Previous.empty()) {
13926     NamedDecl *PrevDecl = Previous.getFoundDecl();
13927     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13928 
13929     // It's okay to have a tag decl in the same scope as a typedef
13930     // which hides a tag decl in the same scope.  Finding this
13931     // insanity with a redeclaration lookup can only actually happen
13932     // in C++.
13933     //
13934     // This is also okay for elaborated-type-specifiers, which is
13935     // technically forbidden by the current standard but which is
13936     // okay according to the likely resolution of an open issue;
13937     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13938     if (getLangOpts().CPlusPlus) {
13939       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13940         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13941           TagDecl *Tag = TT->getDecl();
13942           if (Tag->getDeclName() == Name &&
13943               Tag->getDeclContext()->getRedeclContext()
13944                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
13945             PrevDecl = Tag;
13946             Previous.clear();
13947             Previous.addDecl(Tag);
13948             Previous.resolveKind();
13949           }
13950         }
13951       }
13952     }
13953 
13954     // If this is a redeclaration of a using shadow declaration, it must
13955     // declare a tag in the same context. In MSVC mode, we allow a
13956     // redefinition if either context is within the other.
13957     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13958       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13959       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13960           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
13961           !(OldTag && isAcceptableTagRedeclContext(
13962                           *this, OldTag->getDeclContext(), SearchDC))) {
13963         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13964         Diag(Shadow->getTargetDecl()->getLocation(),
13965              diag::note_using_decl_target);
13966         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13967             << 0;
13968         // Recover by ignoring the old declaration.
13969         Previous.clear();
13970         goto CreateNewDecl;
13971       }
13972     }
13973 
13974     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13975       // If this is a use of a previous tag, or if the tag is already declared
13976       // in the same scope (so that the definition/declaration completes or
13977       // rementions the tag), reuse the decl.
13978       if (TUK == TUK_Reference || TUK == TUK_Friend ||
13979           isDeclInScope(DirectPrevDecl, SearchDC, S,
13980                         SS.isNotEmpty() || isMemberSpecialization)) {
13981         // Make sure that this wasn't declared as an enum and now used as a
13982         // struct or something similar.
13983         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13984                                           TUK == TUK_Definition, KWLoc,
13985                                           Name)) {
13986           bool SafeToContinue
13987             = (PrevTagDecl->getTagKind() != TTK_Enum &&
13988                Kind != TTK_Enum);
13989           if (SafeToContinue)
13990             Diag(KWLoc, diag::err_use_with_wrong_tag)
13991               << Name
13992               << FixItHint::CreateReplacement(SourceRange(KWLoc),
13993                                               PrevTagDecl->getKindName());
13994           else
13995             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13996           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13997 
13998           if (SafeToContinue)
13999             Kind = PrevTagDecl->getTagKind();
14000           else {
14001             // Recover by making this an anonymous redefinition.
14002             Name = nullptr;
14003             Previous.clear();
14004             Invalid = true;
14005           }
14006         }
14007 
14008         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
14009           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
14010 
14011           // If this is an elaborated-type-specifier for a scoped enumeration,
14012           // the 'class' keyword is not necessary and not permitted.
14013           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14014             if (ScopedEnum)
14015               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
14016                 << PrevEnum->isScoped()
14017                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
14018             return PrevTagDecl;
14019           }
14020 
14021           QualType EnumUnderlyingTy;
14022           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14023             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
14024           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
14025             EnumUnderlyingTy = QualType(T, 0);
14026 
14027           // All conflicts with previous declarations are recovered by
14028           // returning the previous declaration, unless this is a definition,
14029           // in which case we want the caller to bail out.
14030           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
14031                                      ScopedEnum, EnumUnderlyingTy,
14032                                      IsFixed, PrevEnum))
14033             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
14034         }
14035 
14036         // C++11 [class.mem]p1:
14037         //   A member shall not be declared twice in the member-specification,
14038         //   except that a nested class or member class template can be declared
14039         //   and then later defined.
14040         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
14041             S->isDeclScope(PrevDecl)) {
14042           Diag(NameLoc, diag::ext_member_redeclared);
14043           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
14044         }
14045 
14046         if (!Invalid) {
14047           // If this is a use, just return the declaration we found, unless
14048           // we have attributes.
14049           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14050             if (Attr) {
14051               // FIXME: Diagnose these attributes. For now, we create a new
14052               // declaration to hold them.
14053             } else if (TUK == TUK_Reference &&
14054                        (PrevTagDecl->getFriendObjectKind() ==
14055                             Decl::FOK_Undeclared ||
14056                         PrevDecl->getOwningModule() != getCurrentModule()) &&
14057                        SS.isEmpty()) {
14058               // This declaration is a reference to an existing entity, but
14059               // has different visibility from that entity: it either makes
14060               // a friend visible or it makes a type visible in a new module.
14061               // In either case, create a new declaration. We only do this if
14062               // the declaration would have meant the same thing if no prior
14063               // declaration were found, that is, if it was found in the same
14064               // scope where we would have injected a declaration.
14065               if (!getTagInjectionContext(CurContext)->getRedeclContext()
14066                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
14067                 return PrevTagDecl;
14068               // This is in the injected scope, create a new declaration in
14069               // that scope.
14070               S = getTagInjectionScope(S, getLangOpts());
14071             } else {
14072               return PrevTagDecl;
14073             }
14074           }
14075 
14076           // Diagnose attempts to redefine a tag.
14077           if (TUK == TUK_Definition) {
14078             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
14079               // If we're defining a specialization and the previous definition
14080               // is from an implicit instantiation, don't emit an error
14081               // here; we'll catch this in the general case below.
14082               bool IsExplicitSpecializationAfterInstantiation = false;
14083               if (isMemberSpecialization) {
14084                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
14085                   IsExplicitSpecializationAfterInstantiation =
14086                     RD->getTemplateSpecializationKind() !=
14087                     TSK_ExplicitSpecialization;
14088                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
14089                   IsExplicitSpecializationAfterInstantiation =
14090                     ED->getTemplateSpecializationKind() !=
14091                     TSK_ExplicitSpecialization;
14092               }
14093 
14094               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
14095               // not keep more that one definition around (merge them). However,
14096               // ensure the decl passes the structural compatibility check in
14097               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
14098               NamedDecl *Hidden = nullptr;
14099               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
14100                 // There is a definition of this tag, but it is not visible. We
14101                 // explicitly make use of C++'s one definition rule here, and
14102                 // assume that this definition is identical to the hidden one
14103                 // we already have. Make the existing definition visible and
14104                 // use it in place of this one.
14105                 if (!getLangOpts().CPlusPlus) {
14106                   // Postpone making the old definition visible until after we
14107                   // complete parsing the new one and do the structural
14108                   // comparison.
14109                   SkipBody->CheckSameAsPrevious = true;
14110                   SkipBody->New = createTagFromNewDecl();
14111                   SkipBody->Previous = Hidden;
14112                 } else {
14113                   SkipBody->ShouldSkip = true;
14114                   makeMergedDefinitionVisible(Hidden);
14115                 }
14116                 return Def;
14117               } else if (!IsExplicitSpecializationAfterInstantiation) {
14118                 // A redeclaration in function prototype scope in C isn't
14119                 // visible elsewhere, so merely issue a warning.
14120                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
14121                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
14122                 else
14123                   Diag(NameLoc, diag::err_redefinition) << Name;
14124                 notePreviousDefinition(Def,
14125                                        NameLoc.isValid() ? NameLoc : KWLoc);
14126                 // If this is a redefinition, recover by making this
14127                 // struct be anonymous, which will make any later
14128                 // references get the previous definition.
14129                 Name = nullptr;
14130                 Previous.clear();
14131                 Invalid = true;
14132               }
14133             } else {
14134               // If the type is currently being defined, complain
14135               // about a nested redefinition.
14136               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
14137               if (TD->isBeingDefined()) {
14138                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
14139                 Diag(PrevTagDecl->getLocation(),
14140                      diag::note_previous_definition);
14141                 Name = nullptr;
14142                 Previous.clear();
14143                 Invalid = true;
14144               }
14145             }
14146 
14147             // Okay, this is definition of a previously declared or referenced
14148             // tag. We're going to create a new Decl for it.
14149           }
14150 
14151           // Okay, we're going to make a redeclaration.  If this is some kind
14152           // of reference, make sure we build the redeclaration in the same DC
14153           // as the original, and ignore the current access specifier.
14154           if (TUK == TUK_Friend || TUK == TUK_Reference) {
14155             SearchDC = PrevTagDecl->getDeclContext();
14156             AS = AS_none;
14157           }
14158         }
14159         // If we get here we have (another) forward declaration or we
14160         // have a definition.  Just create a new decl.
14161 
14162       } else {
14163         // If we get here, this is a definition of a new tag type in a nested
14164         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
14165         // new decl/type.  We set PrevDecl to NULL so that the entities
14166         // have distinct types.
14167         Previous.clear();
14168       }
14169       // If we get here, we're going to create a new Decl. If PrevDecl
14170       // is non-NULL, it's a definition of the tag declared by
14171       // PrevDecl. If it's NULL, we have a new definition.
14172 
14173     // Otherwise, PrevDecl is not a tag, but was found with tag
14174     // lookup.  This is only actually possible in C++, where a few
14175     // things like templates still live in the tag namespace.
14176     } else {
14177       // Use a better diagnostic if an elaborated-type-specifier
14178       // found the wrong kind of type on the first
14179       // (non-redeclaration) lookup.
14180       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
14181           !Previous.isForRedeclaration()) {
14182         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14183         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
14184                                                        << Kind;
14185         Diag(PrevDecl->getLocation(), diag::note_declared_at);
14186         Invalid = true;
14187 
14188       // Otherwise, only diagnose if the declaration is in scope.
14189       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
14190                                 SS.isNotEmpty() || isMemberSpecialization)) {
14191         // do nothing
14192 
14193       // Diagnose implicit declarations introduced by elaborated types.
14194       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
14195         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14196         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
14197         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14198         Invalid = true;
14199 
14200       // Otherwise it's a declaration.  Call out a particularly common
14201       // case here.
14202       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14203         unsigned Kind = 0;
14204         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
14205         Diag(NameLoc, diag::err_tag_definition_of_typedef)
14206           << Name << Kind << TND->getUnderlyingType();
14207         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14208         Invalid = true;
14209 
14210       // Otherwise, diagnose.
14211       } else {
14212         // The tag name clashes with something else in the target scope,
14213         // issue an error and recover by making this tag be anonymous.
14214         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
14215         notePreviousDefinition(PrevDecl, NameLoc);
14216         Name = nullptr;
14217         Invalid = true;
14218       }
14219 
14220       // The existing declaration isn't relevant to us; we're in a
14221       // new scope, so clear out the previous declaration.
14222       Previous.clear();
14223     }
14224   }
14225 
14226 CreateNewDecl:
14227 
14228   TagDecl *PrevDecl = nullptr;
14229   if (Previous.isSingleResult())
14230     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
14231 
14232   // If there is an identifier, use the location of the identifier as the
14233   // location of the decl, otherwise use the location of the struct/union
14234   // keyword.
14235   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14236 
14237   // Otherwise, create a new declaration. If there is a previous
14238   // declaration of the same entity, the two will be linked via
14239   // PrevDecl.
14240   TagDecl *New;
14241 
14242   if (Kind == TTK_Enum) {
14243     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14244     // enum X { A, B, C } D;    D should chain to X.
14245     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
14246                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
14247                            ScopedEnumUsesClassTag, IsFixed);
14248 
14249     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
14250       StdAlignValT = cast<EnumDecl>(New);
14251 
14252     // If this is an undefined enum, warn.
14253     if (TUK != TUK_Definition && !Invalid) {
14254       TagDecl *Def;
14255       if (IsFixed && (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
14256           cast<EnumDecl>(New)->isFixed()) {
14257         // C++0x: 7.2p2: opaque-enum-declaration.
14258         // Conflicts are diagnosed above. Do nothing.
14259       }
14260       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
14261         Diag(Loc, diag::ext_forward_ref_enum_def)
14262           << New;
14263         Diag(Def->getLocation(), diag::note_previous_definition);
14264       } else {
14265         unsigned DiagID = diag::ext_forward_ref_enum;
14266         if (getLangOpts().MSVCCompat)
14267           DiagID = diag::ext_ms_forward_ref_enum;
14268         else if (getLangOpts().CPlusPlus)
14269           DiagID = diag::err_forward_ref_enum;
14270         Diag(Loc, DiagID);
14271       }
14272     }
14273 
14274     if (EnumUnderlying) {
14275       EnumDecl *ED = cast<EnumDecl>(New);
14276       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14277         ED->setIntegerTypeSourceInfo(TI);
14278       else
14279         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
14280       ED->setPromotionType(ED->getIntegerType());
14281       assert(ED->isComplete() && "enum with type should be complete");
14282     }
14283   } else {
14284     // struct/union/class
14285 
14286     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14287     // struct X { int A; } D;    D should chain to X.
14288     if (getLangOpts().CPlusPlus) {
14289       // FIXME: Look for a way to use RecordDecl for simple structs.
14290       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14291                                   cast_or_null<CXXRecordDecl>(PrevDecl));
14292 
14293       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
14294         StdBadAlloc = cast<CXXRecordDecl>(New);
14295     } else
14296       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14297                                cast_or_null<RecordDecl>(PrevDecl));
14298   }
14299 
14300   // C++11 [dcl.type]p3:
14301   //   A type-specifier-seq shall not define a class or enumeration [...].
14302   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
14303       TUK == TUK_Definition) {
14304     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
14305       << Context.getTagDeclType(New);
14306     Invalid = true;
14307   }
14308 
14309   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
14310       DC->getDeclKind() == Decl::Enum) {
14311     Diag(New->getLocation(), diag::err_type_defined_in_enum)
14312       << Context.getTagDeclType(New);
14313     Invalid = true;
14314   }
14315 
14316   // Maybe add qualifier info.
14317   if (SS.isNotEmpty()) {
14318     if (SS.isSet()) {
14319       // If this is either a declaration or a definition, check the
14320       // nested-name-specifier against the current context.
14321       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
14322           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
14323                                        isMemberSpecialization))
14324         Invalid = true;
14325 
14326       New->setQualifierInfo(SS.getWithLocInContext(Context));
14327       if (TemplateParameterLists.size() > 0) {
14328         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
14329       }
14330     }
14331     else
14332       Invalid = true;
14333   }
14334 
14335   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14336     // Add alignment attributes if necessary; these attributes are checked when
14337     // the ASTContext lays out the structure.
14338     //
14339     // It is important for implementing the correct semantics that this
14340     // happen here (in ActOnTag). The #pragma pack stack is
14341     // maintained as a result of parser callbacks which can occur at
14342     // many points during the parsing of a struct declaration (because
14343     // the #pragma tokens are effectively skipped over during the
14344     // parsing of the struct).
14345     if (TUK == TUK_Definition) {
14346       AddAlignmentAttributesForRecord(RD);
14347       AddMsStructLayoutForRecord(RD);
14348     }
14349   }
14350 
14351   if (ModulePrivateLoc.isValid()) {
14352     if (isMemberSpecialization)
14353       Diag(New->getLocation(), diag::err_module_private_specialization)
14354         << 2
14355         << FixItHint::CreateRemoval(ModulePrivateLoc);
14356     // __module_private__ does not apply to local classes. However, we only
14357     // diagnose this as an error when the declaration specifiers are
14358     // freestanding. Here, we just ignore the __module_private__.
14359     else if (!SearchDC->isFunctionOrMethod())
14360       New->setModulePrivate();
14361   }
14362 
14363   // If this is a specialization of a member class (of a class template),
14364   // check the specialization.
14365   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
14366     Invalid = true;
14367 
14368   // If we're declaring or defining a tag in function prototype scope in C,
14369   // note that this type can only be used within the function and add it to
14370   // the list of decls to inject into the function definition scope.
14371   if ((Name || Kind == TTK_Enum) &&
14372       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
14373     if (getLangOpts().CPlusPlus) {
14374       // C++ [dcl.fct]p6:
14375       //   Types shall not be defined in return or parameter types.
14376       if (TUK == TUK_Definition && !IsTypeSpecifier) {
14377         Diag(Loc, diag::err_type_defined_in_param_type)
14378             << Name;
14379         Invalid = true;
14380       }
14381     } else if (!PrevDecl) {
14382       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
14383     }
14384   }
14385 
14386   if (Invalid)
14387     New->setInvalidDecl();
14388 
14389   // Set the lexical context. If the tag has a C++ scope specifier, the
14390   // lexical context will be different from the semantic context.
14391   New->setLexicalDeclContext(CurContext);
14392 
14393   // Mark this as a friend decl if applicable.
14394   // In Microsoft mode, a friend declaration also acts as a forward
14395   // declaration so we always pass true to setObjectOfFriendDecl to make
14396   // the tag name visible.
14397   if (TUK == TUK_Friend)
14398     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
14399 
14400   // Set the access specifier.
14401   if (!Invalid && SearchDC->isRecord())
14402     SetMemberAccessSpecifier(New, PrevDecl, AS);
14403 
14404   if (PrevDecl)
14405     CheckRedeclarationModuleOwnership(New, PrevDecl);
14406 
14407   if (TUK == TUK_Definition)
14408     New->startDefinition();
14409 
14410   if (Attr)
14411     ProcessDeclAttributeList(S, New, Attr);
14412   AddPragmaAttributes(S, New);
14413 
14414   // If this has an identifier, add it to the scope stack.
14415   if (TUK == TUK_Friend) {
14416     // We might be replacing an existing declaration in the lookup tables;
14417     // if so, borrow its access specifier.
14418     if (PrevDecl)
14419       New->setAccess(PrevDecl->getAccess());
14420 
14421     DeclContext *DC = New->getDeclContext()->getRedeclContext();
14422     DC->makeDeclVisibleInContext(New);
14423     if (Name) // can be null along some error paths
14424       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14425         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
14426   } else if (Name) {
14427     S = getNonFieldDeclScope(S);
14428     PushOnScopeChains(New, S, true);
14429   } else {
14430     CurContext->addDecl(New);
14431   }
14432 
14433   // If this is the C FILE type, notify the AST context.
14434   if (IdentifierInfo *II = New->getIdentifier())
14435     if (!New->isInvalidDecl() &&
14436         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
14437         II->isStr("FILE"))
14438       Context.setFILEDecl(New);
14439 
14440   if (PrevDecl)
14441     mergeDeclAttributes(New, PrevDecl);
14442 
14443   // If there's a #pragma GCC visibility in scope, set the visibility of this
14444   // record.
14445   AddPushedVisibilityAttribute(New);
14446 
14447   if (isMemberSpecialization && !New->isInvalidDecl())
14448     CompleteMemberSpecialization(New, Previous);
14449 
14450   OwnedDecl = true;
14451   // In C++, don't return an invalid declaration. We can't recover well from
14452   // the cases where we make the type anonymous.
14453   if (Invalid && getLangOpts().CPlusPlus) {
14454     if (New->isBeingDefined())
14455       if (auto RD = dyn_cast<RecordDecl>(New))
14456         RD->completeDefinition();
14457     return nullptr;
14458   } else {
14459     return New;
14460   }
14461 }
14462 
14463 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
14464   AdjustDeclIfTemplate(TagD);
14465   TagDecl *Tag = cast<TagDecl>(TagD);
14466 
14467   // Enter the tag context.
14468   PushDeclContext(S, Tag);
14469 
14470   ActOnDocumentableDecl(TagD);
14471 
14472   // If there's a #pragma GCC visibility in scope, set the visibility of this
14473   // record.
14474   AddPushedVisibilityAttribute(Tag);
14475 }
14476 
14477 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
14478                                     SkipBodyInfo &SkipBody) {
14479   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
14480     return false;
14481 
14482   // Make the previous decl visible.
14483   makeMergedDefinitionVisible(SkipBody.Previous);
14484   return true;
14485 }
14486 
14487 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
14488   assert(isa<ObjCContainerDecl>(IDecl) &&
14489          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
14490   DeclContext *OCD = cast<DeclContext>(IDecl);
14491   assert(getContainingDC(OCD) == CurContext &&
14492       "The next DeclContext should be lexically contained in the current one.");
14493   CurContext = OCD;
14494   return IDecl;
14495 }
14496 
14497 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
14498                                            SourceLocation FinalLoc,
14499                                            bool IsFinalSpelledSealed,
14500                                            SourceLocation LBraceLoc) {
14501   AdjustDeclIfTemplate(TagD);
14502   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
14503 
14504   FieldCollector->StartClass();
14505 
14506   if (!Record->getIdentifier())
14507     return;
14508 
14509   if (FinalLoc.isValid())
14510     Record->addAttr(new (Context)
14511                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
14512 
14513   // C++ [class]p2:
14514   //   [...] The class-name is also inserted into the scope of the
14515   //   class itself; this is known as the injected-class-name. For
14516   //   purposes of access checking, the injected-class-name is treated
14517   //   as if it were a public member name.
14518   CXXRecordDecl *InjectedClassName
14519     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
14520                             Record->getLocStart(), Record->getLocation(),
14521                             Record->getIdentifier(),
14522                             /*PrevDecl=*/nullptr,
14523                             /*DelayTypeCreation=*/true);
14524   Context.getTypeDeclType(InjectedClassName, Record);
14525   InjectedClassName->setImplicit();
14526   InjectedClassName->setAccess(AS_public);
14527   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
14528       InjectedClassName->setDescribedClassTemplate(Template);
14529   PushOnScopeChains(InjectedClassName, S);
14530   assert(InjectedClassName->isInjectedClassName() &&
14531          "Broken injected-class-name");
14532 }
14533 
14534 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
14535                                     SourceRange BraceRange) {
14536   AdjustDeclIfTemplate(TagD);
14537   TagDecl *Tag = cast<TagDecl>(TagD);
14538   Tag->setBraceRange(BraceRange);
14539 
14540   // Make sure we "complete" the definition even it is invalid.
14541   if (Tag->isBeingDefined()) {
14542     assert(Tag->isInvalidDecl() && "We should already have completed it");
14543     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14544       RD->completeDefinition();
14545   }
14546 
14547   if (isa<CXXRecordDecl>(Tag)) {
14548     FieldCollector->FinishClass();
14549   }
14550 
14551   // Exit this scope of this tag's definition.
14552   PopDeclContext();
14553 
14554   if (getCurLexicalContext()->isObjCContainer() &&
14555       Tag->getDeclContext()->isFileContext())
14556     Tag->setTopLevelDeclInObjCContainer();
14557 
14558   // Notify the consumer that we've defined a tag.
14559   if (!Tag->isInvalidDecl())
14560     Consumer.HandleTagDeclDefinition(Tag);
14561 }
14562 
14563 void Sema::ActOnObjCContainerFinishDefinition() {
14564   // Exit this scope of this interface definition.
14565   PopDeclContext();
14566 }
14567 
14568 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
14569   assert(DC == CurContext && "Mismatch of container contexts");
14570   OriginalLexicalContext = DC;
14571   ActOnObjCContainerFinishDefinition();
14572 }
14573 
14574 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
14575   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
14576   OriginalLexicalContext = nullptr;
14577 }
14578 
14579 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
14580   AdjustDeclIfTemplate(TagD);
14581   TagDecl *Tag = cast<TagDecl>(TagD);
14582   Tag->setInvalidDecl();
14583 
14584   // Make sure we "complete" the definition even it is invalid.
14585   if (Tag->isBeingDefined()) {
14586     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14587       RD->completeDefinition();
14588   }
14589 
14590   // We're undoing ActOnTagStartDefinition here, not
14591   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
14592   // the FieldCollector.
14593 
14594   PopDeclContext();
14595 }
14596 
14597 // Note that FieldName may be null for anonymous bitfields.
14598 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
14599                                 IdentifierInfo *FieldName,
14600                                 QualType FieldTy, bool IsMsStruct,
14601                                 Expr *BitWidth, bool *ZeroWidth) {
14602   // Default to true; that shouldn't confuse checks for emptiness
14603   if (ZeroWidth)
14604     *ZeroWidth = true;
14605 
14606   // C99 6.7.2.1p4 - verify the field type.
14607   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
14608   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
14609     // Handle incomplete types with specific error.
14610     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
14611       return ExprError();
14612     if (FieldName)
14613       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
14614         << FieldName << FieldTy << BitWidth->getSourceRange();
14615     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
14616       << FieldTy << BitWidth->getSourceRange();
14617   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
14618                                              UPPC_BitFieldWidth))
14619     return ExprError();
14620 
14621   // If the bit-width is type- or value-dependent, don't try to check
14622   // it now.
14623   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
14624     return BitWidth;
14625 
14626   llvm::APSInt Value;
14627   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
14628   if (ICE.isInvalid())
14629     return ICE;
14630   BitWidth = ICE.get();
14631 
14632   if (Value != 0 && ZeroWidth)
14633     *ZeroWidth = false;
14634 
14635   // Zero-width bitfield is ok for anonymous field.
14636   if (Value == 0 && FieldName)
14637     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
14638 
14639   if (Value.isSigned() && Value.isNegative()) {
14640     if (FieldName)
14641       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
14642                << FieldName << Value.toString(10);
14643     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
14644       << Value.toString(10);
14645   }
14646 
14647   if (!FieldTy->isDependentType()) {
14648     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
14649     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
14650     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
14651 
14652     // Over-wide bitfields are an error in C or when using the MSVC bitfield
14653     // ABI.
14654     bool CStdConstraintViolation =
14655         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
14656     bool MSBitfieldViolation =
14657         Value.ugt(TypeStorageSize) &&
14658         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
14659     if (CStdConstraintViolation || MSBitfieldViolation) {
14660       unsigned DiagWidth =
14661           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
14662       if (FieldName)
14663         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
14664                << FieldName << (unsigned)Value.getZExtValue()
14665                << !CStdConstraintViolation << DiagWidth;
14666 
14667       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
14668              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
14669              << DiagWidth;
14670     }
14671 
14672     // Warn on types where the user might conceivably expect to get all
14673     // specified bits as value bits: that's all integral types other than
14674     // 'bool'.
14675     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
14676       if (FieldName)
14677         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
14678             << FieldName << (unsigned)Value.getZExtValue()
14679             << (unsigned)TypeWidth;
14680       else
14681         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
14682             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
14683     }
14684   }
14685 
14686   return BitWidth;
14687 }
14688 
14689 /// ActOnField - Each field of a C struct/union is passed into this in order
14690 /// to create a FieldDecl object for it.
14691 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
14692                        Declarator &D, Expr *BitfieldWidth) {
14693   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
14694                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
14695                                /*InitStyle=*/ICIS_NoInit, AS_public);
14696   return Res;
14697 }
14698 
14699 /// HandleField - Analyze a field of a C struct or a C++ data member.
14700 ///
14701 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
14702                              SourceLocation DeclStart,
14703                              Declarator &D, Expr *BitWidth,
14704                              InClassInitStyle InitStyle,
14705                              AccessSpecifier AS) {
14706   if (D.isDecompositionDeclarator()) {
14707     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
14708     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
14709       << Decomp.getSourceRange();
14710     return nullptr;
14711   }
14712 
14713   IdentifierInfo *II = D.getIdentifier();
14714   SourceLocation Loc = DeclStart;
14715   if (II) Loc = D.getIdentifierLoc();
14716 
14717   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14718   QualType T = TInfo->getType();
14719   if (getLangOpts().CPlusPlus) {
14720     CheckExtraCXXDefaultArguments(D);
14721 
14722     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14723                                         UPPC_DataMemberType)) {
14724       D.setInvalidType();
14725       T = Context.IntTy;
14726       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14727     }
14728   }
14729 
14730   // TR 18037 does not allow fields to be declared with address spaces.
14731   if (T.getQualifiers().hasAddressSpace() ||
14732       T->isDependentAddressSpaceType() ||
14733       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
14734     Diag(Loc, diag::err_field_with_address_space);
14735     D.setInvalidType();
14736   }
14737 
14738   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
14739   // used as structure or union field: image, sampler, event or block types.
14740   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
14741                           T->isSamplerT() || T->isBlockPointerType())) {
14742     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
14743     D.setInvalidType();
14744   }
14745 
14746   DiagnoseFunctionSpecifiers(D.getDeclSpec());
14747 
14748   if (D.getDeclSpec().isInlineSpecified())
14749     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14750         << getLangOpts().CPlusPlus17;
14751   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14752     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14753          diag::err_invalid_thread)
14754       << DeclSpec::getSpecifierName(TSCS);
14755 
14756   // Check to see if this name was declared as a member previously
14757   NamedDecl *PrevDecl = nullptr;
14758   LookupResult Previous(*this, II, Loc, LookupMemberName,
14759                         ForVisibleRedeclaration);
14760   LookupName(Previous, S);
14761   switch (Previous.getResultKind()) {
14762     case LookupResult::Found:
14763     case LookupResult::FoundUnresolvedValue:
14764       PrevDecl = Previous.getAsSingle<NamedDecl>();
14765       break;
14766 
14767     case LookupResult::FoundOverloaded:
14768       PrevDecl = Previous.getRepresentativeDecl();
14769       break;
14770 
14771     case LookupResult::NotFound:
14772     case LookupResult::NotFoundInCurrentInstantiation:
14773     case LookupResult::Ambiguous:
14774       break;
14775   }
14776   Previous.suppressDiagnostics();
14777 
14778   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14779     // Maybe we will complain about the shadowed template parameter.
14780     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14781     // Just pretend that we didn't see the previous declaration.
14782     PrevDecl = nullptr;
14783   }
14784 
14785   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14786     PrevDecl = nullptr;
14787 
14788   bool Mutable
14789     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
14790   SourceLocation TSSL = D.getLocStart();
14791   FieldDecl *NewFD
14792     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
14793                      TSSL, AS, PrevDecl, &D);
14794 
14795   if (NewFD->isInvalidDecl())
14796     Record->setInvalidDecl();
14797 
14798   if (D.getDeclSpec().isModulePrivateSpecified())
14799     NewFD->setModulePrivate();
14800 
14801   if (NewFD->isInvalidDecl() && PrevDecl) {
14802     // Don't introduce NewFD into scope; there's already something
14803     // with the same name in the same scope.
14804   } else if (II) {
14805     PushOnScopeChains(NewFD, S);
14806   } else
14807     Record->addDecl(NewFD);
14808 
14809   return NewFD;
14810 }
14811 
14812 /// Build a new FieldDecl and check its well-formedness.
14813 ///
14814 /// This routine builds a new FieldDecl given the fields name, type,
14815 /// record, etc. \p PrevDecl should refer to any previous declaration
14816 /// with the same name and in the same scope as the field to be
14817 /// created.
14818 ///
14819 /// \returns a new FieldDecl.
14820 ///
14821 /// \todo The Declarator argument is a hack. It will be removed once
14822 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
14823                                 TypeSourceInfo *TInfo,
14824                                 RecordDecl *Record, SourceLocation Loc,
14825                                 bool Mutable, Expr *BitWidth,
14826                                 InClassInitStyle InitStyle,
14827                                 SourceLocation TSSL,
14828                                 AccessSpecifier AS, NamedDecl *PrevDecl,
14829                                 Declarator *D) {
14830   IdentifierInfo *II = Name.getAsIdentifierInfo();
14831   bool InvalidDecl = false;
14832   if (D) InvalidDecl = D->isInvalidType();
14833 
14834   // If we receive a broken type, recover by assuming 'int' and
14835   // marking this declaration as invalid.
14836   if (T.isNull()) {
14837     InvalidDecl = true;
14838     T = Context.IntTy;
14839   }
14840 
14841   QualType EltTy = Context.getBaseElementType(T);
14842   if (!EltTy->isDependentType()) {
14843     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
14844       // Fields of incomplete type force their record to be invalid.
14845       Record->setInvalidDecl();
14846       InvalidDecl = true;
14847     } else {
14848       NamedDecl *Def;
14849       EltTy->isIncompleteType(&Def);
14850       if (Def && Def->isInvalidDecl()) {
14851         Record->setInvalidDecl();
14852         InvalidDecl = true;
14853       }
14854     }
14855   }
14856 
14857   // OpenCL v1.2 s6.9.c: bitfields are not supported.
14858   if (BitWidth && getLangOpts().OpenCL) {
14859     Diag(Loc, diag::err_opencl_bitfields);
14860     InvalidDecl = true;
14861   }
14862 
14863   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
14864   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
14865       T.hasQualifiers()) {
14866     InvalidDecl = true;
14867     Diag(Loc, diag::err_anon_bitfield_qualifiers);
14868   }
14869 
14870   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14871   // than a variably modified type.
14872   if (!InvalidDecl && T->isVariablyModifiedType()) {
14873     bool SizeIsNegative;
14874     llvm::APSInt Oversized;
14875 
14876     TypeSourceInfo *FixedTInfo =
14877       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
14878                                                     SizeIsNegative,
14879                                                     Oversized);
14880     if (FixedTInfo) {
14881       Diag(Loc, diag::warn_illegal_constant_array_size);
14882       TInfo = FixedTInfo;
14883       T = FixedTInfo->getType();
14884     } else {
14885       if (SizeIsNegative)
14886         Diag(Loc, diag::err_typecheck_negative_array_size);
14887       else if (Oversized.getBoolValue())
14888         Diag(Loc, diag::err_array_too_large)
14889           << Oversized.toString(10);
14890       else
14891         Diag(Loc, diag::err_typecheck_field_variable_size);
14892       InvalidDecl = true;
14893     }
14894   }
14895 
14896   // Fields can not have abstract class types
14897   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
14898                                              diag::err_abstract_type_in_decl,
14899                                              AbstractFieldType))
14900     InvalidDecl = true;
14901 
14902   bool ZeroWidth = false;
14903   if (InvalidDecl)
14904     BitWidth = nullptr;
14905   // If this is declared as a bit-field, check the bit-field.
14906   if (BitWidth) {
14907     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
14908                               &ZeroWidth).get();
14909     if (!BitWidth) {
14910       InvalidDecl = true;
14911       BitWidth = nullptr;
14912       ZeroWidth = false;
14913     }
14914   }
14915 
14916   // Check that 'mutable' is consistent with the type of the declaration.
14917   if (!InvalidDecl && Mutable) {
14918     unsigned DiagID = 0;
14919     if (T->isReferenceType())
14920       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
14921                                         : diag::err_mutable_reference;
14922     else if (T.isConstQualified())
14923       DiagID = diag::err_mutable_const;
14924 
14925     if (DiagID) {
14926       SourceLocation ErrLoc = Loc;
14927       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
14928         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
14929       Diag(ErrLoc, DiagID);
14930       if (DiagID != diag::ext_mutable_reference) {
14931         Mutable = false;
14932         InvalidDecl = true;
14933       }
14934     }
14935   }
14936 
14937   // C++11 [class.union]p8 (DR1460):
14938   //   At most one variant member of a union may have a
14939   //   brace-or-equal-initializer.
14940   if (InitStyle != ICIS_NoInit)
14941     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14942 
14943   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14944                                        BitWidth, Mutable, InitStyle);
14945   if (InvalidDecl)
14946     NewFD->setInvalidDecl();
14947 
14948   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14949     Diag(Loc, diag::err_duplicate_member) << II;
14950     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14951     NewFD->setInvalidDecl();
14952   }
14953 
14954   if (!InvalidDecl && getLangOpts().CPlusPlus) {
14955     if (Record->isUnion()) {
14956       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14957         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14958         if (RDecl->getDefinition()) {
14959           // C++ [class.union]p1: An object of a class with a non-trivial
14960           // constructor, a non-trivial copy constructor, a non-trivial
14961           // destructor, or a non-trivial copy assignment operator
14962           // cannot be a member of a union, nor can an array of such
14963           // objects.
14964           if (CheckNontrivialField(NewFD))
14965             NewFD->setInvalidDecl();
14966         }
14967       }
14968 
14969       // C++ [class.union]p1: If a union contains a member of reference type,
14970       // the program is ill-formed, except when compiling with MSVC extensions
14971       // enabled.
14972       if (EltTy->isReferenceType()) {
14973         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14974                                     diag::ext_union_member_of_reference_type :
14975                                     diag::err_union_member_of_reference_type)
14976           << NewFD->getDeclName() << EltTy;
14977         if (!getLangOpts().MicrosoftExt)
14978           NewFD->setInvalidDecl();
14979       }
14980     }
14981   }
14982 
14983   // FIXME: We need to pass in the attributes given an AST
14984   // representation, not a parser representation.
14985   if (D) {
14986     // FIXME: The current scope is almost... but not entirely... correct here.
14987     ProcessDeclAttributes(getCurScope(), NewFD, *D);
14988 
14989     if (NewFD->hasAttrs())
14990       CheckAlignasUnderalignment(NewFD);
14991   }
14992 
14993   // In auto-retain/release, infer strong retension for fields of
14994   // retainable type.
14995   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
14996     NewFD->setInvalidDecl();
14997 
14998   if (T.isObjCGCWeak())
14999     Diag(Loc, diag::warn_attribute_weak_on_field);
15000 
15001   NewFD->setAccess(AS);
15002   return NewFD;
15003 }
15004 
15005 bool Sema::CheckNontrivialField(FieldDecl *FD) {
15006   assert(FD);
15007   assert(getLangOpts().CPlusPlus && "valid check only for C++");
15008 
15009   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
15010     return false;
15011 
15012   QualType EltTy = Context.getBaseElementType(FD->getType());
15013   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15014     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
15015     if (RDecl->getDefinition()) {
15016       // We check for copy constructors before constructors
15017       // because otherwise we'll never get complaints about
15018       // copy constructors.
15019 
15020       CXXSpecialMember member = CXXInvalid;
15021       // We're required to check for any non-trivial constructors. Since the
15022       // implicit default constructor is suppressed if there are any
15023       // user-declared constructors, we just need to check that there is a
15024       // trivial default constructor and a trivial copy constructor. (We don't
15025       // worry about move constructors here, since this is a C++98 check.)
15026       if (RDecl->hasNonTrivialCopyConstructor())
15027         member = CXXCopyConstructor;
15028       else if (!RDecl->hasTrivialDefaultConstructor())
15029         member = CXXDefaultConstructor;
15030       else if (RDecl->hasNonTrivialCopyAssignment())
15031         member = CXXCopyAssignment;
15032       else if (RDecl->hasNonTrivialDestructor())
15033         member = CXXDestructor;
15034 
15035       if (member != CXXInvalid) {
15036         if (!getLangOpts().CPlusPlus11 &&
15037             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
15038           // Objective-C++ ARC: it is an error to have a non-trivial field of
15039           // a union. However, system headers in Objective-C programs
15040           // occasionally have Objective-C lifetime objects within unions,
15041           // and rather than cause the program to fail, we make those
15042           // members unavailable.
15043           SourceLocation Loc = FD->getLocation();
15044           if (getSourceManager().isInSystemHeader(Loc)) {
15045             if (!FD->hasAttr<UnavailableAttr>())
15046               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15047                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
15048             return false;
15049           }
15050         }
15051 
15052         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
15053                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
15054                diag::err_illegal_union_or_anon_struct_member)
15055           << FD->getParent()->isUnion() << FD->getDeclName() << member;
15056         DiagnoseNontrivial(RDecl, member);
15057         return !getLangOpts().CPlusPlus11;
15058       }
15059     }
15060   }
15061 
15062   return false;
15063 }
15064 
15065 /// TranslateIvarVisibility - Translate visibility from a token ID to an
15066 ///  AST enum value.
15067 static ObjCIvarDecl::AccessControl
15068 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
15069   switch (ivarVisibility) {
15070   default: llvm_unreachable("Unknown visitibility kind");
15071   case tok::objc_private: return ObjCIvarDecl::Private;
15072   case tok::objc_public: return ObjCIvarDecl::Public;
15073   case tok::objc_protected: return ObjCIvarDecl::Protected;
15074   case tok::objc_package: return ObjCIvarDecl::Package;
15075   }
15076 }
15077 
15078 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
15079 /// in order to create an IvarDecl object for it.
15080 Decl *Sema::ActOnIvar(Scope *S,
15081                                 SourceLocation DeclStart,
15082                                 Declarator &D, Expr *BitfieldWidth,
15083                                 tok::ObjCKeywordKind Visibility) {
15084 
15085   IdentifierInfo *II = D.getIdentifier();
15086   Expr *BitWidth = (Expr*)BitfieldWidth;
15087   SourceLocation Loc = DeclStart;
15088   if (II) Loc = D.getIdentifierLoc();
15089 
15090   // FIXME: Unnamed fields can be handled in various different ways, for
15091   // example, unnamed unions inject all members into the struct namespace!
15092 
15093   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15094   QualType T = TInfo->getType();
15095 
15096   if (BitWidth) {
15097     // 6.7.2.1p3, 6.7.2.1p4
15098     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
15099     if (!BitWidth)
15100       D.setInvalidType();
15101   } else {
15102     // Not a bitfield.
15103 
15104     // validate II.
15105 
15106   }
15107   if (T->isReferenceType()) {
15108     Diag(Loc, diag::err_ivar_reference_type);
15109     D.setInvalidType();
15110   }
15111   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15112   // than a variably modified type.
15113   else if (T->isVariablyModifiedType()) {
15114     Diag(Loc, diag::err_typecheck_ivar_variable_size);
15115     D.setInvalidType();
15116   }
15117 
15118   // Get the visibility (access control) for this ivar.
15119   ObjCIvarDecl::AccessControl ac =
15120     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
15121                                         : ObjCIvarDecl::None;
15122   // Must set ivar's DeclContext to its enclosing interface.
15123   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
15124   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
15125     return nullptr;
15126   ObjCContainerDecl *EnclosingContext;
15127   if (ObjCImplementationDecl *IMPDecl =
15128       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15129     if (LangOpts.ObjCRuntime.isFragile()) {
15130     // Case of ivar declared in an implementation. Context is that of its class.
15131       EnclosingContext = IMPDecl->getClassInterface();
15132       assert(EnclosingContext && "Implementation has no class interface!");
15133     }
15134     else
15135       EnclosingContext = EnclosingDecl;
15136   } else {
15137     if (ObjCCategoryDecl *CDecl =
15138         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15139       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
15140         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
15141         return nullptr;
15142       }
15143     }
15144     EnclosingContext = EnclosingDecl;
15145   }
15146 
15147   // Construct the decl.
15148   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
15149                                              DeclStart, Loc, II, T,
15150                                              TInfo, ac, (Expr *)BitfieldWidth);
15151 
15152   if (II) {
15153     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
15154                                            ForVisibleRedeclaration);
15155     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
15156         && !isa<TagDecl>(PrevDecl)) {
15157       Diag(Loc, diag::err_duplicate_member) << II;
15158       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15159       NewID->setInvalidDecl();
15160     }
15161   }
15162 
15163   // Process attributes attached to the ivar.
15164   ProcessDeclAttributes(S, NewID, D);
15165 
15166   if (D.isInvalidType())
15167     NewID->setInvalidDecl();
15168 
15169   // In ARC, infer 'retaining' for ivars of retainable type.
15170   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
15171     NewID->setInvalidDecl();
15172 
15173   if (D.getDeclSpec().isModulePrivateSpecified())
15174     NewID->setModulePrivate();
15175 
15176   if (II) {
15177     // FIXME: When interfaces are DeclContexts, we'll need to add
15178     // these to the interface.
15179     S->AddDecl(NewID);
15180     IdResolver.AddDecl(NewID);
15181   }
15182 
15183   if (LangOpts.ObjCRuntime.isNonFragile() &&
15184       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
15185     Diag(Loc, diag::warn_ivars_in_interface);
15186 
15187   return NewID;
15188 }
15189 
15190 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
15191 /// class and class extensions. For every class \@interface and class
15192 /// extension \@interface, if the last ivar is a bitfield of any type,
15193 /// then add an implicit `char :0` ivar to the end of that interface.
15194 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
15195                              SmallVectorImpl<Decl *> &AllIvarDecls) {
15196   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
15197     return;
15198 
15199   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
15200   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
15201 
15202   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
15203     return;
15204   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
15205   if (!ID) {
15206     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
15207       if (!CD->IsClassExtension())
15208         return;
15209     }
15210     // No need to add this to end of @implementation.
15211     else
15212       return;
15213   }
15214   // All conditions are met. Add a new bitfield to the tail end of ivars.
15215   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
15216   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
15217 
15218   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
15219                               DeclLoc, DeclLoc, nullptr,
15220                               Context.CharTy,
15221                               Context.getTrivialTypeSourceInfo(Context.CharTy,
15222                                                                DeclLoc),
15223                               ObjCIvarDecl::Private, BW,
15224                               true);
15225   AllIvarDecls.push_back(Ivar);
15226 }
15227 
15228 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
15229                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
15230                        SourceLocation RBrac, AttributeList *Attr) {
15231   assert(EnclosingDecl && "missing record or interface decl");
15232 
15233   // If this is an Objective-C @implementation or category and we have
15234   // new fields here we should reset the layout of the interface since
15235   // it will now change.
15236   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
15237     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
15238     switch (DC->getKind()) {
15239     default: break;
15240     case Decl::ObjCCategory:
15241       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
15242       break;
15243     case Decl::ObjCImplementation:
15244       Context.
15245         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
15246       break;
15247     }
15248   }
15249 
15250   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
15251 
15252   // Start counting up the number of named members; make sure to include
15253   // members of anonymous structs and unions in the total.
15254   unsigned NumNamedMembers = 0;
15255   if (Record) {
15256     for (const auto *I : Record->decls()) {
15257       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
15258         if (IFD->getDeclName())
15259           ++NumNamedMembers;
15260     }
15261   }
15262 
15263   // Verify that all the fields are okay.
15264   SmallVector<FieldDecl*, 32> RecFields;
15265 
15266   bool ObjCFieldLifetimeErrReported = false;
15267   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
15268        i != end; ++i) {
15269     FieldDecl *FD = cast<FieldDecl>(*i);
15270 
15271     // Get the type for the field.
15272     const Type *FDTy = FD->getType().getTypePtr();
15273 
15274     if (!FD->isAnonymousStructOrUnion()) {
15275       // Remember all fields written by the user.
15276       RecFields.push_back(FD);
15277     }
15278 
15279     // If the field is already invalid for some reason, don't emit more
15280     // diagnostics about it.
15281     if (FD->isInvalidDecl()) {
15282       EnclosingDecl->setInvalidDecl();
15283       continue;
15284     }
15285 
15286     // C99 6.7.2.1p2:
15287     //   A structure or union shall not contain a member with
15288     //   incomplete or function type (hence, a structure shall not
15289     //   contain an instance of itself, but may contain a pointer to
15290     //   an instance of itself), except that the last member of a
15291     //   structure with more than one named member may have incomplete
15292     //   array type; such a structure (and any union containing,
15293     //   possibly recursively, a member that is such a structure)
15294     //   shall not be a member of a structure or an element of an
15295     //   array.
15296     bool IsLastField = (i + 1 == Fields.end());
15297     if (FDTy->isFunctionType()) {
15298       // Field declared as a function.
15299       Diag(FD->getLocation(), diag::err_field_declared_as_function)
15300         << FD->getDeclName();
15301       FD->setInvalidDecl();
15302       EnclosingDecl->setInvalidDecl();
15303       continue;
15304     } else if (FDTy->isIncompleteArrayType() &&
15305                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
15306       if (Record) {
15307         // Flexible array member.
15308         // Microsoft and g++ is more permissive regarding flexible array.
15309         // It will accept flexible array in union and also
15310         // as the sole element of a struct/class.
15311         unsigned DiagID = 0;
15312         if (!Record->isUnion() && !IsLastField) {
15313           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
15314             << FD->getDeclName() << FD->getType() << Record->getTagKind();
15315           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
15316           FD->setInvalidDecl();
15317           EnclosingDecl->setInvalidDecl();
15318           continue;
15319         } else if (Record->isUnion())
15320           DiagID = getLangOpts().MicrosoftExt
15321                        ? diag::ext_flexible_array_union_ms
15322                        : getLangOpts().CPlusPlus
15323                              ? diag::ext_flexible_array_union_gnu
15324                              : diag::err_flexible_array_union;
15325         else if (NumNamedMembers < 1)
15326           DiagID = getLangOpts().MicrosoftExt
15327                        ? diag::ext_flexible_array_empty_aggregate_ms
15328                        : getLangOpts().CPlusPlus
15329                              ? diag::ext_flexible_array_empty_aggregate_gnu
15330                              : diag::err_flexible_array_empty_aggregate;
15331 
15332         if (DiagID)
15333           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
15334                                           << Record->getTagKind();
15335         // While the layout of types that contain virtual bases is not specified
15336         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
15337         // virtual bases after the derived members.  This would make a flexible
15338         // array member declared at the end of an object not adjacent to the end
15339         // of the type.
15340         if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
15341           if (RD->getNumVBases() != 0)
15342             Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
15343               << FD->getDeclName() << Record->getTagKind();
15344         if (!getLangOpts().C99)
15345           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
15346             << FD->getDeclName() << Record->getTagKind();
15347 
15348         // If the element type has a non-trivial destructor, we would not
15349         // implicitly destroy the elements, so disallow it for now.
15350         //
15351         // FIXME: GCC allows this. We should probably either implicitly delete
15352         // the destructor of the containing class, or just allow this.
15353         QualType BaseElem = Context.getBaseElementType(FD->getType());
15354         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
15355           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
15356             << FD->getDeclName() << FD->getType();
15357           FD->setInvalidDecl();
15358           EnclosingDecl->setInvalidDecl();
15359           continue;
15360         }
15361         // Okay, we have a legal flexible array member at the end of the struct.
15362         Record->setHasFlexibleArrayMember(true);
15363       } else {
15364         // In ObjCContainerDecl ivars with incomplete array type are accepted,
15365         // unless they are followed by another ivar. That check is done
15366         // elsewhere, after synthesized ivars are known.
15367       }
15368     } else if (!FDTy->isDependentType() &&
15369                RequireCompleteType(FD->getLocation(), FD->getType(),
15370                                    diag::err_field_incomplete)) {
15371       // Incomplete type
15372       FD->setInvalidDecl();
15373       EnclosingDecl->setInvalidDecl();
15374       continue;
15375     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
15376       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
15377         // A type which contains a flexible array member is considered to be a
15378         // flexible array member.
15379         Record->setHasFlexibleArrayMember(true);
15380         if (!Record->isUnion()) {
15381           // If this is a struct/class and this is not the last element, reject
15382           // it.  Note that GCC supports variable sized arrays in the middle of
15383           // structures.
15384           if (!IsLastField)
15385             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
15386               << FD->getDeclName() << FD->getType();
15387           else {
15388             // We support flexible arrays at the end of structs in
15389             // other structs as an extension.
15390             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
15391               << FD->getDeclName();
15392           }
15393         }
15394       }
15395       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
15396           RequireNonAbstractType(FD->getLocation(), FD->getType(),
15397                                  diag::err_abstract_type_in_decl,
15398                                  AbstractIvarType)) {
15399         // Ivars can not have abstract class types
15400         FD->setInvalidDecl();
15401       }
15402       if (Record && FDTTy->getDecl()->hasObjectMember())
15403         Record->setHasObjectMember(true);
15404       if (Record && FDTTy->getDecl()->hasVolatileMember())
15405         Record->setHasVolatileMember(true);
15406     } else if (FDTy->isObjCObjectType()) {
15407       /// A field cannot be an Objective-c object
15408       Diag(FD->getLocation(), diag::err_statically_allocated_object)
15409         << FixItHint::CreateInsertion(FD->getLocation(), "*");
15410       QualType T = Context.getObjCObjectPointerType(FD->getType());
15411       FD->setType(T);
15412     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
15413                Record && !ObjCFieldLifetimeErrReported && Record->isUnion()) {
15414       // It's an error in ARC or Weak if a field has lifetime.
15415       // We don't want to report this in a system header, though,
15416       // so we just make the field unavailable.
15417       // FIXME: that's really not sufficient; we need to make the type
15418       // itself invalid to, say, initialize or copy.
15419       QualType T = FD->getType();
15420       if (T.hasNonTrivialObjCLifetime()) {
15421         SourceLocation loc = FD->getLocation();
15422         if (getSourceManager().isInSystemHeader(loc)) {
15423           if (!FD->hasAttr<UnavailableAttr>()) {
15424             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15425                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
15426           }
15427         } else {
15428           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
15429             << T->isBlockPointerType() << Record->getTagKind();
15430         }
15431         ObjCFieldLifetimeErrReported = true;
15432       }
15433     } else if (getLangOpts().ObjC1 &&
15434                getLangOpts().getGC() != LangOptions::NonGC &&
15435                Record && !Record->hasObjectMember()) {
15436       if (FD->getType()->isObjCObjectPointerType() ||
15437           FD->getType().isObjCGCStrong())
15438         Record->setHasObjectMember(true);
15439       else if (Context.getAsArrayType(FD->getType())) {
15440         QualType BaseType = Context.getBaseElementType(FD->getType());
15441         if (BaseType->isRecordType() &&
15442             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
15443           Record->setHasObjectMember(true);
15444         else if (BaseType->isObjCObjectPointerType() ||
15445                  BaseType.isObjCGCStrong())
15446                Record->setHasObjectMember(true);
15447       }
15448     }
15449 
15450     if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
15451       QualType FT = FD->getType();
15452       if (FT.isNonTrivialToPrimitiveDefaultInitialize())
15453         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
15454       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
15455       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial)
15456         Record->setNonTrivialToPrimitiveCopy(true);
15457       if (FT.isDestructedType()) {
15458         Record->setNonTrivialToPrimitiveDestroy(true);
15459         Record->setParamDestroyedInCallee(true);
15460       }
15461 
15462       if (const auto *RT = FT->getAs<RecordType>()) {
15463         if (RT->getDecl()->getArgPassingRestrictions() ==
15464             RecordDecl::APK_CanNeverPassInRegs)
15465           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
15466       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
15467         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
15468     }
15469 
15470     if (Record && FD->getType().isVolatileQualified())
15471       Record->setHasVolatileMember(true);
15472     // Keep track of the number of named members.
15473     if (FD->getIdentifier())
15474       ++NumNamedMembers;
15475   }
15476 
15477   // Okay, we successfully defined 'Record'.
15478   if (Record) {
15479     bool Completed = false;
15480     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15481       if (!CXXRecord->isInvalidDecl()) {
15482         // Set access bits correctly on the directly-declared conversions.
15483         for (CXXRecordDecl::conversion_iterator
15484                I = CXXRecord->conversion_begin(),
15485                E = CXXRecord->conversion_end(); I != E; ++I)
15486           I.setAccess((*I)->getAccess());
15487       }
15488 
15489       if (!CXXRecord->isDependentType()) {
15490         if (CXXRecord->hasUserDeclaredDestructor()) {
15491           // Adjust user-defined destructor exception spec.
15492           if (getLangOpts().CPlusPlus11)
15493             AdjustDestructorExceptionSpec(CXXRecord,
15494                                           CXXRecord->getDestructor());
15495         }
15496 
15497         // Add any implicitly-declared members to this class.
15498         AddImplicitlyDeclaredMembersToClass(CXXRecord);
15499 
15500         if (!CXXRecord->isInvalidDecl()) {
15501           // If we have virtual base classes, we may end up finding multiple
15502           // final overriders for a given virtual function. Check for this
15503           // problem now.
15504           if (CXXRecord->getNumVBases()) {
15505             CXXFinalOverriderMap FinalOverriders;
15506             CXXRecord->getFinalOverriders(FinalOverriders);
15507 
15508             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
15509                                              MEnd = FinalOverriders.end();
15510                  M != MEnd; ++M) {
15511               for (OverridingMethods::iterator SO = M->second.begin(),
15512                                             SOEnd = M->second.end();
15513                    SO != SOEnd; ++SO) {
15514                 assert(SO->second.size() > 0 &&
15515                        "Virtual function without overriding functions?");
15516                 if (SO->second.size() == 1)
15517                   continue;
15518 
15519                 // C++ [class.virtual]p2:
15520                 //   In a derived class, if a virtual member function of a base
15521                 //   class subobject has more than one final overrider the
15522                 //   program is ill-formed.
15523                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
15524                   << (const NamedDecl *)M->first << Record;
15525                 Diag(M->first->getLocation(),
15526                      diag::note_overridden_virtual_function);
15527                 for (OverridingMethods::overriding_iterator
15528                           OM = SO->second.begin(),
15529                        OMEnd = SO->second.end();
15530                      OM != OMEnd; ++OM)
15531                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
15532                     << (const NamedDecl *)M->first << OM->Method->getParent();
15533 
15534                 Record->setInvalidDecl();
15535               }
15536             }
15537             CXXRecord->completeDefinition(&FinalOverriders);
15538             Completed = true;
15539           }
15540         }
15541       }
15542     }
15543 
15544     if (!Completed)
15545       Record->completeDefinition();
15546 
15547     // Handle attributes before checking the layout.
15548     if (Attr)
15549       ProcessDeclAttributeList(S, Record, Attr);
15550 
15551     // We may have deferred checking for a deleted destructor. Check now.
15552     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15553       auto *Dtor = CXXRecord->getDestructor();
15554       if (Dtor && Dtor->isImplicit() &&
15555           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
15556         CXXRecord->setImplicitDestructorIsDeleted();
15557         SetDeclDeleted(Dtor, CXXRecord->getLocation());
15558       }
15559     }
15560 
15561     if (Record->hasAttrs()) {
15562       CheckAlignasUnderalignment(Record);
15563 
15564       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
15565         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
15566                                            IA->getRange(), IA->getBestCase(),
15567                                            IA->getSemanticSpelling());
15568     }
15569 
15570     // Check if the structure/union declaration is a type that can have zero
15571     // size in C. For C this is a language extension, for C++ it may cause
15572     // compatibility problems.
15573     bool CheckForZeroSize;
15574     if (!getLangOpts().CPlusPlus) {
15575       CheckForZeroSize = true;
15576     } else {
15577       // For C++ filter out types that cannot be referenced in C code.
15578       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
15579       CheckForZeroSize =
15580           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
15581           !CXXRecord->isDependentType() &&
15582           CXXRecord->isCLike();
15583     }
15584     if (CheckForZeroSize) {
15585       bool ZeroSize = true;
15586       bool IsEmpty = true;
15587       unsigned NonBitFields = 0;
15588       for (RecordDecl::field_iterator I = Record->field_begin(),
15589                                       E = Record->field_end();
15590            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
15591         IsEmpty = false;
15592         if (I->isUnnamedBitfield()) {
15593           if (!I->isZeroLengthBitField(Context))
15594             ZeroSize = false;
15595         } else {
15596           ++NonBitFields;
15597           QualType FieldType = I->getType();
15598           if (FieldType->isIncompleteType() ||
15599               !Context.getTypeSizeInChars(FieldType).isZero())
15600             ZeroSize = false;
15601         }
15602       }
15603 
15604       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
15605       // allowed in C++, but warn if its declaration is inside
15606       // extern "C" block.
15607       if (ZeroSize) {
15608         Diag(RecLoc, getLangOpts().CPlusPlus ?
15609                          diag::warn_zero_size_struct_union_in_extern_c :
15610                          diag::warn_zero_size_struct_union_compat)
15611           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
15612       }
15613 
15614       // Structs without named members are extension in C (C99 6.7.2.1p7),
15615       // but are accepted by GCC.
15616       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
15617         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
15618                                diag::ext_no_named_members_in_struct_union)
15619           << Record->isUnion();
15620       }
15621     }
15622   } else {
15623     ObjCIvarDecl **ClsFields =
15624       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
15625     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
15626       ID->setEndOfDefinitionLoc(RBrac);
15627       // Add ivar's to class's DeclContext.
15628       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15629         ClsFields[i]->setLexicalDeclContext(ID);
15630         ID->addDecl(ClsFields[i]);
15631       }
15632       // Must enforce the rule that ivars in the base classes may not be
15633       // duplicates.
15634       if (ID->getSuperClass())
15635         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
15636     } else if (ObjCImplementationDecl *IMPDecl =
15637                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15638       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
15639       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
15640         // Ivar declared in @implementation never belongs to the implementation.
15641         // Only it is in implementation's lexical context.
15642         ClsFields[I]->setLexicalDeclContext(IMPDecl);
15643       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
15644       IMPDecl->setIvarLBraceLoc(LBrac);
15645       IMPDecl->setIvarRBraceLoc(RBrac);
15646     } else if (ObjCCategoryDecl *CDecl =
15647                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15648       // case of ivars in class extension; all other cases have been
15649       // reported as errors elsewhere.
15650       // FIXME. Class extension does not have a LocEnd field.
15651       // CDecl->setLocEnd(RBrac);
15652       // Add ivar's to class extension's DeclContext.
15653       // Diagnose redeclaration of private ivars.
15654       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
15655       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15656         if (IDecl) {
15657           if (const ObjCIvarDecl *ClsIvar =
15658               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
15659             Diag(ClsFields[i]->getLocation(),
15660                  diag::err_duplicate_ivar_declaration);
15661             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
15662             continue;
15663           }
15664           for (const auto *Ext : IDecl->known_extensions()) {
15665             if (const ObjCIvarDecl *ClsExtIvar
15666                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
15667               Diag(ClsFields[i]->getLocation(),
15668                    diag::err_duplicate_ivar_declaration);
15669               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
15670               continue;
15671             }
15672           }
15673         }
15674         ClsFields[i]->setLexicalDeclContext(CDecl);
15675         CDecl->addDecl(ClsFields[i]);
15676       }
15677       CDecl->setIvarLBraceLoc(LBrac);
15678       CDecl->setIvarRBraceLoc(RBrac);
15679     }
15680   }
15681 }
15682 
15683 /// Determine whether the given integral value is representable within
15684 /// the given type T.
15685 static bool isRepresentableIntegerValue(ASTContext &Context,
15686                                         llvm::APSInt &Value,
15687                                         QualType T) {
15688   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
15689          "Integral type required!");
15690   unsigned BitWidth = Context.getIntWidth(T);
15691 
15692   if (Value.isUnsigned() || Value.isNonNegative()) {
15693     if (T->isSignedIntegerOrEnumerationType())
15694       --BitWidth;
15695     return Value.getActiveBits() <= BitWidth;
15696   }
15697   return Value.getMinSignedBits() <= BitWidth;
15698 }
15699 
15700 // Given an integral type, return the next larger integral type
15701 // (or a NULL type of no such type exists).
15702 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
15703   // FIXME: Int128/UInt128 support, which also needs to be introduced into
15704   // enum checking below.
15705   assert((T->isIntegralType(Context) ||
15706          T->isEnumeralType()) && "Integral type required!");
15707   const unsigned NumTypes = 4;
15708   QualType SignedIntegralTypes[NumTypes] = {
15709     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
15710   };
15711   QualType UnsignedIntegralTypes[NumTypes] = {
15712     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
15713     Context.UnsignedLongLongTy
15714   };
15715 
15716   unsigned BitWidth = Context.getTypeSize(T);
15717   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
15718                                                         : UnsignedIntegralTypes;
15719   for (unsigned I = 0; I != NumTypes; ++I)
15720     if (Context.getTypeSize(Types[I]) > BitWidth)
15721       return Types[I];
15722 
15723   return QualType();
15724 }
15725 
15726 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
15727                                           EnumConstantDecl *LastEnumConst,
15728                                           SourceLocation IdLoc,
15729                                           IdentifierInfo *Id,
15730                                           Expr *Val) {
15731   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15732   llvm::APSInt EnumVal(IntWidth);
15733   QualType EltTy;
15734 
15735   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
15736     Val = nullptr;
15737 
15738   if (Val)
15739     Val = DefaultLvalueConversion(Val).get();
15740 
15741   if (Val) {
15742     if (Enum->isDependentType() || Val->isTypeDependent())
15743       EltTy = Context.DependentTy;
15744     else {
15745       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
15746           !getLangOpts().MSVCCompat) {
15747         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
15748         // constant-expression in the enumerator-definition shall be a converted
15749         // constant expression of the underlying type.
15750         EltTy = Enum->getIntegerType();
15751         ExprResult Converted =
15752           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
15753                                            CCEK_Enumerator);
15754         if (Converted.isInvalid())
15755           Val = nullptr;
15756         else
15757           Val = Converted.get();
15758       } else if (!Val->isValueDependent() &&
15759                  !(Val = VerifyIntegerConstantExpression(Val,
15760                                                          &EnumVal).get())) {
15761         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
15762       } else {
15763         if (Enum->isComplete()) {
15764           EltTy = Enum->getIntegerType();
15765 
15766           // In Obj-C and Microsoft mode, require the enumeration value to be
15767           // representable in the underlying type of the enumeration. In C++11,
15768           // we perform a non-narrowing conversion as part of converted constant
15769           // expression checking.
15770           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15771             if (getLangOpts().MSVCCompat) {
15772               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
15773               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
15774             } else
15775               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
15776           } else
15777             Val = ImpCastExprToType(Val, EltTy,
15778                                     EltTy->isBooleanType() ?
15779                                     CK_IntegralToBoolean : CK_IntegralCast)
15780                     .get();
15781         } else if (getLangOpts().CPlusPlus) {
15782           // C++11 [dcl.enum]p5:
15783           //   If the underlying type is not fixed, the type of each enumerator
15784           //   is the type of its initializing value:
15785           //     - If an initializer is specified for an enumerator, the
15786           //       initializing value has the same type as the expression.
15787           EltTy = Val->getType();
15788         } else {
15789           // C99 6.7.2.2p2:
15790           //   The expression that defines the value of an enumeration constant
15791           //   shall be an integer constant expression that has a value
15792           //   representable as an int.
15793 
15794           // Complain if the value is not representable in an int.
15795           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
15796             Diag(IdLoc, diag::ext_enum_value_not_int)
15797               << EnumVal.toString(10) << Val->getSourceRange()
15798               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
15799           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
15800             // Force the type of the expression to 'int'.
15801             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
15802           }
15803           EltTy = Val->getType();
15804         }
15805       }
15806     }
15807   }
15808 
15809   if (!Val) {
15810     if (Enum->isDependentType())
15811       EltTy = Context.DependentTy;
15812     else if (!LastEnumConst) {
15813       // C++0x [dcl.enum]p5:
15814       //   If the underlying type is not fixed, the type of each enumerator
15815       //   is the type of its initializing value:
15816       //     - If no initializer is specified for the first enumerator, the
15817       //       initializing value has an unspecified integral type.
15818       //
15819       // GCC uses 'int' for its unspecified integral type, as does
15820       // C99 6.7.2.2p3.
15821       if (Enum->isFixed()) {
15822         EltTy = Enum->getIntegerType();
15823       }
15824       else {
15825         EltTy = Context.IntTy;
15826       }
15827     } else {
15828       // Assign the last value + 1.
15829       EnumVal = LastEnumConst->getInitVal();
15830       ++EnumVal;
15831       EltTy = LastEnumConst->getType();
15832 
15833       // Check for overflow on increment.
15834       if (EnumVal < LastEnumConst->getInitVal()) {
15835         // C++0x [dcl.enum]p5:
15836         //   If the underlying type is not fixed, the type of each enumerator
15837         //   is the type of its initializing value:
15838         //
15839         //     - Otherwise the type of the initializing value is the same as
15840         //       the type of the initializing value of the preceding enumerator
15841         //       unless the incremented value is not representable in that type,
15842         //       in which case the type is an unspecified integral type
15843         //       sufficient to contain the incremented value. If no such type
15844         //       exists, the program is ill-formed.
15845         QualType T = getNextLargerIntegralType(Context, EltTy);
15846         if (T.isNull() || Enum->isFixed()) {
15847           // There is no integral type larger enough to represent this
15848           // value. Complain, then allow the value to wrap around.
15849           EnumVal = LastEnumConst->getInitVal();
15850           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
15851           ++EnumVal;
15852           if (Enum->isFixed())
15853             // When the underlying type is fixed, this is ill-formed.
15854             Diag(IdLoc, diag::err_enumerator_wrapped)
15855               << EnumVal.toString(10)
15856               << EltTy;
15857           else
15858             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
15859               << EnumVal.toString(10);
15860         } else {
15861           EltTy = T;
15862         }
15863 
15864         // Retrieve the last enumerator's value, extent that type to the
15865         // type that is supposed to be large enough to represent the incremented
15866         // value, then increment.
15867         EnumVal = LastEnumConst->getInitVal();
15868         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15869         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
15870         ++EnumVal;
15871 
15872         // If we're not in C++, diagnose the overflow of enumerator values,
15873         // which in C99 means that the enumerator value is not representable in
15874         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
15875         // permits enumerator values that are representable in some larger
15876         // integral type.
15877         if (!getLangOpts().CPlusPlus && !T.isNull())
15878           Diag(IdLoc, diag::warn_enum_value_overflow);
15879       } else if (!getLangOpts().CPlusPlus &&
15880                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15881         // Enforce C99 6.7.2.2p2 even when we compute the next value.
15882         Diag(IdLoc, diag::ext_enum_value_not_int)
15883           << EnumVal.toString(10) << 1;
15884       }
15885     }
15886   }
15887 
15888   if (!EltTy->isDependentType()) {
15889     // Make the enumerator value match the signedness and size of the
15890     // enumerator's type.
15891     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
15892     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15893   }
15894 
15895   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
15896                                   Val, EnumVal);
15897 }
15898 
15899 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
15900                                                 SourceLocation IILoc) {
15901   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
15902       !getLangOpts().CPlusPlus)
15903     return SkipBodyInfo();
15904 
15905   // We have an anonymous enum definition. Look up the first enumerator to
15906   // determine if we should merge the definition with an existing one and
15907   // skip the body.
15908   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
15909                                          forRedeclarationInCurContext());
15910   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
15911   if (!PrevECD)
15912     return SkipBodyInfo();
15913 
15914   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
15915   NamedDecl *Hidden;
15916   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
15917     SkipBodyInfo Skip;
15918     Skip.Previous = Hidden;
15919     return Skip;
15920   }
15921 
15922   return SkipBodyInfo();
15923 }
15924 
15925 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
15926                               SourceLocation IdLoc, IdentifierInfo *Id,
15927                               AttributeList *Attr,
15928                               SourceLocation EqualLoc, Expr *Val) {
15929   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
15930   EnumConstantDecl *LastEnumConst =
15931     cast_or_null<EnumConstantDecl>(lastEnumConst);
15932 
15933   // The scope passed in may not be a decl scope.  Zip up the scope tree until
15934   // we find one that is.
15935   S = getNonFieldDeclScope(S);
15936 
15937   // Verify that there isn't already something declared with this name in this
15938   // scope.
15939   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
15940                                          ForVisibleRedeclaration);
15941   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15942     // Maybe we will complain about the shadowed template parameter.
15943     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
15944     // Just pretend that we didn't see the previous declaration.
15945     PrevDecl = nullptr;
15946   }
15947 
15948   // C++ [class.mem]p15:
15949   // If T is the name of a class, then each of the following shall have a name
15950   // different from T:
15951   // - every enumerator of every member of class T that is an unscoped
15952   // enumerated type
15953   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
15954     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
15955                             DeclarationNameInfo(Id, IdLoc));
15956 
15957   EnumConstantDecl *New =
15958     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
15959   if (!New)
15960     return nullptr;
15961 
15962   if (PrevDecl) {
15963     // When in C++, we may get a TagDecl with the same name; in this case the
15964     // enum constant will 'hide' the tag.
15965     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
15966            "Received TagDecl when not in C++!");
15967     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
15968       if (isa<EnumConstantDecl>(PrevDecl))
15969         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15970       else
15971         Diag(IdLoc, diag::err_redefinition) << Id;
15972       notePreviousDefinition(PrevDecl, IdLoc);
15973       return nullptr;
15974     }
15975   }
15976 
15977   // Process attributes.
15978   if (Attr) ProcessDeclAttributeList(S, New, Attr);
15979   AddPragmaAttributes(S, New);
15980 
15981   // Register this decl in the current scope stack.
15982   New->setAccess(TheEnumDecl->getAccess());
15983   PushOnScopeChains(New, S);
15984 
15985   ActOnDocumentableDecl(New);
15986 
15987   return New;
15988 }
15989 
15990 // Returns true when the enum initial expression does not trigger the
15991 // duplicate enum warning.  A few common cases are exempted as follows:
15992 // Element2 = Element1
15993 // Element2 = Element1 + 1
15994 // Element2 = Element1 - 1
15995 // Where Element2 and Element1 are from the same enum.
15996 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
15997   Expr *InitExpr = ECD->getInitExpr();
15998   if (!InitExpr)
15999     return true;
16000   InitExpr = InitExpr->IgnoreImpCasts();
16001 
16002   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
16003     if (!BO->isAdditiveOp())
16004       return true;
16005     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
16006     if (!IL)
16007       return true;
16008     if (IL->getValue() != 1)
16009       return true;
16010 
16011     InitExpr = BO->getLHS();
16012   }
16013 
16014   // This checks if the elements are from the same enum.
16015   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
16016   if (!DRE)
16017     return true;
16018 
16019   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
16020   if (!EnumConstant)
16021     return true;
16022 
16023   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
16024       Enum)
16025     return true;
16026 
16027   return false;
16028 }
16029 
16030 // Emits a warning when an element is implicitly set a value that
16031 // a previous element has already been set to.
16032 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
16033                                         EnumDecl *Enum, QualType EnumType) {
16034   // Avoid anonymous enums
16035   if (!Enum->getIdentifier())
16036     return;
16037 
16038   // Only check for small enums.
16039   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
16040     return;
16041 
16042   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
16043     return;
16044 
16045   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
16046   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
16047 
16048   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
16049   typedef llvm::DenseMap<int64_t, DeclOrVector> ValueToVectorMap;
16050 
16051   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
16052   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
16053     llvm::APSInt Val = D->getInitVal();
16054     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
16055   };
16056 
16057   DuplicatesVector DupVector;
16058   ValueToVectorMap EnumMap;
16059 
16060   // Populate the EnumMap with all values represented by enum constants without
16061   // an initializer.
16062   for (auto *Element : Elements) {
16063     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
16064 
16065     // Null EnumConstantDecl means a previous diagnostic has been emitted for
16066     // this constant.  Skip this enum since it may be ill-formed.
16067     if (!ECD) {
16068       return;
16069     }
16070 
16071     // Constants with initalizers are handled in the next loop.
16072     if (ECD->getInitExpr())
16073       continue;
16074 
16075     // Duplicate values are handled in the next loop.
16076     EnumMap.insert({EnumConstantToKey(ECD), ECD});
16077   }
16078 
16079   if (EnumMap.size() == 0)
16080     return;
16081 
16082   // Create vectors for any values that has duplicates.
16083   for (auto *Element : Elements) {
16084     // The last loop returned if any constant was null.
16085     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
16086     if (!ValidDuplicateEnum(ECD, Enum))
16087       continue;
16088 
16089     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
16090     if (Iter == EnumMap.end())
16091       continue;
16092 
16093     DeclOrVector& Entry = Iter->second;
16094     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
16095       // Ensure constants are different.
16096       if (D == ECD)
16097         continue;
16098 
16099       // Create new vector and push values onto it.
16100       auto Vec = llvm::make_unique<ECDVector>();
16101       Vec->push_back(D);
16102       Vec->push_back(ECD);
16103 
16104       // Update entry to point to the duplicates vector.
16105       Entry = Vec.get();
16106 
16107       // Store the vector somewhere we can consult later for quick emission of
16108       // diagnostics.
16109       DupVector.emplace_back(std::move(Vec));
16110       continue;
16111     }
16112 
16113     ECDVector *Vec = Entry.get<ECDVector*>();
16114     // Make sure constants are not added more than once.
16115     if (*Vec->begin() == ECD)
16116       continue;
16117 
16118     Vec->push_back(ECD);
16119   }
16120 
16121   // Emit diagnostics.
16122   for (const auto &Vec : DupVector) {
16123     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
16124 
16125     // Emit warning for one enum constant.
16126     auto *FirstECD = Vec->front();
16127     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
16128       << FirstECD << FirstECD->getInitVal().toString(10)
16129       << FirstECD->getSourceRange();
16130 
16131     // Emit one note for each of the remaining enum constants with
16132     // the same value.
16133     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
16134       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
16135         << ECD << ECD->getInitVal().toString(10)
16136         << ECD->getSourceRange();
16137   }
16138 }
16139 
16140 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
16141                              bool AllowMask) const {
16142   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
16143   assert(ED->isCompleteDefinition() && "expected enum definition");
16144 
16145   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
16146   llvm::APInt &FlagBits = R.first->second;
16147 
16148   if (R.second) {
16149     for (auto *E : ED->enumerators()) {
16150       const auto &EVal = E->getInitVal();
16151       // Only single-bit enumerators introduce new flag values.
16152       if (EVal.isPowerOf2())
16153         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
16154     }
16155   }
16156 
16157   // A value is in a flag enum if either its bits are a subset of the enum's
16158   // flag bits (the first condition) or we are allowing masks and the same is
16159   // true of its complement (the second condition). When masks are allowed, we
16160   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
16161   //
16162   // While it's true that any value could be used as a mask, the assumption is
16163   // that a mask will have all of the insignificant bits set. Anything else is
16164   // likely a logic error.
16165   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
16166   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
16167 }
16168 
16169 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
16170                          Decl *EnumDeclX,
16171                          ArrayRef<Decl *> Elements,
16172                          Scope *S, AttributeList *Attr) {
16173   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
16174   QualType EnumType = Context.getTypeDeclType(Enum);
16175 
16176   if (Attr)
16177     ProcessDeclAttributeList(S, Enum, Attr);
16178 
16179   if (Enum->isDependentType()) {
16180     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16181       EnumConstantDecl *ECD =
16182         cast_or_null<EnumConstantDecl>(Elements[i]);
16183       if (!ECD) continue;
16184 
16185       ECD->setType(EnumType);
16186     }
16187 
16188     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
16189     return;
16190   }
16191 
16192   // TODO: If the result value doesn't fit in an int, it must be a long or long
16193   // long value.  ISO C does not support this, but GCC does as an extension,
16194   // emit a warning.
16195   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16196   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
16197   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
16198 
16199   // Verify that all the values are okay, compute the size of the values, and
16200   // reverse the list.
16201   unsigned NumNegativeBits = 0;
16202   unsigned NumPositiveBits = 0;
16203 
16204   // Keep track of whether all elements have type int.
16205   bool AllElementsInt = true;
16206 
16207   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16208     EnumConstantDecl *ECD =
16209       cast_or_null<EnumConstantDecl>(Elements[i]);
16210     if (!ECD) continue;  // Already issued a diagnostic.
16211 
16212     const llvm::APSInt &InitVal = ECD->getInitVal();
16213 
16214     // Keep track of the size of positive and negative values.
16215     if (InitVal.isUnsigned() || InitVal.isNonNegative())
16216       NumPositiveBits = std::max(NumPositiveBits,
16217                                  (unsigned)InitVal.getActiveBits());
16218     else
16219       NumNegativeBits = std::max(NumNegativeBits,
16220                                  (unsigned)InitVal.getMinSignedBits());
16221 
16222     // Keep track of whether every enum element has type int (very commmon).
16223     if (AllElementsInt)
16224       AllElementsInt = ECD->getType() == Context.IntTy;
16225   }
16226 
16227   // Figure out the type that should be used for this enum.
16228   QualType BestType;
16229   unsigned BestWidth;
16230 
16231   // C++0x N3000 [conv.prom]p3:
16232   //   An rvalue of an unscoped enumeration type whose underlying
16233   //   type is not fixed can be converted to an rvalue of the first
16234   //   of the following types that can represent all the values of
16235   //   the enumeration: int, unsigned int, long int, unsigned long
16236   //   int, long long int, or unsigned long long int.
16237   // C99 6.4.4.3p2:
16238   //   An identifier declared as an enumeration constant has type int.
16239   // The C99 rule is modified by a gcc extension
16240   QualType BestPromotionType;
16241 
16242   bool Packed = Enum->hasAttr<PackedAttr>();
16243   // -fshort-enums is the equivalent to specifying the packed attribute on all
16244   // enum definitions.
16245   if (LangOpts.ShortEnums)
16246     Packed = true;
16247 
16248   // If the enum already has a type because it is fixed or dictated by the
16249   // target, promote that type instead of analyzing the enumerators.
16250   if (Enum->isComplete()) {
16251     BestType = Enum->getIntegerType();
16252     if (BestType->isPromotableIntegerType())
16253       BestPromotionType = Context.getPromotedIntegerType(BestType);
16254     else
16255       BestPromotionType = BestType;
16256 
16257     BestWidth = Context.getIntWidth(BestType);
16258   }
16259   else if (NumNegativeBits) {
16260     // If there is a negative value, figure out the smallest integer type (of
16261     // int/long/longlong) that fits.
16262     // If it's packed, check also if it fits a char or a short.
16263     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
16264       BestType = Context.SignedCharTy;
16265       BestWidth = CharWidth;
16266     } else if (Packed && NumNegativeBits <= ShortWidth &&
16267                NumPositiveBits < ShortWidth) {
16268       BestType = Context.ShortTy;
16269       BestWidth = ShortWidth;
16270     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
16271       BestType = Context.IntTy;
16272       BestWidth = IntWidth;
16273     } else {
16274       BestWidth = Context.getTargetInfo().getLongWidth();
16275 
16276       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
16277         BestType = Context.LongTy;
16278       } else {
16279         BestWidth = Context.getTargetInfo().getLongLongWidth();
16280 
16281         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
16282           Diag(Enum->getLocation(), diag::ext_enum_too_large);
16283         BestType = Context.LongLongTy;
16284       }
16285     }
16286     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
16287   } else {
16288     // If there is no negative value, figure out the smallest type that fits
16289     // all of the enumerator values.
16290     // If it's packed, check also if it fits a char or a short.
16291     if (Packed && NumPositiveBits <= CharWidth) {
16292       BestType = Context.UnsignedCharTy;
16293       BestPromotionType = Context.IntTy;
16294       BestWidth = CharWidth;
16295     } else if (Packed && NumPositiveBits <= ShortWidth) {
16296       BestType = Context.UnsignedShortTy;
16297       BestPromotionType = Context.IntTy;
16298       BestWidth = ShortWidth;
16299     } else if (NumPositiveBits <= IntWidth) {
16300       BestType = Context.UnsignedIntTy;
16301       BestWidth = IntWidth;
16302       BestPromotionType
16303         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16304                            ? Context.UnsignedIntTy : Context.IntTy;
16305     } else if (NumPositiveBits <=
16306                (BestWidth = Context.getTargetInfo().getLongWidth())) {
16307       BestType = Context.UnsignedLongTy;
16308       BestPromotionType
16309         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16310                            ? Context.UnsignedLongTy : Context.LongTy;
16311     } else {
16312       BestWidth = Context.getTargetInfo().getLongLongWidth();
16313       assert(NumPositiveBits <= BestWidth &&
16314              "How could an initializer get larger than ULL?");
16315       BestType = Context.UnsignedLongLongTy;
16316       BestPromotionType
16317         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16318                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
16319     }
16320   }
16321 
16322   // Loop over all of the enumerator constants, changing their types to match
16323   // the type of the enum if needed.
16324   for (auto *D : Elements) {
16325     auto *ECD = cast_or_null<EnumConstantDecl>(D);
16326     if (!ECD) continue;  // Already issued a diagnostic.
16327 
16328     // Standard C says the enumerators have int type, but we allow, as an
16329     // extension, the enumerators to be larger than int size.  If each
16330     // enumerator value fits in an int, type it as an int, otherwise type it the
16331     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
16332     // that X has type 'int', not 'unsigned'.
16333 
16334     // Determine whether the value fits into an int.
16335     llvm::APSInt InitVal = ECD->getInitVal();
16336 
16337     // If it fits into an integer type, force it.  Otherwise force it to match
16338     // the enum decl type.
16339     QualType NewTy;
16340     unsigned NewWidth;
16341     bool NewSign;
16342     if (!getLangOpts().CPlusPlus &&
16343         !Enum->isFixed() &&
16344         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
16345       NewTy = Context.IntTy;
16346       NewWidth = IntWidth;
16347       NewSign = true;
16348     } else if (ECD->getType() == BestType) {
16349       // Already the right type!
16350       if (getLangOpts().CPlusPlus)
16351         // C++ [dcl.enum]p4: Following the closing brace of an
16352         // enum-specifier, each enumerator has the type of its
16353         // enumeration.
16354         ECD->setType(EnumType);
16355       continue;
16356     } else {
16357       NewTy = BestType;
16358       NewWidth = BestWidth;
16359       NewSign = BestType->isSignedIntegerOrEnumerationType();
16360     }
16361 
16362     // Adjust the APSInt value.
16363     InitVal = InitVal.extOrTrunc(NewWidth);
16364     InitVal.setIsSigned(NewSign);
16365     ECD->setInitVal(InitVal);
16366 
16367     // Adjust the Expr initializer and type.
16368     if (ECD->getInitExpr() &&
16369         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
16370       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
16371                                                 CK_IntegralCast,
16372                                                 ECD->getInitExpr(),
16373                                                 /*base paths*/ nullptr,
16374                                                 VK_RValue));
16375     if (getLangOpts().CPlusPlus)
16376       // C++ [dcl.enum]p4: Following the closing brace of an
16377       // enum-specifier, each enumerator has the type of its
16378       // enumeration.
16379       ECD->setType(EnumType);
16380     else
16381       ECD->setType(NewTy);
16382   }
16383 
16384   Enum->completeDefinition(BestType, BestPromotionType,
16385                            NumPositiveBits, NumNegativeBits);
16386 
16387   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
16388 
16389   if (Enum->isClosedFlag()) {
16390     for (Decl *D : Elements) {
16391       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
16392       if (!ECD) continue;  // Already issued a diagnostic.
16393 
16394       llvm::APSInt InitVal = ECD->getInitVal();
16395       if (InitVal != 0 && !InitVal.isPowerOf2() &&
16396           !IsValueInFlagEnum(Enum, InitVal, true))
16397         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
16398           << ECD << Enum;
16399     }
16400   }
16401 
16402   // Now that the enum type is defined, ensure it's not been underaligned.
16403   if (Enum->hasAttrs())
16404     CheckAlignasUnderalignment(Enum);
16405 }
16406 
16407 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
16408                                   SourceLocation StartLoc,
16409                                   SourceLocation EndLoc) {
16410   StringLiteral *AsmString = cast<StringLiteral>(expr);
16411 
16412   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
16413                                                    AsmString, StartLoc,
16414                                                    EndLoc);
16415   CurContext->addDecl(New);
16416   return New;
16417 }
16418 
16419 static void checkModuleImportContext(Sema &S, Module *M,
16420                                      SourceLocation ImportLoc, DeclContext *DC,
16421                                      bool FromInclude = false) {
16422   SourceLocation ExternCLoc;
16423 
16424   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
16425     switch (LSD->getLanguage()) {
16426     case LinkageSpecDecl::lang_c:
16427       if (ExternCLoc.isInvalid())
16428         ExternCLoc = LSD->getLocStart();
16429       break;
16430     case LinkageSpecDecl::lang_cxx:
16431       break;
16432     }
16433     DC = LSD->getParent();
16434   }
16435 
16436   while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
16437     DC = DC->getParent();
16438 
16439   if (!isa<TranslationUnitDecl>(DC)) {
16440     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
16441                           ? diag::ext_module_import_not_at_top_level_noop
16442                           : diag::err_module_import_not_at_top_level_fatal)
16443         << M->getFullModuleName() << DC;
16444     S.Diag(cast<Decl>(DC)->getLocStart(),
16445            diag::note_module_import_not_at_top_level) << DC;
16446   } else if (!M->IsExternC && ExternCLoc.isValid()) {
16447     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
16448       << M->getFullModuleName();
16449     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
16450   }
16451 }
16452 
16453 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
16454                                            SourceLocation ModuleLoc,
16455                                            ModuleDeclKind MDK,
16456                                            ModuleIdPath Path) {
16457   assert(getLangOpts().ModulesTS &&
16458          "should only have module decl in modules TS");
16459 
16460   // A module implementation unit requires that we are not compiling a module
16461   // of any kind. A module interface unit requires that we are not compiling a
16462   // module map.
16463   switch (getLangOpts().getCompilingModule()) {
16464   case LangOptions::CMK_None:
16465     // It's OK to compile a module interface as a normal translation unit.
16466     break;
16467 
16468   case LangOptions::CMK_ModuleInterface:
16469     if (MDK != ModuleDeclKind::Implementation)
16470       break;
16471 
16472     // We were asked to compile a module interface unit but this is a module
16473     // implementation unit. That indicates the 'export' is missing.
16474     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
16475       << FixItHint::CreateInsertion(ModuleLoc, "export ");
16476     MDK = ModuleDeclKind::Interface;
16477     break;
16478 
16479   case LangOptions::CMK_ModuleMap:
16480     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
16481     return nullptr;
16482   }
16483 
16484   assert(ModuleScopes.size() == 1 && "expected to be at global module scope");
16485 
16486   // FIXME: Most of this work should be done by the preprocessor rather than
16487   // here, in order to support macro import.
16488 
16489   // Only one module-declaration is permitted per source file.
16490   if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) {
16491     Diag(ModuleLoc, diag::err_module_redeclaration);
16492     Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
16493          diag::note_prev_module_declaration);
16494     return nullptr;
16495   }
16496 
16497   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
16498   // modules, the dots here are just another character that can appear in a
16499   // module name.
16500   std::string ModuleName;
16501   for (auto &Piece : Path) {
16502     if (!ModuleName.empty())
16503       ModuleName += ".";
16504     ModuleName += Piece.first->getName();
16505   }
16506 
16507   // If a module name was explicitly specified on the command line, it must be
16508   // correct.
16509   if (!getLangOpts().CurrentModule.empty() &&
16510       getLangOpts().CurrentModule != ModuleName) {
16511     Diag(Path.front().second, diag::err_current_module_name_mismatch)
16512         << SourceRange(Path.front().second, Path.back().second)
16513         << getLangOpts().CurrentModule;
16514     return nullptr;
16515   }
16516   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
16517 
16518   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
16519   Module *Mod;
16520 
16521   switch (MDK) {
16522   case ModuleDeclKind::Interface: {
16523     // We can't have parsed or imported a definition of this module or parsed a
16524     // module map defining it already.
16525     if (auto *M = Map.findModule(ModuleName)) {
16526       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
16527       if (M->DefinitionLoc.isValid())
16528         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
16529       else if (const auto *FE = M->getASTFile())
16530         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
16531             << FE->getName();
16532       Mod = M;
16533       break;
16534     }
16535 
16536     // Create a Module for the module that we're defining.
16537     Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16538                                            ModuleScopes.front().Module);
16539     assert(Mod && "module creation should not fail");
16540     break;
16541   }
16542 
16543   case ModuleDeclKind::Partition:
16544     // FIXME: Check we are in a submodule of the named module.
16545     return nullptr;
16546 
16547   case ModuleDeclKind::Implementation:
16548     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
16549         PP.getIdentifierInfo(ModuleName), Path[0].second);
16550     Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible,
16551                                        /*IsIncludeDirective=*/false);
16552     if (!Mod) {
16553       Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
16554       // Create an empty module interface unit for error recovery.
16555       Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16556                                              ModuleScopes.front().Module);
16557     }
16558     break;
16559   }
16560 
16561   // Switch from the global module to the named module.
16562   ModuleScopes.back().Module = Mod;
16563   ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
16564   VisibleModules.setVisible(Mod, ModuleLoc);
16565 
16566   // From now on, we have an owning module for all declarations we see.
16567   // However, those declarations are module-private unless explicitly
16568   // exported.
16569   auto *TU = Context.getTranslationUnitDecl();
16570   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
16571   TU->setLocalOwningModule(Mod);
16572 
16573   // FIXME: Create a ModuleDecl.
16574   return nullptr;
16575 }
16576 
16577 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
16578                                    SourceLocation ImportLoc,
16579                                    ModuleIdPath Path) {
16580   Module *Mod =
16581       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
16582                                    /*IsIncludeDirective=*/false);
16583   if (!Mod)
16584     return true;
16585 
16586   VisibleModules.setVisible(Mod, ImportLoc);
16587 
16588   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
16589 
16590   // FIXME: we should support importing a submodule within a different submodule
16591   // of the same top-level module. Until we do, make it an error rather than
16592   // silently ignoring the import.
16593   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
16594   // warn on a redundant import of the current module?
16595   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
16596       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
16597     Diag(ImportLoc, getLangOpts().isCompilingModule()
16598                         ? diag::err_module_self_import
16599                         : diag::err_module_import_in_implementation)
16600         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
16601 
16602   SmallVector<SourceLocation, 2> IdentifierLocs;
16603   Module *ModCheck = Mod;
16604   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
16605     // If we've run out of module parents, just drop the remaining identifiers.
16606     // We need the length to be consistent.
16607     if (!ModCheck)
16608       break;
16609     ModCheck = ModCheck->Parent;
16610 
16611     IdentifierLocs.push_back(Path[I].second);
16612   }
16613 
16614   ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
16615                                           Mod, IdentifierLocs);
16616   if (!ModuleScopes.empty())
16617     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
16618   CurContext->addDecl(Import);
16619 
16620   // Re-export the module if needed.
16621   if (Import->isExported() &&
16622       !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface)
16623     getCurrentModule()->Exports.emplace_back(Mod, false);
16624 
16625   return Import;
16626 }
16627 
16628 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16629   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16630   BuildModuleInclude(DirectiveLoc, Mod);
16631 }
16632 
16633 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16634   // Determine whether we're in the #include buffer for a module. The #includes
16635   // in that buffer do not qualify as module imports; they're just an
16636   // implementation detail of us building the module.
16637   //
16638   // FIXME: Should we even get ActOnModuleInclude calls for those?
16639   bool IsInModuleIncludes =
16640       TUKind == TU_Module &&
16641       getSourceManager().isWrittenInMainFile(DirectiveLoc);
16642 
16643   bool ShouldAddImport = !IsInModuleIncludes;
16644 
16645   // If this module import was due to an inclusion directive, create an
16646   // implicit import declaration to capture it in the AST.
16647   if (ShouldAddImport) {
16648     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16649     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16650                                                      DirectiveLoc, Mod,
16651                                                      DirectiveLoc);
16652     if (!ModuleScopes.empty())
16653       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
16654     TU->addDecl(ImportD);
16655     Consumer.HandleImplicitImportDecl(ImportD);
16656   }
16657 
16658   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
16659   VisibleModules.setVisible(Mod, DirectiveLoc);
16660 }
16661 
16662 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
16663   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16664 
16665   ModuleScopes.push_back({});
16666   ModuleScopes.back().Module = Mod;
16667   if (getLangOpts().ModulesLocalVisibility)
16668     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
16669 
16670   VisibleModules.setVisible(Mod, DirectiveLoc);
16671 
16672   // The enclosing context is now part of this module.
16673   // FIXME: Consider creating a child DeclContext to hold the entities
16674   // lexically within the module.
16675   if (getLangOpts().trackLocalOwningModule()) {
16676     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16677       cast<Decl>(DC)->setModuleOwnershipKind(
16678           getLangOpts().ModulesLocalVisibility
16679               ? Decl::ModuleOwnershipKind::VisibleWhenImported
16680               : Decl::ModuleOwnershipKind::Visible);
16681       cast<Decl>(DC)->setLocalOwningModule(Mod);
16682     }
16683   }
16684 }
16685 
16686 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
16687   if (getLangOpts().ModulesLocalVisibility) {
16688     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
16689     // Leaving a module hides namespace names, so our visible namespace cache
16690     // is now out of date.
16691     VisibleNamespaceCache.clear();
16692   }
16693 
16694   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
16695          "left the wrong module scope");
16696   ModuleScopes.pop_back();
16697 
16698   // We got to the end of processing a local module. Create an
16699   // ImportDecl as we would for an imported module.
16700   FileID File = getSourceManager().getFileID(EomLoc);
16701   SourceLocation DirectiveLoc;
16702   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
16703     // We reached the end of a #included module header. Use the #include loc.
16704     assert(File != getSourceManager().getMainFileID() &&
16705            "end of submodule in main source file");
16706     DirectiveLoc = getSourceManager().getIncludeLoc(File);
16707   } else {
16708     // We reached an EOM pragma. Use the pragma location.
16709     DirectiveLoc = EomLoc;
16710   }
16711   BuildModuleInclude(DirectiveLoc, Mod);
16712 
16713   // Any further declarations are in whatever module we returned to.
16714   if (getLangOpts().trackLocalOwningModule()) {
16715     // The parser guarantees that this is the same context that we entered
16716     // the module within.
16717     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16718       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
16719       if (!getCurrentModule())
16720         cast<Decl>(DC)->setModuleOwnershipKind(
16721             Decl::ModuleOwnershipKind::Unowned);
16722     }
16723   }
16724 }
16725 
16726 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
16727                                                       Module *Mod) {
16728   // Bail if we're not allowed to implicitly import a module here.
16729   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
16730       VisibleModules.isVisible(Mod))
16731     return;
16732 
16733   // Create the implicit import declaration.
16734   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16735   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16736                                                    Loc, Mod, Loc);
16737   TU->addDecl(ImportD);
16738   Consumer.HandleImplicitImportDecl(ImportD);
16739 
16740   // Make the module visible.
16741   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
16742   VisibleModules.setVisible(Mod, Loc);
16743 }
16744 
16745 /// We have parsed the start of an export declaration, including the '{'
16746 /// (if present).
16747 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
16748                                  SourceLocation LBraceLoc) {
16749   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
16750 
16751   // C++ Modules TS draft:
16752   //   An export-declaration shall appear in the purview of a module other than
16753   //   the global module.
16754   if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface)
16755     Diag(ExportLoc, diag::err_export_not_in_module_interface);
16756 
16757   //   An export-declaration [...] shall not contain more than one
16758   //   export keyword.
16759   //
16760   // The intent here is that an export-declaration cannot appear within another
16761   // export-declaration.
16762   if (D->isExported())
16763     Diag(ExportLoc, diag::err_export_within_export);
16764 
16765   CurContext->addDecl(D);
16766   PushDeclContext(S, D);
16767   D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
16768   return D;
16769 }
16770 
16771 /// Complete the definition of an export declaration.
16772 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
16773   auto *ED = cast<ExportDecl>(D);
16774   if (RBraceLoc.isValid())
16775     ED->setRBraceLoc(RBraceLoc);
16776 
16777   // FIXME: Diagnose export of internal-linkage declaration (including
16778   // anonymous namespace).
16779 
16780   PopDeclContext();
16781   return D;
16782 }
16783 
16784 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
16785                                       IdentifierInfo* AliasName,
16786                                       SourceLocation PragmaLoc,
16787                                       SourceLocation NameLoc,
16788                                       SourceLocation AliasNameLoc) {
16789   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
16790                                          LookupOrdinaryName);
16791   AsmLabelAttr *Attr =
16792       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
16793 
16794   // If a declaration that:
16795   // 1) declares a function or a variable
16796   // 2) has external linkage
16797   // already exists, add a label attribute to it.
16798   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16799     if (isDeclExternC(PrevDecl))
16800       PrevDecl->addAttr(Attr);
16801     else
16802       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
16803           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
16804   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
16805   } else
16806     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
16807 }
16808 
16809 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
16810                              SourceLocation PragmaLoc,
16811                              SourceLocation NameLoc) {
16812   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
16813 
16814   if (PrevDecl) {
16815     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
16816   } else {
16817     (void)WeakUndeclaredIdentifiers.insert(
16818       std::pair<IdentifierInfo*,WeakInfo>
16819         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
16820   }
16821 }
16822 
16823 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
16824                                 IdentifierInfo* AliasName,
16825                                 SourceLocation PragmaLoc,
16826                                 SourceLocation NameLoc,
16827                                 SourceLocation AliasNameLoc) {
16828   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
16829                                     LookupOrdinaryName);
16830   WeakInfo W = WeakInfo(Name, NameLoc);
16831 
16832   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16833     if (!PrevDecl->hasAttr<AliasAttr>())
16834       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
16835         DeclApplyPragmaWeak(TUScope, ND, W);
16836   } else {
16837     (void)WeakUndeclaredIdentifiers.insert(
16838       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
16839   }
16840 }
16841 
16842 Decl *Sema::getObjCDeclContext() const {
16843   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
16844 }
16845