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 /// \brief 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   default:
152     break;
153   }
154 
155   return false;
156 }
157 
158 namespace {
159 enum class UnqualifiedTypeNameLookupResult {
160   NotFound,
161   FoundNonType,
162   FoundType
163 };
164 } // end anonymous namespace
165 
166 /// \brief Tries to perform unqualified lookup of the type decls in bases for
167 /// dependent class.
168 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
169 /// type decl, \a FoundType if only type decls are found.
170 static UnqualifiedTypeNameLookupResult
171 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
172                                 SourceLocation NameLoc,
173                                 const CXXRecordDecl *RD) {
174   if (!RD->hasDefinition())
175     return UnqualifiedTypeNameLookupResult::NotFound;
176   // Look for type decls in base classes.
177   UnqualifiedTypeNameLookupResult FoundTypeDecl =
178       UnqualifiedTypeNameLookupResult::NotFound;
179   for (const auto &Base : RD->bases()) {
180     const CXXRecordDecl *BaseRD = nullptr;
181     if (auto *BaseTT = Base.getType()->getAs<TagType>())
182       BaseRD = BaseTT->getAsCXXRecordDecl();
183     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
184       // Look for type decls in dependent base classes that have known primary
185       // templates.
186       if (!TST || !TST->isDependentType())
187         continue;
188       auto *TD = TST->getTemplateName().getAsTemplateDecl();
189       if (!TD)
190         continue;
191       if (auto *BasePrimaryTemplate =
192           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
193         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
194           BaseRD = BasePrimaryTemplate;
195         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
196           if (const ClassTemplatePartialSpecializationDecl *PS =
197                   CTD->findPartialSpecialization(Base.getType()))
198             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
199               BaseRD = PS;
200         }
201       }
202     }
203     if (BaseRD) {
204       for (NamedDecl *ND : BaseRD->lookup(&II)) {
205         if (!isa<TypeDecl>(ND))
206           return UnqualifiedTypeNameLookupResult::FoundNonType;
207         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
208       }
209       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
210         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
211         case UnqualifiedTypeNameLookupResult::FoundNonType:
212           return UnqualifiedTypeNameLookupResult::FoundNonType;
213         case UnqualifiedTypeNameLookupResult::FoundType:
214           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
215           break;
216         case UnqualifiedTypeNameLookupResult::NotFound:
217           break;
218         }
219       }
220     }
221   }
222 
223   return FoundTypeDecl;
224 }
225 
226 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
227                                                       const IdentifierInfo &II,
228                                                       SourceLocation NameLoc) {
229   // Lookup in the parent class template context, if any.
230   const CXXRecordDecl *RD = nullptr;
231   UnqualifiedTypeNameLookupResult FoundTypeDecl =
232       UnqualifiedTypeNameLookupResult::NotFound;
233   for (DeclContext *DC = S.CurContext;
234        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
235        DC = DC->getParent()) {
236     // Look for type decls in dependent base classes that have known primary
237     // templates.
238     RD = dyn_cast<CXXRecordDecl>(DC);
239     if (RD && RD->getDescribedClassTemplate())
240       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
241   }
242   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
243     return nullptr;
244 
245   // We found some types in dependent base classes.  Recover as if the user
246   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
247   // lookup during template instantiation.
248   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
249 
250   ASTContext &Context = S.Context;
251   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
252                                           cast<Type>(Context.getRecordType(RD)));
253   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
254 
255   CXXScopeSpec SS;
256   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
257 
258   TypeLocBuilder Builder;
259   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
260   DepTL.setNameLoc(NameLoc);
261   DepTL.setElaboratedKeywordLoc(SourceLocation());
262   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
263   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
264 }
265 
266 /// \brief If the identifier refers to a type name within this scope,
267 /// return the declaration of that type.
268 ///
269 /// This routine performs ordinary name lookup of the identifier II
270 /// within the given scope, with optional C++ scope specifier SS, to
271 /// determine whether the name refers to a type. If so, returns an
272 /// opaque pointer (actually a QualType) corresponding to that
273 /// type. Otherwise, returns NULL.
274 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
275                              Scope *S, CXXScopeSpec *SS,
276                              bool isClassName, bool HasTrailingDot,
277                              ParsedType ObjectTypePtr,
278                              bool IsCtorOrDtorName,
279                              bool WantNontrivialTypeSourceInfo,
280                              bool IsClassTemplateDeductionContext,
281                              IdentifierInfo **CorrectedII) {
282   // FIXME: Consider allowing this outside C++1z mode as an extension.
283   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
284                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
285                               !isClassName && !HasTrailingDot;
286 
287   // Determine where we will perform name lookup.
288   DeclContext *LookupCtx = nullptr;
289   if (ObjectTypePtr) {
290     QualType ObjectType = ObjectTypePtr.get();
291     if (ObjectType->isRecordType())
292       LookupCtx = computeDeclContext(ObjectType);
293   } else if (SS && SS->isNotEmpty()) {
294     LookupCtx = computeDeclContext(*SS, false);
295 
296     if (!LookupCtx) {
297       if (isDependentScopeSpecifier(*SS)) {
298         // C++ [temp.res]p3:
299         //   A qualified-id that refers to a type and in which the
300         //   nested-name-specifier depends on a template-parameter (14.6.2)
301         //   shall be prefixed by the keyword typename to indicate that the
302         //   qualified-id denotes a type, forming an
303         //   elaborated-type-specifier (7.1.5.3).
304         //
305         // We therefore do not perform any name lookup if the result would
306         // refer to a member of an unknown specialization.
307         if (!isClassName && !IsCtorOrDtorName)
308           return nullptr;
309 
310         // We know from the grammar that this name refers to a type,
311         // so build a dependent node to describe the type.
312         if (WantNontrivialTypeSourceInfo)
313           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
314 
315         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
316         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
317                                        II, NameLoc);
318         return ParsedType::make(T);
319       }
320 
321       return nullptr;
322     }
323 
324     if (!LookupCtx->isDependentContext() &&
325         RequireCompleteDeclContext(*SS, LookupCtx))
326       return nullptr;
327   }
328 
329   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
330   // lookup for class-names.
331   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
332                                       LookupOrdinaryName;
333   LookupResult Result(*this, &II, NameLoc, Kind);
334   if (LookupCtx) {
335     // Perform "qualified" name lookup into the declaration context we
336     // computed, which is either the type of the base of a member access
337     // expression or the declaration context associated with a prior
338     // nested-name-specifier.
339     LookupQualifiedName(Result, LookupCtx);
340 
341     if (ObjectTypePtr && Result.empty()) {
342       // C++ [basic.lookup.classref]p3:
343       //   If the unqualified-id is ~type-name, the type-name is looked up
344       //   in the context of the entire postfix-expression. If the type T of
345       //   the object expression is of a class type C, the type-name is also
346       //   looked up in the scope of class C. At least one of the lookups shall
347       //   find a name that refers to (possibly cv-qualified) T.
348       LookupName(Result, S);
349     }
350   } else {
351     // Perform unqualified name lookup.
352     LookupName(Result, S);
353 
354     // For unqualified lookup in a class template in MSVC mode, look into
355     // dependent base classes where the primary class template is known.
356     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
357       if (ParsedType TypeInBase =
358               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
359         return TypeInBase;
360     }
361   }
362 
363   NamedDecl *IIDecl = nullptr;
364   switch (Result.getResultKind()) {
365   case LookupResult::NotFound:
366   case LookupResult::NotFoundInCurrentInstantiation:
367     if (CorrectedII) {
368       TypoCorrection Correction =
369           CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
370                       llvm::make_unique<TypeNameValidatorCCC>(
371                           true, isClassName, AllowDeducedTemplate),
372                       CTK_ErrorRecovery);
373       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
374       TemplateTy Template;
375       bool MemberOfUnknownSpecialization;
376       UnqualifiedId TemplateName;
377       TemplateName.setIdentifier(NewII, NameLoc);
378       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
379       CXXScopeSpec NewSS, *NewSSPtr = SS;
380       if (SS && NNS) {
381         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
382         NewSSPtr = &NewSS;
383       }
384       if (Correction && (NNS || NewII != &II) &&
385           // Ignore a correction to a template type as the to-be-corrected
386           // identifier is not a template (typo correction for template names
387           // is handled elsewhere).
388           !(getLangOpts().CPlusPlus && NewSSPtr &&
389             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
390                            Template, MemberOfUnknownSpecialization))) {
391         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
392                                     isClassName, HasTrailingDot, ObjectTypePtr,
393                                     IsCtorOrDtorName,
394                                     WantNontrivialTypeSourceInfo,
395                                     IsClassTemplateDeductionContext);
396         if (Ty) {
397           diagnoseTypo(Correction,
398                        PDiag(diag::err_unknown_type_or_class_name_suggest)
399                          << Result.getLookupName() << isClassName);
400           if (SS && NNS)
401             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
402           *CorrectedII = NewII;
403           return Ty;
404         }
405       }
406     }
407     // If typo correction failed or was not performed, fall through
408     LLVM_FALLTHROUGH;
409   case LookupResult::FoundOverloaded:
410   case LookupResult::FoundUnresolvedValue:
411     Result.suppressDiagnostics();
412     return nullptr;
413 
414   case LookupResult::Ambiguous:
415     // Recover from type-hiding ambiguities by hiding the type.  We'll
416     // do the lookup again when looking for an object, and we can
417     // diagnose the error then.  If we don't do this, then the error
418     // about hiding the type will be immediately followed by an error
419     // that only makes sense if the identifier was treated like a type.
420     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
421       Result.suppressDiagnostics();
422       return nullptr;
423     }
424 
425     // Look to see if we have a type anywhere in the list of results.
426     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
427          Res != ResEnd; ++Res) {
428       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
429           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
430         if (!IIDecl ||
431             (*Res)->getLocation().getRawEncoding() <
432               IIDecl->getLocation().getRawEncoding())
433           IIDecl = *Res;
434       }
435     }
436 
437     if (!IIDecl) {
438       // None of the entities we found is a type, so there is no way
439       // to even assume that the result is a type. In this case, don't
440       // complain about the ambiguity. The parser will either try to
441       // perform this lookup again (e.g., as an object name), which
442       // will produce the ambiguity, or will complain that it expected
443       // a type name.
444       Result.suppressDiagnostics();
445       return nullptr;
446     }
447 
448     // We found a type within the ambiguous lookup; diagnose the
449     // ambiguity and then return that type. This might be the right
450     // answer, or it might not be, but it suppresses any attempt to
451     // perform the name lookup again.
452     break;
453 
454   case LookupResult::Found:
455     IIDecl = Result.getFoundDecl();
456     break;
457   }
458 
459   assert(IIDecl && "Didn't find decl");
460 
461   QualType T;
462   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
463     // C++ [class.qual]p2: A lookup that would find the injected-class-name
464     // instead names the constructors of the class, except when naming a class.
465     // This is ill-formed when we're not actually forming a ctor or dtor name.
466     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
467     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
468     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
469         FoundRD->isInjectedClassName() &&
470         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
471       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
472           << &II << /*Type*/1;
473 
474     DiagnoseUseOfDecl(IIDecl, NameLoc);
475 
476     T = Context.getTypeDeclType(TD);
477     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
478   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
479     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
480     if (!HasTrailingDot)
481       T = Context.getObjCInterfaceType(IDecl);
482   } else if (AllowDeducedTemplate) {
483     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
484       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
485                                                        QualType(), false);
486   }
487 
488   if (T.isNull()) {
489     // If it's not plausibly a type, suppress diagnostics.
490     Result.suppressDiagnostics();
491     return nullptr;
492   }
493 
494   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
495   // constructor or destructor name (in such a case, the scope specifier
496   // will be attached to the enclosing Expr or Decl node).
497   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
498       !isa<ObjCInterfaceDecl>(IIDecl)) {
499     if (WantNontrivialTypeSourceInfo) {
500       // Construct a type with type-source information.
501       TypeLocBuilder Builder;
502       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
503 
504       T = getElaboratedType(ETK_None, *SS, T);
505       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
506       ElabTL.setElaboratedKeywordLoc(SourceLocation());
507       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
508       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
509     } else {
510       T = getElaboratedType(ETK_None, *SS, T);
511     }
512   }
513 
514   return ParsedType::make(T);
515 }
516 
517 // Builds a fake NNS for the given decl context.
518 static NestedNameSpecifier *
519 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
520   for (;; DC = DC->getLookupParent()) {
521     DC = DC->getPrimaryContext();
522     auto *ND = dyn_cast<NamespaceDecl>(DC);
523     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
524       return NestedNameSpecifier::Create(Context, nullptr, ND);
525     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
526       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
527                                          RD->getTypeForDecl());
528     else if (isa<TranslationUnitDecl>(DC))
529       return NestedNameSpecifier::GlobalSpecifier(Context);
530   }
531   llvm_unreachable("something isn't in TU scope?");
532 }
533 
534 /// Find the parent class with dependent bases of the innermost enclosing method
535 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
536 /// up allowing unqualified dependent type names at class-level, which MSVC
537 /// correctly rejects.
538 static const CXXRecordDecl *
539 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
540   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
541     DC = DC->getPrimaryContext();
542     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
543       if (MD->getParent()->hasAnyDependentBases())
544         return MD->getParent();
545   }
546   return nullptr;
547 }
548 
549 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
550                                           SourceLocation NameLoc,
551                                           bool IsTemplateTypeArg) {
552   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
553 
554   NestedNameSpecifier *NNS = nullptr;
555   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
556     // If we weren't able to parse a default template argument, delay lookup
557     // until instantiation time by making a non-dependent DependentTypeName. We
558     // pretend we saw a NestedNameSpecifier referring to the current scope, and
559     // lookup is retried.
560     // FIXME: This hurts our diagnostic quality, since we get errors like "no
561     // type named 'Foo' in 'current_namespace'" when the user didn't write any
562     // name specifiers.
563     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
564     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
565   } else if (const CXXRecordDecl *RD =
566                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
567     // Build a DependentNameType that will perform lookup into RD at
568     // instantiation time.
569     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
570                                       RD->getTypeForDecl());
571 
572     // Diagnose that this identifier was undeclared, and retry the lookup during
573     // template instantiation.
574     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
575                                                                       << RD;
576   } else {
577     // This is not a situation that we should recover from.
578     return ParsedType();
579   }
580 
581   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
582 
583   // Build type location information.  We synthesized the qualifier, so we have
584   // to build a fake NestedNameSpecifierLoc.
585   NestedNameSpecifierLocBuilder NNSLocBuilder;
586   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
587   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
588 
589   TypeLocBuilder Builder;
590   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
591   DepTL.setNameLoc(NameLoc);
592   DepTL.setElaboratedKeywordLoc(SourceLocation());
593   DepTL.setQualifierLoc(QualifierLoc);
594   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
595 }
596 
597 /// isTagName() - This method is called *for error recovery purposes only*
598 /// to determine if the specified name is a valid tag name ("struct foo").  If
599 /// so, this returns the TST for the tag corresponding to it (TST_enum,
600 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
601 /// cases in C where the user forgot to specify the tag.
602 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
603   // Do a tag name lookup in this scope.
604   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
605   LookupName(R, S, false);
606   R.suppressDiagnostics();
607   if (R.getResultKind() == LookupResult::Found)
608     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
609       switch (TD->getTagKind()) {
610       case TTK_Struct: return DeclSpec::TST_struct;
611       case TTK_Interface: return DeclSpec::TST_interface;
612       case TTK_Union:  return DeclSpec::TST_union;
613       case TTK_Class:  return DeclSpec::TST_class;
614       case TTK_Enum:   return DeclSpec::TST_enum;
615       }
616     }
617 
618   return DeclSpec::TST_unspecified;
619 }
620 
621 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
622 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
623 /// then downgrade the missing typename error to a warning.
624 /// This is needed for MSVC compatibility; Example:
625 /// @code
626 /// template<class T> class A {
627 /// public:
628 ///   typedef int TYPE;
629 /// };
630 /// template<class T> class B : public A<T> {
631 /// public:
632 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
633 /// };
634 /// @endcode
635 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
636   if (CurContext->isRecord()) {
637     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
638       return true;
639 
640     const Type *Ty = SS->getScopeRep()->getAsType();
641 
642     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
643     for (const auto &Base : RD->bases())
644       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
645         return true;
646     return S->isFunctionPrototypeScope();
647   }
648   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
649 }
650 
651 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
652                                    SourceLocation IILoc,
653                                    Scope *S,
654                                    CXXScopeSpec *SS,
655                                    ParsedType &SuggestedType,
656                                    bool IsTemplateName) {
657   // Don't report typename errors for editor placeholders.
658   if (II->isEditorPlaceholder())
659     return;
660   // We don't have anything to suggest (yet).
661   SuggestedType = nullptr;
662 
663   // There may have been a typo in the name of the type. Look up typo
664   // results, in case we have something that we can suggest.
665   if (TypoCorrection Corrected =
666           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
667                       llvm::make_unique<TypeNameValidatorCCC>(
668                           false, false, IsTemplateName, !IsTemplateName),
669                       CTK_ErrorRecovery)) {
670     // FIXME: Support error recovery for the template-name case.
671     bool CanRecover = !IsTemplateName;
672     if (Corrected.isKeyword()) {
673       // We corrected to a keyword.
674       diagnoseTypo(Corrected,
675                    PDiag(IsTemplateName ? diag::err_no_template_suggest
676                                         : diag::err_unknown_typename_suggest)
677                        << II);
678       II = Corrected.getCorrectionAsIdentifierInfo();
679     } else {
680       // We found a similarly-named type or interface; suggest that.
681       if (!SS || !SS->isSet()) {
682         diagnoseTypo(Corrected,
683                      PDiag(IsTemplateName ? diag::err_no_template_suggest
684                                           : diag::err_unknown_typename_suggest)
685                          << II, CanRecover);
686       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
687         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
688         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
689                                 II->getName().equals(CorrectedStr);
690         diagnoseTypo(Corrected,
691                      PDiag(IsTemplateName
692                                ? diag::err_no_member_template_suggest
693                                : diag::err_unknown_nested_typename_suggest)
694                          << II << DC << DroppedSpecifier << SS->getRange(),
695                      CanRecover);
696       } else {
697         llvm_unreachable("could not have corrected a typo here");
698       }
699 
700       if (!CanRecover)
701         return;
702 
703       CXXScopeSpec tmpSS;
704       if (Corrected.getCorrectionSpecifier())
705         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
706                           SourceRange(IILoc));
707       // FIXME: Support class template argument deduction here.
708       SuggestedType =
709           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
710                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
711                       /*IsCtorOrDtorName=*/false,
712                       /*NonTrivialTypeSourceInfo=*/true);
713     }
714     return;
715   }
716 
717   if (getLangOpts().CPlusPlus && !IsTemplateName) {
718     // See if II is a class template that the user forgot to pass arguments to.
719     UnqualifiedId Name;
720     Name.setIdentifier(II, IILoc);
721     CXXScopeSpec EmptySS;
722     TemplateTy TemplateResult;
723     bool MemberOfUnknownSpecialization;
724     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
725                        Name, nullptr, true, TemplateResult,
726                        MemberOfUnknownSpecialization) == TNK_Type_template) {
727       TemplateName TplName = TemplateResult.get();
728       Diag(IILoc, diag::err_template_missing_args)
729         << (int)getTemplateNameKindForDiagnostics(TplName) << TplName;
730       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
731         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
732           << TplDecl->getTemplateParameters()->getSourceRange();
733       }
734       return;
735     }
736   }
737 
738   // FIXME: Should we move the logic that tries to recover from a missing tag
739   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
740 
741   if (!SS || (!SS->isSet() && !SS->isInvalid()))
742     Diag(IILoc, IsTemplateName ? diag::err_no_template
743                                : diag::err_unknown_typename)
744         << II;
745   else if (DeclContext *DC = computeDeclContext(*SS, false))
746     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
747                                : diag::err_typename_nested_not_found)
748         << II << DC << SS->getRange();
749   else if (isDependentScopeSpecifier(*SS)) {
750     unsigned DiagID = diag::err_typename_missing;
751     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
752       DiagID = diag::ext_typename_missing;
753 
754     Diag(SS->getRange().getBegin(), DiagID)
755       << SS->getScopeRep() << II->getName()
756       << SourceRange(SS->getRange().getBegin(), IILoc)
757       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
758     SuggestedType = ActOnTypenameType(S, SourceLocation(),
759                                       *SS, *II, IILoc).get();
760   } else {
761     assert(SS && SS->isInvalid() &&
762            "Invalid scope specifier has already been diagnosed");
763   }
764 }
765 
766 /// \brief Determine whether the given result set contains either a type name
767 /// or
768 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
769   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
770                        NextToken.is(tok::less);
771 
772   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
773     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
774       return true;
775 
776     if (CheckTemplate && isa<TemplateDecl>(*I))
777       return true;
778   }
779 
780   return false;
781 }
782 
783 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
784                                     Scope *S, CXXScopeSpec &SS,
785                                     IdentifierInfo *&Name,
786                                     SourceLocation NameLoc) {
787   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
788   SemaRef.LookupParsedName(R, S, &SS);
789   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
790     StringRef FixItTagName;
791     switch (Tag->getTagKind()) {
792       case TTK_Class:
793         FixItTagName = "class ";
794         break;
795 
796       case TTK_Enum:
797         FixItTagName = "enum ";
798         break;
799 
800       case TTK_Struct:
801         FixItTagName = "struct ";
802         break;
803 
804       case TTK_Interface:
805         FixItTagName = "__interface ";
806         break;
807 
808       case TTK_Union:
809         FixItTagName = "union ";
810         break;
811     }
812 
813     StringRef TagName = FixItTagName.drop_back();
814     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
815       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
816       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
817 
818     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
819          I != IEnd; ++I)
820       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
821         << Name << TagName;
822 
823     // Replace lookup results with just the tag decl.
824     Result.clear(Sema::LookupTagName);
825     SemaRef.LookupParsedName(Result, S, &SS);
826     return true;
827   }
828 
829   return false;
830 }
831 
832 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
833 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
834                                   QualType T, SourceLocation NameLoc) {
835   ASTContext &Context = S.Context;
836 
837   TypeLocBuilder Builder;
838   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
839 
840   T = S.getElaboratedType(ETK_None, SS, T);
841   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
842   ElabTL.setElaboratedKeywordLoc(SourceLocation());
843   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
844   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
845 }
846 
847 Sema::NameClassification
848 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
849                    SourceLocation NameLoc, const Token &NextToken,
850                    bool IsAddressOfOperand,
851                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
852   DeclarationNameInfo NameInfo(Name, NameLoc);
853   ObjCMethodDecl *CurMethod = getCurMethodDecl();
854 
855   if (NextToken.is(tok::coloncolon)) {
856     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
857     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
858   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
859              isCurrentClassName(*Name, S, &SS)) {
860     // Per [class.qual]p2, this names the constructors of SS, not the
861     // injected-class-name. We don't have a classification for that.
862     // There's not much point caching this result, since the parser
863     // will reject it later.
864     return NameClassification::Unknown();
865   }
866 
867   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
868   LookupParsedName(Result, S, &SS, !CurMethod);
869 
870   // For unqualified lookup in a class template in MSVC mode, look into
871   // dependent base classes where the primary class template is known.
872   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
873     if (ParsedType TypeInBase =
874             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
875       return TypeInBase;
876   }
877 
878   // Perform lookup for Objective-C instance variables (including automatically
879   // synthesized instance variables), if we're in an Objective-C method.
880   // FIXME: This lookup really, really needs to be folded in to the normal
881   // unqualified lookup mechanism.
882   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
883     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
884     if (E.get() || E.isInvalid())
885       return E;
886   }
887 
888   bool SecondTry = false;
889   bool IsFilteredTemplateName = false;
890 
891 Corrected:
892   switch (Result.getResultKind()) {
893   case LookupResult::NotFound:
894     // If an unqualified-id is followed by a '(', then we have a function
895     // call.
896     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
897       // In C++, this is an ADL-only call.
898       // FIXME: Reference?
899       if (getLangOpts().CPlusPlus)
900         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
901 
902       // C90 6.3.2.2:
903       //   If the expression that precedes the parenthesized argument list in a
904       //   function call consists solely of an identifier, and if no
905       //   declaration is visible for this identifier, the identifier is
906       //   implicitly declared exactly as if, in the innermost block containing
907       //   the function call, the declaration
908       //
909       //     extern int identifier ();
910       //
911       //   appeared.
912       //
913       // We also allow this in C99 as an extension.
914       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
915         Result.addDecl(D);
916         Result.resolveKind();
917         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
918       }
919     }
920 
921     // In C, we first see whether there is a tag type by the same name, in
922     // which case it's likely that the user just forgot to write "enum",
923     // "struct", or "union".
924     if (!getLangOpts().CPlusPlus && !SecondTry &&
925         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
926       break;
927     }
928 
929     // Perform typo correction to determine if there is another name that is
930     // close to this name.
931     if (!SecondTry && CCC) {
932       SecondTry = true;
933       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
934                                                  Result.getLookupKind(), S,
935                                                  &SS, std::move(CCC),
936                                                  CTK_ErrorRecovery)) {
937         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
938         unsigned QualifiedDiag = diag::err_no_member_suggest;
939 
940         NamedDecl *FirstDecl = Corrected.getFoundDecl();
941         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
942         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
943             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
944           UnqualifiedDiag = diag::err_no_template_suggest;
945           QualifiedDiag = diag::err_no_member_template_suggest;
946         } else if (UnderlyingFirstDecl &&
947                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
948                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
949                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
950           UnqualifiedDiag = diag::err_unknown_typename_suggest;
951           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
952         }
953 
954         if (SS.isEmpty()) {
955           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
956         } else {// FIXME: is this even reachable? Test it.
957           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
958           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
959                                   Name->getName().equals(CorrectedStr);
960           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
961                                     << Name << computeDeclContext(SS, false)
962                                     << DroppedSpecifier << SS.getRange());
963         }
964 
965         // Update the name, so that the caller has the new name.
966         Name = Corrected.getCorrectionAsIdentifierInfo();
967 
968         // Typo correction corrected to a keyword.
969         if (Corrected.isKeyword())
970           return Name;
971 
972         // Also update the LookupResult...
973         // FIXME: This should probably go away at some point
974         Result.clear();
975         Result.setLookupName(Corrected.getCorrection());
976         if (FirstDecl)
977           Result.addDecl(FirstDecl);
978 
979         // If we found an Objective-C instance variable, let
980         // LookupInObjCMethod build the appropriate expression to
981         // reference the ivar.
982         // FIXME: This is a gross hack.
983         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
984           Result.clear();
985           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
986           return E;
987         }
988 
989         goto Corrected;
990       }
991     }
992 
993     // We failed to correct; just fall through and let the parser deal with it.
994     Result.suppressDiagnostics();
995     return NameClassification::Unknown();
996 
997   case LookupResult::NotFoundInCurrentInstantiation: {
998     // We performed name lookup into the current instantiation, and there were
999     // dependent bases, so we treat this result the same way as any other
1000     // dependent nested-name-specifier.
1001 
1002     // C++ [temp.res]p2:
1003     //   A name used in a template declaration or definition and that is
1004     //   dependent on a template-parameter is assumed not to name a type
1005     //   unless the applicable name lookup finds a type name or the name is
1006     //   qualified by the keyword typename.
1007     //
1008     // FIXME: If the next token is '<', we might want to ask the parser to
1009     // perform some heroics to see if we actually have a
1010     // template-argument-list, which would indicate a missing 'template'
1011     // keyword here.
1012     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1013                                       NameInfo, IsAddressOfOperand,
1014                                       /*TemplateArgs=*/nullptr);
1015   }
1016 
1017   case LookupResult::Found:
1018   case LookupResult::FoundOverloaded:
1019   case LookupResult::FoundUnresolvedValue:
1020     break;
1021 
1022   case LookupResult::Ambiguous:
1023     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1024         hasAnyAcceptableTemplateNames(Result)) {
1025       // C++ [temp.local]p3:
1026       //   A lookup that finds an injected-class-name (10.2) can result in an
1027       //   ambiguity in certain cases (for example, if it is found in more than
1028       //   one base class). If all of the injected-class-names that are found
1029       //   refer to specializations of the same class template, and if the name
1030       //   is followed by a template-argument-list, the reference refers to the
1031       //   class template itself and not a specialization thereof, and is not
1032       //   ambiguous.
1033       //
1034       // This filtering can make an ambiguous result into an unambiguous one,
1035       // so try again after filtering out template names.
1036       FilterAcceptableTemplateNames(Result);
1037       if (!Result.isAmbiguous()) {
1038         IsFilteredTemplateName = true;
1039         break;
1040       }
1041     }
1042 
1043     // Diagnose the ambiguity and return an error.
1044     return NameClassification::Error();
1045   }
1046 
1047   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1048       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
1049     // C++ [temp.names]p3:
1050     //   After name lookup (3.4) finds that a name is a template-name or that
1051     //   an operator-function-id or a literal- operator-id refers to a set of
1052     //   overloaded functions any member of which is a function template if
1053     //   this is followed by a <, the < is always taken as the delimiter of a
1054     //   template-argument-list and never as the less-than operator.
1055     if (!IsFilteredTemplateName)
1056       FilterAcceptableTemplateNames(Result);
1057 
1058     if (!Result.empty()) {
1059       bool IsFunctionTemplate;
1060       bool IsVarTemplate;
1061       TemplateName Template;
1062       if (Result.end() - Result.begin() > 1) {
1063         IsFunctionTemplate = true;
1064         Template = Context.getOverloadedTemplateName(Result.begin(),
1065                                                      Result.end());
1066       } else {
1067         TemplateDecl *TD
1068           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1069         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1070         IsVarTemplate = isa<VarTemplateDecl>(TD);
1071 
1072         if (SS.isSet() && !SS.isInvalid())
1073           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1074                                                     /*TemplateKeyword=*/false,
1075                                                       TD);
1076         else
1077           Template = TemplateName(TD);
1078       }
1079 
1080       if (IsFunctionTemplate) {
1081         // Function templates always go through overload resolution, at which
1082         // point we'll perform the various checks (e.g., accessibility) we need
1083         // to based on which function we selected.
1084         Result.suppressDiagnostics();
1085 
1086         return NameClassification::FunctionTemplate(Template);
1087       }
1088 
1089       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1090                            : NameClassification::TypeTemplate(Template);
1091     }
1092   }
1093 
1094   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1095   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1096     DiagnoseUseOfDecl(Type, NameLoc);
1097     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1098     QualType T = Context.getTypeDeclType(Type);
1099     if (SS.isNotEmpty())
1100       return buildNestedType(*this, SS, T, NameLoc);
1101     return ParsedType::make(T);
1102   }
1103 
1104   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1105   if (!Class) {
1106     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1107     if (ObjCCompatibleAliasDecl *Alias =
1108             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1109       Class = Alias->getClassInterface();
1110   }
1111 
1112   if (Class) {
1113     DiagnoseUseOfDecl(Class, NameLoc);
1114 
1115     if (NextToken.is(tok::period)) {
1116       // Interface. <something> is parsed as a property reference expression.
1117       // Just return "unknown" as a fall-through for now.
1118       Result.suppressDiagnostics();
1119       return NameClassification::Unknown();
1120     }
1121 
1122     QualType T = Context.getObjCInterfaceType(Class);
1123     return ParsedType::make(T);
1124   }
1125 
1126   // We can have a type template here if we're classifying a template argument.
1127   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1128       !isa<VarTemplateDecl>(FirstDecl))
1129     return NameClassification::TypeTemplate(
1130         TemplateName(cast<TemplateDecl>(FirstDecl)));
1131 
1132   // Check for a tag type hidden by a non-type decl in a few cases where it
1133   // seems likely a type is wanted instead of the non-type that was found.
1134   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1135   if ((NextToken.is(tok::identifier) ||
1136        (NextIsOp &&
1137         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1138       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1139     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1140     DiagnoseUseOfDecl(Type, NameLoc);
1141     QualType T = Context.getTypeDeclType(Type);
1142     if (SS.isNotEmpty())
1143       return buildNestedType(*this, SS, T, NameLoc);
1144     return ParsedType::make(T);
1145   }
1146 
1147   if (FirstDecl->isCXXClassMember())
1148     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1149                                            nullptr, S);
1150 
1151   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1152   return BuildDeclarationNameExpr(SS, Result, ADL);
1153 }
1154 
1155 Sema::TemplateNameKindForDiagnostics
1156 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1157   auto *TD = Name.getAsTemplateDecl();
1158   if (!TD)
1159     return TemplateNameKindForDiagnostics::DependentTemplate;
1160   if (isa<ClassTemplateDecl>(TD))
1161     return TemplateNameKindForDiagnostics::ClassTemplate;
1162   if (isa<FunctionTemplateDecl>(TD))
1163     return TemplateNameKindForDiagnostics::FunctionTemplate;
1164   if (isa<VarTemplateDecl>(TD))
1165     return TemplateNameKindForDiagnostics::VarTemplate;
1166   if (isa<TypeAliasTemplateDecl>(TD))
1167     return TemplateNameKindForDiagnostics::AliasTemplate;
1168   if (isa<TemplateTemplateParmDecl>(TD))
1169     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1170   return TemplateNameKindForDiagnostics::DependentTemplate;
1171 }
1172 
1173 // Determines the context to return to after temporarily entering a
1174 // context.  This depends in an unnecessarily complicated way on the
1175 // exact ordering of callbacks from the parser.
1176 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1177 
1178   // Functions defined inline within classes aren't parsed until we've
1179   // finished parsing the top-level class, so the top-level class is
1180   // the context we'll need to return to.
1181   // A Lambda call operator whose parent is a class must not be treated
1182   // as an inline member function.  A Lambda can be used legally
1183   // either as an in-class member initializer or a default argument.  These
1184   // are parsed once the class has been marked complete and so the containing
1185   // context would be the nested class (when the lambda is defined in one);
1186   // If the class is not complete, then the lambda is being used in an
1187   // ill-formed fashion (such as to specify the width of a bit-field, or
1188   // in an array-bound) - in which case we still want to return the
1189   // lexically containing DC (which could be a nested class).
1190   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1191     DC = DC->getLexicalParent();
1192 
1193     // A function not defined within a class will always return to its
1194     // lexical context.
1195     if (!isa<CXXRecordDecl>(DC))
1196       return DC;
1197 
1198     // A C++ inline method/friend is parsed *after* the topmost class
1199     // it was declared in is fully parsed ("complete");  the topmost
1200     // class is the context we need to return to.
1201     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1202       DC = RD;
1203 
1204     // Return the declaration context of the topmost class the inline method is
1205     // declared in.
1206     return DC;
1207   }
1208 
1209   return DC->getLexicalParent();
1210 }
1211 
1212 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1213   assert(getContainingDC(DC) == CurContext &&
1214       "The next DeclContext should be lexically contained in the current one.");
1215   CurContext = DC;
1216   S->setEntity(DC);
1217 }
1218 
1219 void Sema::PopDeclContext() {
1220   assert(CurContext && "DeclContext imbalance!");
1221 
1222   CurContext = getContainingDC(CurContext);
1223   assert(CurContext && "Popped translation unit!");
1224 }
1225 
1226 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1227                                                                     Decl *D) {
1228   // Unlike PushDeclContext, the context to which we return is not necessarily
1229   // the containing DC of TD, because the new context will be some pre-existing
1230   // TagDecl definition instead of a fresh one.
1231   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1232   CurContext = cast<TagDecl>(D)->getDefinition();
1233   assert(CurContext && "skipping definition of undefined tag");
1234   // Start lookups from the parent of the current context; we don't want to look
1235   // into the pre-existing complete definition.
1236   S->setEntity(CurContext->getLookupParent());
1237   return Result;
1238 }
1239 
1240 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1241   CurContext = static_cast<decltype(CurContext)>(Context);
1242 }
1243 
1244 /// EnterDeclaratorContext - Used when we must lookup names in the context
1245 /// of a declarator's nested name specifier.
1246 ///
1247 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1248   // C++0x [basic.lookup.unqual]p13:
1249   //   A name used in the definition of a static data member of class
1250   //   X (after the qualified-id of the static member) is looked up as
1251   //   if the name was used in a member function of X.
1252   // C++0x [basic.lookup.unqual]p14:
1253   //   If a variable member of a namespace is defined outside of the
1254   //   scope of its namespace then any name used in the definition of
1255   //   the variable member (after the declarator-id) is looked up as
1256   //   if the definition of the variable member occurred in its
1257   //   namespace.
1258   // Both of these imply that we should push a scope whose context
1259   // is the semantic context of the declaration.  We can't use
1260   // PushDeclContext here because that context is not necessarily
1261   // lexically contained in the current context.  Fortunately,
1262   // the containing scope should have the appropriate information.
1263 
1264   assert(!S->getEntity() && "scope already has entity");
1265 
1266 #ifndef NDEBUG
1267   Scope *Ancestor = S->getParent();
1268   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1269   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1270 #endif
1271 
1272   CurContext = DC;
1273   S->setEntity(DC);
1274 }
1275 
1276 void Sema::ExitDeclaratorContext(Scope *S) {
1277   assert(S->getEntity() == CurContext && "Context imbalance!");
1278 
1279   // Switch back to the lexical context.  The safety of this is
1280   // enforced by an assert in EnterDeclaratorContext.
1281   Scope *Ancestor = S->getParent();
1282   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1283   CurContext = Ancestor->getEntity();
1284 
1285   // We don't need to do anything with the scope, which is going to
1286   // disappear.
1287 }
1288 
1289 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1290   // We assume that the caller has already called
1291   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1292   FunctionDecl *FD = D->getAsFunction();
1293   if (!FD)
1294     return;
1295 
1296   // Same implementation as PushDeclContext, but enters the context
1297   // from the lexical parent, rather than the top-level class.
1298   assert(CurContext == FD->getLexicalParent() &&
1299     "The next DeclContext should be lexically contained in the current one.");
1300   CurContext = FD;
1301   S->setEntity(CurContext);
1302 
1303   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1304     ParmVarDecl *Param = FD->getParamDecl(P);
1305     // If the parameter has an identifier, then add it to the scope
1306     if (Param->getIdentifier()) {
1307       S->AddDecl(Param);
1308       IdResolver.AddDecl(Param);
1309     }
1310   }
1311 }
1312 
1313 void Sema::ActOnExitFunctionContext() {
1314   // Same implementation as PopDeclContext, but returns to the lexical parent,
1315   // rather than the top-level class.
1316   assert(CurContext && "DeclContext imbalance!");
1317   CurContext = CurContext->getLexicalParent();
1318   assert(CurContext && "Popped translation unit!");
1319 }
1320 
1321 /// \brief Determine whether we allow overloading of the function
1322 /// PrevDecl with another declaration.
1323 ///
1324 /// This routine determines whether overloading is possible, not
1325 /// whether some new function is actually an overload. It will return
1326 /// true in C++ (where we can always provide overloads) or, as an
1327 /// extension, in C when the previous function is already an
1328 /// overloaded function declaration or has the "overloadable"
1329 /// attribute.
1330 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1331                                        ASTContext &Context,
1332                                        const FunctionDecl *New) {
1333   if (Context.getLangOpts().CPlusPlus)
1334     return true;
1335 
1336   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1337     return true;
1338 
1339   return Previous.getResultKind() == LookupResult::Found &&
1340          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1341           New->hasAttr<OverloadableAttr>());
1342 }
1343 
1344 /// Add this decl to the scope shadowed decl chains.
1345 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1346   // Move up the scope chain until we find the nearest enclosing
1347   // non-transparent context. The declaration will be introduced into this
1348   // scope.
1349   while (S->getEntity() && S->getEntity()->isTransparentContext())
1350     S = S->getParent();
1351 
1352   // Add scoped declarations into their context, so that they can be
1353   // found later. Declarations without a context won't be inserted
1354   // into any context.
1355   if (AddToContext)
1356     CurContext->addDecl(D);
1357 
1358   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1359   // are function-local declarations.
1360   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1361       !D->getDeclContext()->getRedeclContext()->Equals(
1362         D->getLexicalDeclContext()->getRedeclContext()) &&
1363       !D->getLexicalDeclContext()->isFunctionOrMethod())
1364     return;
1365 
1366   // Template instantiations should also not be pushed into scope.
1367   if (isa<FunctionDecl>(D) &&
1368       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1369     return;
1370 
1371   // If this replaces anything in the current scope,
1372   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1373                                IEnd = IdResolver.end();
1374   for (; I != IEnd; ++I) {
1375     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1376       S->RemoveDecl(*I);
1377       IdResolver.RemoveDecl(*I);
1378 
1379       // Should only need to replace one decl.
1380       break;
1381     }
1382   }
1383 
1384   S->AddDecl(D);
1385 
1386   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1387     // Implicitly-generated labels may end up getting generated in an order that
1388     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1389     // the label at the appropriate place in the identifier chain.
1390     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1391       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1392       if (IDC == CurContext) {
1393         if (!S->isDeclScope(*I))
1394           continue;
1395       } else if (IDC->Encloses(CurContext))
1396         break;
1397     }
1398 
1399     IdResolver.InsertDeclAfter(I, D);
1400   } else {
1401     IdResolver.AddDecl(D);
1402   }
1403 }
1404 
1405 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1406   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1407     TUScope->AddDecl(D);
1408 }
1409 
1410 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1411                          bool AllowInlineNamespace) {
1412   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1413 }
1414 
1415 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1416   DeclContext *TargetDC = DC->getPrimaryContext();
1417   do {
1418     if (DeclContext *ScopeDC = S->getEntity())
1419       if (ScopeDC->getPrimaryContext() == TargetDC)
1420         return S;
1421   } while ((S = S->getParent()));
1422 
1423   return nullptr;
1424 }
1425 
1426 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1427                                             DeclContext*,
1428                                             ASTContext&);
1429 
1430 /// Filters out lookup results that don't fall within the given scope
1431 /// as determined by isDeclInScope.
1432 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1433                                 bool ConsiderLinkage,
1434                                 bool AllowInlineNamespace) {
1435   LookupResult::Filter F = R.makeFilter();
1436   while (F.hasNext()) {
1437     NamedDecl *D = F.next();
1438 
1439     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1440       continue;
1441 
1442     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1443       continue;
1444 
1445     F.erase();
1446   }
1447 
1448   F.done();
1449 }
1450 
1451 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1452 /// have compatible owning modules.
1453 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1454   // FIXME: The Modules TS is not clear about how friend declarations are
1455   // to be treated. It's not meaningful to have different owning modules for
1456   // linkage in redeclarations of the same entity, so for now allow the
1457   // redeclaration and change the owning modules to match.
1458   if (New->getFriendObjectKind() &&
1459       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1460     New->setLocalOwningModule(Old->getOwningModule());
1461     makeMergedDefinitionVisible(New);
1462     return false;
1463   }
1464 
1465   Module *NewM = New->getOwningModule();
1466   Module *OldM = Old->getOwningModule();
1467   if (NewM == OldM)
1468     return false;
1469 
1470   // FIXME: Check proclaimed-ownership-declarations here too.
1471   bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit;
1472   bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit;
1473   if (NewIsModuleInterface || OldIsModuleInterface) {
1474     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1475     //   if a declaration of D [...] appears in the purview of a module, all
1476     //   other such declarations shall appear in the purview of the same module
1477     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1478       << New
1479       << NewIsModuleInterface
1480       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1481       << OldIsModuleInterface
1482       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1483     Diag(Old->getLocation(), diag::note_previous_declaration);
1484     New->setInvalidDecl();
1485     return true;
1486   }
1487 
1488   return false;
1489 }
1490 
1491 static bool isUsingDecl(NamedDecl *D) {
1492   return isa<UsingShadowDecl>(D) ||
1493          isa<UnresolvedUsingTypenameDecl>(D) ||
1494          isa<UnresolvedUsingValueDecl>(D);
1495 }
1496 
1497 /// Removes using shadow declarations from the lookup results.
1498 static void RemoveUsingDecls(LookupResult &R) {
1499   LookupResult::Filter F = R.makeFilter();
1500   while (F.hasNext())
1501     if (isUsingDecl(F.next()))
1502       F.erase();
1503 
1504   F.done();
1505 }
1506 
1507 /// \brief Check for this common pattern:
1508 /// @code
1509 /// class S {
1510 ///   S(const S&); // DO NOT IMPLEMENT
1511 ///   void operator=(const S&); // DO NOT IMPLEMENT
1512 /// };
1513 /// @endcode
1514 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1515   // FIXME: Should check for private access too but access is set after we get
1516   // the decl here.
1517   if (D->doesThisDeclarationHaveABody())
1518     return false;
1519 
1520   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1521     return CD->isCopyConstructor();
1522   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1523     return Method->isCopyAssignmentOperator();
1524   return false;
1525 }
1526 
1527 // We need this to handle
1528 //
1529 // typedef struct {
1530 //   void *foo() { return 0; }
1531 // } A;
1532 //
1533 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1534 // for example. If 'A', foo will have external linkage. If we have '*A',
1535 // foo will have no linkage. Since we can't know until we get to the end
1536 // of the typedef, this function finds out if D might have non-external linkage.
1537 // Callers should verify at the end of the TU if it D has external linkage or
1538 // not.
1539 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1540   const DeclContext *DC = D->getDeclContext();
1541   while (!DC->isTranslationUnit()) {
1542     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1543       if (!RD->hasNameForLinkage())
1544         return true;
1545     }
1546     DC = DC->getParent();
1547   }
1548 
1549   return !D->isExternallyVisible();
1550 }
1551 
1552 // FIXME: This needs to be refactored; some other isInMainFile users want
1553 // these semantics.
1554 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1555   if (S.TUKind != TU_Complete)
1556     return false;
1557   return S.SourceMgr.isInMainFile(Loc);
1558 }
1559 
1560 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1561   assert(D);
1562 
1563   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1564     return false;
1565 
1566   // Ignore all entities declared within templates, and out-of-line definitions
1567   // of members of class templates.
1568   if (D->getDeclContext()->isDependentContext() ||
1569       D->getLexicalDeclContext()->isDependentContext())
1570     return false;
1571 
1572   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1573     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1574       return false;
1575     // A non-out-of-line declaration of a member specialization was implicitly
1576     // instantiated; it's the out-of-line declaration that we're interested in.
1577     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1578         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1579       return false;
1580 
1581     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1582       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1583         return false;
1584     } else {
1585       // 'static inline' functions are defined in headers; don't warn.
1586       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1587         return false;
1588     }
1589 
1590     if (FD->doesThisDeclarationHaveABody() &&
1591         Context.DeclMustBeEmitted(FD))
1592       return false;
1593   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1594     // Constants and utility variables are defined in headers with internal
1595     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1596     // like "inline".)
1597     if (!isMainFileLoc(*this, VD->getLocation()))
1598       return false;
1599 
1600     if (Context.DeclMustBeEmitted(VD))
1601       return false;
1602 
1603     if (VD->isStaticDataMember() &&
1604         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1605       return false;
1606     if (VD->isStaticDataMember() &&
1607         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1608         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1609       return false;
1610 
1611     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1612       return false;
1613   } else {
1614     return false;
1615   }
1616 
1617   // Only warn for unused decls internal to the translation unit.
1618   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1619   // for inline functions defined in the main source file, for instance.
1620   return mightHaveNonExternalLinkage(D);
1621 }
1622 
1623 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1624   if (!D)
1625     return;
1626 
1627   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1628     const FunctionDecl *First = FD->getFirstDecl();
1629     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1630       return; // First should already be in the vector.
1631   }
1632 
1633   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1634     const VarDecl *First = VD->getFirstDecl();
1635     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1636       return; // First should already be in the vector.
1637   }
1638 
1639   if (ShouldWarnIfUnusedFileScopedDecl(D))
1640     UnusedFileScopedDecls.push_back(D);
1641 }
1642 
1643 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1644   if (D->isInvalidDecl())
1645     return false;
1646 
1647   bool Referenced = false;
1648   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1649     // For a decomposition declaration, warn if none of the bindings are
1650     // referenced, instead of if the variable itself is referenced (which
1651     // it is, by the bindings' expressions).
1652     for (auto *BD : DD->bindings()) {
1653       if (BD->isReferenced()) {
1654         Referenced = true;
1655         break;
1656       }
1657     }
1658   } else if (!D->getDeclName()) {
1659     return false;
1660   } else if (D->isReferenced() || D->isUsed()) {
1661     Referenced = true;
1662   }
1663 
1664   if (Referenced || D->hasAttr<UnusedAttr>() ||
1665       D->hasAttr<ObjCPreciseLifetimeAttr>())
1666     return false;
1667 
1668   if (isa<LabelDecl>(D))
1669     return true;
1670 
1671   // Except for labels, we only care about unused decls that are local to
1672   // functions.
1673   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1674   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1675     // For dependent types, the diagnostic is deferred.
1676     WithinFunction =
1677         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1678   if (!WithinFunction)
1679     return false;
1680 
1681   if (isa<TypedefNameDecl>(D))
1682     return true;
1683 
1684   // White-list anything that isn't a local variable.
1685   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1686     return false;
1687 
1688   // Types of valid local variables should be complete, so this should succeed.
1689   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1690 
1691     // White-list anything with an __attribute__((unused)) type.
1692     const auto *Ty = VD->getType().getTypePtr();
1693 
1694     // Only look at the outermost level of typedef.
1695     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1696       if (TT->getDecl()->hasAttr<UnusedAttr>())
1697         return false;
1698     }
1699 
1700     // If we failed to complete the type for some reason, or if the type is
1701     // dependent, don't diagnose the variable.
1702     if (Ty->isIncompleteType() || Ty->isDependentType())
1703       return false;
1704 
1705     // Look at the element type to ensure that the warning behaviour is
1706     // consistent for both scalars and arrays.
1707     Ty = Ty->getBaseElementTypeUnsafe();
1708 
1709     if (const TagType *TT = Ty->getAs<TagType>()) {
1710       const TagDecl *Tag = TT->getDecl();
1711       if (Tag->hasAttr<UnusedAttr>())
1712         return false;
1713 
1714       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1715         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1716           return false;
1717 
1718         if (const Expr *Init = VD->getInit()) {
1719           if (const ExprWithCleanups *Cleanups =
1720                   dyn_cast<ExprWithCleanups>(Init))
1721             Init = Cleanups->getSubExpr();
1722           const CXXConstructExpr *Construct =
1723             dyn_cast<CXXConstructExpr>(Init);
1724           if (Construct && !Construct->isElidable()) {
1725             CXXConstructorDecl *CD = Construct->getConstructor();
1726             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1727                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1728               return false;
1729           }
1730         }
1731       }
1732     }
1733 
1734     // TODO: __attribute__((unused)) templates?
1735   }
1736 
1737   return true;
1738 }
1739 
1740 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1741                                      FixItHint &Hint) {
1742   if (isa<LabelDecl>(D)) {
1743     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1744                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1745     if (AfterColon.isInvalid())
1746       return;
1747     Hint = FixItHint::CreateRemoval(CharSourceRange::
1748                                     getCharRange(D->getLocStart(), AfterColon));
1749   }
1750 }
1751 
1752 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1753   if (D->getTypeForDecl()->isDependentType())
1754     return;
1755 
1756   for (auto *TmpD : D->decls()) {
1757     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1758       DiagnoseUnusedDecl(T);
1759     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1760       DiagnoseUnusedNestedTypedefs(R);
1761   }
1762 }
1763 
1764 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1765 /// unless they are marked attr(unused).
1766 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1767   if (!ShouldDiagnoseUnusedDecl(D))
1768     return;
1769 
1770   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1771     // typedefs can be referenced later on, so the diagnostics are emitted
1772     // at end-of-translation-unit.
1773     UnusedLocalTypedefNameCandidates.insert(TD);
1774     return;
1775   }
1776 
1777   FixItHint Hint;
1778   GenerateFixForUnusedDecl(D, Context, Hint);
1779 
1780   unsigned DiagID;
1781   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1782     DiagID = diag::warn_unused_exception_param;
1783   else if (isa<LabelDecl>(D))
1784     DiagID = diag::warn_unused_label;
1785   else
1786     DiagID = diag::warn_unused_variable;
1787 
1788   Diag(D->getLocation(), DiagID) << D << Hint;
1789 }
1790 
1791 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1792   // Verify that we have no forward references left.  If so, there was a goto
1793   // or address of a label taken, but no definition of it.  Label fwd
1794   // definitions are indicated with a null substmt which is also not a resolved
1795   // MS inline assembly label name.
1796   bool Diagnose = false;
1797   if (L->isMSAsmLabel())
1798     Diagnose = !L->isResolvedMSAsmLabel();
1799   else
1800     Diagnose = L->getStmt() == nullptr;
1801   if (Diagnose)
1802     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1803 }
1804 
1805 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1806   S->mergeNRVOIntoParent();
1807 
1808   if (S->decl_empty()) return;
1809   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1810          "Scope shouldn't contain decls!");
1811 
1812   for (auto *TmpD : S->decls()) {
1813     assert(TmpD && "This decl didn't get pushed??");
1814 
1815     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1816     NamedDecl *D = cast<NamedDecl>(TmpD);
1817 
1818     // Diagnose unused variables in this scope.
1819     if (!S->hasUnrecoverableErrorOccurred()) {
1820       DiagnoseUnusedDecl(D);
1821       if (const auto *RD = dyn_cast<RecordDecl>(D))
1822         DiagnoseUnusedNestedTypedefs(RD);
1823     }
1824 
1825     if (!D->getDeclName()) continue;
1826 
1827     // If this was a forward reference to a label, verify it was defined.
1828     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1829       CheckPoppedLabel(LD, *this);
1830 
1831     // Remove this name from our lexical scope, and warn on it if we haven't
1832     // already.
1833     IdResolver.RemoveDecl(D);
1834     auto ShadowI = ShadowingDecls.find(D);
1835     if (ShadowI != ShadowingDecls.end()) {
1836       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1837         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1838             << D << FD << FD->getParent();
1839         Diag(FD->getLocation(), diag::note_previous_declaration);
1840       }
1841       ShadowingDecls.erase(ShadowI);
1842     }
1843   }
1844 }
1845 
1846 /// \brief Look for an Objective-C class in the translation unit.
1847 ///
1848 /// \param Id The name of the Objective-C class we're looking for. If
1849 /// typo-correction fixes this name, the Id will be updated
1850 /// to the fixed name.
1851 ///
1852 /// \param IdLoc The location of the name in the translation unit.
1853 ///
1854 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1855 /// if there is no class with the given name.
1856 ///
1857 /// \returns The declaration of the named Objective-C class, or NULL if the
1858 /// class could not be found.
1859 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1860                                               SourceLocation IdLoc,
1861                                               bool DoTypoCorrection) {
1862   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1863   // creation from this context.
1864   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1865 
1866   if (!IDecl && DoTypoCorrection) {
1867     // Perform typo correction at the given location, but only if we
1868     // find an Objective-C class name.
1869     if (TypoCorrection C = CorrectTypo(
1870             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1871             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1872             CTK_ErrorRecovery)) {
1873       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1874       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1875       Id = IDecl->getIdentifier();
1876     }
1877   }
1878   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1879   // This routine must always return a class definition, if any.
1880   if (Def && Def->getDefinition())
1881       Def = Def->getDefinition();
1882   return Def;
1883 }
1884 
1885 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1886 /// from S, where a non-field would be declared. This routine copes
1887 /// with the difference between C and C++ scoping rules in structs and
1888 /// unions. For example, the following code is well-formed in C but
1889 /// ill-formed in C++:
1890 /// @code
1891 /// struct S6 {
1892 ///   enum { BAR } e;
1893 /// };
1894 ///
1895 /// void test_S6() {
1896 ///   struct S6 a;
1897 ///   a.e = BAR;
1898 /// }
1899 /// @endcode
1900 /// For the declaration of BAR, this routine will return a different
1901 /// scope. The scope S will be the scope of the unnamed enumeration
1902 /// within S6. In C++, this routine will return the scope associated
1903 /// with S6, because the enumeration's scope is a transparent
1904 /// context but structures can contain non-field names. In C, this
1905 /// routine will return the translation unit scope, since the
1906 /// enumeration's scope is a transparent context and structures cannot
1907 /// contain non-field names.
1908 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1909   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1910          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1911          (S->isClassScope() && !getLangOpts().CPlusPlus))
1912     S = S->getParent();
1913   return S;
1914 }
1915 
1916 /// \brief Looks up the declaration of "struct objc_super" and
1917 /// saves it for later use in building builtin declaration of
1918 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1919 /// pre-existing declaration exists no action takes place.
1920 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1921                                         IdentifierInfo *II) {
1922   if (!II->isStr("objc_msgSendSuper"))
1923     return;
1924   ASTContext &Context = ThisSema.Context;
1925 
1926   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1927                       SourceLocation(), Sema::LookupTagName);
1928   ThisSema.LookupName(Result, S);
1929   if (Result.getResultKind() == LookupResult::Found)
1930     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1931       Context.setObjCSuperType(Context.getTagDeclType(TD));
1932 }
1933 
1934 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1935   switch (Error) {
1936   case ASTContext::GE_None:
1937     return "";
1938   case ASTContext::GE_Missing_stdio:
1939     return "stdio.h";
1940   case ASTContext::GE_Missing_setjmp:
1941     return "setjmp.h";
1942   case ASTContext::GE_Missing_ucontext:
1943     return "ucontext.h";
1944   }
1945   llvm_unreachable("unhandled error kind");
1946 }
1947 
1948 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1949 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1950 /// if we're creating this built-in in anticipation of redeclaring the
1951 /// built-in.
1952 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1953                                      Scope *S, bool ForRedeclaration,
1954                                      SourceLocation Loc) {
1955   LookupPredefedObjCSuperType(*this, S, II);
1956 
1957   ASTContext::GetBuiltinTypeError Error;
1958   QualType R = Context.GetBuiltinType(ID, Error);
1959   if (Error) {
1960     if (ForRedeclaration)
1961       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1962           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1963     return nullptr;
1964   }
1965 
1966   if (!ForRedeclaration &&
1967       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1968        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1969     Diag(Loc, diag::ext_implicit_lib_function_decl)
1970         << Context.BuiltinInfo.getName(ID) << R;
1971     if (Context.BuiltinInfo.getHeaderName(ID) &&
1972         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1973       Diag(Loc, diag::note_include_header_or_declare)
1974           << Context.BuiltinInfo.getHeaderName(ID)
1975           << Context.BuiltinInfo.getName(ID);
1976   }
1977 
1978   if (R.isNull())
1979     return nullptr;
1980 
1981   DeclContext *Parent = Context.getTranslationUnitDecl();
1982   if (getLangOpts().CPlusPlus) {
1983     LinkageSpecDecl *CLinkageDecl =
1984         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1985                                 LinkageSpecDecl::lang_c, false);
1986     CLinkageDecl->setImplicit();
1987     Parent->addDecl(CLinkageDecl);
1988     Parent = CLinkageDecl;
1989   }
1990 
1991   FunctionDecl *New = FunctionDecl::Create(Context,
1992                                            Parent,
1993                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1994                                            SC_Extern,
1995                                            false,
1996                                            R->isFunctionProtoType());
1997   New->setImplicit();
1998 
1999   // Create Decl objects for each parameter, adding them to the
2000   // FunctionDecl.
2001   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2002     SmallVector<ParmVarDecl*, 16> Params;
2003     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2004       ParmVarDecl *parm =
2005           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2006                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2007                               SC_None, nullptr);
2008       parm->setScopeInfo(0, i);
2009       Params.push_back(parm);
2010     }
2011     New->setParams(Params);
2012   }
2013 
2014   AddKnownFunctionAttributes(New);
2015   RegisterLocallyScopedExternCDecl(New, S);
2016 
2017   // TUScope is the translation-unit scope to insert this function into.
2018   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2019   // relate Scopes to DeclContexts, and probably eliminate CurContext
2020   // entirely, but we're not there yet.
2021   DeclContext *SavedContext = CurContext;
2022   CurContext = Parent;
2023   PushOnScopeChains(New, TUScope);
2024   CurContext = SavedContext;
2025   return New;
2026 }
2027 
2028 /// Typedef declarations don't have linkage, but they still denote the same
2029 /// entity if their types are the same.
2030 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2031 /// isSameEntity.
2032 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2033                                                      TypedefNameDecl *Decl,
2034                                                      LookupResult &Previous) {
2035   // This is only interesting when modules are enabled.
2036   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2037     return;
2038 
2039   // Empty sets are uninteresting.
2040   if (Previous.empty())
2041     return;
2042 
2043   LookupResult::Filter Filter = Previous.makeFilter();
2044   while (Filter.hasNext()) {
2045     NamedDecl *Old = Filter.next();
2046 
2047     // Non-hidden declarations are never ignored.
2048     if (S.isVisible(Old))
2049       continue;
2050 
2051     // Declarations of the same entity are not ignored, even if they have
2052     // different linkages.
2053     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2054       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2055                                 Decl->getUnderlyingType()))
2056         continue;
2057 
2058       // If both declarations give a tag declaration a typedef name for linkage
2059       // purposes, then they declare the same entity.
2060       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2061           Decl->getAnonDeclWithTypedefName())
2062         continue;
2063     }
2064 
2065     Filter.erase();
2066   }
2067 
2068   Filter.done();
2069 }
2070 
2071 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2072   QualType OldType;
2073   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2074     OldType = OldTypedef->getUnderlyingType();
2075   else
2076     OldType = Context.getTypeDeclType(Old);
2077   QualType NewType = New->getUnderlyingType();
2078 
2079   if (NewType->isVariablyModifiedType()) {
2080     // Must not redefine a typedef with a variably-modified type.
2081     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2082     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2083       << Kind << NewType;
2084     if (Old->getLocation().isValid())
2085       notePreviousDefinition(Old, New->getLocation());
2086     New->setInvalidDecl();
2087     return true;
2088   }
2089 
2090   if (OldType != NewType &&
2091       !OldType->isDependentType() &&
2092       !NewType->isDependentType() &&
2093       !Context.hasSameType(OldType, NewType)) {
2094     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2095     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2096       << Kind << NewType << OldType;
2097     if (Old->getLocation().isValid())
2098       notePreviousDefinition(Old, New->getLocation());
2099     New->setInvalidDecl();
2100     return true;
2101   }
2102   return false;
2103 }
2104 
2105 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2106 /// same name and scope as a previous declaration 'Old'.  Figure out
2107 /// how to resolve this situation, merging decls or emitting
2108 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2109 ///
2110 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2111                                 LookupResult &OldDecls) {
2112   // If the new decl is known invalid already, don't bother doing any
2113   // merging checks.
2114   if (New->isInvalidDecl()) return;
2115 
2116   // Allow multiple definitions for ObjC built-in typedefs.
2117   // FIXME: Verify the underlying types are equivalent!
2118   if (getLangOpts().ObjC1) {
2119     const IdentifierInfo *TypeID = New->getIdentifier();
2120     switch (TypeID->getLength()) {
2121     default: break;
2122     case 2:
2123       {
2124         if (!TypeID->isStr("id"))
2125           break;
2126         QualType T = New->getUnderlyingType();
2127         if (!T->isPointerType())
2128           break;
2129         if (!T->isVoidPointerType()) {
2130           QualType PT = T->getAs<PointerType>()->getPointeeType();
2131           if (!PT->isStructureType())
2132             break;
2133         }
2134         Context.setObjCIdRedefinitionType(T);
2135         // Install the built-in type for 'id', ignoring the current definition.
2136         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2137         return;
2138       }
2139     case 5:
2140       if (!TypeID->isStr("Class"))
2141         break;
2142       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2143       // Install the built-in type for 'Class', ignoring the current definition.
2144       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2145       return;
2146     case 3:
2147       if (!TypeID->isStr("SEL"))
2148         break;
2149       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2150       // Install the built-in type for 'SEL', ignoring the current definition.
2151       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2152       return;
2153     }
2154     // Fall through - the typedef name was not a builtin type.
2155   }
2156 
2157   // Verify the old decl was also a type.
2158   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2159   if (!Old) {
2160     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2161       << New->getDeclName();
2162 
2163     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2164     if (OldD->getLocation().isValid())
2165       notePreviousDefinition(OldD, New->getLocation());
2166 
2167     return New->setInvalidDecl();
2168   }
2169 
2170   // If the old declaration is invalid, just give up here.
2171   if (Old->isInvalidDecl())
2172     return New->setInvalidDecl();
2173 
2174   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2175     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2176     auto *NewTag = New->getAnonDeclWithTypedefName();
2177     NamedDecl *Hidden = nullptr;
2178     if (OldTag && NewTag &&
2179         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2180         !hasVisibleDefinition(OldTag, &Hidden)) {
2181       // There is a definition of this tag, but it is not visible. Use it
2182       // instead of our tag.
2183       New->setTypeForDecl(OldTD->getTypeForDecl());
2184       if (OldTD->isModed())
2185         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2186                                     OldTD->getUnderlyingType());
2187       else
2188         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2189 
2190       // Make the old tag definition visible.
2191       makeMergedDefinitionVisible(Hidden);
2192 
2193       // If this was an unscoped enumeration, yank all of its enumerators
2194       // out of the scope.
2195       if (isa<EnumDecl>(NewTag)) {
2196         Scope *EnumScope = getNonFieldDeclScope(S);
2197         for (auto *D : NewTag->decls()) {
2198           auto *ED = cast<EnumConstantDecl>(D);
2199           assert(EnumScope->isDeclScope(ED));
2200           EnumScope->RemoveDecl(ED);
2201           IdResolver.RemoveDecl(ED);
2202           ED->getLexicalDeclContext()->removeDecl(ED);
2203         }
2204       }
2205     }
2206   }
2207 
2208   // If the typedef types are not identical, reject them in all languages and
2209   // with any extensions enabled.
2210   if (isIncompatibleTypedef(Old, New))
2211     return;
2212 
2213   // The types match.  Link up the redeclaration chain and merge attributes if
2214   // the old declaration was a typedef.
2215   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2216     New->setPreviousDecl(Typedef);
2217     mergeDeclAttributes(New, Old);
2218   }
2219 
2220   if (getLangOpts().MicrosoftExt)
2221     return;
2222 
2223   if (getLangOpts().CPlusPlus) {
2224     // C++ [dcl.typedef]p2:
2225     //   In a given non-class scope, a typedef specifier can be used to
2226     //   redefine the name of any type declared in that scope to refer
2227     //   to the type to which it already refers.
2228     if (!isa<CXXRecordDecl>(CurContext))
2229       return;
2230 
2231     // C++0x [dcl.typedef]p4:
2232     //   In a given class scope, a typedef specifier can be used to redefine
2233     //   any class-name declared in that scope that is not also a typedef-name
2234     //   to refer to the type to which it already refers.
2235     //
2236     // This wording came in via DR424, which was a correction to the
2237     // wording in DR56, which accidentally banned code like:
2238     //
2239     //   struct S {
2240     //     typedef struct A { } A;
2241     //   };
2242     //
2243     // in the C++03 standard. We implement the C++0x semantics, which
2244     // allow the above but disallow
2245     //
2246     //   struct S {
2247     //     typedef int I;
2248     //     typedef int I;
2249     //   };
2250     //
2251     // since that was the intent of DR56.
2252     if (!isa<TypedefNameDecl>(Old))
2253       return;
2254 
2255     Diag(New->getLocation(), diag::err_redefinition)
2256       << New->getDeclName();
2257     notePreviousDefinition(Old, New->getLocation());
2258     return New->setInvalidDecl();
2259   }
2260 
2261   // Modules always permit redefinition of typedefs, as does C11.
2262   if (getLangOpts().Modules || getLangOpts().C11)
2263     return;
2264 
2265   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2266   // is normally mapped to an error, but can be controlled with
2267   // -Wtypedef-redefinition.  If either the original or the redefinition is
2268   // in a system header, don't emit this for compatibility with GCC.
2269   if (getDiagnostics().getSuppressSystemWarnings() &&
2270       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2271       (Old->isImplicit() ||
2272        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2273        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2274     return;
2275 
2276   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2277     << New->getDeclName();
2278   notePreviousDefinition(Old, New->getLocation());
2279 }
2280 
2281 /// DeclhasAttr - returns true if decl Declaration already has the target
2282 /// attribute.
2283 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2284   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2285   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2286   for (const auto *i : D->attrs())
2287     if (i->getKind() == A->getKind()) {
2288       if (Ann) {
2289         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2290           return true;
2291         continue;
2292       }
2293       // FIXME: Don't hardcode this check
2294       if (OA && isa<OwnershipAttr>(i))
2295         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2296       return true;
2297     }
2298 
2299   return false;
2300 }
2301 
2302 static bool isAttributeTargetADefinition(Decl *D) {
2303   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2304     return VD->isThisDeclarationADefinition();
2305   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2306     return TD->isCompleteDefinition() || TD->isBeingDefined();
2307   return true;
2308 }
2309 
2310 /// Merge alignment attributes from \p Old to \p New, taking into account the
2311 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2312 ///
2313 /// \return \c true if any attributes were added to \p New.
2314 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2315   // Look for alignas attributes on Old, and pick out whichever attribute
2316   // specifies the strictest alignment requirement.
2317   AlignedAttr *OldAlignasAttr = nullptr;
2318   AlignedAttr *OldStrictestAlignAttr = nullptr;
2319   unsigned OldAlign = 0;
2320   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2321     // FIXME: We have no way of representing inherited dependent alignments
2322     // in a case like:
2323     //   template<int A, int B> struct alignas(A) X;
2324     //   template<int A, int B> struct alignas(B) X {};
2325     // For now, we just ignore any alignas attributes which are not on the
2326     // definition in such a case.
2327     if (I->isAlignmentDependent())
2328       return false;
2329 
2330     if (I->isAlignas())
2331       OldAlignasAttr = I;
2332 
2333     unsigned Align = I->getAlignment(S.Context);
2334     if (Align > OldAlign) {
2335       OldAlign = Align;
2336       OldStrictestAlignAttr = I;
2337     }
2338   }
2339 
2340   // Look for alignas attributes on New.
2341   AlignedAttr *NewAlignasAttr = nullptr;
2342   unsigned NewAlign = 0;
2343   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2344     if (I->isAlignmentDependent())
2345       return false;
2346 
2347     if (I->isAlignas())
2348       NewAlignasAttr = I;
2349 
2350     unsigned Align = I->getAlignment(S.Context);
2351     if (Align > NewAlign)
2352       NewAlign = Align;
2353   }
2354 
2355   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2356     // Both declarations have 'alignas' attributes. We require them to match.
2357     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2358     // fall short. (If two declarations both have alignas, they must both match
2359     // every definition, and so must match each other if there is a definition.)
2360 
2361     // If either declaration only contains 'alignas(0)' specifiers, then it
2362     // specifies the natural alignment for the type.
2363     if (OldAlign == 0 || NewAlign == 0) {
2364       QualType Ty;
2365       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2366         Ty = VD->getType();
2367       else
2368         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2369 
2370       if (OldAlign == 0)
2371         OldAlign = S.Context.getTypeAlign(Ty);
2372       if (NewAlign == 0)
2373         NewAlign = S.Context.getTypeAlign(Ty);
2374     }
2375 
2376     if (OldAlign != NewAlign) {
2377       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2378         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2379         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2380       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2381     }
2382   }
2383 
2384   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2385     // C++11 [dcl.align]p6:
2386     //   if any declaration of an entity has an alignment-specifier,
2387     //   every defining declaration of that entity shall specify an
2388     //   equivalent alignment.
2389     // C11 6.7.5/7:
2390     //   If the definition of an object does not have an alignment
2391     //   specifier, any other declaration of that object shall also
2392     //   have no alignment specifier.
2393     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2394       << OldAlignasAttr;
2395     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2396       << OldAlignasAttr;
2397   }
2398 
2399   bool AnyAdded = false;
2400 
2401   // Ensure we have an attribute representing the strictest alignment.
2402   if (OldAlign > NewAlign) {
2403     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2404     Clone->setInherited(true);
2405     New->addAttr(Clone);
2406     AnyAdded = true;
2407   }
2408 
2409   // Ensure we have an alignas attribute if the old declaration had one.
2410   if (OldAlignasAttr && !NewAlignasAttr &&
2411       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2412     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2413     Clone->setInherited(true);
2414     New->addAttr(Clone);
2415     AnyAdded = true;
2416   }
2417 
2418   return AnyAdded;
2419 }
2420 
2421 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2422                                const InheritableAttr *Attr,
2423                                Sema::AvailabilityMergeKind AMK) {
2424   // This function copies an attribute Attr from a previous declaration to the
2425   // new declaration D if the new declaration doesn't itself have that attribute
2426   // yet or if that attribute allows duplicates.
2427   // If you're adding a new attribute that requires logic different from
2428   // "use explicit attribute on decl if present, else use attribute from
2429   // previous decl", for example if the attribute needs to be consistent
2430   // between redeclarations, you need to call a custom merge function here.
2431   InheritableAttr *NewAttr = nullptr;
2432   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2433   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2434     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2435                                       AA->isImplicit(), AA->getIntroduced(),
2436                                       AA->getDeprecated(),
2437                                       AA->getObsoleted(), AA->getUnavailable(),
2438                                       AA->getMessage(), AA->getStrict(),
2439                                       AA->getReplacement(), AMK,
2440                                       AttrSpellingListIndex);
2441   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2442     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2443                                     AttrSpellingListIndex);
2444   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2445     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2446                                         AttrSpellingListIndex);
2447   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2448     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2449                                    AttrSpellingListIndex);
2450   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2451     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2452                                    AttrSpellingListIndex);
2453   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2454     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2455                                 FA->getFormatIdx(), FA->getFirstArg(),
2456                                 AttrSpellingListIndex);
2457   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2458     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2459                                  AttrSpellingListIndex);
2460   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2461     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2462                                        AttrSpellingListIndex,
2463                                        IA->getSemanticSpelling());
2464   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2465     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2466                                       &S.Context.Idents.get(AA->getSpelling()),
2467                                       AttrSpellingListIndex);
2468   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2469            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2470             isa<CUDAGlobalAttr>(Attr))) {
2471     // CUDA target attributes are part of function signature for
2472     // overloading purposes and must not be merged.
2473     return false;
2474   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2475     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2476   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2477     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2478   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2479     NewAttr = S.mergeInternalLinkageAttr(
2480         D, InternalLinkageA->getRange(),
2481         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2482         AttrSpellingListIndex);
2483   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2484     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2485                                 &S.Context.Idents.get(CommonA->getSpelling()),
2486                                 AttrSpellingListIndex);
2487   else if (isa<AlignedAttr>(Attr))
2488     // AlignedAttrs are handled separately, because we need to handle all
2489     // such attributes on a declaration at the same time.
2490     NewAttr = nullptr;
2491   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2492            (AMK == Sema::AMK_Override ||
2493             AMK == Sema::AMK_ProtocolImplementation))
2494     NewAttr = nullptr;
2495   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2496     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2497                               UA->getGuid());
2498   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2499     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2500 
2501   if (NewAttr) {
2502     NewAttr->setInherited(true);
2503     D->addAttr(NewAttr);
2504     if (isa<MSInheritanceAttr>(NewAttr))
2505       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2506     return true;
2507   }
2508 
2509   return false;
2510 }
2511 
2512 static const NamedDecl *getDefinition(const Decl *D) {
2513   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2514     return TD->getDefinition();
2515   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2516     const VarDecl *Def = VD->getDefinition();
2517     if (Def)
2518       return Def;
2519     return VD->getActingDefinition();
2520   }
2521   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2522     return FD->getDefinition();
2523   return nullptr;
2524 }
2525 
2526 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2527   for (const auto *Attribute : D->attrs())
2528     if (Attribute->getKind() == Kind)
2529       return true;
2530   return false;
2531 }
2532 
2533 /// checkNewAttributesAfterDef - If we already have a definition, check that
2534 /// there are no new attributes in this declaration.
2535 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2536   if (!New->hasAttrs())
2537     return;
2538 
2539   const NamedDecl *Def = getDefinition(Old);
2540   if (!Def || Def == New)
2541     return;
2542 
2543   AttrVec &NewAttributes = New->getAttrs();
2544   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2545     const Attr *NewAttribute = NewAttributes[I];
2546 
2547     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2548       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2549         Sema::SkipBodyInfo SkipBody;
2550         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2551 
2552         // If we're skipping this definition, drop the "alias" attribute.
2553         if (SkipBody.ShouldSkip) {
2554           NewAttributes.erase(NewAttributes.begin() + I);
2555           --E;
2556           continue;
2557         }
2558       } else {
2559         VarDecl *VD = cast<VarDecl>(New);
2560         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2561                                 VarDecl::TentativeDefinition
2562                             ? diag::err_alias_after_tentative
2563                             : diag::err_redefinition;
2564         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2565         if (Diag == diag::err_redefinition)
2566           S.notePreviousDefinition(Def, VD->getLocation());
2567         else
2568           S.Diag(Def->getLocation(), diag::note_previous_definition);
2569         VD->setInvalidDecl();
2570       }
2571       ++I;
2572       continue;
2573     }
2574 
2575     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2576       // Tentative definitions are only interesting for the alias check above.
2577       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2578         ++I;
2579         continue;
2580       }
2581     }
2582 
2583     if (hasAttribute(Def, NewAttribute->getKind())) {
2584       ++I;
2585       continue; // regular attr merging will take care of validating this.
2586     }
2587 
2588     if (isa<C11NoReturnAttr>(NewAttribute)) {
2589       // C's _Noreturn is allowed to be added to a function after it is defined.
2590       ++I;
2591       continue;
2592     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2593       if (AA->isAlignas()) {
2594         // C++11 [dcl.align]p6:
2595         //   if any declaration of an entity has an alignment-specifier,
2596         //   every defining declaration of that entity shall specify an
2597         //   equivalent alignment.
2598         // C11 6.7.5/7:
2599         //   If the definition of an object does not have an alignment
2600         //   specifier, any other declaration of that object shall also
2601         //   have no alignment specifier.
2602         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2603           << AA;
2604         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2605           << AA;
2606         NewAttributes.erase(NewAttributes.begin() + I);
2607         --E;
2608         continue;
2609       }
2610     }
2611 
2612     S.Diag(NewAttribute->getLocation(),
2613            diag::warn_attribute_precede_definition);
2614     S.Diag(Def->getLocation(), diag::note_previous_definition);
2615     NewAttributes.erase(NewAttributes.begin() + I);
2616     --E;
2617   }
2618 }
2619 
2620 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2621 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2622                                AvailabilityMergeKind AMK) {
2623   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2624     UsedAttr *NewAttr = OldAttr->clone(Context);
2625     NewAttr->setInherited(true);
2626     New->addAttr(NewAttr);
2627   }
2628 
2629   if (!Old->hasAttrs() && !New->hasAttrs())
2630     return;
2631 
2632   // Attributes declared post-definition are currently ignored.
2633   checkNewAttributesAfterDef(*this, New, Old);
2634 
2635   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2636     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2637       if (OldA->getLabel() != NewA->getLabel()) {
2638         // This redeclaration changes __asm__ label.
2639         Diag(New->getLocation(), diag::err_different_asm_label);
2640         Diag(OldA->getLocation(), diag::note_previous_declaration);
2641       }
2642     } else if (Old->isUsed()) {
2643       // This redeclaration adds an __asm__ label to a declaration that has
2644       // already been ODR-used.
2645       Diag(New->getLocation(), diag::err_late_asm_label_name)
2646         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2647     }
2648   }
2649 
2650   // Re-declaration cannot add abi_tag's.
2651   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2652     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2653       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2654         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2655                       NewTag) == OldAbiTagAttr->tags_end()) {
2656           Diag(NewAbiTagAttr->getLocation(),
2657                diag::err_new_abi_tag_on_redeclaration)
2658               << NewTag;
2659           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2660         }
2661       }
2662     } else {
2663       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2664       Diag(Old->getLocation(), diag::note_previous_declaration);
2665     }
2666   }
2667 
2668   // This redeclaration adds a section attribute.
2669   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2670     if (auto *VD = dyn_cast<VarDecl>(New)) {
2671       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2672         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2673         Diag(Old->getLocation(), diag::note_previous_declaration);
2674       }
2675     }
2676   }
2677 
2678   if (!Old->hasAttrs())
2679     return;
2680 
2681   bool foundAny = New->hasAttrs();
2682 
2683   // Ensure that any moving of objects within the allocated map is done before
2684   // we process them.
2685   if (!foundAny) New->setAttrs(AttrVec());
2686 
2687   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2688     // Ignore deprecated/unavailable/availability attributes if requested.
2689     AvailabilityMergeKind LocalAMK = AMK_None;
2690     if (isa<DeprecatedAttr>(I) ||
2691         isa<UnavailableAttr>(I) ||
2692         isa<AvailabilityAttr>(I)) {
2693       switch (AMK) {
2694       case AMK_None:
2695         continue;
2696 
2697       case AMK_Redeclaration:
2698       case AMK_Override:
2699       case AMK_ProtocolImplementation:
2700         LocalAMK = AMK;
2701         break;
2702       }
2703     }
2704 
2705     // Already handled.
2706     if (isa<UsedAttr>(I))
2707       continue;
2708 
2709     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2710       foundAny = true;
2711   }
2712 
2713   if (mergeAlignedAttrs(*this, New, Old))
2714     foundAny = true;
2715 
2716   if (!foundAny) New->dropAttrs();
2717 }
2718 
2719 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2720 /// to the new one.
2721 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2722                                      const ParmVarDecl *oldDecl,
2723                                      Sema &S) {
2724   // C++11 [dcl.attr.depend]p2:
2725   //   The first declaration of a function shall specify the
2726   //   carries_dependency attribute for its declarator-id if any declaration
2727   //   of the function specifies the carries_dependency attribute.
2728   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2729   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2730     S.Diag(CDA->getLocation(),
2731            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2732     // Find the first declaration of the parameter.
2733     // FIXME: Should we build redeclaration chains for function parameters?
2734     const FunctionDecl *FirstFD =
2735       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2736     const ParmVarDecl *FirstVD =
2737       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2738     S.Diag(FirstVD->getLocation(),
2739            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2740   }
2741 
2742   if (!oldDecl->hasAttrs())
2743     return;
2744 
2745   bool foundAny = newDecl->hasAttrs();
2746 
2747   // Ensure that any moving of objects within the allocated map is
2748   // done before we process them.
2749   if (!foundAny) newDecl->setAttrs(AttrVec());
2750 
2751   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2752     if (!DeclHasAttr(newDecl, I)) {
2753       InheritableAttr *newAttr =
2754         cast<InheritableParamAttr>(I->clone(S.Context));
2755       newAttr->setInherited(true);
2756       newDecl->addAttr(newAttr);
2757       foundAny = true;
2758     }
2759   }
2760 
2761   if (!foundAny) newDecl->dropAttrs();
2762 }
2763 
2764 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2765                                 const ParmVarDecl *OldParam,
2766                                 Sema &S) {
2767   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2768     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2769       if (*Oldnullability != *Newnullability) {
2770         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2771           << DiagNullabilityKind(
2772                *Newnullability,
2773                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2774                 != 0))
2775           << DiagNullabilityKind(
2776                *Oldnullability,
2777                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2778                 != 0));
2779         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2780       }
2781     } else {
2782       QualType NewT = NewParam->getType();
2783       NewT = S.Context.getAttributedType(
2784                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2785                          NewT, NewT);
2786       NewParam->setType(NewT);
2787     }
2788   }
2789 }
2790 
2791 namespace {
2792 
2793 /// Used in MergeFunctionDecl to keep track of function parameters in
2794 /// C.
2795 struct GNUCompatibleParamWarning {
2796   ParmVarDecl *OldParm;
2797   ParmVarDecl *NewParm;
2798   QualType PromotedType;
2799 };
2800 
2801 } // end anonymous namespace
2802 
2803 /// getSpecialMember - get the special member enum for a method.
2804 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2805   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2806     if (Ctor->isDefaultConstructor())
2807       return Sema::CXXDefaultConstructor;
2808 
2809     if (Ctor->isCopyConstructor())
2810       return Sema::CXXCopyConstructor;
2811 
2812     if (Ctor->isMoveConstructor())
2813       return Sema::CXXMoveConstructor;
2814   } else if (isa<CXXDestructorDecl>(MD)) {
2815     return Sema::CXXDestructor;
2816   } else if (MD->isCopyAssignmentOperator()) {
2817     return Sema::CXXCopyAssignment;
2818   } else if (MD->isMoveAssignmentOperator()) {
2819     return Sema::CXXMoveAssignment;
2820   }
2821 
2822   return Sema::CXXInvalid;
2823 }
2824 
2825 // Determine whether the previous declaration was a definition, implicit
2826 // declaration, or a declaration.
2827 template <typename T>
2828 static std::pair<diag::kind, SourceLocation>
2829 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2830   diag::kind PrevDiag;
2831   SourceLocation OldLocation = Old->getLocation();
2832   if (Old->isThisDeclarationADefinition())
2833     PrevDiag = diag::note_previous_definition;
2834   else if (Old->isImplicit()) {
2835     PrevDiag = diag::note_previous_implicit_declaration;
2836     if (OldLocation.isInvalid())
2837       OldLocation = New->getLocation();
2838   } else
2839     PrevDiag = diag::note_previous_declaration;
2840   return std::make_pair(PrevDiag, OldLocation);
2841 }
2842 
2843 /// canRedefineFunction - checks if a function can be redefined. Currently,
2844 /// only extern inline functions can be redefined, and even then only in
2845 /// GNU89 mode.
2846 static bool canRedefineFunction(const FunctionDecl *FD,
2847                                 const LangOptions& LangOpts) {
2848   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2849           !LangOpts.CPlusPlus &&
2850           FD->isInlineSpecified() &&
2851           FD->getStorageClass() == SC_Extern);
2852 }
2853 
2854 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2855   const AttributedType *AT = T->getAs<AttributedType>();
2856   while (AT && !AT->isCallingConv())
2857     AT = AT->getModifiedType()->getAs<AttributedType>();
2858   return AT;
2859 }
2860 
2861 template <typename T>
2862 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2863   const DeclContext *DC = Old->getDeclContext();
2864   if (DC->isRecord())
2865     return false;
2866 
2867   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2868   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2869     return true;
2870   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2871     return true;
2872   return false;
2873 }
2874 
2875 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2876 static bool isExternC(VarTemplateDecl *) { return false; }
2877 
2878 /// \brief Check whether a redeclaration of an entity introduced by a
2879 /// using-declaration is valid, given that we know it's not an overload
2880 /// (nor a hidden tag declaration).
2881 template<typename ExpectedDecl>
2882 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2883                                    ExpectedDecl *New) {
2884   // C++11 [basic.scope.declarative]p4:
2885   //   Given a set of declarations in a single declarative region, each of
2886   //   which specifies the same unqualified name,
2887   //   -- they shall all refer to the same entity, or all refer to functions
2888   //      and function templates; or
2889   //   -- exactly one declaration shall declare a class name or enumeration
2890   //      name that is not a typedef name and the other declarations shall all
2891   //      refer to the same variable or enumerator, or all refer to functions
2892   //      and function templates; in this case the class name or enumeration
2893   //      name is hidden (3.3.10).
2894 
2895   // C++11 [namespace.udecl]p14:
2896   //   If a function declaration in namespace scope or block scope has the
2897   //   same name and the same parameter-type-list as a function introduced
2898   //   by a using-declaration, and the declarations do not declare the same
2899   //   function, the program is ill-formed.
2900 
2901   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2902   if (Old &&
2903       !Old->getDeclContext()->getRedeclContext()->Equals(
2904           New->getDeclContext()->getRedeclContext()) &&
2905       !(isExternC(Old) && isExternC(New)))
2906     Old = nullptr;
2907 
2908   if (!Old) {
2909     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2910     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2911     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2912     return true;
2913   }
2914   return false;
2915 }
2916 
2917 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2918                                             const FunctionDecl *B) {
2919   assert(A->getNumParams() == B->getNumParams());
2920 
2921   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2922     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2923     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2924     if (AttrA == AttrB)
2925       return true;
2926     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2927   };
2928 
2929   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2930 }
2931 
2932 /// If necessary, adjust the semantic declaration context for a qualified
2933 /// declaration to name the correct inline namespace within the qualifier.
2934 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
2935                                                DeclaratorDecl *OldD) {
2936   // The only case where we need to update the DeclContext is when
2937   // redeclaration lookup for a qualified name finds a declaration
2938   // in an inline namespace within the context named by the qualifier:
2939   //
2940   //   inline namespace N { int f(); }
2941   //   int ::f(); // Sema DC needs adjusting from :: to N::.
2942   //
2943   // For unqualified declarations, the semantic context *can* change
2944   // along the redeclaration chain (for local extern declarations,
2945   // extern "C" declarations, and friend declarations in particular).
2946   if (!NewD->getQualifier())
2947     return;
2948 
2949   // NewD is probably already in the right context.
2950   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
2951   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
2952   if (NamedDC->Equals(SemaDC))
2953     return;
2954 
2955   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
2956           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
2957          "unexpected context for redeclaration");
2958 
2959   auto *LexDC = NewD->getLexicalDeclContext();
2960   auto FixSemaDC = [=](NamedDecl *D) {
2961     if (!D)
2962       return;
2963     D->setDeclContext(SemaDC);
2964     D->setLexicalDeclContext(LexDC);
2965   };
2966 
2967   FixSemaDC(NewD);
2968   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
2969     FixSemaDC(FD->getDescribedFunctionTemplate());
2970   else if (auto *VD = dyn_cast<VarDecl>(NewD))
2971     FixSemaDC(VD->getDescribedVarTemplate());
2972 }
2973 
2974 /// MergeFunctionDecl - We just parsed a function 'New' from
2975 /// declarator D which has the same name and scope as a previous
2976 /// declaration 'Old'.  Figure out how to resolve this situation,
2977 /// merging decls or emitting diagnostics as appropriate.
2978 ///
2979 /// In C++, New and Old must be declarations that are not
2980 /// overloaded. Use IsOverload to determine whether New and Old are
2981 /// overloaded, and to select the Old declaration that New should be
2982 /// merged with.
2983 ///
2984 /// Returns true if there was an error, false otherwise.
2985 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2986                              Scope *S, bool MergeTypeWithOld) {
2987   // Verify the old decl was also a function.
2988   FunctionDecl *Old = OldD->getAsFunction();
2989   if (!Old) {
2990     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2991       if (New->getFriendObjectKind()) {
2992         Diag(New->getLocation(), diag::err_using_decl_friend);
2993         Diag(Shadow->getTargetDecl()->getLocation(),
2994              diag::note_using_decl_target);
2995         Diag(Shadow->getUsingDecl()->getLocation(),
2996              diag::note_using_decl) << 0;
2997         return true;
2998       }
2999 
3000       // Check whether the two declarations might declare the same function.
3001       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3002         return true;
3003       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3004     } else {
3005       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3006         << New->getDeclName();
3007       notePreviousDefinition(OldD, New->getLocation());
3008       return true;
3009     }
3010   }
3011 
3012   // If the old declaration is invalid, just give up here.
3013   if (Old->isInvalidDecl())
3014     return true;
3015 
3016   diag::kind PrevDiag;
3017   SourceLocation OldLocation;
3018   std::tie(PrevDiag, OldLocation) =
3019       getNoteDiagForInvalidRedeclaration(Old, New);
3020 
3021   // Don't complain about this if we're in GNU89 mode and the old function
3022   // is an extern inline function.
3023   // Don't complain about specializations. They are not supposed to have
3024   // storage classes.
3025   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3026       New->getStorageClass() == SC_Static &&
3027       Old->hasExternalFormalLinkage() &&
3028       !New->getTemplateSpecializationInfo() &&
3029       !canRedefineFunction(Old, getLangOpts())) {
3030     if (getLangOpts().MicrosoftExt) {
3031       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3032       Diag(OldLocation, PrevDiag);
3033     } else {
3034       Diag(New->getLocation(), diag::err_static_non_static) << New;
3035       Diag(OldLocation, PrevDiag);
3036       return true;
3037     }
3038   }
3039 
3040   if (New->hasAttr<InternalLinkageAttr>() &&
3041       !Old->hasAttr<InternalLinkageAttr>()) {
3042     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3043         << New->getDeclName();
3044     notePreviousDefinition(Old, New->getLocation());
3045     New->dropAttr<InternalLinkageAttr>();
3046   }
3047 
3048   if (CheckRedeclarationModuleOwnership(New, Old))
3049     return true;
3050 
3051   if (!getLangOpts().CPlusPlus) {
3052     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3053     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3054       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3055         << New << OldOvl;
3056 
3057       // Try our best to find a decl that actually has the overloadable
3058       // attribute for the note. In most cases (e.g. programs with only one
3059       // broken declaration/definition), this won't matter.
3060       //
3061       // FIXME: We could do this if we juggled some extra state in
3062       // OverloadableAttr, rather than just removing it.
3063       const Decl *DiagOld = Old;
3064       if (OldOvl) {
3065         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3066           const auto *A = D->getAttr<OverloadableAttr>();
3067           return A && !A->isImplicit();
3068         });
3069         // If we've implicitly added *all* of the overloadable attrs to this
3070         // chain, emitting a "previous redecl" note is pointless.
3071         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3072       }
3073 
3074       if (DiagOld)
3075         Diag(DiagOld->getLocation(),
3076              diag::note_attribute_overloadable_prev_overload)
3077           << OldOvl;
3078 
3079       if (OldOvl)
3080         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3081       else
3082         New->dropAttr<OverloadableAttr>();
3083     }
3084   }
3085 
3086   // If a function is first declared with a calling convention, but is later
3087   // declared or defined without one, all following decls assume the calling
3088   // convention of the first.
3089   //
3090   // It's OK if a function is first declared without a calling convention,
3091   // but is later declared or defined with the default calling convention.
3092   //
3093   // To test if either decl has an explicit calling convention, we look for
3094   // AttributedType sugar nodes on the type as written.  If they are missing or
3095   // were canonicalized away, we assume the calling convention was implicit.
3096   //
3097   // Note also that we DO NOT return at this point, because we still have
3098   // other tests to run.
3099   QualType OldQType = Context.getCanonicalType(Old->getType());
3100   QualType NewQType = Context.getCanonicalType(New->getType());
3101   const FunctionType *OldType = cast<FunctionType>(OldQType);
3102   const FunctionType *NewType = cast<FunctionType>(NewQType);
3103   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3104   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3105   bool RequiresAdjustment = false;
3106 
3107   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3108     FunctionDecl *First = Old->getFirstDecl();
3109     const FunctionType *FT =
3110         First->getType().getCanonicalType()->castAs<FunctionType>();
3111     FunctionType::ExtInfo FI = FT->getExtInfo();
3112     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3113     if (!NewCCExplicit) {
3114       // Inherit the CC from the previous declaration if it was specified
3115       // there but not here.
3116       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3117       RequiresAdjustment = true;
3118     } else {
3119       // Calling conventions aren't compatible, so complain.
3120       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3121       Diag(New->getLocation(), diag::err_cconv_change)
3122         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3123         << !FirstCCExplicit
3124         << (!FirstCCExplicit ? "" :
3125             FunctionType::getNameForCallConv(FI.getCC()));
3126 
3127       // Put the note on the first decl, since it is the one that matters.
3128       Diag(First->getLocation(), diag::note_previous_declaration);
3129       return true;
3130     }
3131   }
3132 
3133   // FIXME: diagnose the other way around?
3134   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3135     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3136     RequiresAdjustment = true;
3137   }
3138 
3139   // Merge regparm attribute.
3140   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3141       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3142     if (NewTypeInfo.getHasRegParm()) {
3143       Diag(New->getLocation(), diag::err_regparm_mismatch)
3144         << NewType->getRegParmType()
3145         << OldType->getRegParmType();
3146       Diag(OldLocation, diag::note_previous_declaration);
3147       return true;
3148     }
3149 
3150     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3151     RequiresAdjustment = true;
3152   }
3153 
3154   // Merge ns_returns_retained attribute.
3155   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3156     if (NewTypeInfo.getProducesResult()) {
3157       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3158           << "'ns_returns_retained'";
3159       Diag(OldLocation, diag::note_previous_declaration);
3160       return true;
3161     }
3162 
3163     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3164     RequiresAdjustment = true;
3165   }
3166 
3167   if (OldTypeInfo.getNoCallerSavedRegs() !=
3168       NewTypeInfo.getNoCallerSavedRegs()) {
3169     if (NewTypeInfo.getNoCallerSavedRegs()) {
3170       AnyX86NoCallerSavedRegistersAttr *Attr =
3171         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3172       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3173       Diag(OldLocation, diag::note_previous_declaration);
3174       return true;
3175     }
3176 
3177     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3178     RequiresAdjustment = true;
3179   }
3180 
3181   if (RequiresAdjustment) {
3182     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3183     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3184     New->setType(QualType(AdjustedType, 0));
3185     NewQType = Context.getCanonicalType(New->getType());
3186     NewType = cast<FunctionType>(NewQType);
3187   }
3188 
3189   // If this redeclaration makes the function inline, we may need to add it to
3190   // UndefinedButUsed.
3191   if (!Old->isInlined() && New->isInlined() &&
3192       !New->hasAttr<GNUInlineAttr>() &&
3193       !getLangOpts().GNUInline &&
3194       Old->isUsed(false) &&
3195       !Old->isDefined() && !New->isThisDeclarationADefinition())
3196     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3197                                            SourceLocation()));
3198 
3199   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3200   // about it.
3201   if (New->hasAttr<GNUInlineAttr>() &&
3202       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3203     UndefinedButUsed.erase(Old->getCanonicalDecl());
3204   }
3205 
3206   // If pass_object_size params don't match up perfectly, this isn't a valid
3207   // redeclaration.
3208   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3209       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3210     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3211         << New->getDeclName();
3212     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3213     return true;
3214   }
3215 
3216   if (getLangOpts().CPlusPlus) {
3217     // C++1z [over.load]p2
3218     //   Certain function declarations cannot be overloaded:
3219     //     -- Function declarations that differ only in the return type,
3220     //        the exception specification, or both cannot be overloaded.
3221 
3222     // Check the exception specifications match. This may recompute the type of
3223     // both Old and New if it resolved exception specifications, so grab the
3224     // types again after this. Because this updates the type, we do this before
3225     // any of the other checks below, which may update the "de facto" NewQType
3226     // but do not necessarily update the type of New.
3227     if (CheckEquivalentExceptionSpec(Old, New))
3228       return true;
3229     OldQType = Context.getCanonicalType(Old->getType());
3230     NewQType = Context.getCanonicalType(New->getType());
3231 
3232     // Go back to the type source info to compare the declared return types,
3233     // per C++1y [dcl.type.auto]p13:
3234     //   Redeclarations or specializations of a function or function template
3235     //   with a declared return type that uses a placeholder type shall also
3236     //   use that placeholder, not a deduced type.
3237     QualType OldDeclaredReturnType =
3238         (Old->getTypeSourceInfo()
3239              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3240              : OldType)->getReturnType();
3241     QualType NewDeclaredReturnType =
3242         (New->getTypeSourceInfo()
3243              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3244              : NewType)->getReturnType();
3245     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3246         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3247           New->isLocalExternDecl())) {
3248       QualType ResQT;
3249       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3250           OldDeclaredReturnType->isObjCObjectPointerType())
3251         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3252       if (ResQT.isNull()) {
3253         if (New->isCXXClassMember() && New->isOutOfLine())
3254           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3255               << New << New->getReturnTypeSourceRange();
3256         else
3257           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3258               << New->getReturnTypeSourceRange();
3259         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3260                                     << Old->getReturnTypeSourceRange();
3261         return true;
3262       }
3263       else
3264         NewQType = ResQT;
3265     }
3266 
3267     QualType OldReturnType = OldType->getReturnType();
3268     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3269     if (OldReturnType != NewReturnType) {
3270       // If this function has a deduced return type and has already been
3271       // defined, copy the deduced value from the old declaration.
3272       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3273       if (OldAT && OldAT->isDeduced()) {
3274         New->setType(
3275             SubstAutoType(New->getType(),
3276                           OldAT->isDependentType() ? Context.DependentTy
3277                                                    : OldAT->getDeducedType()));
3278         NewQType = Context.getCanonicalType(
3279             SubstAutoType(NewQType,
3280                           OldAT->isDependentType() ? Context.DependentTy
3281                                                    : OldAT->getDeducedType()));
3282       }
3283     }
3284 
3285     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3286     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3287     if (OldMethod && NewMethod) {
3288       // Preserve triviality.
3289       NewMethod->setTrivial(OldMethod->isTrivial());
3290 
3291       // MSVC allows explicit template specialization at class scope:
3292       // 2 CXXMethodDecls referring to the same function will be injected.
3293       // We don't want a redeclaration error.
3294       bool IsClassScopeExplicitSpecialization =
3295                               OldMethod->isFunctionTemplateSpecialization() &&
3296                               NewMethod->isFunctionTemplateSpecialization();
3297       bool isFriend = NewMethod->getFriendObjectKind();
3298 
3299       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3300           !IsClassScopeExplicitSpecialization) {
3301         //    -- Member function declarations with the same name and the
3302         //       same parameter types cannot be overloaded if any of them
3303         //       is a static member function declaration.
3304         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3305           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3306           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3307           return true;
3308         }
3309 
3310         // C++ [class.mem]p1:
3311         //   [...] A member shall not be declared twice in the
3312         //   member-specification, except that a nested class or member
3313         //   class template can be declared and then later defined.
3314         if (!inTemplateInstantiation()) {
3315           unsigned NewDiag;
3316           if (isa<CXXConstructorDecl>(OldMethod))
3317             NewDiag = diag::err_constructor_redeclared;
3318           else if (isa<CXXDestructorDecl>(NewMethod))
3319             NewDiag = diag::err_destructor_redeclared;
3320           else if (isa<CXXConversionDecl>(NewMethod))
3321             NewDiag = diag::err_conv_function_redeclared;
3322           else
3323             NewDiag = diag::err_member_redeclared;
3324 
3325           Diag(New->getLocation(), NewDiag);
3326         } else {
3327           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3328             << New << New->getType();
3329         }
3330         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3331         return true;
3332 
3333       // Complain if this is an explicit declaration of a special
3334       // member that was initially declared implicitly.
3335       //
3336       // As an exception, it's okay to befriend such methods in order
3337       // to permit the implicit constructor/destructor/operator calls.
3338       } else if (OldMethod->isImplicit()) {
3339         if (isFriend) {
3340           NewMethod->setImplicit();
3341         } else {
3342           Diag(NewMethod->getLocation(),
3343                diag::err_definition_of_implicitly_declared_member)
3344             << New << getSpecialMember(OldMethod);
3345           return true;
3346         }
3347       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3348         Diag(NewMethod->getLocation(),
3349              diag::err_definition_of_explicitly_defaulted_member)
3350           << getSpecialMember(OldMethod);
3351         return true;
3352       }
3353     }
3354 
3355     // C++11 [dcl.attr.noreturn]p1:
3356     //   The first declaration of a function shall specify the noreturn
3357     //   attribute if any declaration of that function specifies the noreturn
3358     //   attribute.
3359     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3360     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3361       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3362       Diag(Old->getFirstDecl()->getLocation(),
3363            diag::note_noreturn_missing_first_decl);
3364     }
3365 
3366     // C++11 [dcl.attr.depend]p2:
3367     //   The first declaration of a function shall specify the
3368     //   carries_dependency attribute for its declarator-id if any declaration
3369     //   of the function specifies the carries_dependency attribute.
3370     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3371     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3372       Diag(CDA->getLocation(),
3373            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3374       Diag(Old->getFirstDecl()->getLocation(),
3375            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3376     }
3377 
3378     // (C++98 8.3.5p3):
3379     //   All declarations for a function shall agree exactly in both the
3380     //   return type and the parameter-type-list.
3381     // We also want to respect all the extended bits except noreturn.
3382 
3383     // noreturn should now match unless the old type info didn't have it.
3384     QualType OldQTypeForComparison = OldQType;
3385     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3386       auto *OldType = OldQType->castAs<FunctionProtoType>();
3387       const FunctionType *OldTypeForComparison
3388         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3389       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3390       assert(OldQTypeForComparison.isCanonical());
3391     }
3392 
3393     if (haveIncompatibleLanguageLinkages(Old, New)) {
3394       // As a special case, retain the language linkage from previous
3395       // declarations of a friend function as an extension.
3396       //
3397       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3398       // and is useful because there's otherwise no way to specify language
3399       // linkage within class scope.
3400       //
3401       // Check cautiously as the friend object kind isn't yet complete.
3402       if (New->getFriendObjectKind() != Decl::FOK_None) {
3403         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3404         Diag(OldLocation, PrevDiag);
3405       } else {
3406         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3407         Diag(OldLocation, PrevDiag);
3408         return true;
3409       }
3410     }
3411 
3412     if (OldQTypeForComparison == NewQType)
3413       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3414 
3415     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3416         New->isLocalExternDecl()) {
3417       // It's OK if we couldn't merge types for a local function declaraton
3418       // if either the old or new type is dependent. We'll merge the types
3419       // when we instantiate the function.
3420       return false;
3421     }
3422 
3423     // Fall through for conflicting redeclarations and redefinitions.
3424   }
3425 
3426   // C: Function types need to be compatible, not identical. This handles
3427   // duplicate function decls like "void f(int); void f(enum X);" properly.
3428   if (!getLangOpts().CPlusPlus &&
3429       Context.typesAreCompatible(OldQType, NewQType)) {
3430     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3431     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3432     const FunctionProtoType *OldProto = nullptr;
3433     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3434         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3435       // The old declaration provided a function prototype, but the
3436       // new declaration does not. Merge in the prototype.
3437       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3438       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3439       NewQType =
3440           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3441                                   OldProto->getExtProtoInfo());
3442       New->setType(NewQType);
3443       New->setHasInheritedPrototype();
3444 
3445       // Synthesize parameters with the same types.
3446       SmallVector<ParmVarDecl*, 16> Params;
3447       for (const auto &ParamType : OldProto->param_types()) {
3448         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3449                                                  SourceLocation(), nullptr,
3450                                                  ParamType, /*TInfo=*/nullptr,
3451                                                  SC_None, nullptr);
3452         Param->setScopeInfo(0, Params.size());
3453         Param->setImplicit();
3454         Params.push_back(Param);
3455       }
3456 
3457       New->setParams(Params);
3458     }
3459 
3460     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3461   }
3462 
3463   // GNU C permits a K&R definition to follow a prototype declaration
3464   // if the declared types of the parameters in the K&R definition
3465   // match the types in the prototype declaration, even when the
3466   // promoted types of the parameters from the K&R definition differ
3467   // from the types in the prototype. GCC then keeps the types from
3468   // the prototype.
3469   //
3470   // If a variadic prototype is followed by a non-variadic K&R definition,
3471   // the K&R definition becomes variadic.  This is sort of an edge case, but
3472   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3473   // C99 6.9.1p8.
3474   if (!getLangOpts().CPlusPlus &&
3475       Old->hasPrototype() && !New->hasPrototype() &&
3476       New->getType()->getAs<FunctionProtoType>() &&
3477       Old->getNumParams() == New->getNumParams()) {
3478     SmallVector<QualType, 16> ArgTypes;
3479     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3480     const FunctionProtoType *OldProto
3481       = Old->getType()->getAs<FunctionProtoType>();
3482     const FunctionProtoType *NewProto
3483       = New->getType()->getAs<FunctionProtoType>();
3484 
3485     // Determine whether this is the GNU C extension.
3486     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3487                                                NewProto->getReturnType());
3488     bool LooseCompatible = !MergedReturn.isNull();
3489     for (unsigned Idx = 0, End = Old->getNumParams();
3490          LooseCompatible && Idx != End; ++Idx) {
3491       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3492       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3493       if (Context.typesAreCompatible(OldParm->getType(),
3494                                      NewProto->getParamType(Idx))) {
3495         ArgTypes.push_back(NewParm->getType());
3496       } else if (Context.typesAreCompatible(OldParm->getType(),
3497                                             NewParm->getType(),
3498                                             /*CompareUnqualified=*/true)) {
3499         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3500                                            NewProto->getParamType(Idx) };
3501         Warnings.push_back(Warn);
3502         ArgTypes.push_back(NewParm->getType());
3503       } else
3504         LooseCompatible = false;
3505     }
3506 
3507     if (LooseCompatible) {
3508       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3509         Diag(Warnings[Warn].NewParm->getLocation(),
3510              diag::ext_param_promoted_not_compatible_with_prototype)
3511           << Warnings[Warn].PromotedType
3512           << Warnings[Warn].OldParm->getType();
3513         if (Warnings[Warn].OldParm->getLocation().isValid())
3514           Diag(Warnings[Warn].OldParm->getLocation(),
3515                diag::note_previous_declaration);
3516       }
3517 
3518       if (MergeTypeWithOld)
3519         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3520                                              OldProto->getExtProtoInfo()));
3521       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3522     }
3523 
3524     // Fall through to diagnose conflicting types.
3525   }
3526 
3527   // A function that has already been declared has been redeclared or
3528   // defined with a different type; show an appropriate diagnostic.
3529 
3530   // If the previous declaration was an implicitly-generated builtin
3531   // declaration, then at the very least we should use a specialized note.
3532   unsigned BuiltinID;
3533   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3534     // If it's actually a library-defined builtin function like 'malloc'
3535     // or 'printf', just warn about the incompatible redeclaration.
3536     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3537       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3538       Diag(OldLocation, diag::note_previous_builtin_declaration)
3539         << Old << Old->getType();
3540 
3541       // If this is a global redeclaration, just forget hereafter
3542       // about the "builtin-ness" of the function.
3543       //
3544       // Doing this for local extern declarations is problematic.  If
3545       // the builtin declaration remains visible, a second invalid
3546       // local declaration will produce a hard error; if it doesn't
3547       // remain visible, a single bogus local redeclaration (which is
3548       // actually only a warning) could break all the downstream code.
3549       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3550         New->getIdentifier()->revertBuiltin();
3551 
3552       return false;
3553     }
3554 
3555     PrevDiag = diag::note_previous_builtin_declaration;
3556   }
3557 
3558   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3559   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3560   return true;
3561 }
3562 
3563 /// \brief Completes the merge of two function declarations that are
3564 /// known to be compatible.
3565 ///
3566 /// This routine handles the merging of attributes and other
3567 /// properties of function declarations from the old declaration to
3568 /// the new declaration, once we know that New is in fact a
3569 /// redeclaration of Old.
3570 ///
3571 /// \returns false
3572 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3573                                         Scope *S, bool MergeTypeWithOld) {
3574   // Merge the attributes
3575   mergeDeclAttributes(New, Old);
3576 
3577   // Merge "pure" flag.
3578   if (Old->isPure())
3579     New->setPure();
3580 
3581   // Merge "used" flag.
3582   if (Old->getMostRecentDecl()->isUsed(false))
3583     New->setIsUsed();
3584 
3585   // Merge attributes from the parameters.  These can mismatch with K&R
3586   // declarations.
3587   if (New->getNumParams() == Old->getNumParams())
3588       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3589         ParmVarDecl *NewParam = New->getParamDecl(i);
3590         ParmVarDecl *OldParam = Old->getParamDecl(i);
3591         mergeParamDeclAttributes(NewParam, OldParam, *this);
3592         mergeParamDeclTypes(NewParam, OldParam, *this);
3593       }
3594 
3595   if (getLangOpts().CPlusPlus)
3596     return MergeCXXFunctionDecl(New, Old, S);
3597 
3598   // Merge the function types so the we get the composite types for the return
3599   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3600   // was visible.
3601   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3602   if (!Merged.isNull() && MergeTypeWithOld)
3603     New->setType(Merged);
3604 
3605   return false;
3606 }
3607 
3608 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3609                                 ObjCMethodDecl *oldMethod) {
3610   // Merge the attributes, including deprecated/unavailable
3611   AvailabilityMergeKind MergeKind =
3612     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3613       ? AMK_ProtocolImplementation
3614       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3615                                                        : AMK_Override;
3616 
3617   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3618 
3619   // Merge attributes from the parameters.
3620   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3621                                        oe = oldMethod->param_end();
3622   for (ObjCMethodDecl::param_iterator
3623          ni = newMethod->param_begin(), ne = newMethod->param_end();
3624        ni != ne && oi != oe; ++ni, ++oi)
3625     mergeParamDeclAttributes(*ni, *oi, *this);
3626 
3627   CheckObjCMethodOverride(newMethod, oldMethod);
3628 }
3629 
3630 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3631   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3632 
3633   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3634          ? diag::err_redefinition_different_type
3635          : diag::err_redeclaration_different_type)
3636     << New->getDeclName() << New->getType() << Old->getType();
3637 
3638   diag::kind PrevDiag;
3639   SourceLocation OldLocation;
3640   std::tie(PrevDiag, OldLocation)
3641     = getNoteDiagForInvalidRedeclaration(Old, New);
3642   S.Diag(OldLocation, PrevDiag);
3643   New->setInvalidDecl();
3644 }
3645 
3646 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3647 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3648 /// emitting diagnostics as appropriate.
3649 ///
3650 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3651 /// to here in AddInitializerToDecl. We can't check them before the initializer
3652 /// is attached.
3653 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3654                              bool MergeTypeWithOld) {
3655   if (New->isInvalidDecl() || Old->isInvalidDecl())
3656     return;
3657 
3658   QualType MergedT;
3659   if (getLangOpts().CPlusPlus) {
3660     if (New->getType()->isUndeducedType()) {
3661       // We don't know what the new type is until the initializer is attached.
3662       return;
3663     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3664       // These could still be something that needs exception specs checked.
3665       return MergeVarDeclExceptionSpecs(New, Old);
3666     }
3667     // C++ [basic.link]p10:
3668     //   [...] the types specified by all declarations referring to a given
3669     //   object or function shall be identical, except that declarations for an
3670     //   array object can specify array types that differ by the presence or
3671     //   absence of a major array bound (8.3.4).
3672     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3673       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3674       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3675 
3676       // We are merging a variable declaration New into Old. If it has an array
3677       // bound, and that bound differs from Old's bound, we should diagnose the
3678       // mismatch.
3679       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3680         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3681              PrevVD = PrevVD->getPreviousDecl()) {
3682           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3683           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3684             continue;
3685 
3686           if (!Context.hasSameType(NewArray, PrevVDTy))
3687             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3688         }
3689       }
3690 
3691       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3692         if (Context.hasSameType(OldArray->getElementType(),
3693                                 NewArray->getElementType()))
3694           MergedT = New->getType();
3695       }
3696       // FIXME: Check visibility. New is hidden but has a complete type. If New
3697       // has no array bound, it should not inherit one from Old, if Old is not
3698       // visible.
3699       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3700         if (Context.hasSameType(OldArray->getElementType(),
3701                                 NewArray->getElementType()))
3702           MergedT = Old->getType();
3703       }
3704     }
3705     else if (New->getType()->isObjCObjectPointerType() &&
3706                Old->getType()->isObjCObjectPointerType()) {
3707       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3708                                               Old->getType());
3709     }
3710   } else {
3711     // C 6.2.7p2:
3712     //   All declarations that refer to the same object or function shall have
3713     //   compatible type.
3714     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3715   }
3716   if (MergedT.isNull()) {
3717     // It's OK if we couldn't merge types if either type is dependent, for a
3718     // block-scope variable. In other cases (static data members of class
3719     // templates, variable templates, ...), we require the types to be
3720     // equivalent.
3721     // FIXME: The C++ standard doesn't say anything about this.
3722     if ((New->getType()->isDependentType() ||
3723          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3724       // If the old type was dependent, we can't merge with it, so the new type
3725       // becomes dependent for now. We'll reproduce the original type when we
3726       // instantiate the TypeSourceInfo for the variable.
3727       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3728         New->setType(Context.DependentTy);
3729       return;
3730     }
3731     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3732   }
3733 
3734   // Don't actually update the type on the new declaration if the old
3735   // declaration was an extern declaration in a different scope.
3736   if (MergeTypeWithOld)
3737     New->setType(MergedT);
3738 }
3739 
3740 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3741                                   LookupResult &Previous) {
3742   // C11 6.2.7p4:
3743   //   For an identifier with internal or external linkage declared
3744   //   in a scope in which a prior declaration of that identifier is
3745   //   visible, if the prior declaration specifies internal or
3746   //   external linkage, the type of the identifier at the later
3747   //   declaration becomes the composite type.
3748   //
3749   // If the variable isn't visible, we do not merge with its type.
3750   if (Previous.isShadowed())
3751     return false;
3752 
3753   if (S.getLangOpts().CPlusPlus) {
3754     // C++11 [dcl.array]p3:
3755     //   If there is a preceding declaration of the entity in the same
3756     //   scope in which the bound was specified, an omitted array bound
3757     //   is taken to be the same as in that earlier declaration.
3758     return NewVD->isPreviousDeclInSameBlockScope() ||
3759            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3760             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3761   } else {
3762     // If the old declaration was function-local, don't merge with its
3763     // type unless we're in the same function.
3764     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3765            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3766   }
3767 }
3768 
3769 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3770 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3771 /// situation, merging decls or emitting diagnostics as appropriate.
3772 ///
3773 /// Tentative definition rules (C99 6.9.2p2) are checked by
3774 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3775 /// definitions here, since the initializer hasn't been attached.
3776 ///
3777 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3778   // If the new decl is already invalid, don't do any other checking.
3779   if (New->isInvalidDecl())
3780     return;
3781 
3782   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3783     return;
3784 
3785   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3786 
3787   // Verify the old decl was also a variable or variable template.
3788   VarDecl *Old = nullptr;
3789   VarTemplateDecl *OldTemplate = nullptr;
3790   if (Previous.isSingleResult()) {
3791     if (NewTemplate) {
3792       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3793       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3794 
3795       if (auto *Shadow =
3796               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3797         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3798           return New->setInvalidDecl();
3799     } else {
3800       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3801 
3802       if (auto *Shadow =
3803               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3804         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3805           return New->setInvalidDecl();
3806     }
3807   }
3808   if (!Old) {
3809     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3810         << New->getDeclName();
3811     notePreviousDefinition(Previous.getRepresentativeDecl(),
3812                            New->getLocation());
3813     return New->setInvalidDecl();
3814   }
3815 
3816   // Ensure the template parameters are compatible.
3817   if (NewTemplate &&
3818       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3819                                       OldTemplate->getTemplateParameters(),
3820                                       /*Complain=*/true, TPL_TemplateMatch))
3821     return New->setInvalidDecl();
3822 
3823   // C++ [class.mem]p1:
3824   //   A member shall not be declared twice in the member-specification [...]
3825   //
3826   // Here, we need only consider static data members.
3827   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3828     Diag(New->getLocation(), diag::err_duplicate_member)
3829       << New->getIdentifier();
3830     Diag(Old->getLocation(), diag::note_previous_declaration);
3831     New->setInvalidDecl();
3832   }
3833 
3834   mergeDeclAttributes(New, Old);
3835   // Warn if an already-declared variable is made a weak_import in a subsequent
3836   // declaration
3837   if (New->hasAttr<WeakImportAttr>() &&
3838       Old->getStorageClass() == SC_None &&
3839       !Old->hasAttr<WeakImportAttr>()) {
3840     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3841     notePreviousDefinition(Old, New->getLocation());
3842     // Remove weak_import attribute on new declaration.
3843     New->dropAttr<WeakImportAttr>();
3844   }
3845 
3846   if (New->hasAttr<InternalLinkageAttr>() &&
3847       !Old->hasAttr<InternalLinkageAttr>()) {
3848     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3849         << New->getDeclName();
3850     notePreviousDefinition(Old, New->getLocation());
3851     New->dropAttr<InternalLinkageAttr>();
3852   }
3853 
3854   // Merge the types.
3855   VarDecl *MostRecent = Old->getMostRecentDecl();
3856   if (MostRecent != Old) {
3857     MergeVarDeclTypes(New, MostRecent,
3858                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3859     if (New->isInvalidDecl())
3860       return;
3861   }
3862 
3863   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3864   if (New->isInvalidDecl())
3865     return;
3866 
3867   diag::kind PrevDiag;
3868   SourceLocation OldLocation;
3869   std::tie(PrevDiag, OldLocation) =
3870       getNoteDiagForInvalidRedeclaration(Old, New);
3871 
3872   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3873   if (New->getStorageClass() == SC_Static &&
3874       !New->isStaticDataMember() &&
3875       Old->hasExternalFormalLinkage()) {
3876     if (getLangOpts().MicrosoftExt) {
3877       Diag(New->getLocation(), diag::ext_static_non_static)
3878           << New->getDeclName();
3879       Diag(OldLocation, PrevDiag);
3880     } else {
3881       Diag(New->getLocation(), diag::err_static_non_static)
3882           << New->getDeclName();
3883       Diag(OldLocation, PrevDiag);
3884       return New->setInvalidDecl();
3885     }
3886   }
3887   // C99 6.2.2p4:
3888   //   For an identifier declared with the storage-class specifier
3889   //   extern in a scope in which a prior declaration of that
3890   //   identifier is visible,23) if the prior declaration specifies
3891   //   internal or external linkage, the linkage of the identifier at
3892   //   the later declaration is the same as the linkage specified at
3893   //   the prior declaration. If no prior declaration is visible, or
3894   //   if the prior declaration specifies no linkage, then the
3895   //   identifier has external linkage.
3896   if (New->hasExternalStorage() && Old->hasLinkage())
3897     /* Okay */;
3898   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3899            !New->isStaticDataMember() &&
3900            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3901     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3902     Diag(OldLocation, PrevDiag);
3903     return New->setInvalidDecl();
3904   }
3905 
3906   // Check if extern is followed by non-extern and vice-versa.
3907   if (New->hasExternalStorage() &&
3908       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3909     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3910     Diag(OldLocation, PrevDiag);
3911     return New->setInvalidDecl();
3912   }
3913   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3914       !New->hasExternalStorage()) {
3915     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3916     Diag(OldLocation, PrevDiag);
3917     return New->setInvalidDecl();
3918   }
3919 
3920   if (CheckRedeclarationModuleOwnership(New, Old))
3921     return;
3922 
3923   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3924 
3925   // FIXME: The test for external storage here seems wrong? We still
3926   // need to check for mismatches.
3927   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3928       // Don't complain about out-of-line definitions of static members.
3929       !(Old->getLexicalDeclContext()->isRecord() &&
3930         !New->getLexicalDeclContext()->isRecord())) {
3931     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3932     Diag(OldLocation, PrevDiag);
3933     return New->setInvalidDecl();
3934   }
3935 
3936   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3937     if (VarDecl *Def = Old->getDefinition()) {
3938       // C++1z [dcl.fcn.spec]p4:
3939       //   If the definition of a variable appears in a translation unit before
3940       //   its first declaration as inline, the program is ill-formed.
3941       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3942       Diag(Def->getLocation(), diag::note_previous_definition);
3943     }
3944   }
3945 
3946   // If this redeclaration makes the variable inline, we may need to add it to
3947   // UndefinedButUsed.
3948   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3949       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3950     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3951                                            SourceLocation()));
3952 
3953   if (New->getTLSKind() != Old->getTLSKind()) {
3954     if (!Old->getTLSKind()) {
3955       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3956       Diag(OldLocation, PrevDiag);
3957     } else if (!New->getTLSKind()) {
3958       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3959       Diag(OldLocation, PrevDiag);
3960     } else {
3961       // Do not allow redeclaration to change the variable between requiring
3962       // static and dynamic initialization.
3963       // FIXME: GCC allows this, but uses the TLS keyword on the first
3964       // declaration to determine the kind. Do we need to be compatible here?
3965       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3966         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3967       Diag(OldLocation, PrevDiag);
3968     }
3969   }
3970 
3971   // C++ doesn't have tentative definitions, so go right ahead and check here.
3972   if (getLangOpts().CPlusPlus &&
3973       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3974     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3975         Old->getCanonicalDecl()->isConstexpr()) {
3976       // This definition won't be a definition any more once it's been merged.
3977       Diag(New->getLocation(),
3978            diag::warn_deprecated_redundant_constexpr_static_def);
3979     } else if (VarDecl *Def = Old->getDefinition()) {
3980       if (checkVarDeclRedefinition(Def, New))
3981         return;
3982     }
3983   }
3984 
3985   if (haveIncompatibleLanguageLinkages(Old, New)) {
3986     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3987     Diag(OldLocation, PrevDiag);
3988     New->setInvalidDecl();
3989     return;
3990   }
3991 
3992   // Merge "used" flag.
3993   if (Old->getMostRecentDecl()->isUsed(false))
3994     New->setIsUsed();
3995 
3996   // Keep a chain of previous declarations.
3997   New->setPreviousDecl(Old);
3998   if (NewTemplate)
3999     NewTemplate->setPreviousDecl(OldTemplate);
4000   adjustDeclContextForDeclaratorDecl(New, Old);
4001 
4002   // Inherit access appropriately.
4003   New->setAccess(Old->getAccess());
4004   if (NewTemplate)
4005     NewTemplate->setAccess(New->getAccess());
4006 
4007   if (Old->isInline())
4008     New->setImplicitlyInline();
4009 }
4010 
4011 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4012   SourceManager &SrcMgr = getSourceManager();
4013   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4014   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4015   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4016   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4017   auto &HSI = PP.getHeaderSearchInfo();
4018   StringRef HdrFilename =
4019       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4020 
4021   auto noteFromModuleOrInclude = [&](Module *Mod,
4022                                      SourceLocation IncLoc) -> bool {
4023     // Redefinition errors with modules are common with non modular mapped
4024     // headers, example: a non-modular header H in module A that also gets
4025     // included directly in a TU. Pointing twice to the same header/definition
4026     // is confusing, try to get better diagnostics when modules is on.
4027     if (IncLoc.isValid()) {
4028       if (Mod) {
4029         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4030             << HdrFilename.str() << Mod->getFullModuleName();
4031         if (!Mod->DefinitionLoc.isInvalid())
4032           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4033               << Mod->getFullModuleName();
4034       } else {
4035         Diag(IncLoc, diag::note_redefinition_include_same_file)
4036             << HdrFilename.str();
4037       }
4038       return true;
4039     }
4040 
4041     return false;
4042   };
4043 
4044   // Is it the same file and same offset? Provide more information on why
4045   // this leads to a redefinition error.
4046   bool EmittedDiag = false;
4047   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4048     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4049     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4050     EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4051     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4052 
4053     // If the header has no guards, emit a note suggesting one.
4054     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4055       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4056 
4057     if (EmittedDiag)
4058       return;
4059   }
4060 
4061   // Redefinition coming from different files or couldn't do better above.
4062   Diag(Old->getLocation(), diag::note_previous_definition);
4063 }
4064 
4065 /// We've just determined that \p Old and \p New both appear to be definitions
4066 /// of the same variable. Either diagnose or fix the problem.
4067 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4068   if (!hasVisibleDefinition(Old) &&
4069       (New->getFormalLinkage() == InternalLinkage ||
4070        New->isInline() ||
4071        New->getDescribedVarTemplate() ||
4072        New->getNumTemplateParameterLists() ||
4073        New->getDeclContext()->isDependentContext())) {
4074     // The previous definition is hidden, and multiple definitions are
4075     // permitted (in separate TUs). Demote this to a declaration.
4076     New->demoteThisDefinitionToDeclaration();
4077 
4078     // Make the canonical definition visible.
4079     if (auto *OldTD = Old->getDescribedVarTemplate())
4080       makeMergedDefinitionVisible(OldTD);
4081     makeMergedDefinitionVisible(Old);
4082     return false;
4083   } else {
4084     Diag(New->getLocation(), diag::err_redefinition) << New;
4085     notePreviousDefinition(Old, New->getLocation());
4086     New->setInvalidDecl();
4087     return true;
4088   }
4089 }
4090 
4091 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4092 /// no declarator (e.g. "struct foo;") is parsed.
4093 Decl *
4094 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4095                                  RecordDecl *&AnonRecord) {
4096   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4097                                     AnonRecord);
4098 }
4099 
4100 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4101 // disambiguate entities defined in different scopes.
4102 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4103 // compatibility.
4104 // We will pick our mangling number depending on which version of MSVC is being
4105 // targeted.
4106 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4107   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4108              ? S->getMSCurManglingNumber()
4109              : S->getMSLastManglingNumber();
4110 }
4111 
4112 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4113   if (!Context.getLangOpts().CPlusPlus)
4114     return;
4115 
4116   if (isa<CXXRecordDecl>(Tag->getParent())) {
4117     // If this tag is the direct child of a class, number it if
4118     // it is anonymous.
4119     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4120       return;
4121     MangleNumberingContext &MCtx =
4122         Context.getManglingNumberContext(Tag->getParent());
4123     Context.setManglingNumber(
4124         Tag, MCtx.getManglingNumber(
4125                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4126     return;
4127   }
4128 
4129   // If this tag isn't a direct child of a class, number it if it is local.
4130   Decl *ManglingContextDecl;
4131   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4132           Tag->getDeclContext(), ManglingContextDecl)) {
4133     Context.setManglingNumber(
4134         Tag, MCtx->getManglingNumber(
4135                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4136   }
4137 }
4138 
4139 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4140                                         TypedefNameDecl *NewTD) {
4141   if (TagFromDeclSpec->isInvalidDecl())
4142     return;
4143 
4144   // Do nothing if the tag already has a name for linkage purposes.
4145   if (TagFromDeclSpec->hasNameForLinkage())
4146     return;
4147 
4148   // A well-formed anonymous tag must always be a TUK_Definition.
4149   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4150 
4151   // The type must match the tag exactly;  no qualifiers allowed.
4152   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4153                            Context.getTagDeclType(TagFromDeclSpec))) {
4154     if (getLangOpts().CPlusPlus)
4155       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4156     return;
4157   }
4158 
4159   // If we've already computed linkage for the anonymous tag, then
4160   // adding a typedef name for the anonymous decl can change that
4161   // linkage, which might be a serious problem.  Diagnose this as
4162   // unsupported and ignore the typedef name.  TODO: we should
4163   // pursue this as a language defect and establish a formal rule
4164   // for how to handle it.
4165   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4166     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4167 
4168     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4169     tagLoc = getLocForEndOfToken(tagLoc);
4170 
4171     llvm::SmallString<40> textToInsert;
4172     textToInsert += ' ';
4173     textToInsert += NewTD->getIdentifier()->getName();
4174     Diag(tagLoc, diag::note_typedef_changes_linkage)
4175         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4176     return;
4177   }
4178 
4179   // Otherwise, set this is the anon-decl typedef for the tag.
4180   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4181 }
4182 
4183 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4184   switch (T) {
4185   case DeclSpec::TST_class:
4186     return 0;
4187   case DeclSpec::TST_struct:
4188     return 1;
4189   case DeclSpec::TST_interface:
4190     return 2;
4191   case DeclSpec::TST_union:
4192     return 3;
4193   case DeclSpec::TST_enum:
4194     return 4;
4195   default:
4196     llvm_unreachable("unexpected type specifier");
4197   }
4198 }
4199 
4200 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4201 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4202 /// parameters to cope with template friend declarations.
4203 Decl *
4204 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4205                                  MultiTemplateParamsArg TemplateParams,
4206                                  bool IsExplicitInstantiation,
4207                                  RecordDecl *&AnonRecord) {
4208   Decl *TagD = nullptr;
4209   TagDecl *Tag = nullptr;
4210   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4211       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4212       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4213       DS.getTypeSpecType() == DeclSpec::TST_union ||
4214       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4215     TagD = DS.getRepAsDecl();
4216 
4217     if (!TagD) // We probably had an error
4218       return nullptr;
4219 
4220     // Note that the above type specs guarantee that the
4221     // type rep is a Decl, whereas in many of the others
4222     // it's a Type.
4223     if (isa<TagDecl>(TagD))
4224       Tag = cast<TagDecl>(TagD);
4225     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4226       Tag = CTD->getTemplatedDecl();
4227   }
4228 
4229   if (Tag) {
4230     handleTagNumbering(Tag, S);
4231     Tag->setFreeStanding();
4232     if (Tag->isInvalidDecl())
4233       return Tag;
4234   }
4235 
4236   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4237     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4238     // or incomplete types shall not be restrict-qualified."
4239     if (TypeQuals & DeclSpec::TQ_restrict)
4240       Diag(DS.getRestrictSpecLoc(),
4241            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4242            << DS.getSourceRange();
4243   }
4244 
4245   if (DS.isInlineSpecified())
4246     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4247         << getLangOpts().CPlusPlus17;
4248 
4249   if (DS.isConstexprSpecified()) {
4250     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4251     // and definitions of functions and variables.
4252     if (Tag)
4253       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4254           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4255     else
4256       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4257     // Don't emit warnings after this error.
4258     return TagD;
4259   }
4260 
4261   DiagnoseFunctionSpecifiers(DS);
4262 
4263   if (DS.isFriendSpecified()) {
4264     // If we're dealing with a decl but not a TagDecl, assume that
4265     // whatever routines created it handled the friendship aspect.
4266     if (TagD && !Tag)
4267       return nullptr;
4268     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4269   }
4270 
4271   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4272   bool IsExplicitSpecialization =
4273     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4274   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4275       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4276       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4277     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4278     // nested-name-specifier unless it is an explicit instantiation
4279     // or an explicit specialization.
4280     //
4281     // FIXME: We allow class template partial specializations here too, per the
4282     // obvious intent of DR1819.
4283     //
4284     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4285     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4286         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4287     return nullptr;
4288   }
4289 
4290   // Track whether this decl-specifier declares anything.
4291   bool DeclaresAnything = true;
4292 
4293   // Handle anonymous struct definitions.
4294   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4295     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4296         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4297       if (getLangOpts().CPlusPlus ||
4298           Record->getDeclContext()->isRecord()) {
4299         // If CurContext is a DeclContext that can contain statements,
4300         // RecursiveASTVisitor won't visit the decls that
4301         // BuildAnonymousStructOrUnion() will put into CurContext.
4302         // Also store them here so that they can be part of the
4303         // DeclStmt that gets created in this case.
4304         // FIXME: Also return the IndirectFieldDecls created by
4305         // BuildAnonymousStructOr union, for the same reason?
4306         if (CurContext->isFunctionOrMethod())
4307           AnonRecord = Record;
4308         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4309                                            Context.getPrintingPolicy());
4310       }
4311 
4312       DeclaresAnything = false;
4313     }
4314   }
4315 
4316   // C11 6.7.2.1p2:
4317   //   A struct-declaration that does not declare an anonymous structure or
4318   //   anonymous union shall contain a struct-declarator-list.
4319   //
4320   // This rule also existed in C89 and C99; the grammar for struct-declaration
4321   // did not permit a struct-declaration without a struct-declarator-list.
4322   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4323       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4324     // Check for Microsoft C extension: anonymous struct/union member.
4325     // Handle 2 kinds of anonymous struct/union:
4326     //   struct STRUCT;
4327     //   union UNION;
4328     // and
4329     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4330     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4331     if ((Tag && Tag->getDeclName()) ||
4332         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4333       RecordDecl *Record = nullptr;
4334       if (Tag)
4335         Record = dyn_cast<RecordDecl>(Tag);
4336       else if (const RecordType *RT =
4337                    DS.getRepAsType().get()->getAsStructureType())
4338         Record = RT->getDecl();
4339       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4340         Record = UT->getDecl();
4341 
4342       if (Record && getLangOpts().MicrosoftExt) {
4343         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4344           << Record->isUnion() << DS.getSourceRange();
4345         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4346       }
4347 
4348       DeclaresAnything = false;
4349     }
4350   }
4351 
4352   // Skip all the checks below if we have a type error.
4353   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4354       (TagD && TagD->isInvalidDecl()))
4355     return TagD;
4356 
4357   if (getLangOpts().CPlusPlus &&
4358       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4359     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4360       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4361           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4362         DeclaresAnything = false;
4363 
4364   if (!DS.isMissingDeclaratorOk()) {
4365     // Customize diagnostic for a typedef missing a name.
4366     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4367       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4368         << DS.getSourceRange();
4369     else
4370       DeclaresAnything = false;
4371   }
4372 
4373   if (DS.isModulePrivateSpecified() &&
4374       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4375     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4376       << Tag->getTagKind()
4377       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4378 
4379   ActOnDocumentableDecl(TagD);
4380 
4381   // C 6.7/2:
4382   //   A declaration [...] shall declare at least a declarator [...], a tag,
4383   //   or the members of an enumeration.
4384   // C++ [dcl.dcl]p3:
4385   //   [If there are no declarators], and except for the declaration of an
4386   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4387   //   names into the program, or shall redeclare a name introduced by a
4388   //   previous declaration.
4389   if (!DeclaresAnything) {
4390     // In C, we allow this as a (popular) extension / bug. Don't bother
4391     // producing further diagnostics for redundant qualifiers after this.
4392     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4393     return TagD;
4394   }
4395 
4396   // C++ [dcl.stc]p1:
4397   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4398   //   init-declarator-list of the declaration shall not be empty.
4399   // C++ [dcl.fct.spec]p1:
4400   //   If a cv-qualifier appears in a decl-specifier-seq, the
4401   //   init-declarator-list of the declaration shall not be empty.
4402   //
4403   // Spurious qualifiers here appear to be valid in C.
4404   unsigned DiagID = diag::warn_standalone_specifier;
4405   if (getLangOpts().CPlusPlus)
4406     DiagID = diag::ext_standalone_specifier;
4407 
4408   // Note that a linkage-specification sets a storage class, but
4409   // 'extern "C" struct foo;' is actually valid and not theoretically
4410   // useless.
4411   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4412     if (SCS == DeclSpec::SCS_mutable)
4413       // Since mutable is not a viable storage class specifier in C, there is
4414       // no reason to treat it as an extension. Instead, diagnose as an error.
4415       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4416     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4417       Diag(DS.getStorageClassSpecLoc(), DiagID)
4418         << DeclSpec::getSpecifierName(SCS);
4419   }
4420 
4421   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4422     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4423       << DeclSpec::getSpecifierName(TSCS);
4424   if (DS.getTypeQualifiers()) {
4425     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4426       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4427     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4428       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4429     // Restrict is covered above.
4430     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4431       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4432     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4433       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4434   }
4435 
4436   // Warn about ignored type attributes, for example:
4437   // __attribute__((aligned)) struct A;
4438   // Attributes should be placed after tag to apply to type declaration.
4439   if (!DS.getAttributes().empty()) {
4440     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4441     if (TypeSpecType == DeclSpec::TST_class ||
4442         TypeSpecType == DeclSpec::TST_struct ||
4443         TypeSpecType == DeclSpec::TST_interface ||
4444         TypeSpecType == DeclSpec::TST_union ||
4445         TypeSpecType == DeclSpec::TST_enum) {
4446       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4447            attrs = attrs->getNext())
4448         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4449             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4450     }
4451   }
4452 
4453   return TagD;
4454 }
4455 
4456 /// We are trying to inject an anonymous member into the given scope;
4457 /// check if there's an existing declaration that can't be overloaded.
4458 ///
4459 /// \return true if this is a forbidden redeclaration
4460 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4461                                          Scope *S,
4462                                          DeclContext *Owner,
4463                                          DeclarationName Name,
4464                                          SourceLocation NameLoc,
4465                                          bool IsUnion) {
4466   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4467                  Sema::ForVisibleRedeclaration);
4468   if (!SemaRef.LookupName(R, S)) return false;
4469 
4470   // Pick a representative declaration.
4471   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4472   assert(PrevDecl && "Expected a non-null Decl");
4473 
4474   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4475     return false;
4476 
4477   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4478     << IsUnion << Name;
4479   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4480 
4481   return true;
4482 }
4483 
4484 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4485 /// anonymous struct or union AnonRecord into the owning context Owner
4486 /// and scope S. This routine will be invoked just after we realize
4487 /// that an unnamed union or struct is actually an anonymous union or
4488 /// struct, e.g.,
4489 ///
4490 /// @code
4491 /// union {
4492 ///   int i;
4493 ///   float f;
4494 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4495 ///    // f into the surrounding scope.x
4496 /// @endcode
4497 ///
4498 /// This routine is recursive, injecting the names of nested anonymous
4499 /// structs/unions into the owning context and scope as well.
4500 static bool
4501 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4502                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4503                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4504   bool Invalid = false;
4505 
4506   // Look every FieldDecl and IndirectFieldDecl with a name.
4507   for (auto *D : AnonRecord->decls()) {
4508     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4509         cast<NamedDecl>(D)->getDeclName()) {
4510       ValueDecl *VD = cast<ValueDecl>(D);
4511       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4512                                        VD->getLocation(),
4513                                        AnonRecord->isUnion())) {
4514         // C++ [class.union]p2:
4515         //   The names of the members of an anonymous union shall be
4516         //   distinct from the names of any other entity in the
4517         //   scope in which the anonymous union is declared.
4518         Invalid = true;
4519       } else {
4520         // C++ [class.union]p2:
4521         //   For the purpose of name lookup, after the anonymous union
4522         //   definition, the members of the anonymous union are
4523         //   considered to have been defined in the scope in which the
4524         //   anonymous union is declared.
4525         unsigned OldChainingSize = Chaining.size();
4526         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4527           Chaining.append(IF->chain_begin(), IF->chain_end());
4528         else
4529           Chaining.push_back(VD);
4530 
4531         assert(Chaining.size() >= 2);
4532         NamedDecl **NamedChain =
4533           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4534         for (unsigned i = 0; i < Chaining.size(); i++)
4535           NamedChain[i] = Chaining[i];
4536 
4537         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4538             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4539             VD->getType(), {NamedChain, Chaining.size()});
4540 
4541         for (const auto *Attr : VD->attrs())
4542           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4543 
4544         IndirectField->setAccess(AS);
4545         IndirectField->setImplicit();
4546         SemaRef.PushOnScopeChains(IndirectField, S);
4547 
4548         // That includes picking up the appropriate access specifier.
4549         if (AS != AS_none) IndirectField->setAccess(AS);
4550 
4551         Chaining.resize(OldChainingSize);
4552       }
4553     }
4554   }
4555 
4556   return Invalid;
4557 }
4558 
4559 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4560 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4561 /// illegal input values are mapped to SC_None.
4562 static StorageClass
4563 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4564   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4565   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4566          "Parser allowed 'typedef' as storage class VarDecl.");
4567   switch (StorageClassSpec) {
4568   case DeclSpec::SCS_unspecified:    return SC_None;
4569   case DeclSpec::SCS_extern:
4570     if (DS.isExternInLinkageSpec())
4571       return SC_None;
4572     return SC_Extern;
4573   case DeclSpec::SCS_static:         return SC_Static;
4574   case DeclSpec::SCS_auto:           return SC_Auto;
4575   case DeclSpec::SCS_register:       return SC_Register;
4576   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4577     // Illegal SCSs map to None: error reporting is up to the caller.
4578   case DeclSpec::SCS_mutable:        // Fall through.
4579   case DeclSpec::SCS_typedef:        return SC_None;
4580   }
4581   llvm_unreachable("unknown storage class specifier");
4582 }
4583 
4584 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4585   assert(Record->hasInClassInitializer());
4586 
4587   for (const auto *I : Record->decls()) {
4588     const auto *FD = dyn_cast<FieldDecl>(I);
4589     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4590       FD = IFD->getAnonField();
4591     if (FD && FD->hasInClassInitializer())
4592       return FD->getLocation();
4593   }
4594 
4595   llvm_unreachable("couldn't find in-class initializer");
4596 }
4597 
4598 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4599                                       SourceLocation DefaultInitLoc) {
4600   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4601     return;
4602 
4603   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4604   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4605 }
4606 
4607 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4608                                       CXXRecordDecl *AnonUnion) {
4609   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4610     return;
4611 
4612   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4613 }
4614 
4615 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4616 /// anonymous structure or union. Anonymous unions are a C++ feature
4617 /// (C++ [class.union]) and a C11 feature; anonymous structures
4618 /// are a C11 feature and GNU C++ extension.
4619 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4620                                         AccessSpecifier AS,
4621                                         RecordDecl *Record,
4622                                         const PrintingPolicy &Policy) {
4623   DeclContext *Owner = Record->getDeclContext();
4624 
4625   // Diagnose whether this anonymous struct/union is an extension.
4626   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4627     Diag(Record->getLocation(), diag::ext_anonymous_union);
4628   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4629     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4630   else if (!Record->isUnion() && !getLangOpts().C11)
4631     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4632 
4633   // C and C++ require different kinds of checks for anonymous
4634   // structs/unions.
4635   bool Invalid = false;
4636   if (getLangOpts().CPlusPlus) {
4637     const char *PrevSpec = nullptr;
4638     unsigned DiagID;
4639     if (Record->isUnion()) {
4640       // C++ [class.union]p6:
4641       //   Anonymous unions declared in a named namespace or in the
4642       //   global namespace shall be declared static.
4643       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4644           (isa<TranslationUnitDecl>(Owner) ||
4645            (isa<NamespaceDecl>(Owner) &&
4646             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4647         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4648           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4649 
4650         // Recover by adding 'static'.
4651         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4652                                PrevSpec, DiagID, Policy);
4653       }
4654       // C++ [class.union]p6:
4655       //   A storage class is not allowed in a declaration of an
4656       //   anonymous union in a class scope.
4657       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4658                isa<RecordDecl>(Owner)) {
4659         Diag(DS.getStorageClassSpecLoc(),
4660              diag::err_anonymous_union_with_storage_spec)
4661           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4662 
4663         // Recover by removing the storage specifier.
4664         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4665                                SourceLocation(),
4666                                PrevSpec, DiagID, Context.getPrintingPolicy());
4667       }
4668     }
4669 
4670     // Ignore const/volatile/restrict qualifiers.
4671     if (DS.getTypeQualifiers()) {
4672       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4673         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4674           << Record->isUnion() << "const"
4675           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4676       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4677         Diag(DS.getVolatileSpecLoc(),
4678              diag::ext_anonymous_struct_union_qualified)
4679           << Record->isUnion() << "volatile"
4680           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4681       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4682         Diag(DS.getRestrictSpecLoc(),
4683              diag::ext_anonymous_struct_union_qualified)
4684           << Record->isUnion() << "restrict"
4685           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4686       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4687         Diag(DS.getAtomicSpecLoc(),
4688              diag::ext_anonymous_struct_union_qualified)
4689           << Record->isUnion() << "_Atomic"
4690           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4691       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4692         Diag(DS.getUnalignedSpecLoc(),
4693              diag::ext_anonymous_struct_union_qualified)
4694           << Record->isUnion() << "__unaligned"
4695           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4696 
4697       DS.ClearTypeQualifiers();
4698     }
4699 
4700     // C++ [class.union]p2:
4701     //   The member-specification of an anonymous union shall only
4702     //   define non-static data members. [Note: nested types and
4703     //   functions cannot be declared within an anonymous union. ]
4704     for (auto *Mem : Record->decls()) {
4705       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4706         // C++ [class.union]p3:
4707         //   An anonymous union shall not have private or protected
4708         //   members (clause 11).
4709         assert(FD->getAccess() != AS_none);
4710         if (FD->getAccess() != AS_public) {
4711           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4712             << Record->isUnion() << (FD->getAccess() == AS_protected);
4713           Invalid = true;
4714         }
4715 
4716         // C++ [class.union]p1
4717         //   An object of a class with a non-trivial constructor, a non-trivial
4718         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4719         //   assignment operator cannot be a member of a union, nor can an
4720         //   array of such objects.
4721         if (CheckNontrivialField(FD))
4722           Invalid = true;
4723       } else if (Mem->isImplicit()) {
4724         // Any implicit members are fine.
4725       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4726         // This is a type that showed up in an
4727         // elaborated-type-specifier inside the anonymous struct or
4728         // union, but which actually declares a type outside of the
4729         // anonymous struct or union. It's okay.
4730       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4731         if (!MemRecord->isAnonymousStructOrUnion() &&
4732             MemRecord->getDeclName()) {
4733           // Visual C++ allows type definition in anonymous struct or union.
4734           if (getLangOpts().MicrosoftExt)
4735             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4736               << Record->isUnion();
4737           else {
4738             // This is a nested type declaration.
4739             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4740               << Record->isUnion();
4741             Invalid = true;
4742           }
4743         } else {
4744           // This is an anonymous type definition within another anonymous type.
4745           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4746           // not part of standard C++.
4747           Diag(MemRecord->getLocation(),
4748                diag::ext_anonymous_record_with_anonymous_type)
4749             << Record->isUnion();
4750         }
4751       } else if (isa<AccessSpecDecl>(Mem)) {
4752         // Any access specifier is fine.
4753       } else if (isa<StaticAssertDecl>(Mem)) {
4754         // In C++1z, static_assert declarations are also fine.
4755       } else {
4756         // We have something that isn't a non-static data
4757         // member. Complain about it.
4758         unsigned DK = diag::err_anonymous_record_bad_member;
4759         if (isa<TypeDecl>(Mem))
4760           DK = diag::err_anonymous_record_with_type;
4761         else if (isa<FunctionDecl>(Mem))
4762           DK = diag::err_anonymous_record_with_function;
4763         else if (isa<VarDecl>(Mem))
4764           DK = diag::err_anonymous_record_with_static;
4765 
4766         // Visual C++ allows type definition in anonymous struct or union.
4767         if (getLangOpts().MicrosoftExt &&
4768             DK == diag::err_anonymous_record_with_type)
4769           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4770             << Record->isUnion();
4771         else {
4772           Diag(Mem->getLocation(), DK) << Record->isUnion();
4773           Invalid = true;
4774         }
4775       }
4776     }
4777 
4778     // C++11 [class.union]p8 (DR1460):
4779     //   At most one variant member of a union may have a
4780     //   brace-or-equal-initializer.
4781     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4782         Owner->isRecord())
4783       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4784                                 cast<CXXRecordDecl>(Record));
4785   }
4786 
4787   if (!Record->isUnion() && !Owner->isRecord()) {
4788     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4789       << getLangOpts().CPlusPlus;
4790     Invalid = true;
4791   }
4792 
4793   // Mock up a declarator.
4794   Declarator Dc(DS, DeclaratorContext::MemberContext);
4795   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4796   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4797 
4798   // Create a declaration for this anonymous struct/union.
4799   NamedDecl *Anon = nullptr;
4800   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4801     Anon = FieldDecl::Create(Context, OwningClass,
4802                              DS.getLocStart(),
4803                              Record->getLocation(),
4804                              /*IdentifierInfo=*/nullptr,
4805                              Context.getTypeDeclType(Record),
4806                              TInfo,
4807                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4808                              /*InitStyle=*/ICIS_NoInit);
4809     Anon->setAccess(AS);
4810     if (getLangOpts().CPlusPlus)
4811       FieldCollector->Add(cast<FieldDecl>(Anon));
4812   } else {
4813     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4814     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4815     if (SCSpec == DeclSpec::SCS_mutable) {
4816       // mutable can only appear on non-static class members, so it's always
4817       // an error here
4818       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4819       Invalid = true;
4820       SC = SC_None;
4821     }
4822 
4823     Anon = VarDecl::Create(Context, Owner,
4824                            DS.getLocStart(),
4825                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4826                            Context.getTypeDeclType(Record),
4827                            TInfo, SC);
4828 
4829     // Default-initialize the implicit variable. This initialization will be
4830     // trivial in almost all cases, except if a union member has an in-class
4831     // initializer:
4832     //   union { int n = 0; };
4833     ActOnUninitializedDecl(Anon);
4834   }
4835   Anon->setImplicit();
4836 
4837   // Mark this as an anonymous struct/union type.
4838   Record->setAnonymousStructOrUnion(true);
4839 
4840   // Add the anonymous struct/union object to the current
4841   // context. We'll be referencing this object when we refer to one of
4842   // its members.
4843   Owner->addDecl(Anon);
4844 
4845   // Inject the members of the anonymous struct/union into the owning
4846   // context and into the identifier resolver chain for name lookup
4847   // purposes.
4848   SmallVector<NamedDecl*, 2> Chain;
4849   Chain.push_back(Anon);
4850 
4851   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4852     Invalid = true;
4853 
4854   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4855     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4856       Decl *ManglingContextDecl;
4857       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4858               NewVD->getDeclContext(), ManglingContextDecl)) {
4859         Context.setManglingNumber(
4860             NewVD, MCtx->getManglingNumber(
4861                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4862         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4863       }
4864     }
4865   }
4866 
4867   if (Invalid)
4868     Anon->setInvalidDecl();
4869 
4870   return Anon;
4871 }
4872 
4873 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4874 /// Microsoft C anonymous structure.
4875 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4876 /// Example:
4877 ///
4878 /// struct A { int a; };
4879 /// struct B { struct A; int b; };
4880 ///
4881 /// void foo() {
4882 ///   B var;
4883 ///   var.a = 3;
4884 /// }
4885 ///
4886 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4887                                            RecordDecl *Record) {
4888   assert(Record && "expected a record!");
4889 
4890   // Mock up a declarator.
4891   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
4892   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4893   assert(TInfo && "couldn't build declarator info for anonymous struct");
4894 
4895   auto *ParentDecl = cast<RecordDecl>(CurContext);
4896   QualType RecTy = Context.getTypeDeclType(Record);
4897 
4898   // Create a declaration for this anonymous struct.
4899   NamedDecl *Anon = FieldDecl::Create(Context,
4900                              ParentDecl,
4901                              DS.getLocStart(),
4902                              DS.getLocStart(),
4903                              /*IdentifierInfo=*/nullptr,
4904                              RecTy,
4905                              TInfo,
4906                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4907                              /*InitStyle=*/ICIS_NoInit);
4908   Anon->setImplicit();
4909 
4910   // Add the anonymous struct object to the current context.
4911   CurContext->addDecl(Anon);
4912 
4913   // Inject the members of the anonymous struct into the current
4914   // context and into the identifier resolver chain for name lookup
4915   // purposes.
4916   SmallVector<NamedDecl*, 2> Chain;
4917   Chain.push_back(Anon);
4918 
4919   RecordDecl *RecordDef = Record->getDefinition();
4920   if (RequireCompleteType(Anon->getLocation(), RecTy,
4921                           diag::err_field_incomplete) ||
4922       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4923                                           AS_none, Chain)) {
4924     Anon->setInvalidDecl();
4925     ParentDecl->setInvalidDecl();
4926   }
4927 
4928   return Anon;
4929 }
4930 
4931 /// GetNameForDeclarator - Determine the full declaration name for the
4932 /// given Declarator.
4933 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4934   return GetNameFromUnqualifiedId(D.getName());
4935 }
4936 
4937 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4938 DeclarationNameInfo
4939 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4940   DeclarationNameInfo NameInfo;
4941   NameInfo.setLoc(Name.StartLocation);
4942 
4943   switch (Name.getKind()) {
4944 
4945   case UnqualifiedIdKind::IK_ImplicitSelfParam:
4946   case UnqualifiedIdKind::IK_Identifier:
4947     NameInfo.setName(Name.Identifier);
4948     NameInfo.setLoc(Name.StartLocation);
4949     return NameInfo;
4950 
4951   case UnqualifiedIdKind::IK_DeductionGuideName: {
4952     // C++ [temp.deduct.guide]p3:
4953     //   The simple-template-id shall name a class template specialization.
4954     //   The template-name shall be the same identifier as the template-name
4955     //   of the simple-template-id.
4956     // These together intend to imply that the template-name shall name a
4957     // class template.
4958     // FIXME: template<typename T> struct X {};
4959     //        template<typename T> using Y = X<T>;
4960     //        Y(int) -> Y<int>;
4961     //   satisfies these rules but does not name a class template.
4962     TemplateName TN = Name.TemplateName.get().get();
4963     auto *Template = TN.getAsTemplateDecl();
4964     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4965       Diag(Name.StartLocation,
4966            diag::err_deduction_guide_name_not_class_template)
4967         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4968       if (Template)
4969         Diag(Template->getLocation(), diag::note_template_decl_here);
4970       return DeclarationNameInfo();
4971     }
4972 
4973     NameInfo.setName(
4974         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4975     NameInfo.setLoc(Name.StartLocation);
4976     return NameInfo;
4977   }
4978 
4979   case UnqualifiedIdKind::IK_OperatorFunctionId:
4980     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4981                                            Name.OperatorFunctionId.Operator));
4982     NameInfo.setLoc(Name.StartLocation);
4983     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4984       = Name.OperatorFunctionId.SymbolLocations[0];
4985     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4986       = Name.EndLocation.getRawEncoding();
4987     return NameInfo;
4988 
4989   case UnqualifiedIdKind::IK_LiteralOperatorId:
4990     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4991                                                            Name.Identifier));
4992     NameInfo.setLoc(Name.StartLocation);
4993     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4994     return NameInfo;
4995 
4996   case UnqualifiedIdKind::IK_ConversionFunctionId: {
4997     TypeSourceInfo *TInfo;
4998     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4999     if (Ty.isNull())
5000       return DeclarationNameInfo();
5001     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5002                                                Context.getCanonicalType(Ty)));
5003     NameInfo.setLoc(Name.StartLocation);
5004     NameInfo.setNamedTypeInfo(TInfo);
5005     return NameInfo;
5006   }
5007 
5008   case UnqualifiedIdKind::IK_ConstructorName: {
5009     TypeSourceInfo *TInfo;
5010     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5011     if (Ty.isNull())
5012       return DeclarationNameInfo();
5013     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5014                                               Context.getCanonicalType(Ty)));
5015     NameInfo.setLoc(Name.StartLocation);
5016     NameInfo.setNamedTypeInfo(TInfo);
5017     return NameInfo;
5018   }
5019 
5020   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5021     // In well-formed code, we can only have a constructor
5022     // template-id that refers to the current context, so go there
5023     // to find the actual type being constructed.
5024     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5025     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5026       return DeclarationNameInfo();
5027 
5028     // Determine the type of the class being constructed.
5029     QualType CurClassType = Context.getTypeDeclType(CurClass);
5030 
5031     // FIXME: Check two things: that the template-id names the same type as
5032     // CurClassType, and that the template-id does not occur when the name
5033     // was qualified.
5034 
5035     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5036                                     Context.getCanonicalType(CurClassType)));
5037     NameInfo.setLoc(Name.StartLocation);
5038     // FIXME: should we retrieve TypeSourceInfo?
5039     NameInfo.setNamedTypeInfo(nullptr);
5040     return NameInfo;
5041   }
5042 
5043   case UnqualifiedIdKind::IK_DestructorName: {
5044     TypeSourceInfo *TInfo;
5045     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5046     if (Ty.isNull())
5047       return DeclarationNameInfo();
5048     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5049                                               Context.getCanonicalType(Ty)));
5050     NameInfo.setLoc(Name.StartLocation);
5051     NameInfo.setNamedTypeInfo(TInfo);
5052     return NameInfo;
5053   }
5054 
5055   case UnqualifiedIdKind::IK_TemplateId: {
5056     TemplateName TName = Name.TemplateId->Template.get();
5057     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5058     return Context.getNameForTemplate(TName, TNameLoc);
5059   }
5060 
5061   } // switch (Name.getKind())
5062 
5063   llvm_unreachable("Unknown name kind");
5064 }
5065 
5066 static QualType getCoreType(QualType Ty) {
5067   do {
5068     if (Ty->isPointerType() || Ty->isReferenceType())
5069       Ty = Ty->getPointeeType();
5070     else if (Ty->isArrayType())
5071       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5072     else
5073       return Ty.withoutLocalFastQualifiers();
5074   } while (true);
5075 }
5076 
5077 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5078 /// and Definition have "nearly" matching parameters. This heuristic is
5079 /// used to improve diagnostics in the case where an out-of-line function
5080 /// definition doesn't match any declaration within the class or namespace.
5081 /// Also sets Params to the list of indices to the parameters that differ
5082 /// between the declaration and the definition. If hasSimilarParameters
5083 /// returns true and Params is empty, then all of the parameters match.
5084 static bool hasSimilarParameters(ASTContext &Context,
5085                                      FunctionDecl *Declaration,
5086                                      FunctionDecl *Definition,
5087                                      SmallVectorImpl<unsigned> &Params) {
5088   Params.clear();
5089   if (Declaration->param_size() != Definition->param_size())
5090     return false;
5091   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5092     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5093     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5094 
5095     // The parameter types are identical
5096     if (Context.hasSameType(DefParamTy, DeclParamTy))
5097       continue;
5098 
5099     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5100     QualType DefParamBaseTy = getCoreType(DefParamTy);
5101     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5102     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5103 
5104     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5105         (DeclTyName && DeclTyName == DefTyName))
5106       Params.push_back(Idx);
5107     else  // The two parameters aren't even close
5108       return false;
5109   }
5110 
5111   return true;
5112 }
5113 
5114 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5115 /// declarator needs to be rebuilt in the current instantiation.
5116 /// Any bits of declarator which appear before the name are valid for
5117 /// consideration here.  That's specifically the type in the decl spec
5118 /// and the base type in any member-pointer chunks.
5119 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5120                                                     DeclarationName Name) {
5121   // The types we specifically need to rebuild are:
5122   //   - typenames, typeofs, and decltypes
5123   //   - types which will become injected class names
5124   // Of course, we also need to rebuild any type referencing such a
5125   // type.  It's safest to just say "dependent", but we call out a
5126   // few cases here.
5127 
5128   DeclSpec &DS = D.getMutableDeclSpec();
5129   switch (DS.getTypeSpecType()) {
5130   case DeclSpec::TST_typename:
5131   case DeclSpec::TST_typeofType:
5132   case DeclSpec::TST_underlyingType:
5133   case DeclSpec::TST_atomic: {
5134     // Grab the type from the parser.
5135     TypeSourceInfo *TSI = nullptr;
5136     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5137     if (T.isNull() || !T->isDependentType()) break;
5138 
5139     // Make sure there's a type source info.  This isn't really much
5140     // of a waste; most dependent types should have type source info
5141     // attached already.
5142     if (!TSI)
5143       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5144 
5145     // Rebuild the type in the current instantiation.
5146     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5147     if (!TSI) return true;
5148 
5149     // Store the new type back in the decl spec.
5150     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5151     DS.UpdateTypeRep(LocType);
5152     break;
5153   }
5154 
5155   case DeclSpec::TST_decltype:
5156   case DeclSpec::TST_typeofExpr: {
5157     Expr *E = DS.getRepAsExpr();
5158     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5159     if (Result.isInvalid()) return true;
5160     DS.UpdateExprRep(Result.get());
5161     break;
5162   }
5163 
5164   default:
5165     // Nothing to do for these decl specs.
5166     break;
5167   }
5168 
5169   // It doesn't matter what order we do this in.
5170   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5171     DeclaratorChunk &Chunk = D.getTypeObject(I);
5172 
5173     // The only type information in the declarator which can come
5174     // before the declaration name is the base type of a member
5175     // pointer.
5176     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5177       continue;
5178 
5179     // Rebuild the scope specifier in-place.
5180     CXXScopeSpec &SS = Chunk.Mem.Scope();
5181     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5182       return true;
5183   }
5184 
5185   return false;
5186 }
5187 
5188 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5189   D.setFunctionDefinitionKind(FDK_Declaration);
5190   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5191 
5192   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5193       Dcl && Dcl->getDeclContext()->isFileContext())
5194     Dcl->setTopLevelDeclInObjCContainer();
5195 
5196   if (getLangOpts().OpenCL)
5197     setCurrentOpenCLExtensionForDecl(Dcl);
5198 
5199   return Dcl;
5200 }
5201 
5202 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5203 ///   If T is the name of a class, then each of the following shall have a
5204 ///   name different from T:
5205 ///     - every static data member of class T;
5206 ///     - every member function of class T
5207 ///     - every member of class T that is itself a type;
5208 /// \returns true if the declaration name violates these rules.
5209 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5210                                    DeclarationNameInfo NameInfo) {
5211   DeclarationName Name = NameInfo.getName();
5212 
5213   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5214   while (Record && Record->isAnonymousStructOrUnion())
5215     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5216   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5217     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5218     return true;
5219   }
5220 
5221   return false;
5222 }
5223 
5224 /// \brief Diagnose a declaration whose declarator-id has the given
5225 /// nested-name-specifier.
5226 ///
5227 /// \param SS The nested-name-specifier of the declarator-id.
5228 ///
5229 /// \param DC The declaration context to which the nested-name-specifier
5230 /// resolves.
5231 ///
5232 /// \param Name The name of the entity being declared.
5233 ///
5234 /// \param Loc The location of the name of the entity being declared.
5235 ///
5236 /// \returns true if we cannot safely recover from this error, false otherwise.
5237 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5238                                         DeclarationName Name,
5239                                         SourceLocation Loc) {
5240   DeclContext *Cur = CurContext;
5241   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5242     Cur = Cur->getParent();
5243 
5244   // If the user provided a superfluous scope specifier that refers back to the
5245   // class in which the entity is already declared, diagnose and ignore it.
5246   //
5247   // class X {
5248   //   void X::f();
5249   // };
5250   //
5251   // Note, it was once ill-formed to give redundant qualification in all
5252   // contexts, but that rule was removed by DR482.
5253   if (Cur->Equals(DC)) {
5254     if (Cur->isRecord()) {
5255       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5256                                       : diag::err_member_extra_qualification)
5257         << Name << FixItHint::CreateRemoval(SS.getRange());
5258       SS.clear();
5259     } else {
5260       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5261     }
5262     return false;
5263   }
5264 
5265   // Check whether the qualifying scope encloses the scope of the original
5266   // declaration.
5267   if (!Cur->Encloses(DC)) {
5268     if (Cur->isRecord())
5269       Diag(Loc, diag::err_member_qualification)
5270         << Name << SS.getRange();
5271     else if (isa<TranslationUnitDecl>(DC))
5272       Diag(Loc, diag::err_invalid_declarator_global_scope)
5273         << Name << SS.getRange();
5274     else if (isa<FunctionDecl>(Cur))
5275       Diag(Loc, diag::err_invalid_declarator_in_function)
5276         << Name << SS.getRange();
5277     else if (isa<BlockDecl>(Cur))
5278       Diag(Loc, diag::err_invalid_declarator_in_block)
5279         << Name << SS.getRange();
5280     else
5281       Diag(Loc, diag::err_invalid_declarator_scope)
5282       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5283 
5284     return true;
5285   }
5286 
5287   if (Cur->isRecord()) {
5288     // Cannot qualify members within a class.
5289     Diag(Loc, diag::err_member_qualification)
5290       << Name << SS.getRange();
5291     SS.clear();
5292 
5293     // C++ constructors and destructors with incorrect scopes can break
5294     // our AST invariants by having the wrong underlying types. If
5295     // that's the case, then drop this declaration entirely.
5296     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5297          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5298         !Context.hasSameType(Name.getCXXNameType(),
5299                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5300       return true;
5301 
5302     return false;
5303   }
5304 
5305   // C++11 [dcl.meaning]p1:
5306   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5307   //   not begin with a decltype-specifer"
5308   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5309   while (SpecLoc.getPrefix())
5310     SpecLoc = SpecLoc.getPrefix();
5311   if (dyn_cast_or_null<DecltypeType>(
5312         SpecLoc.getNestedNameSpecifier()->getAsType()))
5313     Diag(Loc, diag::err_decltype_in_declarator)
5314       << SpecLoc.getTypeLoc().getSourceRange();
5315 
5316   return false;
5317 }
5318 
5319 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5320                                   MultiTemplateParamsArg TemplateParamLists) {
5321   // TODO: consider using NameInfo for diagnostic.
5322   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5323   DeclarationName Name = NameInfo.getName();
5324 
5325   // All of these full declarators require an identifier.  If it doesn't have
5326   // one, the ParsedFreeStandingDeclSpec action should be used.
5327   if (D.isDecompositionDeclarator()) {
5328     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5329   } else if (!Name) {
5330     if (!D.isInvalidType())  // Reject this if we think it is valid.
5331       Diag(D.getDeclSpec().getLocStart(),
5332            diag::err_declarator_need_ident)
5333         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5334     return nullptr;
5335   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5336     return nullptr;
5337 
5338   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5339   // we find one that is.
5340   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5341          (S->getFlags() & Scope::TemplateParamScope) != 0)
5342     S = S->getParent();
5343 
5344   DeclContext *DC = CurContext;
5345   if (D.getCXXScopeSpec().isInvalid())
5346     D.setInvalidType();
5347   else if (D.getCXXScopeSpec().isSet()) {
5348     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5349                                         UPPC_DeclarationQualifier))
5350       return nullptr;
5351 
5352     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5353     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5354     if (!DC || isa<EnumDecl>(DC)) {
5355       // If we could not compute the declaration context, it's because the
5356       // declaration context is dependent but does not refer to a class,
5357       // class template, or class template partial specialization. Complain
5358       // and return early, to avoid the coming semantic disaster.
5359       Diag(D.getIdentifierLoc(),
5360            diag::err_template_qualified_declarator_no_match)
5361         << D.getCXXScopeSpec().getScopeRep()
5362         << D.getCXXScopeSpec().getRange();
5363       return nullptr;
5364     }
5365     bool IsDependentContext = DC->isDependentContext();
5366 
5367     if (!IsDependentContext &&
5368         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5369       return nullptr;
5370 
5371     // If a class is incomplete, do not parse entities inside it.
5372     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5373       Diag(D.getIdentifierLoc(),
5374            diag::err_member_def_undefined_record)
5375         << Name << DC << D.getCXXScopeSpec().getRange();
5376       return nullptr;
5377     }
5378     if (!D.getDeclSpec().isFriendSpecified()) {
5379       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
5380                                       Name, D.getIdentifierLoc())) {
5381         if (DC->isRecord())
5382           return nullptr;
5383 
5384         D.setInvalidType();
5385       }
5386     }
5387 
5388     // Check whether we need to rebuild the type of the given
5389     // declaration in the current instantiation.
5390     if (EnteringContext && IsDependentContext &&
5391         TemplateParamLists.size() != 0) {
5392       ContextRAII SavedContext(*this, DC);
5393       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5394         D.setInvalidType();
5395     }
5396   }
5397 
5398   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5399   QualType R = TInfo->getType();
5400 
5401   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5402                                       UPPC_DeclarationType))
5403     D.setInvalidType();
5404 
5405   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5406                         forRedeclarationInCurContext());
5407 
5408   // See if this is a redefinition of a variable in the same scope.
5409   if (!D.getCXXScopeSpec().isSet()) {
5410     bool IsLinkageLookup = false;
5411     bool CreateBuiltins = false;
5412 
5413     // If the declaration we're planning to build will be a function
5414     // or object with linkage, then look for another declaration with
5415     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5416     //
5417     // If the declaration we're planning to build will be declared with
5418     // external linkage in the translation unit, create any builtin with
5419     // the same name.
5420     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5421       /* Do nothing*/;
5422     else if (CurContext->isFunctionOrMethod() &&
5423              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5424               R->isFunctionType())) {
5425       IsLinkageLookup = true;
5426       CreateBuiltins =
5427           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5428     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5429                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5430       CreateBuiltins = true;
5431 
5432     if (IsLinkageLookup) {
5433       Previous.clear(LookupRedeclarationWithLinkage);
5434       Previous.setRedeclarationKind(ForExternalRedeclaration);
5435     }
5436 
5437     LookupName(Previous, S, CreateBuiltins);
5438   } else { // Something like "int foo::x;"
5439     LookupQualifiedName(Previous, DC);
5440 
5441     // C++ [dcl.meaning]p1:
5442     //   When the declarator-id is qualified, the declaration shall refer to a
5443     //  previously declared member of the class or namespace to which the
5444     //  qualifier refers (or, in the case of a namespace, of an element of the
5445     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5446     //  thereof; [...]
5447     //
5448     // Note that we already checked the context above, and that we do not have
5449     // enough information to make sure that Previous contains the declaration
5450     // we want to match. For example, given:
5451     //
5452     //   class X {
5453     //     void f();
5454     //     void f(float);
5455     //   };
5456     //
5457     //   void X::f(int) { } // ill-formed
5458     //
5459     // In this case, Previous will point to the overload set
5460     // containing the two f's declared in X, but neither of them
5461     // matches.
5462 
5463     // C++ [dcl.meaning]p1:
5464     //   [...] the member shall not merely have been introduced by a
5465     //   using-declaration in the scope of the class or namespace nominated by
5466     //   the nested-name-specifier of the declarator-id.
5467     RemoveUsingDecls(Previous);
5468   }
5469 
5470   if (Previous.isSingleResult() &&
5471       Previous.getFoundDecl()->isTemplateParameter()) {
5472     // Maybe we will complain about the shadowed template parameter.
5473     if (!D.isInvalidType())
5474       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5475                                       Previous.getFoundDecl());
5476 
5477     // Just pretend that we didn't see the previous declaration.
5478     Previous.clear();
5479   }
5480 
5481   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5482     // Forget that the previous declaration is the injected-class-name.
5483     Previous.clear();
5484 
5485   // In C++, the previous declaration we find might be a tag type
5486   // (class or enum). In this case, the new declaration will hide the
5487   // tag type. Note that this applies to functions, function templates, and
5488   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5489   if (Previous.isSingleTagDecl() &&
5490       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5491       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5492     Previous.clear();
5493 
5494   // Check that there are no default arguments other than in the parameters
5495   // of a function declaration (C++ only).
5496   if (getLangOpts().CPlusPlus)
5497     CheckExtraCXXDefaultArguments(D);
5498 
5499   NamedDecl *New;
5500 
5501   bool AddToScope = true;
5502   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5503     if (TemplateParamLists.size()) {
5504       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5505       return nullptr;
5506     }
5507 
5508     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5509   } else if (R->isFunctionType()) {
5510     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5511                                   TemplateParamLists,
5512                                   AddToScope);
5513   } else {
5514     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5515                                   AddToScope);
5516   }
5517 
5518   if (!New)
5519     return nullptr;
5520 
5521   // If this has an identifier and is not a function template specialization,
5522   // add it to the scope stack.
5523   if (New->getDeclName() && AddToScope) {
5524     // Only make a locally-scoped extern declaration visible if it is the first
5525     // declaration of this entity. Qualified lookup for such an entity should
5526     // only find this declaration if there is no visible declaration of it.
5527     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5528     PushOnScopeChains(New, S, AddToContext);
5529     if (!AddToContext)
5530       CurContext->addHiddenDecl(New);
5531   }
5532 
5533   if (isInOpenMPDeclareTargetContext())
5534     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5535 
5536   return New;
5537 }
5538 
5539 /// Helper method to turn variable array types into constant array
5540 /// types in certain situations which would otherwise be errors (for
5541 /// GCC compatibility).
5542 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5543                                                     ASTContext &Context,
5544                                                     bool &SizeIsNegative,
5545                                                     llvm::APSInt &Oversized) {
5546   // This method tries to turn a variable array into a constant
5547   // array even when the size isn't an ICE.  This is necessary
5548   // for compatibility with code that depends on gcc's buggy
5549   // constant expression folding, like struct {char x[(int)(char*)2];}
5550   SizeIsNegative = false;
5551   Oversized = 0;
5552 
5553   if (T->isDependentType())
5554     return QualType();
5555 
5556   QualifierCollector Qs;
5557   const Type *Ty = Qs.strip(T);
5558 
5559   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5560     QualType Pointee = PTy->getPointeeType();
5561     QualType FixedType =
5562         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5563                                             Oversized);
5564     if (FixedType.isNull()) return FixedType;
5565     FixedType = Context.getPointerType(FixedType);
5566     return Qs.apply(Context, FixedType);
5567   }
5568   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5569     QualType Inner = PTy->getInnerType();
5570     QualType FixedType =
5571         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5572                                             Oversized);
5573     if (FixedType.isNull()) return FixedType;
5574     FixedType = Context.getParenType(FixedType);
5575     return Qs.apply(Context, FixedType);
5576   }
5577 
5578   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5579   if (!VLATy)
5580     return QualType();
5581   // FIXME: We should probably handle this case
5582   if (VLATy->getElementType()->isVariablyModifiedType())
5583     return QualType();
5584 
5585   llvm::APSInt Res;
5586   if (!VLATy->getSizeExpr() ||
5587       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5588     return QualType();
5589 
5590   // Check whether the array size is negative.
5591   if (Res.isSigned() && Res.isNegative()) {
5592     SizeIsNegative = true;
5593     return QualType();
5594   }
5595 
5596   // Check whether the array is too large to be addressed.
5597   unsigned ActiveSizeBits
5598     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5599                                               Res);
5600   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5601     Oversized = Res;
5602     return QualType();
5603   }
5604 
5605   return Context.getConstantArrayType(VLATy->getElementType(),
5606                                       Res, ArrayType::Normal, 0);
5607 }
5608 
5609 static void
5610 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5611   SrcTL = SrcTL.getUnqualifiedLoc();
5612   DstTL = DstTL.getUnqualifiedLoc();
5613   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5614     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5615     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5616                                       DstPTL.getPointeeLoc());
5617     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5618     return;
5619   }
5620   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5621     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5622     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5623                                       DstPTL.getInnerLoc());
5624     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5625     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5626     return;
5627   }
5628   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5629   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5630   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5631   TypeLoc DstElemTL = DstATL.getElementLoc();
5632   DstElemTL.initializeFullCopy(SrcElemTL);
5633   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5634   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5635   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5636 }
5637 
5638 /// Helper method to turn variable array types into constant array
5639 /// types in certain situations which would otherwise be errors (for
5640 /// GCC compatibility).
5641 static TypeSourceInfo*
5642 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5643                                               ASTContext &Context,
5644                                               bool &SizeIsNegative,
5645                                               llvm::APSInt &Oversized) {
5646   QualType FixedTy
5647     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5648                                           SizeIsNegative, Oversized);
5649   if (FixedTy.isNull())
5650     return nullptr;
5651   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5652   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5653                                     FixedTInfo->getTypeLoc());
5654   return FixedTInfo;
5655 }
5656 
5657 /// \brief Register the given locally-scoped extern "C" declaration so
5658 /// that it can be found later for redeclarations. We include any extern "C"
5659 /// declaration that is not visible in the translation unit here, not just
5660 /// function-scope declarations.
5661 void
5662 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5663   if (!getLangOpts().CPlusPlus &&
5664       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5665     // Don't need to track declarations in the TU in C.
5666     return;
5667 
5668   // Note that we have a locally-scoped external with this name.
5669   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5670 }
5671 
5672 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5673   // FIXME: We can have multiple results via __attribute__((overloadable)).
5674   auto Result = Context.getExternCContextDecl()->lookup(Name);
5675   return Result.empty() ? nullptr : *Result.begin();
5676 }
5677 
5678 /// \brief Diagnose function specifiers on a declaration of an identifier that
5679 /// does not identify a function.
5680 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5681   // FIXME: We should probably indicate the identifier in question to avoid
5682   // confusion for constructs like "virtual int a(), b;"
5683   if (DS.isVirtualSpecified())
5684     Diag(DS.getVirtualSpecLoc(),
5685          diag::err_virtual_non_function);
5686 
5687   if (DS.isExplicitSpecified())
5688     Diag(DS.getExplicitSpecLoc(),
5689          diag::err_explicit_non_function);
5690 
5691   if (DS.isNoreturnSpecified())
5692     Diag(DS.getNoreturnSpecLoc(),
5693          diag::err_noreturn_non_function);
5694 }
5695 
5696 NamedDecl*
5697 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5698                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5699   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5700   if (D.getCXXScopeSpec().isSet()) {
5701     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5702       << D.getCXXScopeSpec().getRange();
5703     D.setInvalidType();
5704     // Pretend we didn't see the scope specifier.
5705     DC = CurContext;
5706     Previous.clear();
5707   }
5708 
5709   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5710 
5711   if (D.getDeclSpec().isInlineSpecified())
5712     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5713         << getLangOpts().CPlusPlus17;
5714   if (D.getDeclSpec().isConstexprSpecified())
5715     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5716       << 1;
5717 
5718   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5719     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5720       Diag(D.getName().StartLocation,
5721            diag::err_deduction_guide_invalid_specifier)
5722           << "typedef";
5723     else
5724       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5725           << D.getName().getSourceRange();
5726     return nullptr;
5727   }
5728 
5729   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5730   if (!NewTD) return nullptr;
5731 
5732   // Handle attributes prior to checking for duplicates in MergeVarDecl
5733   ProcessDeclAttributes(S, NewTD, D);
5734 
5735   CheckTypedefForVariablyModifiedType(S, NewTD);
5736 
5737   bool Redeclaration = D.isRedeclaration();
5738   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5739   D.setRedeclaration(Redeclaration);
5740   return ND;
5741 }
5742 
5743 void
5744 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5745   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5746   // then it shall have block scope.
5747   // Note that variably modified types must be fixed before merging the decl so
5748   // that redeclarations will match.
5749   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5750   QualType T = TInfo->getType();
5751   if (T->isVariablyModifiedType()) {
5752     getCurFunction()->setHasBranchProtectedScope();
5753 
5754     if (S->getFnParent() == nullptr) {
5755       bool SizeIsNegative;
5756       llvm::APSInt Oversized;
5757       TypeSourceInfo *FixedTInfo =
5758         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5759                                                       SizeIsNegative,
5760                                                       Oversized);
5761       if (FixedTInfo) {
5762         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5763         NewTD->setTypeSourceInfo(FixedTInfo);
5764       } else {
5765         if (SizeIsNegative)
5766           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5767         else if (T->isVariableArrayType())
5768           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5769         else if (Oversized.getBoolValue())
5770           Diag(NewTD->getLocation(), diag::err_array_too_large)
5771             << Oversized.toString(10);
5772         else
5773           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5774         NewTD->setInvalidDecl();
5775       }
5776     }
5777   }
5778 }
5779 
5780 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5781 /// declares a typedef-name, either using the 'typedef' type specifier or via
5782 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5783 NamedDecl*
5784 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5785                            LookupResult &Previous, bool &Redeclaration) {
5786 
5787   // Find the shadowed declaration before filtering for scope.
5788   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5789 
5790   // Merge the decl with the existing one if appropriate. If the decl is
5791   // in an outer scope, it isn't the same thing.
5792   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5793                        /*AllowInlineNamespace*/false);
5794   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5795   if (!Previous.empty()) {
5796     Redeclaration = true;
5797     MergeTypedefNameDecl(S, NewTD, Previous);
5798   }
5799 
5800   if (ShadowedDecl && !Redeclaration)
5801     CheckShadow(NewTD, ShadowedDecl, Previous);
5802 
5803   // If this is the C FILE type, notify the AST context.
5804   if (IdentifierInfo *II = NewTD->getIdentifier())
5805     if (!NewTD->isInvalidDecl() &&
5806         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5807       if (II->isStr("FILE"))
5808         Context.setFILEDecl(NewTD);
5809       else if (II->isStr("jmp_buf"))
5810         Context.setjmp_bufDecl(NewTD);
5811       else if (II->isStr("sigjmp_buf"))
5812         Context.setsigjmp_bufDecl(NewTD);
5813       else if (II->isStr("ucontext_t"))
5814         Context.setucontext_tDecl(NewTD);
5815     }
5816 
5817   return NewTD;
5818 }
5819 
5820 /// \brief Determines whether the given declaration is an out-of-scope
5821 /// previous declaration.
5822 ///
5823 /// This routine should be invoked when name lookup has found a
5824 /// previous declaration (PrevDecl) that is not in the scope where a
5825 /// new declaration by the same name is being introduced. If the new
5826 /// declaration occurs in a local scope, previous declarations with
5827 /// linkage may still be considered previous declarations (C99
5828 /// 6.2.2p4-5, C++ [basic.link]p6).
5829 ///
5830 /// \param PrevDecl the previous declaration found by name
5831 /// lookup
5832 ///
5833 /// \param DC the context in which the new declaration is being
5834 /// declared.
5835 ///
5836 /// \returns true if PrevDecl is an out-of-scope previous declaration
5837 /// for a new delcaration with the same name.
5838 static bool
5839 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5840                                 ASTContext &Context) {
5841   if (!PrevDecl)
5842     return false;
5843 
5844   if (!PrevDecl->hasLinkage())
5845     return false;
5846 
5847   if (Context.getLangOpts().CPlusPlus) {
5848     // C++ [basic.link]p6:
5849     //   If there is a visible declaration of an entity with linkage
5850     //   having the same name and type, ignoring entities declared
5851     //   outside the innermost enclosing namespace scope, the block
5852     //   scope declaration declares that same entity and receives the
5853     //   linkage of the previous declaration.
5854     DeclContext *OuterContext = DC->getRedeclContext();
5855     if (!OuterContext->isFunctionOrMethod())
5856       // This rule only applies to block-scope declarations.
5857       return false;
5858 
5859     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5860     if (PrevOuterContext->isRecord())
5861       // We found a member function: ignore it.
5862       return false;
5863 
5864     // Find the innermost enclosing namespace for the new and
5865     // previous declarations.
5866     OuterContext = OuterContext->getEnclosingNamespaceContext();
5867     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5868 
5869     // The previous declaration is in a different namespace, so it
5870     // isn't the same function.
5871     if (!OuterContext->Equals(PrevOuterContext))
5872       return false;
5873   }
5874 
5875   return true;
5876 }
5877 
5878 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5879   CXXScopeSpec &SS = D.getCXXScopeSpec();
5880   if (!SS.isSet()) return;
5881   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5882 }
5883 
5884 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5885   QualType type = decl->getType();
5886   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5887   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5888     // Various kinds of declaration aren't allowed to be __autoreleasing.
5889     unsigned kind = -1U;
5890     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5891       if (var->hasAttr<BlocksAttr>())
5892         kind = 0; // __block
5893       else if (!var->hasLocalStorage())
5894         kind = 1; // global
5895     } else if (isa<ObjCIvarDecl>(decl)) {
5896       kind = 3; // ivar
5897     } else if (isa<FieldDecl>(decl)) {
5898       kind = 2; // field
5899     }
5900 
5901     if (kind != -1U) {
5902       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5903         << kind;
5904     }
5905   } else if (lifetime == Qualifiers::OCL_None) {
5906     // Try to infer lifetime.
5907     if (!type->isObjCLifetimeType())
5908       return false;
5909 
5910     lifetime = type->getObjCARCImplicitLifetime();
5911     type = Context.getLifetimeQualifiedType(type, lifetime);
5912     decl->setType(type);
5913   }
5914 
5915   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5916     // Thread-local variables cannot have lifetime.
5917     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5918         var->getTLSKind()) {
5919       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5920         << var->getType();
5921       return true;
5922     }
5923   }
5924 
5925   return false;
5926 }
5927 
5928 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5929   // Ensure that an auto decl is deduced otherwise the checks below might cache
5930   // the wrong linkage.
5931   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5932 
5933   // 'weak' only applies to declarations with external linkage.
5934   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5935     if (!ND.isExternallyVisible()) {
5936       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5937       ND.dropAttr<WeakAttr>();
5938     }
5939   }
5940   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5941     if (ND.isExternallyVisible()) {
5942       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5943       ND.dropAttr<WeakRefAttr>();
5944       ND.dropAttr<AliasAttr>();
5945     }
5946   }
5947 
5948   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5949     if (VD->hasInit()) {
5950       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5951         assert(VD->isThisDeclarationADefinition() &&
5952                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5953         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5954         VD->dropAttr<AliasAttr>();
5955       }
5956     }
5957   }
5958 
5959   // 'selectany' only applies to externally visible variable declarations.
5960   // It does not apply to functions.
5961   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5962     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5963       S.Diag(Attr->getLocation(),
5964              diag::err_attribute_selectany_non_extern_data);
5965       ND.dropAttr<SelectAnyAttr>();
5966     }
5967   }
5968 
5969   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5970     // dll attributes require external linkage. Static locals may have external
5971     // linkage but still cannot be explicitly imported or exported.
5972     auto *VD = dyn_cast<VarDecl>(&ND);
5973     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5974       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5975         << &ND << Attr;
5976       ND.setInvalidDecl();
5977     }
5978   }
5979 
5980   // Virtual functions cannot be marked as 'notail'.
5981   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5982     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5983       if (MD->isVirtual()) {
5984         S.Diag(ND.getLocation(),
5985                diag::err_invalid_attribute_on_virtual_function)
5986             << Attr;
5987         ND.dropAttr<NotTailCalledAttr>();
5988       }
5989 }
5990 
5991 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5992                                            NamedDecl *NewDecl,
5993                                            bool IsSpecialization,
5994                                            bool IsDefinition) {
5995   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
5996     return;
5997 
5998   bool IsTemplate = false;
5999   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6000     OldDecl = OldTD->getTemplatedDecl();
6001     IsTemplate = true;
6002     if (!IsSpecialization)
6003       IsDefinition = false;
6004   }
6005   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6006     NewDecl = NewTD->getTemplatedDecl();
6007     IsTemplate = true;
6008   }
6009 
6010   if (!OldDecl || !NewDecl)
6011     return;
6012 
6013   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6014   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6015   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6016   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6017 
6018   // dllimport and dllexport are inheritable attributes so we have to exclude
6019   // inherited attribute instances.
6020   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6021                     (NewExportAttr && !NewExportAttr->isInherited());
6022 
6023   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6024   // the only exception being explicit specializations.
6025   // Implicitly generated declarations are also excluded for now because there
6026   // is no other way to switch these to use dllimport or dllexport.
6027   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6028 
6029   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6030     // Allow with a warning for free functions and global variables.
6031     bool JustWarn = false;
6032     if (!OldDecl->isCXXClassMember()) {
6033       auto *VD = dyn_cast<VarDecl>(OldDecl);
6034       if (VD && !VD->getDescribedVarTemplate())
6035         JustWarn = true;
6036       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6037       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6038         JustWarn = true;
6039     }
6040 
6041     // We cannot change a declaration that's been used because IR has already
6042     // been emitted. Dllimported functions will still work though (modulo
6043     // address equality) as they can use the thunk.
6044     if (OldDecl->isUsed())
6045       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6046         JustWarn = false;
6047 
6048     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6049                                : diag::err_attribute_dll_redeclaration;
6050     S.Diag(NewDecl->getLocation(), DiagID)
6051         << NewDecl
6052         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6053     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6054     if (!JustWarn) {
6055       NewDecl->setInvalidDecl();
6056       return;
6057     }
6058   }
6059 
6060   // A redeclaration is not allowed to drop a dllimport attribute, the only
6061   // exceptions being inline function definitions (except for function
6062   // templates), local extern declarations, qualified friend declarations or
6063   // special MSVC extension: in the last case, the declaration is treated as if
6064   // it were marked dllexport.
6065   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6066   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6067   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6068     // Ignore static data because out-of-line definitions are diagnosed
6069     // separately.
6070     IsStaticDataMember = VD->isStaticDataMember();
6071     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6072                    VarDecl::DeclarationOnly;
6073   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6074     IsInline = FD->isInlined();
6075     IsQualifiedFriend = FD->getQualifier() &&
6076                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6077   }
6078 
6079   if (OldImportAttr && !HasNewAttr &&
6080       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6081       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6082     if (IsMicrosoft && IsDefinition) {
6083       S.Diag(NewDecl->getLocation(),
6084              diag::warn_redeclaration_without_import_attribute)
6085           << NewDecl;
6086       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6087       NewDecl->dropAttr<DLLImportAttr>();
6088       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6089           NewImportAttr->getRange(), S.Context,
6090           NewImportAttr->getSpellingListIndex()));
6091     } else {
6092       S.Diag(NewDecl->getLocation(),
6093              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6094           << NewDecl << OldImportAttr;
6095       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6096       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6097       OldDecl->dropAttr<DLLImportAttr>();
6098       NewDecl->dropAttr<DLLImportAttr>();
6099     }
6100   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6101     // In MinGW, seeing a function declared inline drops the dllimport
6102     // attribute.
6103     OldDecl->dropAttr<DLLImportAttr>();
6104     NewDecl->dropAttr<DLLImportAttr>();
6105     S.Diag(NewDecl->getLocation(),
6106            diag::warn_dllimport_dropped_from_inline_function)
6107         << NewDecl << OldImportAttr;
6108   }
6109 
6110   // A specialization of a class template member function is processed here
6111   // since it's a redeclaration. If the parent class is dllexport, the
6112   // specialization inherits that attribute. This doesn't happen automatically
6113   // since the parent class isn't instantiated until later.
6114   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6115     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6116         !NewImportAttr && !NewExportAttr) {
6117       if (const DLLExportAttr *ParentExportAttr =
6118               MD->getParent()->getAttr<DLLExportAttr>()) {
6119         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6120         NewAttr->setInherited(true);
6121         NewDecl->addAttr(NewAttr);
6122       }
6123     }
6124   }
6125 }
6126 
6127 /// Given that we are within the definition of the given function,
6128 /// will that definition behave like C99's 'inline', where the
6129 /// definition is discarded except for optimization purposes?
6130 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6131   // Try to avoid calling GetGVALinkageForFunction.
6132 
6133   // All cases of this require the 'inline' keyword.
6134   if (!FD->isInlined()) return false;
6135 
6136   // This is only possible in C++ with the gnu_inline attribute.
6137   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6138     return false;
6139 
6140   // Okay, go ahead and call the relatively-more-expensive function.
6141   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6142 }
6143 
6144 /// Determine whether a variable is extern "C" prior to attaching
6145 /// an initializer. We can't just call isExternC() here, because that
6146 /// will also compute and cache whether the declaration is externally
6147 /// visible, which might change when we attach the initializer.
6148 ///
6149 /// This can only be used if the declaration is known to not be a
6150 /// redeclaration of an internal linkage declaration.
6151 ///
6152 /// For instance:
6153 ///
6154 ///   auto x = []{};
6155 ///
6156 /// Attaching the initializer here makes this declaration not externally
6157 /// visible, because its type has internal linkage.
6158 ///
6159 /// FIXME: This is a hack.
6160 template<typename T>
6161 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6162   if (S.getLangOpts().CPlusPlus) {
6163     // In C++, the overloadable attribute negates the effects of extern "C".
6164     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6165       return false;
6166 
6167     // So do CUDA's host/device attributes.
6168     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6169                                  D->template hasAttr<CUDAHostAttr>()))
6170       return false;
6171   }
6172   return D->isExternC();
6173 }
6174 
6175 static bool shouldConsiderLinkage(const VarDecl *VD) {
6176   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6177   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
6178     return VD->hasExternalStorage();
6179   if (DC->isFileContext())
6180     return true;
6181   if (DC->isRecord())
6182     return false;
6183   llvm_unreachable("Unexpected context");
6184 }
6185 
6186 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6187   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6188   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6189       isa<OMPDeclareReductionDecl>(DC))
6190     return true;
6191   if (DC->isRecord())
6192     return false;
6193   llvm_unreachable("Unexpected context");
6194 }
6195 
6196 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
6197                           AttributeList::Kind Kind) {
6198   for (const AttributeList *L = AttrList; L; L = L->getNext())
6199     if (L->getKind() == Kind)
6200       return true;
6201   return false;
6202 }
6203 
6204 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6205                           AttributeList::Kind Kind) {
6206   // Check decl attributes on the DeclSpec.
6207   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
6208     return true;
6209 
6210   // Walk the declarator structure, checking decl attributes that were in a type
6211   // position to the decl itself.
6212   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6213     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
6214       return true;
6215   }
6216 
6217   // Finally, check attributes on the decl itself.
6218   return hasParsedAttr(S, PD.getAttributes(), Kind);
6219 }
6220 
6221 /// Adjust the \c DeclContext for a function or variable that might be a
6222 /// function-local external declaration.
6223 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6224   if (!DC->isFunctionOrMethod())
6225     return false;
6226 
6227   // If this is a local extern function or variable declared within a function
6228   // template, don't add it into the enclosing namespace scope until it is
6229   // instantiated; it might have a dependent type right now.
6230   if (DC->isDependentContext())
6231     return true;
6232 
6233   // C++11 [basic.link]p7:
6234   //   When a block scope declaration of an entity with linkage is not found to
6235   //   refer to some other declaration, then that entity is a member of the
6236   //   innermost enclosing namespace.
6237   //
6238   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6239   // semantically-enclosing namespace, not a lexically-enclosing one.
6240   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6241     DC = DC->getParent();
6242   return true;
6243 }
6244 
6245 /// \brief Returns true if given declaration has external C language linkage.
6246 static bool isDeclExternC(const Decl *D) {
6247   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6248     return FD->isExternC();
6249   if (const auto *VD = dyn_cast<VarDecl>(D))
6250     return VD->isExternC();
6251 
6252   llvm_unreachable("Unknown type of decl!");
6253 }
6254 
6255 NamedDecl *Sema::ActOnVariableDeclarator(
6256     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6257     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6258     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6259   QualType R = TInfo->getType();
6260   DeclarationName Name = GetNameForDeclarator(D).getName();
6261 
6262   IdentifierInfo *II = Name.getAsIdentifierInfo();
6263 
6264   if (D.isDecompositionDeclarator()) {
6265     // Take the name of the first declarator as our name for diagnostic
6266     // purposes.
6267     auto &Decomp = D.getDecompositionDeclarator();
6268     if (!Decomp.bindings().empty()) {
6269       II = Decomp.bindings()[0].Name;
6270       Name = II;
6271     }
6272   } else if (!II) {
6273     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6274     return nullptr;
6275   }
6276 
6277   if (getLangOpts().OpenCL) {
6278     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6279     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6280     // argument.
6281     if (R->isImageType() || R->isPipeType()) {
6282       Diag(D.getIdentifierLoc(),
6283            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6284           << R;
6285       D.setInvalidType();
6286       return nullptr;
6287     }
6288 
6289     // OpenCL v1.2 s6.9.r:
6290     // The event type cannot be used to declare a program scope variable.
6291     // OpenCL v2.0 s6.9.q:
6292     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6293     if (NULL == S->getParent()) {
6294       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6295         Diag(D.getIdentifierLoc(),
6296              diag::err_invalid_type_for_program_scope_var) << R;
6297         D.setInvalidType();
6298         return nullptr;
6299       }
6300     }
6301 
6302     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6303     QualType NR = R;
6304     while (NR->isPointerType()) {
6305       if (NR->isFunctionPointerType()) {
6306         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6307         D.setInvalidType();
6308         break;
6309       }
6310       NR = NR->getPointeeType();
6311     }
6312 
6313     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6314       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6315       // half array type (unless the cl_khr_fp16 extension is enabled).
6316       if (Context.getBaseElementType(R)->isHalfType()) {
6317         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6318         D.setInvalidType();
6319       }
6320     }
6321 
6322     if (R->isSamplerT()) {
6323       // OpenCL v1.2 s6.9.b p4:
6324       // The sampler type cannot be used with the __local and __global address
6325       // space qualifiers.
6326       if (R.getAddressSpace() == LangAS::opencl_local ||
6327           R.getAddressSpace() == LangAS::opencl_global) {
6328         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6329       }
6330 
6331       // OpenCL v1.2 s6.12.14.1:
6332       // A global sampler must be declared with either the constant address
6333       // space qualifier or with the const qualifier.
6334       if (DC->isTranslationUnit() &&
6335           !(R.getAddressSpace() == LangAS::opencl_constant ||
6336           R.isConstQualified())) {
6337         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6338         D.setInvalidType();
6339       }
6340     }
6341 
6342     // OpenCL v1.2 s6.9.r:
6343     // The event type cannot be used with the __local, __constant and __global
6344     // address space qualifiers.
6345     if (R->isEventT()) {
6346       if (R.getAddressSpace() != LangAS::opencl_private) {
6347         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6348         D.setInvalidType();
6349       }
6350     }
6351   }
6352 
6353   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6354   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6355 
6356   // dllimport globals without explicit storage class are treated as extern. We
6357   // have to change the storage class this early to get the right DeclContext.
6358   if (SC == SC_None && !DC->isRecord() &&
6359       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
6360       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
6361     SC = SC_Extern;
6362 
6363   DeclContext *OriginalDC = DC;
6364   bool IsLocalExternDecl = SC == SC_Extern &&
6365                            adjustContextForLocalExternDecl(DC);
6366 
6367   if (SCSpec == DeclSpec::SCS_mutable) {
6368     // mutable can only appear on non-static class members, so it's always
6369     // an error here
6370     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6371     D.setInvalidType();
6372     SC = SC_None;
6373   }
6374 
6375   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6376       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6377                               D.getDeclSpec().getStorageClassSpecLoc())) {
6378     // In C++11, the 'register' storage class specifier is deprecated.
6379     // Suppress the warning in system macros, it's used in macros in some
6380     // popular C system headers, such as in glibc's htonl() macro.
6381     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6382          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6383                                    : diag::warn_deprecated_register)
6384       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6385   }
6386 
6387   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6388 
6389   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6390     // C99 6.9p2: The storage-class specifiers auto and register shall not
6391     // appear in the declaration specifiers in an external declaration.
6392     // Global Register+Asm is a GNU extension we support.
6393     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6394       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6395       D.setInvalidType();
6396     }
6397   }
6398 
6399   bool IsMemberSpecialization = false;
6400   bool IsVariableTemplateSpecialization = false;
6401   bool IsPartialSpecialization = false;
6402   bool IsVariableTemplate = false;
6403   VarDecl *NewVD = nullptr;
6404   VarTemplateDecl *NewTemplate = nullptr;
6405   TemplateParameterList *TemplateParams = nullptr;
6406   if (!getLangOpts().CPlusPlus) {
6407     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6408                             D.getIdentifierLoc(), II,
6409                             R, TInfo, SC);
6410 
6411     if (R->getContainedDeducedType())
6412       ParsingInitForAutoVars.insert(NewVD);
6413 
6414     if (D.isInvalidType())
6415       NewVD->setInvalidDecl();
6416   } else {
6417     bool Invalid = false;
6418 
6419     if (DC->isRecord() && !CurContext->isRecord()) {
6420       // This is an out-of-line definition of a static data member.
6421       switch (SC) {
6422       case SC_None:
6423         break;
6424       case SC_Static:
6425         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6426              diag::err_static_out_of_line)
6427           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6428         break;
6429       case SC_Auto:
6430       case SC_Register:
6431       case SC_Extern:
6432         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6433         // to names of variables declared in a block or to function parameters.
6434         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6435         // of class members
6436 
6437         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6438              diag::err_storage_class_for_static_member)
6439           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6440         break;
6441       case SC_PrivateExtern:
6442         llvm_unreachable("C storage class in c++!");
6443       }
6444     }
6445 
6446     if (SC == SC_Static && CurContext->isRecord()) {
6447       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6448         if (RD->isLocalClass())
6449           Diag(D.getIdentifierLoc(),
6450                diag::err_static_data_member_not_allowed_in_local_class)
6451             << Name << RD->getDeclName();
6452 
6453         // C++98 [class.union]p1: If a union contains a static data member,
6454         // the program is ill-formed. C++11 drops this restriction.
6455         if (RD->isUnion())
6456           Diag(D.getIdentifierLoc(),
6457                getLangOpts().CPlusPlus11
6458                  ? diag::warn_cxx98_compat_static_data_member_in_union
6459                  : diag::ext_static_data_member_in_union) << Name;
6460         // We conservatively disallow static data members in anonymous structs.
6461         else if (!RD->getDeclName())
6462           Diag(D.getIdentifierLoc(),
6463                diag::err_static_data_member_not_allowed_in_anon_struct)
6464             << Name << RD->isUnion();
6465       }
6466     }
6467 
6468     // Match up the template parameter lists with the scope specifier, then
6469     // determine whether we have a template or a template specialization.
6470     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6471         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6472         D.getCXXScopeSpec(),
6473         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6474             ? D.getName().TemplateId
6475             : nullptr,
6476         TemplateParamLists,
6477         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6478 
6479     if (TemplateParams) {
6480       if (!TemplateParams->size() &&
6481           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6482         // There is an extraneous 'template<>' for this variable. Complain
6483         // about it, but allow the declaration of the variable.
6484         Diag(TemplateParams->getTemplateLoc(),
6485              diag::err_template_variable_noparams)
6486           << II
6487           << SourceRange(TemplateParams->getTemplateLoc(),
6488                          TemplateParams->getRAngleLoc());
6489         TemplateParams = nullptr;
6490       } else {
6491         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6492           // This is an explicit specialization or a partial specialization.
6493           // FIXME: Check that we can declare a specialization here.
6494           IsVariableTemplateSpecialization = true;
6495           IsPartialSpecialization = TemplateParams->size() > 0;
6496         } else { // if (TemplateParams->size() > 0)
6497           // This is a template declaration.
6498           IsVariableTemplate = true;
6499 
6500           // Check that we can declare a template here.
6501           if (CheckTemplateDeclScope(S, TemplateParams))
6502             return nullptr;
6503 
6504           // Only C++1y supports variable templates (N3651).
6505           Diag(D.getIdentifierLoc(),
6506                getLangOpts().CPlusPlus14
6507                    ? diag::warn_cxx11_compat_variable_template
6508                    : diag::ext_variable_template);
6509         }
6510       }
6511     } else {
6512       assert((Invalid ||
6513               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6514              "should have a 'template<>' for this decl");
6515     }
6516 
6517     if (IsVariableTemplateSpecialization) {
6518       SourceLocation TemplateKWLoc =
6519           TemplateParamLists.size() > 0
6520               ? TemplateParamLists[0]->getTemplateLoc()
6521               : SourceLocation();
6522       DeclResult Res = ActOnVarTemplateSpecialization(
6523           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6524           IsPartialSpecialization);
6525       if (Res.isInvalid())
6526         return nullptr;
6527       NewVD = cast<VarDecl>(Res.get());
6528       AddToScope = false;
6529     } else if (D.isDecompositionDeclarator()) {
6530       NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6531                                         D.getIdentifierLoc(), R, TInfo, SC,
6532                                         Bindings);
6533     } else
6534       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6535                               D.getIdentifierLoc(), II, R, TInfo, SC);
6536 
6537     // If this is supposed to be a variable template, create it as such.
6538     if (IsVariableTemplate) {
6539       NewTemplate =
6540           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6541                                   TemplateParams, NewVD);
6542       NewVD->setDescribedVarTemplate(NewTemplate);
6543     }
6544 
6545     // If this decl has an auto type in need of deduction, make a note of the
6546     // Decl so we can diagnose uses of it in its own initializer.
6547     if (R->getContainedDeducedType())
6548       ParsingInitForAutoVars.insert(NewVD);
6549 
6550     if (D.isInvalidType() || Invalid) {
6551       NewVD->setInvalidDecl();
6552       if (NewTemplate)
6553         NewTemplate->setInvalidDecl();
6554     }
6555 
6556     SetNestedNameSpecifier(NewVD, D);
6557 
6558     // If we have any template parameter lists that don't directly belong to
6559     // the variable (matching the scope specifier), store them.
6560     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6561     if (TemplateParamLists.size() > VDTemplateParamLists)
6562       NewVD->setTemplateParameterListsInfo(
6563           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6564 
6565     if (D.getDeclSpec().isConstexprSpecified()) {
6566       NewVD->setConstexpr(true);
6567       // C++1z [dcl.spec.constexpr]p1:
6568       //   A static data member declared with the constexpr specifier is
6569       //   implicitly an inline variable.
6570       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
6571         NewVD->setImplicitlyInline();
6572     }
6573   }
6574 
6575   if (D.getDeclSpec().isInlineSpecified()) {
6576     if (!getLangOpts().CPlusPlus) {
6577       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6578           << 0;
6579     } else if (CurContext->isFunctionOrMethod()) {
6580       // 'inline' is not allowed on block scope variable declaration.
6581       Diag(D.getDeclSpec().getInlineSpecLoc(),
6582            diag::err_inline_declaration_block_scope) << Name
6583         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6584     } else {
6585       Diag(D.getDeclSpec().getInlineSpecLoc(),
6586            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6587                                      : diag::ext_inline_variable);
6588       NewVD->setInlineSpecified();
6589     }
6590   }
6591 
6592   // Set the lexical context. If the declarator has a C++ scope specifier, the
6593   // lexical context will be different from the semantic context.
6594   NewVD->setLexicalDeclContext(CurContext);
6595   if (NewTemplate)
6596     NewTemplate->setLexicalDeclContext(CurContext);
6597 
6598   if (IsLocalExternDecl) {
6599     if (D.isDecompositionDeclarator())
6600       for (auto *B : Bindings)
6601         B->setLocalExternDecl();
6602     else
6603       NewVD->setLocalExternDecl();
6604   }
6605 
6606   bool EmitTLSUnsupportedError = false;
6607   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6608     // C++11 [dcl.stc]p4:
6609     //   When thread_local is applied to a variable of block scope the
6610     //   storage-class-specifier static is implied if it does not appear
6611     //   explicitly.
6612     // Core issue: 'static' is not implied if the variable is declared
6613     //   'extern'.
6614     if (NewVD->hasLocalStorage() &&
6615         (SCSpec != DeclSpec::SCS_unspecified ||
6616          TSCS != DeclSpec::TSCS_thread_local ||
6617          !DC->isFunctionOrMethod()))
6618       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6619            diag::err_thread_non_global)
6620         << DeclSpec::getSpecifierName(TSCS);
6621     else if (!Context.getTargetInfo().isTLSSupported()) {
6622       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6623         // Postpone error emission until we've collected attributes required to
6624         // figure out whether it's a host or device variable and whether the
6625         // error should be ignored.
6626         EmitTLSUnsupportedError = true;
6627         // We still need to mark the variable as TLS so it shows up in AST with
6628         // proper storage class for other tools to use even if we're not going
6629         // to emit any code for it.
6630         NewVD->setTSCSpec(TSCS);
6631       } else
6632         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6633              diag::err_thread_unsupported);
6634     } else
6635       NewVD->setTSCSpec(TSCS);
6636   }
6637 
6638   // C99 6.7.4p3
6639   //   An inline definition of a function with external linkage shall
6640   //   not contain a definition of a modifiable object with static or
6641   //   thread storage duration...
6642   // We only apply this when the function is required to be defined
6643   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6644   // that a local variable with thread storage duration still has to
6645   // be marked 'static'.  Also note that it's possible to get these
6646   // semantics in C++ using __attribute__((gnu_inline)).
6647   if (SC == SC_Static && S->getFnParent() != nullptr &&
6648       !NewVD->getType().isConstQualified()) {
6649     FunctionDecl *CurFD = getCurFunctionDecl();
6650     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6651       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6652            diag::warn_static_local_in_extern_inline);
6653       MaybeSuggestAddingStaticToDecl(CurFD);
6654     }
6655   }
6656 
6657   if (D.getDeclSpec().isModulePrivateSpecified()) {
6658     if (IsVariableTemplateSpecialization)
6659       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6660           << (IsPartialSpecialization ? 1 : 0)
6661           << FixItHint::CreateRemoval(
6662                  D.getDeclSpec().getModulePrivateSpecLoc());
6663     else if (IsMemberSpecialization)
6664       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6665         << 2
6666         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6667     else if (NewVD->hasLocalStorage())
6668       Diag(NewVD->getLocation(), diag::err_module_private_local)
6669         << 0 << NewVD->getDeclName()
6670         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6671         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6672     else {
6673       NewVD->setModulePrivate();
6674       if (NewTemplate)
6675         NewTemplate->setModulePrivate();
6676       for (auto *B : Bindings)
6677         B->setModulePrivate();
6678     }
6679   }
6680 
6681   // Handle attributes prior to checking for duplicates in MergeVarDecl
6682   ProcessDeclAttributes(S, NewVD, D);
6683 
6684   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6685     if (EmitTLSUnsupportedError &&
6686         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6687          (getLangOpts().OpenMPIsDevice &&
6688           NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6689       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6690            diag::err_thread_unsupported);
6691     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6692     // storage [duration]."
6693     if (SC == SC_None && S->getFnParent() != nullptr &&
6694         (NewVD->hasAttr<CUDASharedAttr>() ||
6695          NewVD->hasAttr<CUDAConstantAttr>())) {
6696       NewVD->setStorageClass(SC_Static);
6697     }
6698   }
6699 
6700   // Ensure that dllimport globals without explicit storage class are treated as
6701   // extern. The storage class is set above using parsed attributes. Now we can
6702   // check the VarDecl itself.
6703   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6704          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6705          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6706 
6707   // In auto-retain/release, infer strong retension for variables of
6708   // retainable type.
6709   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6710     NewVD->setInvalidDecl();
6711 
6712   // Handle GNU asm-label extension (encoded as an attribute).
6713   if (Expr *E = (Expr*)D.getAsmLabel()) {
6714     // The parser guarantees this is a string.
6715     StringLiteral *SE = cast<StringLiteral>(E);
6716     StringRef Label = SE->getString();
6717     if (S->getFnParent() != nullptr) {
6718       switch (SC) {
6719       case SC_None:
6720       case SC_Auto:
6721         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6722         break;
6723       case SC_Register:
6724         // Local Named register
6725         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6726             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6727           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6728         break;
6729       case SC_Static:
6730       case SC_Extern:
6731       case SC_PrivateExtern:
6732         break;
6733       }
6734     } else if (SC == SC_Register) {
6735       // Global Named register
6736       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6737         const auto &TI = Context.getTargetInfo();
6738         bool HasSizeMismatch;
6739 
6740         if (!TI.isValidGCCRegisterName(Label))
6741           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6742         else if (!TI.validateGlobalRegisterVariable(Label,
6743                                                     Context.getTypeSize(R),
6744                                                     HasSizeMismatch))
6745           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6746         else if (HasSizeMismatch)
6747           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6748       }
6749 
6750       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6751         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6752         NewVD->setInvalidDecl(true);
6753       }
6754     }
6755 
6756     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6757                                                 Context, Label, 0));
6758   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6759     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6760       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6761     if (I != ExtnameUndeclaredIdentifiers.end()) {
6762       if (isDeclExternC(NewVD)) {
6763         NewVD->addAttr(I->second);
6764         ExtnameUndeclaredIdentifiers.erase(I);
6765       } else
6766         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6767             << /*Variable*/1 << NewVD;
6768     }
6769   }
6770 
6771   // Find the shadowed declaration before filtering for scope.
6772   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6773                                 ? getShadowedDeclaration(NewVD, Previous)
6774                                 : nullptr;
6775 
6776   // Don't consider existing declarations that are in a different
6777   // scope and are out-of-semantic-context declarations (if the new
6778   // declaration has linkage).
6779   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6780                        D.getCXXScopeSpec().isNotEmpty() ||
6781                        IsMemberSpecialization ||
6782                        IsVariableTemplateSpecialization);
6783 
6784   // Check whether the previous declaration is in the same block scope. This
6785   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6786   if (getLangOpts().CPlusPlus &&
6787       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6788     NewVD->setPreviousDeclInSameBlockScope(
6789         Previous.isSingleResult() && !Previous.isShadowed() &&
6790         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6791 
6792   if (!getLangOpts().CPlusPlus) {
6793     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6794   } else {
6795     // If this is an explicit specialization of a static data member, check it.
6796     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6797         CheckMemberSpecialization(NewVD, Previous))
6798       NewVD->setInvalidDecl();
6799 
6800     // Merge the decl with the existing one if appropriate.
6801     if (!Previous.empty()) {
6802       if (Previous.isSingleResult() &&
6803           isa<FieldDecl>(Previous.getFoundDecl()) &&
6804           D.getCXXScopeSpec().isSet()) {
6805         // The user tried to define a non-static data member
6806         // out-of-line (C++ [dcl.meaning]p1).
6807         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6808           << D.getCXXScopeSpec().getRange();
6809         Previous.clear();
6810         NewVD->setInvalidDecl();
6811       }
6812     } else if (D.getCXXScopeSpec().isSet()) {
6813       // No previous declaration in the qualifying scope.
6814       Diag(D.getIdentifierLoc(), diag::err_no_member)
6815         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6816         << D.getCXXScopeSpec().getRange();
6817       NewVD->setInvalidDecl();
6818     }
6819 
6820     if (!IsVariableTemplateSpecialization)
6821       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6822 
6823     if (NewTemplate) {
6824       VarTemplateDecl *PrevVarTemplate =
6825           NewVD->getPreviousDecl()
6826               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6827               : nullptr;
6828 
6829       // Check the template parameter list of this declaration, possibly
6830       // merging in the template parameter list from the previous variable
6831       // template declaration.
6832       if (CheckTemplateParameterList(
6833               TemplateParams,
6834               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6835                               : nullptr,
6836               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6837                DC->isDependentContext())
6838                   ? TPC_ClassTemplateMember
6839                   : TPC_VarTemplate))
6840         NewVD->setInvalidDecl();
6841 
6842       // If we are providing an explicit specialization of a static variable
6843       // template, make a note of that.
6844       if (PrevVarTemplate &&
6845           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6846         PrevVarTemplate->setMemberSpecialization();
6847     }
6848   }
6849 
6850   // Diagnose shadowed variables iff this isn't a redeclaration.
6851   if (ShadowedDecl && !D.isRedeclaration())
6852     CheckShadow(NewVD, ShadowedDecl, Previous);
6853 
6854   ProcessPragmaWeak(S, NewVD);
6855 
6856   // If this is the first declaration of an extern C variable, update
6857   // the map of such variables.
6858   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6859       isIncompleteDeclExternC(*this, NewVD))
6860     RegisterLocallyScopedExternCDecl(NewVD, S);
6861 
6862   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6863     Decl *ManglingContextDecl;
6864     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6865             NewVD->getDeclContext(), ManglingContextDecl)) {
6866       Context.setManglingNumber(
6867           NewVD, MCtx->getManglingNumber(
6868                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6869       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6870     }
6871   }
6872 
6873   // Special handling of variable named 'main'.
6874   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6875       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6876       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6877 
6878     // C++ [basic.start.main]p3
6879     // A program that declares a variable main at global scope is ill-formed.
6880     if (getLangOpts().CPlusPlus)
6881       Diag(D.getLocStart(), diag::err_main_global_variable);
6882 
6883     // In C, and external-linkage variable named main results in undefined
6884     // behavior.
6885     else if (NewVD->hasExternalFormalLinkage())
6886       Diag(D.getLocStart(), diag::warn_main_redefined);
6887   }
6888 
6889   if (D.isRedeclaration() && !Previous.empty()) {
6890     checkDLLAttributeRedeclaration(
6891         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6892         IsMemberSpecialization, D.isFunctionDefinition());
6893   }
6894 
6895   if (NewTemplate) {
6896     if (NewVD->isInvalidDecl())
6897       NewTemplate->setInvalidDecl();
6898     ActOnDocumentableDecl(NewTemplate);
6899     return NewTemplate;
6900   }
6901 
6902   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6903     CompleteMemberSpecialization(NewVD, Previous);
6904 
6905   return NewVD;
6906 }
6907 
6908 /// Enum describing the %select options in diag::warn_decl_shadow.
6909 enum ShadowedDeclKind {
6910   SDK_Local,
6911   SDK_Global,
6912   SDK_StaticMember,
6913   SDK_Field,
6914   SDK_Typedef,
6915   SDK_Using
6916 };
6917 
6918 /// Determine what kind of declaration we're shadowing.
6919 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6920                                                 const DeclContext *OldDC) {
6921   if (isa<TypeAliasDecl>(ShadowedDecl))
6922     return SDK_Using;
6923   else if (isa<TypedefDecl>(ShadowedDecl))
6924     return SDK_Typedef;
6925   else if (isa<RecordDecl>(OldDC))
6926     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6927 
6928   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6929 }
6930 
6931 /// Return the location of the capture if the given lambda captures the given
6932 /// variable \p VD, or an invalid source location otherwise.
6933 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6934                                          const VarDecl *VD) {
6935   for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
6936     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6937       return Capture.getLocation();
6938   }
6939   return SourceLocation();
6940 }
6941 
6942 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6943                                      const LookupResult &R) {
6944   // Only diagnose if we're shadowing an unambiguous field or variable.
6945   if (R.getResultKind() != LookupResult::Found)
6946     return false;
6947 
6948   // Return false if warning is ignored.
6949   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6950 }
6951 
6952 /// \brief Return the declaration shadowed by the given variable \p D, or null
6953 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6954 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6955                                         const LookupResult &R) {
6956   if (!shouldWarnIfShadowedDecl(Diags, R))
6957     return nullptr;
6958 
6959   // Don't diagnose declarations at file scope.
6960   if (D->hasGlobalStorage())
6961     return nullptr;
6962 
6963   NamedDecl *ShadowedDecl = R.getFoundDecl();
6964   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6965              ? ShadowedDecl
6966              : nullptr;
6967 }
6968 
6969 /// \brief Return the declaration shadowed by the given typedef \p D, or null
6970 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6971 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
6972                                         const LookupResult &R) {
6973   // Don't warn if typedef declaration is part of a class
6974   if (D->getDeclContext()->isRecord())
6975     return nullptr;
6976 
6977   if (!shouldWarnIfShadowedDecl(Diags, R))
6978     return nullptr;
6979 
6980   NamedDecl *ShadowedDecl = R.getFoundDecl();
6981   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
6982 }
6983 
6984 /// \brief Diagnose variable or built-in function shadowing.  Implements
6985 /// -Wshadow.
6986 ///
6987 /// This method is called whenever a VarDecl is added to a "useful"
6988 /// scope.
6989 ///
6990 /// \param ShadowedDecl the declaration that is shadowed by the given variable
6991 /// \param R the lookup of the name
6992 ///
6993 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
6994                        const LookupResult &R) {
6995   DeclContext *NewDC = D->getDeclContext();
6996 
6997   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6998     // Fields are not shadowed by variables in C++ static methods.
6999     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7000       if (MD->isStatic())
7001         return;
7002 
7003     // Fields shadowed by constructor parameters are a special case. Usually
7004     // the constructor initializes the field with the parameter.
7005     if (isa<CXXConstructorDecl>(NewDC))
7006       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7007         // Remember that this was shadowed so we can either warn about its
7008         // modification or its existence depending on warning settings.
7009         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7010         return;
7011       }
7012   }
7013 
7014   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7015     if (shadowedVar->isExternC()) {
7016       // For shadowing external vars, make sure that we point to the global
7017       // declaration, not a locally scoped extern declaration.
7018       for (auto I : shadowedVar->redecls())
7019         if (I->isFileVarDecl()) {
7020           ShadowedDecl = I;
7021           break;
7022         }
7023     }
7024 
7025   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7026 
7027   unsigned WarningDiag = diag::warn_decl_shadow;
7028   SourceLocation CaptureLoc;
7029   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7030       isa<CXXMethodDecl>(NewDC)) {
7031     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7032       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7033         if (RD->getLambdaCaptureDefault() == LCD_None) {
7034           // Try to avoid warnings for lambdas with an explicit capture list.
7035           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7036           // Warn only when the lambda captures the shadowed decl explicitly.
7037           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7038           if (CaptureLoc.isInvalid())
7039             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7040         } else {
7041           // Remember that this was shadowed so we can avoid the warning if the
7042           // shadowed decl isn't captured and the warning settings allow it.
7043           cast<LambdaScopeInfo>(getCurFunction())
7044               ->ShadowingDecls.push_back(
7045                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7046           return;
7047         }
7048       }
7049 
7050       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7051         // A variable can't shadow a local variable in an enclosing scope, if
7052         // they are separated by a non-capturing declaration context.
7053         for (DeclContext *ParentDC = NewDC;
7054              ParentDC && !ParentDC->Equals(OldDC);
7055              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7056           // Only block literals, captured statements, and lambda expressions
7057           // can capture; other scopes don't.
7058           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7059               !isLambdaCallOperator(ParentDC)) {
7060             return;
7061           }
7062         }
7063       }
7064     }
7065   }
7066 
7067   // Only warn about certain kinds of shadowing for class members.
7068   if (NewDC && NewDC->isRecord()) {
7069     // In particular, don't warn about shadowing non-class members.
7070     if (!OldDC->isRecord())
7071       return;
7072 
7073     // TODO: should we warn about static data members shadowing
7074     // static data members from base classes?
7075 
7076     // TODO: don't diagnose for inaccessible shadowed members.
7077     // This is hard to do perfectly because we might friend the
7078     // shadowing context, but that's just a false negative.
7079   }
7080 
7081 
7082   DeclarationName Name = R.getLookupName();
7083 
7084   // Emit warning and note.
7085   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7086     return;
7087   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7088   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7089   if (!CaptureLoc.isInvalid())
7090     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7091         << Name << /*explicitly*/ 1;
7092   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7093 }
7094 
7095 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7096 /// when these variables are captured by the lambda.
7097 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7098   for (const auto &Shadow : LSI->ShadowingDecls) {
7099     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7100     // Try to avoid the warning when the shadowed decl isn't captured.
7101     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7102     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7103     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7104                                        ? diag::warn_decl_shadow_uncaptured_local
7105                                        : diag::warn_decl_shadow)
7106         << Shadow.VD->getDeclName()
7107         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7108     if (!CaptureLoc.isInvalid())
7109       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7110           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7111     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7112   }
7113 }
7114 
7115 /// \brief Check -Wshadow without the advantage of a previous lookup.
7116 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7117   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7118     return;
7119 
7120   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7121                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7122   LookupName(R, S);
7123   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7124     CheckShadow(D, ShadowedDecl, R);
7125 }
7126 
7127 /// Check if 'E', which is an expression that is about to be modified, refers
7128 /// to a constructor parameter that shadows a field.
7129 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7130   // Quickly ignore expressions that can't be shadowing ctor parameters.
7131   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7132     return;
7133   E = E->IgnoreParenImpCasts();
7134   auto *DRE = dyn_cast<DeclRefExpr>(E);
7135   if (!DRE)
7136     return;
7137   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7138   auto I = ShadowingDecls.find(D);
7139   if (I == ShadowingDecls.end())
7140     return;
7141   const NamedDecl *ShadowedDecl = I->second;
7142   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7143   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7144   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7145   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7146 
7147   // Avoid issuing multiple warnings about the same decl.
7148   ShadowingDecls.erase(I);
7149 }
7150 
7151 /// Check for conflict between this global or extern "C" declaration and
7152 /// previous global or extern "C" declarations. This is only used in C++.
7153 template<typename T>
7154 static bool checkGlobalOrExternCConflict(
7155     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7156   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7157   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7158 
7159   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7160     // The common case: this global doesn't conflict with any extern "C"
7161     // declaration.
7162     return false;
7163   }
7164 
7165   if (Prev) {
7166     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7167       // Both the old and new declarations have C language linkage. This is a
7168       // redeclaration.
7169       Previous.clear();
7170       Previous.addDecl(Prev);
7171       return true;
7172     }
7173 
7174     // This is a global, non-extern "C" declaration, and there is a previous
7175     // non-global extern "C" declaration. Diagnose if this is a variable
7176     // declaration.
7177     if (!isa<VarDecl>(ND))
7178       return false;
7179   } else {
7180     // The declaration is extern "C". Check for any declaration in the
7181     // translation unit which might conflict.
7182     if (IsGlobal) {
7183       // We have already performed the lookup into the translation unit.
7184       IsGlobal = false;
7185       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7186            I != E; ++I) {
7187         if (isa<VarDecl>(*I)) {
7188           Prev = *I;
7189           break;
7190         }
7191       }
7192     } else {
7193       DeclContext::lookup_result R =
7194           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7195       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7196            I != E; ++I) {
7197         if (isa<VarDecl>(*I)) {
7198           Prev = *I;
7199           break;
7200         }
7201         // FIXME: If we have any other entity with this name in global scope,
7202         // the declaration is ill-formed, but that is a defect: it breaks the
7203         // 'stat' hack, for instance. Only variables can have mangled name
7204         // clashes with extern "C" declarations, so only they deserve a
7205         // diagnostic.
7206       }
7207     }
7208 
7209     if (!Prev)
7210       return false;
7211   }
7212 
7213   // Use the first declaration's location to ensure we point at something which
7214   // is lexically inside an extern "C" linkage-spec.
7215   assert(Prev && "should have found a previous declaration to diagnose");
7216   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7217     Prev = FD->getFirstDecl();
7218   else
7219     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7220 
7221   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7222     << IsGlobal << ND;
7223   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7224     << IsGlobal;
7225   return false;
7226 }
7227 
7228 /// Apply special rules for handling extern "C" declarations. Returns \c true
7229 /// if we have found that this is a redeclaration of some prior entity.
7230 ///
7231 /// Per C++ [dcl.link]p6:
7232 ///   Two declarations [for a function or variable] with C language linkage
7233 ///   with the same name that appear in different scopes refer to the same
7234 ///   [entity]. An entity with C language linkage shall not be declared with
7235 ///   the same name as an entity in global scope.
7236 template<typename T>
7237 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7238                                                   LookupResult &Previous) {
7239   if (!S.getLangOpts().CPlusPlus) {
7240     // In C, when declaring a global variable, look for a corresponding 'extern'
7241     // variable declared in function scope. We don't need this in C++, because
7242     // we find local extern decls in the surrounding file-scope DeclContext.
7243     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7244       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7245         Previous.clear();
7246         Previous.addDecl(Prev);
7247         return true;
7248       }
7249     }
7250     return false;
7251   }
7252 
7253   // A declaration in the translation unit can conflict with an extern "C"
7254   // declaration.
7255   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7256     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7257 
7258   // An extern "C" declaration can conflict with a declaration in the
7259   // translation unit or can be a redeclaration of an extern "C" declaration
7260   // in another scope.
7261   if (isIncompleteDeclExternC(S,ND))
7262     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7263 
7264   // Neither global nor extern "C": nothing to do.
7265   return false;
7266 }
7267 
7268 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7269   // If the decl is already known invalid, don't check it.
7270   if (NewVD->isInvalidDecl())
7271     return;
7272 
7273   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
7274   QualType T = TInfo->getType();
7275 
7276   // Defer checking an 'auto' type until its initializer is attached.
7277   if (T->isUndeducedType())
7278     return;
7279 
7280   if (NewVD->hasAttrs())
7281     CheckAlignasUnderalignment(NewVD);
7282 
7283   if (T->isObjCObjectType()) {
7284     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7285       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7286     T = Context.getObjCObjectPointerType(T);
7287     NewVD->setType(T);
7288   }
7289 
7290   // Emit an error if an address space was applied to decl with local storage.
7291   // This includes arrays of objects with address space qualifiers, but not
7292   // automatic variables that point to other address spaces.
7293   // ISO/IEC TR 18037 S5.1.2
7294   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7295       T.getAddressSpace() != LangAS::Default) {
7296     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7297     NewVD->setInvalidDecl();
7298     return;
7299   }
7300 
7301   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7302   // scope.
7303   if (getLangOpts().OpenCLVersion == 120 &&
7304       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7305       NewVD->isStaticLocal()) {
7306     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7307     NewVD->setInvalidDecl();
7308     return;
7309   }
7310 
7311   if (getLangOpts().OpenCL) {
7312     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7313     if (NewVD->hasAttr<BlocksAttr>()) {
7314       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7315       return;
7316     }
7317 
7318     if (T->isBlockPointerType()) {
7319       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7320       // can't use 'extern' storage class.
7321       if (!T.isConstQualified()) {
7322         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7323             << 0 /*const*/;
7324         NewVD->setInvalidDecl();
7325         return;
7326       }
7327       if (NewVD->hasExternalStorage()) {
7328         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7329         NewVD->setInvalidDecl();
7330         return;
7331       }
7332     }
7333     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7334     // __constant address space.
7335     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7336     // variables inside a function can also be declared in the global
7337     // address space.
7338     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7339         NewVD->hasExternalStorage()) {
7340       if (!T->isSamplerT() &&
7341           !(T.getAddressSpace() == LangAS::opencl_constant ||
7342             (T.getAddressSpace() == LangAS::opencl_global &&
7343              getLangOpts().OpenCLVersion == 200))) {
7344         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7345         if (getLangOpts().OpenCLVersion == 200)
7346           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7347               << Scope << "global or constant";
7348         else
7349           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7350               << Scope << "constant";
7351         NewVD->setInvalidDecl();
7352         return;
7353       }
7354     } else {
7355       if (T.getAddressSpace() == LangAS::opencl_global) {
7356         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7357             << 1 /*is any function*/ << "global";
7358         NewVD->setInvalidDecl();
7359         return;
7360       }
7361       if (T.getAddressSpace() == LangAS::opencl_constant ||
7362           T.getAddressSpace() == LangAS::opencl_local) {
7363         FunctionDecl *FD = getCurFunctionDecl();
7364         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7365         // in functions.
7366         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7367           if (T.getAddressSpace() == LangAS::opencl_constant)
7368             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7369                 << 0 /*non-kernel only*/ << "constant";
7370           else
7371             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7372                 << 0 /*non-kernel only*/ << "local";
7373           NewVD->setInvalidDecl();
7374           return;
7375         }
7376         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7377         // in the outermost scope of a kernel function.
7378         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7379           if (!getCurScope()->isFunctionScope()) {
7380             if (T.getAddressSpace() == LangAS::opencl_constant)
7381               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7382                   << "constant";
7383             else
7384               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7385                   << "local";
7386             NewVD->setInvalidDecl();
7387             return;
7388           }
7389         }
7390       } else if (T.getAddressSpace() != LangAS::opencl_private) {
7391         // Do not allow other address spaces on automatic variable.
7392         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7393         NewVD->setInvalidDecl();
7394         return;
7395       }
7396     }
7397   }
7398 
7399   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7400       && !NewVD->hasAttr<BlocksAttr>()) {
7401     if (getLangOpts().getGC() != LangOptions::NonGC)
7402       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7403     else {
7404       assert(!getLangOpts().ObjCAutoRefCount);
7405       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7406     }
7407   }
7408 
7409   bool isVM = T->isVariablyModifiedType();
7410   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7411       NewVD->hasAttr<BlocksAttr>())
7412     getCurFunction()->setHasBranchProtectedScope();
7413 
7414   if ((isVM && NewVD->hasLinkage()) ||
7415       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7416     bool SizeIsNegative;
7417     llvm::APSInt Oversized;
7418     TypeSourceInfo *FixedTInfo =
7419       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7420                                                     SizeIsNegative, Oversized);
7421     if (!FixedTInfo && T->isVariableArrayType()) {
7422       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7423       // FIXME: This won't give the correct result for
7424       // int a[10][n];
7425       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7426 
7427       if (NewVD->isFileVarDecl())
7428         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7429         << SizeRange;
7430       else if (NewVD->isStaticLocal())
7431         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7432         << SizeRange;
7433       else
7434         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7435         << SizeRange;
7436       NewVD->setInvalidDecl();
7437       return;
7438     }
7439 
7440     if (!FixedTInfo) {
7441       if (NewVD->isFileVarDecl())
7442         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7443       else
7444         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7445       NewVD->setInvalidDecl();
7446       return;
7447     }
7448 
7449     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7450     NewVD->setType(FixedTInfo->getType());
7451     NewVD->setTypeSourceInfo(FixedTInfo);
7452   }
7453 
7454   if (T->isVoidType()) {
7455     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7456     //                    of objects and functions.
7457     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7458       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7459         << T;
7460       NewVD->setInvalidDecl();
7461       return;
7462     }
7463   }
7464 
7465   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7466     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7467     NewVD->setInvalidDecl();
7468     return;
7469   }
7470 
7471   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7472     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7473     NewVD->setInvalidDecl();
7474     return;
7475   }
7476 
7477   if (NewVD->isConstexpr() && !T->isDependentType() &&
7478       RequireLiteralType(NewVD->getLocation(), T,
7479                          diag::err_constexpr_var_non_literal)) {
7480     NewVD->setInvalidDecl();
7481     return;
7482   }
7483 }
7484 
7485 /// \brief Perform semantic checking on a newly-created variable
7486 /// declaration.
7487 ///
7488 /// This routine performs all of the type-checking required for a
7489 /// variable declaration once it has been built. It is used both to
7490 /// check variables after they have been parsed and their declarators
7491 /// have been translated into a declaration, and to check variables
7492 /// that have been instantiated from a template.
7493 ///
7494 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7495 ///
7496 /// Returns true if the variable declaration is a redeclaration.
7497 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7498   CheckVariableDeclarationType(NewVD);
7499 
7500   // If the decl is already known invalid, don't check it.
7501   if (NewVD->isInvalidDecl())
7502     return false;
7503 
7504   // If we did not find anything by this name, look for a non-visible
7505   // extern "C" declaration with the same name.
7506   if (Previous.empty() &&
7507       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7508     Previous.setShadowed();
7509 
7510   if (!Previous.empty()) {
7511     MergeVarDecl(NewVD, Previous);
7512     return true;
7513   }
7514   return false;
7515 }
7516 
7517 namespace {
7518 struct FindOverriddenMethod {
7519   Sema *S;
7520   CXXMethodDecl *Method;
7521 
7522   /// Member lookup function that determines whether a given C++
7523   /// method overrides a method in a base class, to be used with
7524   /// CXXRecordDecl::lookupInBases().
7525   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7526     RecordDecl *BaseRecord =
7527         Specifier->getType()->getAs<RecordType>()->getDecl();
7528 
7529     DeclarationName Name = Method->getDeclName();
7530 
7531     // FIXME: Do we care about other names here too?
7532     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7533       // We really want to find the base class destructor here.
7534       QualType T = S->Context.getTypeDeclType(BaseRecord);
7535       CanQualType CT = S->Context.getCanonicalType(T);
7536 
7537       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7538     }
7539 
7540     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7541          Path.Decls = Path.Decls.slice(1)) {
7542       NamedDecl *D = Path.Decls.front();
7543       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7544         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7545           return true;
7546       }
7547     }
7548 
7549     return false;
7550   }
7551 };
7552 
7553 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7554 } // end anonymous namespace
7555 
7556 /// \brief Report an error regarding overriding, along with any relevant
7557 /// overriden methods.
7558 ///
7559 /// \param DiagID the primary error to report.
7560 /// \param MD the overriding method.
7561 /// \param OEK which overrides to include as notes.
7562 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7563                             OverrideErrorKind OEK = OEK_All) {
7564   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7565   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7566     // This check (& the OEK parameter) could be replaced by a predicate, but
7567     // without lambdas that would be overkill. This is still nicer than writing
7568     // out the diag loop 3 times.
7569     if ((OEK == OEK_All) ||
7570         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7571         (OEK == OEK_Deleted && O->isDeleted()))
7572       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7573   }
7574 }
7575 
7576 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7577 /// and if so, check that it's a valid override and remember it.
7578 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7579   // Look for methods in base classes that this method might override.
7580   CXXBasePaths Paths;
7581   FindOverriddenMethod FOM;
7582   FOM.Method = MD;
7583   FOM.S = this;
7584   bool hasDeletedOverridenMethods = false;
7585   bool hasNonDeletedOverridenMethods = false;
7586   bool AddedAny = false;
7587   if (DC->lookupInBases(FOM, Paths)) {
7588     for (auto *I : Paths.found_decls()) {
7589       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7590         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7591         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7592             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7593             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7594             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7595           hasDeletedOverridenMethods |= OldMD->isDeleted();
7596           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7597           AddedAny = true;
7598         }
7599       }
7600     }
7601   }
7602 
7603   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7604     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7605   }
7606   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7607     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7608   }
7609 
7610   return AddedAny;
7611 }
7612 
7613 namespace {
7614   // Struct for holding all of the extra arguments needed by
7615   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7616   struct ActOnFDArgs {
7617     Scope *S;
7618     Declarator &D;
7619     MultiTemplateParamsArg TemplateParamLists;
7620     bool AddToScope;
7621   };
7622 } // end anonymous namespace
7623 
7624 namespace {
7625 
7626 // Callback to only accept typo corrections that have a non-zero edit distance.
7627 // Also only accept corrections that have the same parent decl.
7628 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7629  public:
7630   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7631                             CXXRecordDecl *Parent)
7632       : Context(Context), OriginalFD(TypoFD),
7633         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7634 
7635   bool ValidateCandidate(const TypoCorrection &candidate) override {
7636     if (candidate.getEditDistance() == 0)
7637       return false;
7638 
7639     SmallVector<unsigned, 1> MismatchedParams;
7640     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7641                                           CDeclEnd = candidate.end();
7642          CDecl != CDeclEnd; ++CDecl) {
7643       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7644 
7645       if (FD && !FD->hasBody() &&
7646           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7647         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7648           CXXRecordDecl *Parent = MD->getParent();
7649           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7650             return true;
7651         } else if (!ExpectedParent) {
7652           return true;
7653         }
7654       }
7655     }
7656 
7657     return false;
7658   }
7659 
7660  private:
7661   ASTContext &Context;
7662   FunctionDecl *OriginalFD;
7663   CXXRecordDecl *ExpectedParent;
7664 };
7665 
7666 } // end anonymous namespace
7667 
7668 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7669   TypoCorrectedFunctionDefinitions.insert(F);
7670 }
7671 
7672 /// \brief Generate diagnostics for an invalid function redeclaration.
7673 ///
7674 /// This routine handles generating the diagnostic messages for an invalid
7675 /// function redeclaration, including finding possible similar declarations
7676 /// or performing typo correction if there are no previous declarations with
7677 /// the same name.
7678 ///
7679 /// Returns a NamedDecl iff typo correction was performed and substituting in
7680 /// the new declaration name does not cause new errors.
7681 static NamedDecl *DiagnoseInvalidRedeclaration(
7682     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7683     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7684   DeclarationName Name = NewFD->getDeclName();
7685   DeclContext *NewDC = NewFD->getDeclContext();
7686   SmallVector<unsigned, 1> MismatchedParams;
7687   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7688   TypoCorrection Correction;
7689   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7690   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7691                                    : diag::err_member_decl_does_not_match;
7692   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7693                     IsLocalFriend ? Sema::LookupLocalFriendName
7694                                   : Sema::LookupOrdinaryName,
7695                     Sema::ForVisibleRedeclaration);
7696 
7697   NewFD->setInvalidDecl();
7698   if (IsLocalFriend)
7699     SemaRef.LookupName(Prev, S);
7700   else
7701     SemaRef.LookupQualifiedName(Prev, NewDC);
7702   assert(!Prev.isAmbiguous() &&
7703          "Cannot have an ambiguity in previous-declaration lookup");
7704   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7705   if (!Prev.empty()) {
7706     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7707          Func != FuncEnd; ++Func) {
7708       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7709       if (FD &&
7710           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7711         // Add 1 to the index so that 0 can mean the mismatch didn't
7712         // involve a parameter
7713         unsigned ParamNum =
7714             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7715         NearMatches.push_back(std::make_pair(FD, ParamNum));
7716       }
7717     }
7718   // If the qualified name lookup yielded nothing, try typo correction
7719   } else if ((Correction = SemaRef.CorrectTypo(
7720                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7721                   &ExtraArgs.D.getCXXScopeSpec(),
7722                   llvm::make_unique<DifferentNameValidatorCCC>(
7723                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7724                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7725     // Set up everything for the call to ActOnFunctionDeclarator
7726     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7727                               ExtraArgs.D.getIdentifierLoc());
7728     Previous.clear();
7729     Previous.setLookupName(Correction.getCorrection());
7730     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7731                                     CDeclEnd = Correction.end();
7732          CDecl != CDeclEnd; ++CDecl) {
7733       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7734       if (FD && !FD->hasBody() &&
7735           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7736         Previous.addDecl(FD);
7737       }
7738     }
7739     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7740 
7741     NamedDecl *Result;
7742     // Retry building the function declaration with the new previous
7743     // declarations, and with errors suppressed.
7744     {
7745       // Trap errors.
7746       Sema::SFINAETrap Trap(SemaRef);
7747 
7748       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7749       // pieces need to verify the typo-corrected C++ declaration and hopefully
7750       // eliminate the need for the parameter pack ExtraArgs.
7751       Result = SemaRef.ActOnFunctionDeclarator(
7752           ExtraArgs.S, ExtraArgs.D,
7753           Correction.getCorrectionDecl()->getDeclContext(),
7754           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7755           ExtraArgs.AddToScope);
7756 
7757       if (Trap.hasErrorOccurred())
7758         Result = nullptr;
7759     }
7760 
7761     if (Result) {
7762       // Determine which correction we picked.
7763       Decl *Canonical = Result->getCanonicalDecl();
7764       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7765            I != E; ++I)
7766         if ((*I)->getCanonicalDecl() == Canonical)
7767           Correction.setCorrectionDecl(*I);
7768 
7769       // Let Sema know about the correction.
7770       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7771       SemaRef.diagnoseTypo(
7772           Correction,
7773           SemaRef.PDiag(IsLocalFriend
7774                           ? diag::err_no_matching_local_friend_suggest
7775                           : diag::err_member_decl_does_not_match_suggest)
7776             << Name << NewDC << IsDefinition);
7777       return Result;
7778     }
7779 
7780     // Pretend the typo correction never occurred
7781     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7782                               ExtraArgs.D.getIdentifierLoc());
7783     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7784     Previous.clear();
7785     Previous.setLookupName(Name);
7786   }
7787 
7788   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7789       << Name << NewDC << IsDefinition << NewFD->getLocation();
7790 
7791   bool NewFDisConst = false;
7792   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7793     NewFDisConst = NewMD->isConst();
7794 
7795   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7796        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7797        NearMatch != NearMatchEnd; ++NearMatch) {
7798     FunctionDecl *FD = NearMatch->first;
7799     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7800     bool FDisConst = MD && MD->isConst();
7801     bool IsMember = MD || !IsLocalFriend;
7802 
7803     // FIXME: These notes are poorly worded for the local friend case.
7804     if (unsigned Idx = NearMatch->second) {
7805       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7806       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7807       if (Loc.isInvalid()) Loc = FD->getLocation();
7808       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7809                                  : diag::note_local_decl_close_param_match)
7810         << Idx << FDParam->getType()
7811         << NewFD->getParamDecl(Idx - 1)->getType();
7812     } else if (FDisConst != NewFDisConst) {
7813       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7814           << NewFDisConst << FD->getSourceRange().getEnd();
7815     } else
7816       SemaRef.Diag(FD->getLocation(),
7817                    IsMember ? diag::note_member_def_close_match
7818                             : diag::note_local_decl_close_match);
7819   }
7820   return nullptr;
7821 }
7822 
7823 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7824   switch (D.getDeclSpec().getStorageClassSpec()) {
7825   default: llvm_unreachable("Unknown storage class!");
7826   case DeclSpec::SCS_auto:
7827   case DeclSpec::SCS_register:
7828   case DeclSpec::SCS_mutable:
7829     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7830                  diag::err_typecheck_sclass_func);
7831     D.getMutableDeclSpec().ClearStorageClassSpecs();
7832     D.setInvalidType();
7833     break;
7834   case DeclSpec::SCS_unspecified: break;
7835   case DeclSpec::SCS_extern:
7836     if (D.getDeclSpec().isExternInLinkageSpec())
7837       return SC_None;
7838     return SC_Extern;
7839   case DeclSpec::SCS_static: {
7840     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7841       // C99 6.7.1p5:
7842       //   The declaration of an identifier for a function that has
7843       //   block scope shall have no explicit storage-class specifier
7844       //   other than extern
7845       // See also (C++ [dcl.stc]p4).
7846       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7847                    diag::err_static_block_func);
7848       break;
7849     } else
7850       return SC_Static;
7851   }
7852   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7853   }
7854 
7855   // No explicit storage class has already been returned
7856   return SC_None;
7857 }
7858 
7859 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7860                                            DeclContext *DC, QualType &R,
7861                                            TypeSourceInfo *TInfo,
7862                                            StorageClass SC,
7863                                            bool &IsVirtualOkay) {
7864   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7865   DeclarationName Name = NameInfo.getName();
7866 
7867   FunctionDecl *NewFD = nullptr;
7868   bool isInline = D.getDeclSpec().isInlineSpecified();
7869 
7870   if (!SemaRef.getLangOpts().CPlusPlus) {
7871     // Determine whether the function was written with a
7872     // prototype. This true when:
7873     //   - there is a prototype in the declarator, or
7874     //   - the type R of the function is some kind of typedef or other non-
7875     //     attributed reference to a type name (which eventually refers to a
7876     //     function type).
7877     bool HasPrototype =
7878       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7879       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7880 
7881     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7882                                  D.getLocStart(), NameInfo, R,
7883                                  TInfo, SC, isInline,
7884                                  HasPrototype, false);
7885     if (D.isInvalidType())
7886       NewFD->setInvalidDecl();
7887 
7888     return NewFD;
7889   }
7890 
7891   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7892   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7893 
7894   // Check that the return type is not an abstract class type.
7895   // For record types, this is done by the AbstractClassUsageDiagnoser once
7896   // the class has been completely parsed.
7897   if (!DC->isRecord() &&
7898       SemaRef.RequireNonAbstractType(
7899           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7900           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7901     D.setInvalidType();
7902 
7903   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7904     // This is a C++ constructor declaration.
7905     assert(DC->isRecord() &&
7906            "Constructors can only be declared in a member context");
7907 
7908     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7909     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7910                                       D.getLocStart(), NameInfo,
7911                                       R, TInfo, isExplicit, isInline,
7912                                       /*isImplicitlyDeclared=*/false,
7913                                       isConstexpr);
7914 
7915   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7916     // This is a C++ destructor declaration.
7917     if (DC->isRecord()) {
7918       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7919       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7920       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7921                                         SemaRef.Context, Record,
7922                                         D.getLocStart(),
7923                                         NameInfo, R, TInfo, isInline,
7924                                         /*isImplicitlyDeclared=*/false);
7925 
7926       // If the class is complete, then we now create the implicit exception
7927       // specification. If the class is incomplete or dependent, we can't do
7928       // it yet.
7929       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7930           Record->getDefinition() && !Record->isBeingDefined() &&
7931           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7932         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7933       }
7934 
7935       IsVirtualOkay = true;
7936       return NewDD;
7937 
7938     } else {
7939       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7940       D.setInvalidType();
7941 
7942       // Create a FunctionDecl to satisfy the function definition parsing
7943       // code path.
7944       return FunctionDecl::Create(SemaRef.Context, DC,
7945                                   D.getLocStart(),
7946                                   D.getIdentifierLoc(), Name, R, TInfo,
7947                                   SC, isInline,
7948                                   /*hasPrototype=*/true, isConstexpr);
7949     }
7950 
7951   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7952     if (!DC->isRecord()) {
7953       SemaRef.Diag(D.getIdentifierLoc(),
7954            diag::err_conv_function_not_member);
7955       return nullptr;
7956     }
7957 
7958     SemaRef.CheckConversionDeclarator(D, R, SC);
7959     IsVirtualOkay = true;
7960     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7961                                      D.getLocStart(), NameInfo,
7962                                      R, TInfo, isInline, isExplicit,
7963                                      isConstexpr, SourceLocation());
7964 
7965   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7966     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7967 
7968     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
7969                                          isExplicit, NameInfo, R, TInfo,
7970                                          D.getLocEnd());
7971   } else if (DC->isRecord()) {
7972     // If the name of the function is the same as the name of the record,
7973     // then this must be an invalid constructor that has a return type.
7974     // (The parser checks for a return type and makes the declarator a
7975     // constructor if it has no return type).
7976     if (Name.getAsIdentifierInfo() &&
7977         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7978       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7979         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7980         << SourceRange(D.getIdentifierLoc());
7981       return nullptr;
7982     }
7983 
7984     // This is a C++ method declaration.
7985     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7986                                                cast<CXXRecordDecl>(DC),
7987                                                D.getLocStart(), NameInfo, R,
7988                                                TInfo, SC, isInline,
7989                                                isConstexpr, SourceLocation());
7990     IsVirtualOkay = !Ret->isStatic();
7991     return Ret;
7992   } else {
7993     bool isFriend =
7994         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7995     if (!isFriend && SemaRef.CurContext->isRecord())
7996       return nullptr;
7997 
7998     // Determine whether the function was written with a
7999     // prototype. This true when:
8000     //   - we're in C++ (where every function has a prototype),
8001     return FunctionDecl::Create(SemaRef.Context, DC,
8002                                 D.getLocStart(),
8003                                 NameInfo, R, TInfo, SC, isInline,
8004                                 true/*HasPrototype*/, isConstexpr);
8005   }
8006 }
8007 
8008 enum OpenCLParamType {
8009   ValidKernelParam,
8010   PtrPtrKernelParam,
8011   PtrKernelParam,
8012   InvalidAddrSpacePtrKernelParam,
8013   InvalidKernelParam,
8014   RecordKernelParam
8015 };
8016 
8017 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8018   if (PT->isPointerType()) {
8019     QualType PointeeType = PT->getPointeeType();
8020     if (PointeeType->isPointerType())
8021       return PtrPtrKernelParam;
8022     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8023         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8024         PointeeType.getAddressSpace() == LangAS::Default)
8025       return InvalidAddrSpacePtrKernelParam;
8026     return PtrKernelParam;
8027   }
8028 
8029   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
8030   // be used as builtin types.
8031 
8032   if (PT->isImageType())
8033     return PtrKernelParam;
8034 
8035   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8036     return InvalidKernelParam;
8037 
8038   // OpenCL extension spec v1.2 s9.5:
8039   // This extension adds support for half scalar and vector types as built-in
8040   // types that can be used for arithmetic operations, conversions etc.
8041   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8042     return InvalidKernelParam;
8043 
8044   if (PT->isRecordType())
8045     return RecordKernelParam;
8046 
8047   return ValidKernelParam;
8048 }
8049 
8050 static void checkIsValidOpenCLKernelParameter(
8051   Sema &S,
8052   Declarator &D,
8053   ParmVarDecl *Param,
8054   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8055   QualType PT = Param->getType();
8056 
8057   // Cache the valid types we encounter to avoid rechecking structs that are
8058   // used again
8059   if (ValidTypes.count(PT.getTypePtr()))
8060     return;
8061 
8062   switch (getOpenCLKernelParameterType(S, PT)) {
8063   case PtrPtrKernelParam:
8064     // OpenCL v1.2 s6.9.a:
8065     // A kernel function argument cannot be declared as a
8066     // pointer to a pointer type.
8067     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8068     D.setInvalidType();
8069     return;
8070 
8071   case InvalidAddrSpacePtrKernelParam:
8072     // OpenCL v1.0 s6.5:
8073     // __kernel function arguments declared to be a pointer of a type can point
8074     // to one of the following address spaces only : __global, __local or
8075     // __constant.
8076     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8077     D.setInvalidType();
8078     return;
8079 
8080     // OpenCL v1.2 s6.9.k:
8081     // Arguments to kernel functions in a program cannot be declared with the
8082     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8083     // uintptr_t or a struct and/or union that contain fields declared to be
8084     // one of these built-in scalar types.
8085 
8086   case InvalidKernelParam:
8087     // OpenCL v1.2 s6.8 n:
8088     // A kernel function argument cannot be declared
8089     // of event_t type.
8090     // Do not diagnose half type since it is diagnosed as invalid argument
8091     // type for any function elsewhere.
8092     if (!PT->isHalfType())
8093       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8094     D.setInvalidType();
8095     return;
8096 
8097   case PtrKernelParam:
8098   case ValidKernelParam:
8099     ValidTypes.insert(PT.getTypePtr());
8100     return;
8101 
8102   case RecordKernelParam:
8103     break;
8104   }
8105 
8106   // Track nested structs we will inspect
8107   SmallVector<const Decl *, 4> VisitStack;
8108 
8109   // Track where we are in the nested structs. Items will migrate from
8110   // VisitStack to HistoryStack as we do the DFS for bad field.
8111   SmallVector<const FieldDecl *, 4> HistoryStack;
8112   HistoryStack.push_back(nullptr);
8113 
8114   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
8115   VisitStack.push_back(PD);
8116 
8117   assert(VisitStack.back() && "First decl null?");
8118 
8119   do {
8120     const Decl *Next = VisitStack.pop_back_val();
8121     if (!Next) {
8122       assert(!HistoryStack.empty());
8123       // Found a marker, we have gone up a level
8124       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8125         ValidTypes.insert(Hist->getType().getTypePtr());
8126 
8127       continue;
8128     }
8129 
8130     // Adds everything except the original parameter declaration (which is not a
8131     // field itself) to the history stack.
8132     const RecordDecl *RD;
8133     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8134       HistoryStack.push_back(Field);
8135       RD = Field->getType()->castAs<RecordType>()->getDecl();
8136     } else {
8137       RD = cast<RecordDecl>(Next);
8138     }
8139 
8140     // Add a null marker so we know when we've gone back up a level
8141     VisitStack.push_back(nullptr);
8142 
8143     for (const auto *FD : RD->fields()) {
8144       QualType QT = FD->getType();
8145 
8146       if (ValidTypes.count(QT.getTypePtr()))
8147         continue;
8148 
8149       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8150       if (ParamType == ValidKernelParam)
8151         continue;
8152 
8153       if (ParamType == RecordKernelParam) {
8154         VisitStack.push_back(FD);
8155         continue;
8156       }
8157 
8158       // OpenCL v1.2 s6.9.p:
8159       // Arguments to kernel functions that are declared to be a struct or union
8160       // do not allow OpenCL objects to be passed as elements of the struct or
8161       // union.
8162       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8163           ParamType == InvalidAddrSpacePtrKernelParam) {
8164         S.Diag(Param->getLocation(),
8165                diag::err_record_with_pointers_kernel_param)
8166           << PT->isUnionType()
8167           << PT;
8168       } else {
8169         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8170       }
8171 
8172       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
8173         << PD->getDeclName();
8174 
8175       // We have an error, now let's go back up through history and show where
8176       // the offending field came from
8177       for (ArrayRef<const FieldDecl *>::const_iterator
8178                I = HistoryStack.begin() + 1,
8179                E = HistoryStack.end();
8180            I != E; ++I) {
8181         const FieldDecl *OuterField = *I;
8182         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8183           << OuterField->getType();
8184       }
8185 
8186       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8187         << QT->isPointerType()
8188         << QT;
8189       D.setInvalidType();
8190       return;
8191     }
8192   } while (!VisitStack.empty());
8193 }
8194 
8195 /// Find the DeclContext in which a tag is implicitly declared if we see an
8196 /// elaborated type specifier in the specified context, and lookup finds
8197 /// nothing.
8198 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8199   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8200     DC = DC->getParent();
8201   return DC;
8202 }
8203 
8204 /// Find the Scope in which a tag is implicitly declared if we see an
8205 /// elaborated type specifier in the specified context, and lookup finds
8206 /// nothing.
8207 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8208   while (S->isClassScope() ||
8209          (LangOpts.CPlusPlus &&
8210           S->isFunctionPrototypeScope()) ||
8211          ((S->getFlags() & Scope::DeclScope) == 0) ||
8212          (S->getEntity() && S->getEntity()->isTransparentContext()))
8213     S = S->getParent();
8214   return S;
8215 }
8216 
8217 NamedDecl*
8218 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8219                               TypeSourceInfo *TInfo, LookupResult &Previous,
8220                               MultiTemplateParamsArg TemplateParamLists,
8221                               bool &AddToScope) {
8222   QualType R = TInfo->getType();
8223 
8224   assert(R.getTypePtr()->isFunctionType());
8225 
8226   // TODO: consider using NameInfo for diagnostic.
8227   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8228   DeclarationName Name = NameInfo.getName();
8229   StorageClass SC = getFunctionStorageClass(*this, D);
8230 
8231   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8232     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8233          diag::err_invalid_thread)
8234       << DeclSpec::getSpecifierName(TSCS);
8235 
8236   if (D.isFirstDeclarationOfMember())
8237     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8238                            D.getIdentifierLoc());
8239 
8240   bool isFriend = false;
8241   FunctionTemplateDecl *FunctionTemplate = nullptr;
8242   bool isMemberSpecialization = false;
8243   bool isFunctionTemplateSpecialization = false;
8244 
8245   bool isDependentClassScopeExplicitSpecialization = false;
8246   bool HasExplicitTemplateArgs = false;
8247   TemplateArgumentListInfo TemplateArgs;
8248 
8249   bool isVirtualOkay = false;
8250 
8251   DeclContext *OriginalDC = DC;
8252   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8253 
8254   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8255                                               isVirtualOkay);
8256   if (!NewFD) return nullptr;
8257 
8258   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8259     NewFD->setTopLevelDeclInObjCContainer();
8260 
8261   // Set the lexical context. If this is a function-scope declaration, or has a
8262   // C++ scope specifier, or is the object of a friend declaration, the lexical
8263   // context will be different from the semantic context.
8264   NewFD->setLexicalDeclContext(CurContext);
8265 
8266   if (IsLocalExternDecl)
8267     NewFD->setLocalExternDecl();
8268 
8269   if (getLangOpts().CPlusPlus) {
8270     bool isInline = D.getDeclSpec().isInlineSpecified();
8271     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8272     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8273     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8274     isFriend = D.getDeclSpec().isFriendSpecified();
8275     if (isFriend && !isInline && D.isFunctionDefinition()) {
8276       // C++ [class.friend]p5
8277       //   A function can be defined in a friend declaration of a
8278       //   class . . . . Such a function is implicitly inline.
8279       NewFD->setImplicitlyInline();
8280     }
8281 
8282     // If this is a method defined in an __interface, and is not a constructor
8283     // or an overloaded operator, then set the pure flag (isVirtual will already
8284     // return true).
8285     if (const CXXRecordDecl *Parent =
8286           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8287       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8288         NewFD->setPure(true);
8289 
8290       // C++ [class.union]p2
8291       //   A union can have member functions, but not virtual functions.
8292       if (isVirtual && Parent->isUnion())
8293         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8294     }
8295 
8296     SetNestedNameSpecifier(NewFD, D);
8297     isMemberSpecialization = false;
8298     isFunctionTemplateSpecialization = false;
8299     if (D.isInvalidType())
8300       NewFD->setInvalidDecl();
8301 
8302     // Match up the template parameter lists with the scope specifier, then
8303     // determine whether we have a template or a template specialization.
8304     bool Invalid = false;
8305     if (TemplateParameterList *TemplateParams =
8306             MatchTemplateParametersToScopeSpecifier(
8307                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
8308                 D.getCXXScopeSpec(),
8309                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8310                     ? D.getName().TemplateId
8311                     : nullptr,
8312                 TemplateParamLists, isFriend, isMemberSpecialization,
8313                 Invalid)) {
8314       if (TemplateParams->size() > 0) {
8315         // This is a function template
8316 
8317         // Check that we can declare a template here.
8318         if (CheckTemplateDeclScope(S, TemplateParams))
8319           NewFD->setInvalidDecl();
8320 
8321         // A destructor cannot be a template.
8322         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8323           Diag(NewFD->getLocation(), diag::err_destructor_template);
8324           NewFD->setInvalidDecl();
8325         }
8326 
8327         // If we're adding a template to a dependent context, we may need to
8328         // rebuilding some of the types used within the template parameter list,
8329         // now that we know what the current instantiation is.
8330         if (DC->isDependentContext()) {
8331           ContextRAII SavedContext(*this, DC);
8332           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8333             Invalid = true;
8334         }
8335 
8336         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8337                                                         NewFD->getLocation(),
8338                                                         Name, TemplateParams,
8339                                                         NewFD);
8340         FunctionTemplate->setLexicalDeclContext(CurContext);
8341         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8342 
8343         // For source fidelity, store the other template param lists.
8344         if (TemplateParamLists.size() > 1) {
8345           NewFD->setTemplateParameterListsInfo(Context,
8346                                                TemplateParamLists.drop_back(1));
8347         }
8348       } else {
8349         // This is a function template specialization.
8350         isFunctionTemplateSpecialization = true;
8351         // For source fidelity, store all the template param lists.
8352         if (TemplateParamLists.size() > 0)
8353           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8354 
8355         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8356         if (isFriend) {
8357           // We want to remove the "template<>", found here.
8358           SourceRange RemoveRange = TemplateParams->getSourceRange();
8359 
8360           // If we remove the template<> and the name is not a
8361           // template-id, we're actually silently creating a problem:
8362           // the friend declaration will refer to an untemplated decl,
8363           // and clearly the user wants a template specialization.  So
8364           // we need to insert '<>' after the name.
8365           SourceLocation InsertLoc;
8366           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8367             InsertLoc = D.getName().getSourceRange().getEnd();
8368             InsertLoc = getLocForEndOfToken(InsertLoc);
8369           }
8370 
8371           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8372             << Name << RemoveRange
8373             << FixItHint::CreateRemoval(RemoveRange)
8374             << FixItHint::CreateInsertion(InsertLoc, "<>");
8375         }
8376       }
8377     }
8378     else {
8379       // All template param lists were matched against the scope specifier:
8380       // this is NOT (an explicit specialization of) a template.
8381       if (TemplateParamLists.size() > 0)
8382         // For source fidelity, store all the template param lists.
8383         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8384     }
8385 
8386     if (Invalid) {
8387       NewFD->setInvalidDecl();
8388       if (FunctionTemplate)
8389         FunctionTemplate->setInvalidDecl();
8390     }
8391 
8392     // C++ [dcl.fct.spec]p5:
8393     //   The virtual specifier shall only be used in declarations of
8394     //   nonstatic class member functions that appear within a
8395     //   member-specification of a class declaration; see 10.3.
8396     //
8397     if (isVirtual && !NewFD->isInvalidDecl()) {
8398       if (!isVirtualOkay) {
8399         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8400              diag::err_virtual_non_function);
8401       } else if (!CurContext->isRecord()) {
8402         // 'virtual' was specified outside of the class.
8403         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8404              diag::err_virtual_out_of_class)
8405           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8406       } else if (NewFD->getDescribedFunctionTemplate()) {
8407         // C++ [temp.mem]p3:
8408         //  A member function template shall not be virtual.
8409         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8410              diag::err_virtual_member_function_template)
8411           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8412       } else {
8413         // Okay: Add virtual to the method.
8414         NewFD->setVirtualAsWritten(true);
8415       }
8416 
8417       if (getLangOpts().CPlusPlus14 &&
8418           NewFD->getReturnType()->isUndeducedType())
8419         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8420     }
8421 
8422     if (getLangOpts().CPlusPlus14 &&
8423         (NewFD->isDependentContext() ||
8424          (isFriend && CurContext->isDependentContext())) &&
8425         NewFD->getReturnType()->isUndeducedType()) {
8426       // If the function template is referenced directly (for instance, as a
8427       // member of the current instantiation), pretend it has a dependent type.
8428       // This is not really justified by the standard, but is the only sane
8429       // thing to do.
8430       // FIXME: For a friend function, we have not marked the function as being
8431       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8432       const FunctionProtoType *FPT =
8433           NewFD->getType()->castAs<FunctionProtoType>();
8434       QualType Result =
8435           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8436       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8437                                              FPT->getExtProtoInfo()));
8438     }
8439 
8440     // C++ [dcl.fct.spec]p3:
8441     //  The inline specifier shall not appear on a block scope function
8442     //  declaration.
8443     if (isInline && !NewFD->isInvalidDecl()) {
8444       if (CurContext->isFunctionOrMethod()) {
8445         // 'inline' is not allowed on block scope function declaration.
8446         Diag(D.getDeclSpec().getInlineSpecLoc(),
8447              diag::err_inline_declaration_block_scope) << Name
8448           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8449       }
8450     }
8451 
8452     // C++ [dcl.fct.spec]p6:
8453     //  The explicit specifier shall be used only in the declaration of a
8454     //  constructor or conversion function within its class definition;
8455     //  see 12.3.1 and 12.3.2.
8456     if (isExplicit && !NewFD->isInvalidDecl() &&
8457         !isa<CXXDeductionGuideDecl>(NewFD)) {
8458       if (!CurContext->isRecord()) {
8459         // 'explicit' was specified outside of the class.
8460         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8461              diag::err_explicit_out_of_class)
8462           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8463       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8464                  !isa<CXXConversionDecl>(NewFD)) {
8465         // 'explicit' was specified on a function that wasn't a constructor
8466         // or conversion function.
8467         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8468              diag::err_explicit_non_ctor_or_conv_function)
8469           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8470       }
8471     }
8472 
8473     if (isConstexpr) {
8474       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8475       // are implicitly inline.
8476       NewFD->setImplicitlyInline();
8477 
8478       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8479       // be either constructors or to return a literal type. Therefore,
8480       // destructors cannot be declared constexpr.
8481       if (isa<CXXDestructorDecl>(NewFD))
8482         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8483     }
8484 
8485     // If __module_private__ was specified, mark the function accordingly.
8486     if (D.getDeclSpec().isModulePrivateSpecified()) {
8487       if (isFunctionTemplateSpecialization) {
8488         SourceLocation ModulePrivateLoc
8489           = D.getDeclSpec().getModulePrivateSpecLoc();
8490         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8491           << 0
8492           << FixItHint::CreateRemoval(ModulePrivateLoc);
8493       } else {
8494         NewFD->setModulePrivate();
8495         if (FunctionTemplate)
8496           FunctionTemplate->setModulePrivate();
8497       }
8498     }
8499 
8500     if (isFriend) {
8501       if (FunctionTemplate) {
8502         FunctionTemplate->setObjectOfFriendDecl();
8503         FunctionTemplate->setAccess(AS_public);
8504       }
8505       NewFD->setObjectOfFriendDecl();
8506       NewFD->setAccess(AS_public);
8507     }
8508 
8509     // If a function is defined as defaulted or deleted, mark it as such now.
8510     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8511     // definition kind to FDK_Definition.
8512     switch (D.getFunctionDefinitionKind()) {
8513       case FDK_Declaration:
8514       case FDK_Definition:
8515         break;
8516 
8517       case FDK_Defaulted:
8518         NewFD->setDefaulted();
8519         break;
8520 
8521       case FDK_Deleted:
8522         NewFD->setDeletedAsWritten();
8523         break;
8524     }
8525 
8526     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8527         D.isFunctionDefinition()) {
8528       // C++ [class.mfct]p2:
8529       //   A member function may be defined (8.4) in its class definition, in
8530       //   which case it is an inline member function (7.1.2)
8531       NewFD->setImplicitlyInline();
8532     }
8533 
8534     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8535         !CurContext->isRecord()) {
8536       // C++ [class.static]p1:
8537       //   A data or function member of a class may be declared static
8538       //   in a class definition, in which case it is a static member of
8539       //   the class.
8540 
8541       // Complain about the 'static' specifier if it's on an out-of-line
8542       // member function definition.
8543       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8544            diag::err_static_out_of_line)
8545         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8546     }
8547 
8548     // C++11 [except.spec]p15:
8549     //   A deallocation function with no exception-specification is treated
8550     //   as if it were specified with noexcept(true).
8551     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8552     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8553          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8554         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8555       NewFD->setType(Context.getFunctionType(
8556           FPT->getReturnType(), FPT->getParamTypes(),
8557           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8558   }
8559 
8560   // Filter out previous declarations that don't match the scope.
8561   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8562                        D.getCXXScopeSpec().isNotEmpty() ||
8563                        isMemberSpecialization ||
8564                        isFunctionTemplateSpecialization);
8565 
8566   // Handle GNU asm-label extension (encoded as an attribute).
8567   if (Expr *E = (Expr*) D.getAsmLabel()) {
8568     // The parser guarantees this is a string.
8569     StringLiteral *SE = cast<StringLiteral>(E);
8570     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8571                                                 SE->getString(), 0));
8572   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8573     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8574       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8575     if (I != ExtnameUndeclaredIdentifiers.end()) {
8576       if (isDeclExternC(NewFD)) {
8577         NewFD->addAttr(I->second);
8578         ExtnameUndeclaredIdentifiers.erase(I);
8579       } else
8580         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8581             << /*Variable*/0 << NewFD;
8582     }
8583   }
8584 
8585   // Copy the parameter declarations from the declarator D to the function
8586   // declaration NewFD, if they are available.  First scavenge them into Params.
8587   SmallVector<ParmVarDecl*, 16> Params;
8588   unsigned FTIIdx;
8589   if (D.isFunctionDeclarator(FTIIdx)) {
8590     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8591 
8592     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8593     // function that takes no arguments, not a function that takes a
8594     // single void argument.
8595     // We let through "const void" here because Sema::GetTypeForDeclarator
8596     // already checks for that case.
8597     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8598       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8599         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8600         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8601         Param->setDeclContext(NewFD);
8602         Params.push_back(Param);
8603 
8604         if (Param->isInvalidDecl())
8605           NewFD->setInvalidDecl();
8606       }
8607     }
8608 
8609     if (!getLangOpts().CPlusPlus) {
8610       // In C, find all the tag declarations from the prototype and move them
8611       // into the function DeclContext. Remove them from the surrounding tag
8612       // injection context of the function, which is typically but not always
8613       // the TU.
8614       DeclContext *PrototypeTagContext =
8615           getTagInjectionContext(NewFD->getLexicalDeclContext());
8616       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8617         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8618 
8619         // We don't want to reparent enumerators. Look at their parent enum
8620         // instead.
8621         if (!TD) {
8622           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8623             TD = cast<EnumDecl>(ECD->getDeclContext());
8624         }
8625         if (!TD)
8626           continue;
8627         DeclContext *TagDC = TD->getLexicalDeclContext();
8628         if (!TagDC->containsDecl(TD))
8629           continue;
8630         TagDC->removeDecl(TD);
8631         TD->setDeclContext(NewFD);
8632         NewFD->addDecl(TD);
8633 
8634         // Preserve the lexical DeclContext if it is not the surrounding tag
8635         // injection context of the FD. In this example, the semantic context of
8636         // E will be f and the lexical context will be S, while both the
8637         // semantic and lexical contexts of S will be f:
8638         //   void f(struct S { enum E { a } f; } s);
8639         if (TagDC != PrototypeTagContext)
8640           TD->setLexicalDeclContext(TagDC);
8641       }
8642     }
8643   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8644     // When we're declaring a function with a typedef, typeof, etc as in the
8645     // following example, we'll need to synthesize (unnamed)
8646     // parameters for use in the declaration.
8647     //
8648     // @code
8649     // typedef void fn(int);
8650     // fn f;
8651     // @endcode
8652 
8653     // Synthesize a parameter for each argument type.
8654     for (const auto &AI : FT->param_types()) {
8655       ParmVarDecl *Param =
8656           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8657       Param->setScopeInfo(0, Params.size());
8658       Params.push_back(Param);
8659     }
8660   } else {
8661     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8662            "Should not need args for typedef of non-prototype fn");
8663   }
8664 
8665   // Finally, we know we have the right number of parameters, install them.
8666   NewFD->setParams(Params);
8667 
8668   if (D.getDeclSpec().isNoreturnSpecified())
8669     NewFD->addAttr(
8670         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8671                                        Context, 0));
8672 
8673   // Functions returning a variably modified type violate C99 6.7.5.2p2
8674   // because all functions have linkage.
8675   if (!NewFD->isInvalidDecl() &&
8676       NewFD->getReturnType()->isVariablyModifiedType()) {
8677     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8678     NewFD->setInvalidDecl();
8679   }
8680 
8681   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8682   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8683       !NewFD->hasAttr<SectionAttr>()) {
8684     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8685                                                  PragmaClangTextSection.SectionName,
8686                                                  PragmaClangTextSection.PragmaLocation));
8687   }
8688 
8689   // Apply an implicit SectionAttr if #pragma code_seg is active.
8690   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8691       !NewFD->hasAttr<SectionAttr>()) {
8692     NewFD->addAttr(
8693         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8694                                     CodeSegStack.CurrentValue->getString(),
8695                                     CodeSegStack.CurrentPragmaLocation));
8696     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8697                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8698                          ASTContext::PSF_Read,
8699                      NewFD))
8700       NewFD->dropAttr<SectionAttr>();
8701   }
8702 
8703   // Handle attributes.
8704   ProcessDeclAttributes(S, NewFD, D);
8705 
8706   if (getLangOpts().OpenCL) {
8707     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8708     // type declaration will generate a compilation error.
8709     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
8710     if (AddressSpace != LangAS::Default) {
8711       Diag(NewFD->getLocation(),
8712            diag::err_opencl_return_value_with_address_space);
8713       NewFD->setInvalidDecl();
8714     }
8715   }
8716 
8717   if (!getLangOpts().CPlusPlus) {
8718     // Perform semantic checking on the function declaration.
8719     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8720       CheckMain(NewFD, D.getDeclSpec());
8721 
8722     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8723       CheckMSVCRTEntryPoint(NewFD);
8724 
8725     if (!NewFD->isInvalidDecl())
8726       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8727                                                   isMemberSpecialization));
8728     else if (!Previous.empty())
8729       // Recover gracefully from an invalid redeclaration.
8730       D.setRedeclaration(true);
8731     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8732             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8733            "previous declaration set still overloaded");
8734 
8735     // Diagnose no-prototype function declarations with calling conventions that
8736     // don't support variadic calls. Only do this in C and do it after merging
8737     // possibly prototyped redeclarations.
8738     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8739     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8740       CallingConv CC = FT->getExtInfo().getCC();
8741       if (!supportsVariadicCall(CC)) {
8742         // Windows system headers sometimes accidentally use stdcall without
8743         // (void) parameters, so we relax this to a warning.
8744         int DiagID =
8745             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8746         Diag(NewFD->getLocation(), DiagID)
8747             << FunctionType::getNameForCallConv(CC);
8748       }
8749     }
8750   } else {
8751     // C++11 [replacement.functions]p3:
8752     //  The program's definitions shall not be specified as inline.
8753     //
8754     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8755     //
8756     // Suppress the diagnostic if the function is __attribute__((used)), since
8757     // that forces an external definition to be emitted.
8758     if (D.getDeclSpec().isInlineSpecified() &&
8759         NewFD->isReplaceableGlobalAllocationFunction() &&
8760         !NewFD->hasAttr<UsedAttr>())
8761       Diag(D.getDeclSpec().getInlineSpecLoc(),
8762            diag::ext_operator_new_delete_declared_inline)
8763         << NewFD->getDeclName();
8764 
8765     // If the declarator is a template-id, translate the parser's template
8766     // argument list into our AST format.
8767     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
8768       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8769       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8770       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8771       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8772                                          TemplateId->NumArgs);
8773       translateTemplateArguments(TemplateArgsPtr,
8774                                  TemplateArgs);
8775 
8776       HasExplicitTemplateArgs = true;
8777 
8778       if (NewFD->isInvalidDecl()) {
8779         HasExplicitTemplateArgs = false;
8780       } else if (FunctionTemplate) {
8781         // Function template with explicit template arguments.
8782         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8783           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8784 
8785         HasExplicitTemplateArgs = false;
8786       } else {
8787         assert((isFunctionTemplateSpecialization ||
8788                 D.getDeclSpec().isFriendSpecified()) &&
8789                "should have a 'template<>' for this decl");
8790         // "friend void foo<>(int);" is an implicit specialization decl.
8791         isFunctionTemplateSpecialization = true;
8792       }
8793     } else if (isFriend && isFunctionTemplateSpecialization) {
8794       // This combination is only possible in a recovery case;  the user
8795       // wrote something like:
8796       //   template <> friend void foo(int);
8797       // which we're recovering from as if the user had written:
8798       //   friend void foo<>(int);
8799       // Go ahead and fake up a template id.
8800       HasExplicitTemplateArgs = true;
8801       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8802       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8803     }
8804 
8805     // We do not add HD attributes to specializations here because
8806     // they may have different constexpr-ness compared to their
8807     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8808     // may end up with different effective targets. Instead, a
8809     // specialization inherits its target attributes from its template
8810     // in the CheckFunctionTemplateSpecialization() call below.
8811     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8812       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8813 
8814     // If it's a friend (and only if it's a friend), it's possible
8815     // that either the specialized function type or the specialized
8816     // template is dependent, and therefore matching will fail.  In
8817     // this case, don't check the specialization yet.
8818     bool InstantiationDependent = false;
8819     if (isFunctionTemplateSpecialization && isFriend &&
8820         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8821          TemplateSpecializationType::anyDependentTemplateArguments(
8822             TemplateArgs,
8823             InstantiationDependent))) {
8824       assert(HasExplicitTemplateArgs &&
8825              "friend function specialization without template args");
8826       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8827                                                        Previous))
8828         NewFD->setInvalidDecl();
8829     } else if (isFunctionTemplateSpecialization) {
8830       if (CurContext->isDependentContext() && CurContext->isRecord()
8831           && !isFriend) {
8832         isDependentClassScopeExplicitSpecialization = true;
8833         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8834           diag::ext_function_specialization_in_class :
8835           diag::err_function_specialization_in_class)
8836           << NewFD->getDeclName();
8837       } else if (!NewFD->isInvalidDecl() &&
8838                  CheckFunctionTemplateSpecialization(
8839                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
8840                      Previous))
8841         NewFD->setInvalidDecl();
8842 
8843       // C++ [dcl.stc]p1:
8844       //   A storage-class-specifier shall not be specified in an explicit
8845       //   specialization (14.7.3)
8846       FunctionTemplateSpecializationInfo *Info =
8847           NewFD->getTemplateSpecializationInfo();
8848       if (Info && SC != SC_None) {
8849         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8850           Diag(NewFD->getLocation(),
8851                diag::err_explicit_specialization_inconsistent_storage_class)
8852             << SC
8853             << FixItHint::CreateRemoval(
8854                                       D.getDeclSpec().getStorageClassSpecLoc());
8855 
8856         else
8857           Diag(NewFD->getLocation(),
8858                diag::ext_explicit_specialization_storage_class)
8859             << FixItHint::CreateRemoval(
8860                                       D.getDeclSpec().getStorageClassSpecLoc());
8861       }
8862     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8863       if (CheckMemberSpecialization(NewFD, Previous))
8864           NewFD->setInvalidDecl();
8865     }
8866 
8867     // Perform semantic checking on the function declaration.
8868     if (!isDependentClassScopeExplicitSpecialization) {
8869       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8870         CheckMain(NewFD, D.getDeclSpec());
8871 
8872       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8873         CheckMSVCRTEntryPoint(NewFD);
8874 
8875       if (!NewFD->isInvalidDecl())
8876         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8877                                                     isMemberSpecialization));
8878       else if (!Previous.empty())
8879         // Recover gracefully from an invalid redeclaration.
8880         D.setRedeclaration(true);
8881     }
8882 
8883     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8884             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8885            "previous declaration set still overloaded");
8886 
8887     NamedDecl *PrincipalDecl = (FunctionTemplate
8888                                 ? cast<NamedDecl>(FunctionTemplate)
8889                                 : NewFD);
8890 
8891     if (isFriend && NewFD->getPreviousDecl()) {
8892       AccessSpecifier Access = AS_public;
8893       if (!NewFD->isInvalidDecl())
8894         Access = NewFD->getPreviousDecl()->getAccess();
8895 
8896       NewFD->setAccess(Access);
8897       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8898     }
8899 
8900     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8901         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8902       PrincipalDecl->setNonMemberOperator();
8903 
8904     // If we have a function template, check the template parameter
8905     // list. This will check and merge default template arguments.
8906     if (FunctionTemplate) {
8907       FunctionTemplateDecl *PrevTemplate =
8908                                      FunctionTemplate->getPreviousDecl();
8909       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8910                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8911                                     : nullptr,
8912                             D.getDeclSpec().isFriendSpecified()
8913                               ? (D.isFunctionDefinition()
8914                                    ? TPC_FriendFunctionTemplateDefinition
8915                                    : TPC_FriendFunctionTemplate)
8916                               : (D.getCXXScopeSpec().isSet() &&
8917                                  DC && DC->isRecord() &&
8918                                  DC->isDependentContext())
8919                                   ? TPC_ClassTemplateMember
8920                                   : TPC_FunctionTemplate);
8921     }
8922 
8923     if (NewFD->isInvalidDecl()) {
8924       // Ignore all the rest of this.
8925     } else if (!D.isRedeclaration()) {
8926       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8927                                        AddToScope };
8928       // Fake up an access specifier if it's supposed to be a class member.
8929       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8930         NewFD->setAccess(AS_public);
8931 
8932       // Qualified decls generally require a previous declaration.
8933       if (D.getCXXScopeSpec().isSet()) {
8934         // ...with the major exception of templated-scope or
8935         // dependent-scope friend declarations.
8936 
8937         // TODO: we currently also suppress this check in dependent
8938         // contexts because (1) the parameter depth will be off when
8939         // matching friend templates and (2) we might actually be
8940         // selecting a friend based on a dependent factor.  But there
8941         // are situations where these conditions don't apply and we
8942         // can actually do this check immediately.
8943         if (isFriend &&
8944             (TemplateParamLists.size() ||
8945              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8946              CurContext->isDependentContext())) {
8947           // ignore these
8948         } else {
8949           // The user tried to provide an out-of-line definition for a
8950           // function that is a member of a class or namespace, but there
8951           // was no such member function declared (C++ [class.mfct]p2,
8952           // C++ [namespace.memdef]p2). For example:
8953           //
8954           // class X {
8955           //   void f() const;
8956           // };
8957           //
8958           // void X::f() { } // ill-formed
8959           //
8960           // Complain about this problem, and attempt to suggest close
8961           // matches (e.g., those that differ only in cv-qualifiers and
8962           // whether the parameter types are references).
8963 
8964           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8965                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8966             AddToScope = ExtraArgs.AddToScope;
8967             return Result;
8968           }
8969         }
8970 
8971         // Unqualified local friend declarations are required to resolve
8972         // to something.
8973       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8974         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8975                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8976           AddToScope = ExtraArgs.AddToScope;
8977           return Result;
8978         }
8979       }
8980     } else if (!D.isFunctionDefinition() &&
8981                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8982                !isFriend && !isFunctionTemplateSpecialization &&
8983                !isMemberSpecialization) {
8984       // An out-of-line member function declaration must also be a
8985       // definition (C++ [class.mfct]p2).
8986       // Note that this is not the case for explicit specializations of
8987       // function templates or member functions of class templates, per
8988       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8989       // extension for compatibility with old SWIG code which likes to
8990       // generate them.
8991       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8992         << D.getCXXScopeSpec().getRange();
8993     }
8994   }
8995 
8996   ProcessPragmaWeak(S, NewFD);
8997   checkAttributesAfterMerging(*this, *NewFD);
8998 
8999   AddKnownFunctionAttributes(NewFD);
9000 
9001   if (NewFD->hasAttr<OverloadableAttr>() &&
9002       !NewFD->getType()->getAs<FunctionProtoType>()) {
9003     Diag(NewFD->getLocation(),
9004          diag::err_attribute_overloadable_no_prototype)
9005       << NewFD;
9006 
9007     // Turn this into a variadic function with no parameters.
9008     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9009     FunctionProtoType::ExtProtoInfo EPI(
9010         Context.getDefaultCallingConvention(true, false));
9011     EPI.Variadic = true;
9012     EPI.ExtInfo = FT->getExtInfo();
9013 
9014     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9015     NewFD->setType(R);
9016   }
9017 
9018   // If there's a #pragma GCC visibility in scope, and this isn't a class
9019   // member, set the visibility of this function.
9020   if (!DC->isRecord() && NewFD->isExternallyVisible())
9021     AddPushedVisibilityAttribute(NewFD);
9022 
9023   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9024   // marking the function.
9025   AddCFAuditedAttribute(NewFD);
9026 
9027   // If this is a function definition, check if we have to apply optnone due to
9028   // a pragma.
9029   if(D.isFunctionDefinition())
9030     AddRangeBasedOptnone(NewFD);
9031 
9032   // If this is the first declaration of an extern C variable, update
9033   // the map of such variables.
9034   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9035       isIncompleteDeclExternC(*this, NewFD))
9036     RegisterLocallyScopedExternCDecl(NewFD, S);
9037 
9038   // Set this FunctionDecl's range up to the right paren.
9039   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9040 
9041   if (D.isRedeclaration() && !Previous.empty()) {
9042     checkDLLAttributeRedeclaration(
9043         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
9044         isMemberSpecialization || isFunctionTemplateSpecialization,
9045         D.isFunctionDefinition());
9046   }
9047 
9048   if (getLangOpts().CUDA) {
9049     IdentifierInfo *II = NewFD->getIdentifier();
9050     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
9051         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9052       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9053         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
9054 
9055       Context.setcudaConfigureCallDecl(NewFD);
9056     }
9057 
9058     // Variadic functions, other than a *declaration* of printf, are not allowed
9059     // in device-side CUDA code, unless someone passed
9060     // -fcuda-allow-variadic-functions.
9061     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9062         (NewFD->hasAttr<CUDADeviceAttr>() ||
9063          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9064         !(II && II->isStr("printf") && NewFD->isExternC() &&
9065           !D.isFunctionDefinition())) {
9066       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9067     }
9068   }
9069 
9070   MarkUnusedFileScopedDecl(NewFD);
9071 
9072   if (getLangOpts().CPlusPlus) {
9073     if (FunctionTemplate) {
9074       if (NewFD->isInvalidDecl())
9075         FunctionTemplate->setInvalidDecl();
9076       return FunctionTemplate;
9077     }
9078 
9079     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9080       CompleteMemberSpecialization(NewFD, Previous);
9081   }
9082 
9083   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9084     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9085     if ((getLangOpts().OpenCLVersion >= 120)
9086         && (SC == SC_Static)) {
9087       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9088       D.setInvalidType();
9089     }
9090 
9091     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9092     if (!NewFD->getReturnType()->isVoidType()) {
9093       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9094       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9095           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9096                                 : FixItHint());
9097       D.setInvalidType();
9098     }
9099 
9100     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9101     for (auto Param : NewFD->parameters())
9102       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9103   }
9104   for (const ParmVarDecl *Param : NewFD->parameters()) {
9105     QualType PT = Param->getType();
9106 
9107     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9108     // types.
9109     if (getLangOpts().OpenCLVersion >= 200) {
9110       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9111         QualType ElemTy = PipeTy->getElementType();
9112           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9113             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9114             D.setInvalidType();
9115           }
9116       }
9117     }
9118   }
9119 
9120   // Here we have an function template explicit specialization at class scope.
9121   // The actually specialization will be postponed to template instatiation
9122   // time via the ClassScopeFunctionSpecializationDecl node.
9123   if (isDependentClassScopeExplicitSpecialization) {
9124     ClassScopeFunctionSpecializationDecl *NewSpec =
9125                          ClassScopeFunctionSpecializationDecl::Create(
9126                                 Context, CurContext, SourceLocation(),
9127                                 cast<CXXMethodDecl>(NewFD),
9128                                 HasExplicitTemplateArgs, TemplateArgs);
9129     CurContext->addDecl(NewSpec);
9130     AddToScope = false;
9131   }
9132 
9133   return NewFD;
9134 }
9135 
9136 /// \brief Checks if the new declaration declared in dependent context must be
9137 /// put in the same redeclaration chain as the specified declaration.
9138 ///
9139 /// \param D Declaration that is checked.
9140 /// \param PrevDecl Previous declaration found with proper lookup method for the
9141 ///                 same declaration name.
9142 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9143 ///          belongs to.
9144 ///
9145 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9146   // Any declarations should be put into redeclaration chains except for
9147   // friend declaration in a dependent context that names a function in
9148   // namespace scope.
9149   //
9150   // This allows to compile code like:
9151   //
9152   //       void func();
9153   //       template<typename T> class C1 { friend void func() { } };
9154   //       template<typename T> class C2 { friend void func() { } };
9155   //
9156   // This code snippet is a valid code unless both templates are instantiated.
9157   return !(D->getLexicalDeclContext()->isDependentContext() &&
9158            D->getDeclContext()->isFileContext() &&
9159            D->getFriendObjectKind() != Decl::FOK_None);
9160 }
9161 
9162 /// \brief Check the target attribute of the function for MultiVersion
9163 /// validity.
9164 ///
9165 /// Returns true if there was an error, false otherwise.
9166 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9167   const auto *TA = FD->getAttr<TargetAttr>();
9168   assert(TA && "MultiVersion Candidate requires a target attribute");
9169   TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9170   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9171   enum ErrType { Feature = 0, Architecture = 1 };
9172 
9173   if (!ParseInfo.Architecture.empty() &&
9174       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9175     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9176         << Architecture << ParseInfo.Architecture;
9177     return true;
9178   }
9179 
9180   for (const auto &Feat : ParseInfo.Features) {
9181     auto BareFeat = StringRef{Feat}.substr(1);
9182     if (Feat[0] == '-') {
9183       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9184           << Feature << ("no-" + BareFeat).str();
9185       return true;
9186     }
9187 
9188     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9189         !TargetInfo.isValidFeatureName(BareFeat)) {
9190       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9191           << Feature << BareFeat;
9192       return true;
9193     }
9194   }
9195   return false;
9196 }
9197 
9198 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9199                                              const FunctionDecl *NewFD,
9200                                              bool CausesMV) {
9201   enum DoesntSupport {
9202     FuncTemplates = 0,
9203     VirtFuncs = 1,
9204     DeducedReturn = 2,
9205     Constructors = 3,
9206     Destructors = 4,
9207     DeletedFuncs = 5,
9208     DefaultedFuncs = 6
9209   };
9210   enum Different {
9211     CallingConv = 0,
9212     ReturnType = 1,
9213     ConstexprSpec = 2,
9214     InlineSpec = 3,
9215     StorageClass = 4,
9216     Linkage = 5
9217   };
9218 
9219   // For now, disallow all other attributes.  These should be opt-in, but
9220   // an analysis of all of them is a future FIXME.
9221   if (CausesMV && OldFD &&
9222       std::distance(OldFD->attr_begin(), OldFD->attr_end()) != 1) {
9223     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs);
9224     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9225     return true;
9226   }
9227 
9228   if (std::distance(NewFD->attr_begin(), NewFD->attr_end()) != 1)
9229     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs);
9230 
9231   if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9232     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9233            << FuncTemplates;
9234 
9235   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9236     if (NewCXXFD->isVirtual())
9237       return S.Diag(NewCXXFD->getLocation(),
9238                     diag::err_multiversion_doesnt_support)
9239              << VirtFuncs;
9240 
9241     if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
9242       return S.Diag(NewCXXCtor->getLocation(),
9243                     diag::err_multiversion_doesnt_support)
9244              << Constructors;
9245 
9246     if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
9247       return S.Diag(NewCXXDtor->getLocation(),
9248                     diag::err_multiversion_doesnt_support)
9249              << Destructors;
9250   }
9251 
9252   if (NewFD->isDeleted())
9253     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9254            << DeletedFuncs;
9255 
9256   if (NewFD->isDefaulted())
9257     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9258            << DefaultedFuncs;
9259 
9260   QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
9261   const auto *NewType = cast<FunctionType>(NewQType);
9262   QualType NewReturnType = NewType->getReturnType();
9263 
9264   if (NewReturnType->isUndeducedType())
9265     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9266            << DeducedReturn;
9267 
9268   // Only allow transition to MultiVersion if it hasn't been used.
9269   if (OldFD && CausesMV && OldFD->isUsed(false))
9270     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9271 
9272   // Ensure the return type is identical.
9273   if (OldFD) {
9274     QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
9275     const auto *OldType = cast<FunctionType>(OldQType);
9276     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9277     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9278 
9279     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9280       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9281              << CallingConv;
9282 
9283     QualType OldReturnType = OldType->getReturnType();
9284 
9285     if (OldReturnType != NewReturnType)
9286       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9287              << ReturnType;
9288 
9289     if (OldFD->isConstexpr() != NewFD->isConstexpr())
9290       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9291              << ConstexprSpec;
9292 
9293     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9294       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9295              << InlineSpec;
9296 
9297     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9298       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9299              << StorageClass;
9300 
9301     if (OldFD->isExternC() != NewFD->isExternC())
9302       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9303              << Linkage;
9304 
9305     if (S.CheckEquivalentExceptionSpec(
9306             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9307             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9308       return true;
9309   }
9310   return false;
9311 }
9312 
9313 /// \brief Check the validity of a mulitversion function declaration.
9314 /// Also sets the multiversion'ness' of the function itself.
9315 ///
9316 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9317 ///
9318 /// Returns true if there was an error, false otherwise.
9319 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
9320                                       bool &Redeclaration, NamedDecl *&OldDecl,
9321                                       bool &MergeTypeWithPrevious,
9322                                       LookupResult &Previous) {
9323   const auto *NewTA = NewFD->getAttr<TargetAttr>();
9324   if (NewFD->isMain()) {
9325     if (NewTA && NewTA->isDefaultVersion()) {
9326       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
9327       NewFD->setInvalidDecl();
9328       return true;
9329     }
9330     return false;
9331   }
9332 
9333   // If there is no matching previous decl, only 'default' can
9334   // cause MultiVersioning.
9335   if (!OldDecl) {
9336     if (NewTA && NewTA->isDefaultVersion()) {
9337       if (!NewFD->getType()->getAs<FunctionProtoType>()) {
9338         S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
9339         NewFD->setInvalidDecl();
9340         return true;
9341       }
9342       if (CheckMultiVersionAdditionalRules(S, nullptr, NewFD, true)) {
9343         NewFD->setInvalidDecl();
9344         return true;
9345       }
9346       if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9347         S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9348         NewFD->setInvalidDecl();
9349         return true;
9350       }
9351 
9352       NewFD->setIsMultiVersion();
9353     }
9354     return false;
9355   }
9356 
9357   if (OldDecl->getDeclContext()->getRedeclContext() !=
9358       NewFD->getDeclContext()->getRedeclContext())
9359     return false;
9360 
9361   FunctionDecl *OldFD = OldDecl->getAsFunction();
9362   // Unresolved 'using' statements (the other way OldDecl can be not a function)
9363   // likely cannot cause a problem here.
9364   if (!OldFD)
9365     return false;
9366 
9367   if (!OldFD->isMultiVersion() && !NewTA)
9368     return false;
9369 
9370   if (OldFD->isMultiVersion() && !NewTA) {
9371     S.Diag(NewFD->getLocation(), diag::err_target_required_in_redecl);
9372     NewFD->setInvalidDecl();
9373     return true;
9374   }
9375 
9376   TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9377   // Sort order doesn't matter, it just needs to be consistent.
9378   std::sort(NewParsed.Features.begin(), NewParsed.Features.end());
9379 
9380   const auto *OldTA = OldFD->getAttr<TargetAttr>();
9381   if (!OldFD->isMultiVersion()) {
9382     // If the old decl is NOT MultiVersioned yet, and we don't cause that
9383     // to change, this is a simple redeclaration.
9384     if (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())
9385       return false;
9386 
9387     // Otherwise, this decl causes MultiVersioning.
9388     if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9389       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9390       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9391       NewFD->setInvalidDecl();
9392       return true;
9393     }
9394 
9395     if (!OldFD->getType()->getAs<FunctionProtoType>()) {
9396       S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
9397       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9398       NewFD->setInvalidDecl();
9399       return true;
9400     }
9401 
9402     if (CheckMultiVersionValue(S, NewFD)) {
9403       NewFD->setInvalidDecl();
9404       return true;
9405     }
9406 
9407     if (CheckMultiVersionValue(S, OldFD)) {
9408       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9409       NewFD->setInvalidDecl();
9410       return true;
9411     }
9412 
9413     TargetAttr::ParsedTargetAttr OldParsed =
9414         OldTA->parse(std::less<std::string>());
9415 
9416     if (OldParsed == NewParsed) {
9417       S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9418       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9419       NewFD->setInvalidDecl();
9420       return true;
9421     }
9422 
9423     for (const auto *FD : OldFD->redecls()) {
9424       const auto *CurTA = FD->getAttr<TargetAttr>();
9425       if (!CurTA || CurTA->isInherited()) {
9426         S.Diag(FD->getLocation(), diag::err_target_required_in_redecl);
9427         S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9428         NewFD->setInvalidDecl();
9429         return true;
9430       }
9431     }
9432 
9433     if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true)) {
9434       NewFD->setInvalidDecl();
9435       return true;
9436     }
9437 
9438     OldFD->setIsMultiVersion();
9439     NewFD->setIsMultiVersion();
9440     Redeclaration = false;
9441     MergeTypeWithPrevious = false;
9442     OldDecl = nullptr;
9443     Previous.clear();
9444     return false;
9445   }
9446 
9447   bool UseMemberUsingDeclRules =
9448       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
9449 
9450   // Next, check ALL non-overloads to see if this is a redeclaration of a
9451   // previous member of the MultiVersion set.
9452   for (NamedDecl *ND : Previous) {
9453     FunctionDecl *CurFD = ND->getAsFunction();
9454     if (!CurFD)
9455       continue;
9456     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
9457       continue;
9458 
9459     const auto *CurTA = CurFD->getAttr<TargetAttr>();
9460     if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
9461       NewFD->setIsMultiVersion();
9462       Redeclaration = true;
9463       OldDecl = ND;
9464       return false;
9465     }
9466 
9467     TargetAttr::ParsedTargetAttr CurParsed =
9468         CurTA->parse(std::less<std::string>());
9469 
9470     if (CurParsed == NewParsed) {
9471       S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9472       S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9473       NewFD->setInvalidDecl();
9474       return true;
9475     }
9476   }
9477 
9478   // Else, this is simply a non-redecl case.
9479   if (CheckMultiVersionValue(S, NewFD)) {
9480     NewFD->setInvalidDecl();
9481     return true;
9482   }
9483 
9484   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, false)) {
9485     NewFD->setInvalidDecl();
9486     return true;
9487   }
9488 
9489   NewFD->setIsMultiVersion();
9490   Redeclaration = false;
9491   MergeTypeWithPrevious = false;
9492   OldDecl = nullptr;
9493   Previous.clear();
9494   return false;
9495 }
9496 
9497 /// \brief Perform semantic checking of a new function declaration.
9498 ///
9499 /// Performs semantic analysis of the new function declaration
9500 /// NewFD. This routine performs all semantic checking that does not
9501 /// require the actual declarator involved in the declaration, and is
9502 /// used both for the declaration of functions as they are parsed
9503 /// (called via ActOnDeclarator) and for the declaration of functions
9504 /// that have been instantiated via C++ template instantiation (called
9505 /// via InstantiateDecl).
9506 ///
9507 /// \param IsMemberSpecialization whether this new function declaration is
9508 /// a member specialization (that replaces any definition provided by the
9509 /// previous declaration).
9510 ///
9511 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9512 ///
9513 /// \returns true if the function declaration is a redeclaration.
9514 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9515                                     LookupResult &Previous,
9516                                     bool IsMemberSpecialization) {
9517   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9518          "Variably modified return types are not handled here");
9519 
9520   // Determine whether the type of this function should be merged with
9521   // a previous visible declaration. This never happens for functions in C++,
9522   // and always happens in C if the previous declaration was visible.
9523   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9524                                !Previous.isShadowed();
9525 
9526   bool Redeclaration = false;
9527   NamedDecl *OldDecl = nullptr;
9528   bool MayNeedOverloadableChecks = false;
9529 
9530   // Merge or overload the declaration with an existing declaration of
9531   // the same name, if appropriate.
9532   if (!Previous.empty()) {
9533     // Determine whether NewFD is an overload of PrevDecl or
9534     // a declaration that requires merging. If it's an overload,
9535     // there's no more work to do here; we'll just add the new
9536     // function to the scope.
9537     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
9538       NamedDecl *Candidate = Previous.getRepresentativeDecl();
9539       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9540         Redeclaration = true;
9541         OldDecl = Candidate;
9542       }
9543     } else {
9544       MayNeedOverloadableChecks = true;
9545       switch (CheckOverload(S, NewFD, Previous, OldDecl,
9546                             /*NewIsUsingDecl*/ false)) {
9547       case Ovl_Match:
9548         Redeclaration = true;
9549         break;
9550 
9551       case Ovl_NonFunction:
9552         Redeclaration = true;
9553         break;
9554 
9555       case Ovl_Overload:
9556         Redeclaration = false;
9557         break;
9558       }
9559     }
9560   }
9561 
9562   // Check for a previous extern "C" declaration with this name.
9563   if (!Redeclaration &&
9564       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9565     if (!Previous.empty()) {
9566       // This is an extern "C" declaration with the same name as a previous
9567       // declaration, and thus redeclares that entity...
9568       Redeclaration = true;
9569       OldDecl = Previous.getFoundDecl();
9570       MergeTypeWithPrevious = false;
9571 
9572       // ... except in the presence of __attribute__((overloadable)).
9573       if (OldDecl->hasAttr<OverloadableAttr>() ||
9574           NewFD->hasAttr<OverloadableAttr>()) {
9575         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9576           MayNeedOverloadableChecks = true;
9577           Redeclaration = false;
9578           OldDecl = nullptr;
9579         }
9580       }
9581     }
9582   }
9583 
9584   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
9585                                 MergeTypeWithPrevious, Previous))
9586     return Redeclaration;
9587 
9588   // C++11 [dcl.constexpr]p8:
9589   //   A constexpr specifier for a non-static member function that is not
9590   //   a constructor declares that member function to be const.
9591   //
9592   // This needs to be delayed until we know whether this is an out-of-line
9593   // definition of a static member function.
9594   //
9595   // This rule is not present in C++1y, so we produce a backwards
9596   // compatibility warning whenever it happens in C++11.
9597   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9598   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9599       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9600       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9601     CXXMethodDecl *OldMD = nullptr;
9602     if (OldDecl)
9603       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9604     if (!OldMD || !OldMD->isStatic()) {
9605       const FunctionProtoType *FPT =
9606         MD->getType()->castAs<FunctionProtoType>();
9607       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9608       EPI.TypeQuals |= Qualifiers::Const;
9609       MD->setType(Context.getFunctionType(FPT->getReturnType(),
9610                                           FPT->getParamTypes(), EPI));
9611 
9612       // Warn that we did this, if we're not performing template instantiation.
9613       // In that case, we'll have warned already when the template was defined.
9614       if (!inTemplateInstantiation()) {
9615         SourceLocation AddConstLoc;
9616         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
9617                 .IgnoreParens().getAs<FunctionTypeLoc>())
9618           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
9619 
9620         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
9621           << FixItHint::CreateInsertion(AddConstLoc, " const");
9622       }
9623     }
9624   }
9625 
9626   if (Redeclaration) {
9627     // NewFD and OldDecl represent declarations that need to be
9628     // merged.
9629     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
9630       NewFD->setInvalidDecl();
9631       return Redeclaration;
9632     }
9633 
9634     Previous.clear();
9635     Previous.addDecl(OldDecl);
9636 
9637     if (FunctionTemplateDecl *OldTemplateDecl
9638                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
9639       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
9640       NewFD->setPreviousDeclaration(OldFD);
9641       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
9642       FunctionTemplateDecl *NewTemplateDecl
9643         = NewFD->getDescribedFunctionTemplate();
9644       assert(NewTemplateDecl && "Template/non-template mismatch");
9645       if (auto *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9646         Method->setAccess(OldTemplateDecl->getAccess());
9647         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
9648       }
9649 
9650       // If this is an explicit specialization of a member that is a function
9651       // template, mark it as a member specialization.
9652       if (IsMemberSpecialization &&
9653           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
9654         NewTemplateDecl->setMemberSpecialization();
9655         assert(OldTemplateDecl->isMemberSpecialization());
9656         // Explicit specializations of a member template do not inherit deleted
9657         // status from the parent member template that they are specializing.
9658         if (OldFD->isDeleted()) {
9659           // FIXME: This assert will not hold in the presence of modules.
9660           assert(OldFD->getCanonicalDecl() == OldFD);
9661           // FIXME: We need an update record for this AST mutation.
9662           OldFD->setDeletedAsWritten(false);
9663         }
9664       }
9665 
9666     } else {
9667       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9668         auto *OldFD = cast<FunctionDecl>(OldDecl);
9669         // This needs to happen first so that 'inline' propagates.
9670         NewFD->setPreviousDeclaration(OldFD);
9671         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
9672         if (isa<CXXMethodDecl>(NewFD))
9673           NewFD->setAccess(OldFD->getAccess());
9674       }
9675     }
9676   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
9677              !NewFD->getAttr<OverloadableAttr>()) {
9678     assert((Previous.empty() ||
9679             llvm::any_of(Previous,
9680                          [](const NamedDecl *ND) {
9681                            return ND->hasAttr<OverloadableAttr>();
9682                          })) &&
9683            "Non-redecls shouldn't happen without overloadable present");
9684 
9685     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
9686       const auto *FD = dyn_cast<FunctionDecl>(ND);
9687       return FD && !FD->hasAttr<OverloadableAttr>();
9688     });
9689 
9690     if (OtherUnmarkedIter != Previous.end()) {
9691       Diag(NewFD->getLocation(),
9692            diag::err_attribute_overloadable_multiple_unmarked_overloads);
9693       Diag((*OtherUnmarkedIter)->getLocation(),
9694            diag::note_attribute_overloadable_prev_overload)
9695           << false;
9696 
9697       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9698     }
9699   }
9700 
9701   // Semantic checking for this function declaration (in isolation).
9702 
9703   if (getLangOpts().CPlusPlus) {
9704     // C++-specific checks.
9705     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9706       CheckConstructor(Constructor);
9707     } else if (CXXDestructorDecl *Destructor =
9708                 dyn_cast<CXXDestructorDecl>(NewFD)) {
9709       CXXRecordDecl *Record = Destructor->getParent();
9710       QualType ClassType = Context.getTypeDeclType(Record);
9711 
9712       // FIXME: Shouldn't we be able to perform this check even when the class
9713       // type is dependent? Both gcc and edg can handle that.
9714       if (!ClassType->isDependentType()) {
9715         DeclarationName Name
9716           = Context.DeclarationNames.getCXXDestructorName(
9717                                         Context.getCanonicalType(ClassType));
9718         if (NewFD->getDeclName() != Name) {
9719           Diag(NewFD->getLocation(), diag::err_destructor_name);
9720           NewFD->setInvalidDecl();
9721           return Redeclaration;
9722         }
9723       }
9724     } else if (CXXConversionDecl *Conversion
9725                = dyn_cast<CXXConversionDecl>(NewFD)) {
9726       ActOnConversionDeclarator(Conversion);
9727     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
9728       if (auto *TD = Guide->getDescribedFunctionTemplate())
9729         CheckDeductionGuideTemplate(TD);
9730 
9731       // A deduction guide is not on the list of entities that can be
9732       // explicitly specialized.
9733       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
9734         Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
9735             << /*explicit specialization*/ 1;
9736     }
9737 
9738     // Find any virtual functions that this function overrides.
9739     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9740       if (!Method->isFunctionTemplateSpecialization() &&
9741           !Method->getDescribedFunctionTemplate() &&
9742           Method->isCanonicalDecl()) {
9743         if (AddOverriddenMethods(Method->getParent(), Method)) {
9744           // If the function was marked as "static", we have a problem.
9745           if (NewFD->getStorageClass() == SC_Static) {
9746             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
9747           }
9748         }
9749       }
9750 
9751       if (Method->isStatic())
9752         checkThisInStaticMemberFunctionType(Method);
9753     }
9754 
9755     // Extra checking for C++ overloaded operators (C++ [over.oper]).
9756     if (NewFD->isOverloadedOperator() &&
9757         CheckOverloadedOperatorDeclaration(NewFD)) {
9758       NewFD->setInvalidDecl();
9759       return Redeclaration;
9760     }
9761 
9762     // Extra checking for C++0x literal operators (C++0x [over.literal]).
9763     if (NewFD->getLiteralIdentifier() &&
9764         CheckLiteralOperatorDeclaration(NewFD)) {
9765       NewFD->setInvalidDecl();
9766       return Redeclaration;
9767     }
9768 
9769     // In C++, check default arguments now that we have merged decls. Unless
9770     // the lexical context is the class, because in this case this is done
9771     // during delayed parsing anyway.
9772     if (!CurContext->isRecord())
9773       CheckCXXDefaultArguments(NewFD);
9774 
9775     // If this function declares a builtin function, check the type of this
9776     // declaration against the expected type for the builtin.
9777     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9778       ASTContext::GetBuiltinTypeError Error;
9779       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9780       QualType T = Context.GetBuiltinType(BuiltinID, Error);
9781       // If the type of the builtin differs only in its exception
9782       // specification, that's OK.
9783       // FIXME: If the types do differ in this way, it would be better to
9784       // retain the 'noexcept' form of the type.
9785       if (!T.isNull() &&
9786           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
9787                                                             NewFD->getType()))
9788         // The type of this function differs from the type of the builtin,
9789         // so forget about the builtin entirely.
9790         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9791     }
9792 
9793     // If this function is declared as being extern "C", then check to see if
9794     // the function returns a UDT (class, struct, or union type) that is not C
9795     // compatible, and if it does, warn the user.
9796     // But, issue any diagnostic on the first declaration only.
9797     if (Previous.empty() && NewFD->isExternC()) {
9798       QualType R = NewFD->getReturnType();
9799       if (R->isIncompleteType() && !R->isVoidType())
9800         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9801             << NewFD << R;
9802       else if (!R.isPODType(Context) && !R->isVoidType() &&
9803                !R->isObjCObjectPointerType())
9804         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9805     }
9806 
9807     // C++1z [dcl.fct]p6:
9808     //   [...] whether the function has a non-throwing exception-specification
9809     //   [is] part of the function type
9810     //
9811     // This results in an ABI break between C++14 and C++17 for functions whose
9812     // declared type includes an exception-specification in a parameter or
9813     // return type. (Exception specifications on the function itself are OK in
9814     // most cases, and exception specifications are not permitted in most other
9815     // contexts where they could make it into a mangling.)
9816     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
9817       auto HasNoexcept = [&](QualType T) -> bool {
9818         // Strip off declarator chunks that could be between us and a function
9819         // type. We don't need to look far, exception specifications are very
9820         // restricted prior to C++17.
9821         if (auto *RT = T->getAs<ReferenceType>())
9822           T = RT->getPointeeType();
9823         else if (T->isAnyPointerType())
9824           T = T->getPointeeType();
9825         else if (auto *MPT = T->getAs<MemberPointerType>())
9826           T = MPT->getPointeeType();
9827         if (auto *FPT = T->getAs<FunctionProtoType>())
9828           if (FPT->isNothrow(Context))
9829             return true;
9830         return false;
9831       };
9832 
9833       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9834       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9835       for (QualType T : FPT->param_types())
9836         AnyNoexcept |= HasNoexcept(T);
9837       if (AnyNoexcept)
9838         Diag(NewFD->getLocation(),
9839              diag::warn_cxx17_compat_exception_spec_in_signature)
9840             << NewFD;
9841     }
9842 
9843     if (!Redeclaration && LangOpts.CUDA)
9844       checkCUDATargetOverload(NewFD, Previous);
9845   }
9846   return Redeclaration;
9847 }
9848 
9849 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9850   // C++11 [basic.start.main]p3:
9851   //   A program that [...] declares main to be inline, static or
9852   //   constexpr is ill-formed.
9853   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
9854   //   appear in a declaration of main.
9855   // static main is not an error under C99, but we should warn about it.
9856   // We accept _Noreturn main as an extension.
9857   if (FD->getStorageClass() == SC_Static)
9858     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9859          ? diag::err_static_main : diag::warn_static_main)
9860       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9861   if (FD->isInlineSpecified())
9862     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9863       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9864   if (DS.isNoreturnSpecified()) {
9865     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9866     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9867     Diag(NoreturnLoc, diag::ext_noreturn_main);
9868     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9869       << FixItHint::CreateRemoval(NoreturnRange);
9870   }
9871   if (FD->isConstexpr()) {
9872     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9873       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9874     FD->setConstexpr(false);
9875   }
9876 
9877   if (getLangOpts().OpenCL) {
9878     Diag(FD->getLocation(), diag::err_opencl_no_main)
9879         << FD->hasAttr<OpenCLKernelAttr>();
9880     FD->setInvalidDecl();
9881     return;
9882   }
9883 
9884   QualType T = FD->getType();
9885   assert(T->isFunctionType() && "function decl is not of function type");
9886   const FunctionType* FT = T->castAs<FunctionType>();
9887 
9888   // Set default calling convention for main()
9889   if (FT->getCallConv() != CC_C) {
9890     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
9891     FD->setType(QualType(FT, 0));
9892     T = Context.getCanonicalType(FD->getType());
9893   }
9894 
9895   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9896     // In C with GNU extensions we allow main() to have non-integer return
9897     // type, but we should warn about the extension, and we disable the
9898     // implicit-return-zero rule.
9899 
9900     // GCC in C mode accepts qualified 'int'.
9901     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9902       FD->setHasImplicitReturnZero(true);
9903     else {
9904       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9905       SourceRange RTRange = FD->getReturnTypeSourceRange();
9906       if (RTRange.isValid())
9907         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9908             << FixItHint::CreateReplacement(RTRange, "int");
9909     }
9910   } else {
9911     // In C and C++, main magically returns 0 if you fall off the end;
9912     // set the flag which tells us that.
9913     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9914 
9915     // All the standards say that main() should return 'int'.
9916     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9917       FD->setHasImplicitReturnZero(true);
9918     else {
9919       // Otherwise, this is just a flat-out error.
9920       SourceRange RTRange = FD->getReturnTypeSourceRange();
9921       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9922           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9923                                 : FixItHint());
9924       FD->setInvalidDecl(true);
9925     }
9926   }
9927 
9928   // Treat protoless main() as nullary.
9929   if (isa<FunctionNoProtoType>(FT)) return;
9930 
9931   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9932   unsigned nparams = FTP->getNumParams();
9933   assert(FD->getNumParams() == nparams);
9934 
9935   bool HasExtraParameters = (nparams > 3);
9936 
9937   if (FTP->isVariadic()) {
9938     Diag(FD->getLocation(), diag::ext_variadic_main);
9939     // FIXME: if we had information about the location of the ellipsis, we
9940     // could add a FixIt hint to remove it as a parameter.
9941   }
9942 
9943   // Darwin passes an undocumented fourth argument of type char**.  If
9944   // other platforms start sprouting these, the logic below will start
9945   // getting shifty.
9946   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9947     HasExtraParameters = false;
9948 
9949   if (HasExtraParameters) {
9950     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9951     FD->setInvalidDecl(true);
9952     nparams = 3;
9953   }
9954 
9955   // FIXME: a lot of the following diagnostics would be improved
9956   // if we had some location information about types.
9957 
9958   QualType CharPP =
9959     Context.getPointerType(Context.getPointerType(Context.CharTy));
9960   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9961 
9962   for (unsigned i = 0; i < nparams; ++i) {
9963     QualType AT = FTP->getParamType(i);
9964 
9965     bool mismatch = true;
9966 
9967     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9968       mismatch = false;
9969     else if (Expected[i] == CharPP) {
9970       // As an extension, the following forms are okay:
9971       //   char const **
9972       //   char const * const *
9973       //   char * const *
9974 
9975       QualifierCollector qs;
9976       const PointerType* PT;
9977       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9978           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9979           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9980                               Context.CharTy)) {
9981         qs.removeConst();
9982         mismatch = !qs.empty();
9983       }
9984     }
9985 
9986     if (mismatch) {
9987       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9988       // TODO: suggest replacing given type with expected type
9989       FD->setInvalidDecl(true);
9990     }
9991   }
9992 
9993   if (nparams == 1 && !FD->isInvalidDecl()) {
9994     Diag(FD->getLocation(), diag::warn_main_one_arg);
9995   }
9996 
9997   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9998     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9999     FD->setInvalidDecl();
10000   }
10001 }
10002 
10003 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10004   QualType T = FD->getType();
10005   assert(T->isFunctionType() && "function decl is not of function type");
10006   const FunctionType *FT = T->castAs<FunctionType>();
10007 
10008   // Set an implicit return of 'zero' if the function can return some integral,
10009   // enumeration, pointer or nullptr type.
10010   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10011       FT->getReturnType()->isAnyPointerType() ||
10012       FT->getReturnType()->isNullPtrType())
10013     // DllMain is exempt because a return value of zero means it failed.
10014     if (FD->getName() != "DllMain")
10015       FD->setHasImplicitReturnZero(true);
10016 
10017   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10018     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10019     FD->setInvalidDecl();
10020   }
10021 }
10022 
10023 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10024   // FIXME: Need strict checking.  In C89, we need to check for
10025   // any assignment, increment, decrement, function-calls, or
10026   // commas outside of a sizeof.  In C99, it's the same list,
10027   // except that the aforementioned are allowed in unevaluated
10028   // expressions.  Everything else falls under the
10029   // "may accept other forms of constant expressions" exception.
10030   // (We never end up here for C++, so the constant expression
10031   // rules there don't matter.)
10032   const Expr *Culprit;
10033   if (Init->isConstantInitializer(Context, false, &Culprit))
10034     return false;
10035   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10036     << Culprit->getSourceRange();
10037   return true;
10038 }
10039 
10040 namespace {
10041   // Visits an initialization expression to see if OrigDecl is evaluated in
10042   // its own initialization and throws a warning if it does.
10043   class SelfReferenceChecker
10044       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10045     Sema &S;
10046     Decl *OrigDecl;
10047     bool isRecordType;
10048     bool isPODType;
10049     bool isReferenceType;
10050 
10051     bool isInitList;
10052     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10053 
10054   public:
10055     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10056 
10057     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10058                                                     S(S), OrigDecl(OrigDecl) {
10059       isPODType = false;
10060       isRecordType = false;
10061       isReferenceType = false;
10062       isInitList = false;
10063       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10064         isPODType = VD->getType().isPODType(S.Context);
10065         isRecordType = VD->getType()->isRecordType();
10066         isReferenceType = VD->getType()->isReferenceType();
10067       }
10068     }
10069 
10070     // For most expressions, just call the visitor.  For initializer lists,
10071     // track the index of the field being initialized since fields are
10072     // initialized in order allowing use of previously initialized fields.
10073     void CheckExpr(Expr *E) {
10074       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10075       if (!InitList) {
10076         Visit(E);
10077         return;
10078       }
10079 
10080       // Track and increment the index here.
10081       isInitList = true;
10082       InitFieldIndex.push_back(0);
10083       for (auto Child : InitList->children()) {
10084         CheckExpr(cast<Expr>(Child));
10085         ++InitFieldIndex.back();
10086       }
10087       InitFieldIndex.pop_back();
10088     }
10089 
10090     // Returns true if MemberExpr is checked and no further checking is needed.
10091     // Returns false if additional checking is required.
10092     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10093       llvm::SmallVector<FieldDecl*, 4> Fields;
10094       Expr *Base = E;
10095       bool ReferenceField = false;
10096 
10097       // Get the field memebers used.
10098       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10099         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10100         if (!FD)
10101           return false;
10102         Fields.push_back(FD);
10103         if (FD->getType()->isReferenceType())
10104           ReferenceField = true;
10105         Base = ME->getBase()->IgnoreParenImpCasts();
10106       }
10107 
10108       // Keep checking only if the base Decl is the same.
10109       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10110       if (!DRE || DRE->getDecl() != OrigDecl)
10111         return false;
10112 
10113       // A reference field can be bound to an unininitialized field.
10114       if (CheckReference && !ReferenceField)
10115         return true;
10116 
10117       // Convert FieldDecls to their index number.
10118       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10119       for (const FieldDecl *I : llvm::reverse(Fields))
10120         UsedFieldIndex.push_back(I->getFieldIndex());
10121 
10122       // See if a warning is needed by checking the first difference in index
10123       // numbers.  If field being used has index less than the field being
10124       // initialized, then the use is safe.
10125       for (auto UsedIter = UsedFieldIndex.begin(),
10126                 UsedEnd = UsedFieldIndex.end(),
10127                 OrigIter = InitFieldIndex.begin(),
10128                 OrigEnd = InitFieldIndex.end();
10129            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10130         if (*UsedIter < *OrigIter)
10131           return true;
10132         if (*UsedIter > *OrigIter)
10133           break;
10134       }
10135 
10136       // TODO: Add a different warning which will print the field names.
10137       HandleDeclRefExpr(DRE);
10138       return true;
10139     }
10140 
10141     // For most expressions, the cast is directly above the DeclRefExpr.
10142     // For conditional operators, the cast can be outside the conditional
10143     // operator if both expressions are DeclRefExpr's.
10144     void HandleValue(Expr *E) {
10145       E = E->IgnoreParens();
10146       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10147         HandleDeclRefExpr(DRE);
10148         return;
10149       }
10150 
10151       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10152         Visit(CO->getCond());
10153         HandleValue(CO->getTrueExpr());
10154         HandleValue(CO->getFalseExpr());
10155         return;
10156       }
10157 
10158       if (BinaryConditionalOperator *BCO =
10159               dyn_cast<BinaryConditionalOperator>(E)) {
10160         Visit(BCO->getCond());
10161         HandleValue(BCO->getFalseExpr());
10162         return;
10163       }
10164 
10165       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10166         HandleValue(OVE->getSourceExpr());
10167         return;
10168       }
10169 
10170       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10171         if (BO->getOpcode() == BO_Comma) {
10172           Visit(BO->getLHS());
10173           HandleValue(BO->getRHS());
10174           return;
10175         }
10176       }
10177 
10178       if (isa<MemberExpr>(E)) {
10179         if (isInitList) {
10180           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10181                                       false /*CheckReference*/))
10182             return;
10183         }
10184 
10185         Expr *Base = E->IgnoreParenImpCasts();
10186         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10187           // Check for static member variables and don't warn on them.
10188           if (!isa<FieldDecl>(ME->getMemberDecl()))
10189             return;
10190           Base = ME->getBase()->IgnoreParenImpCasts();
10191         }
10192         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10193           HandleDeclRefExpr(DRE);
10194         return;
10195       }
10196 
10197       Visit(E);
10198     }
10199 
10200     // Reference types not handled in HandleValue are handled here since all
10201     // uses of references are bad, not just r-value uses.
10202     void VisitDeclRefExpr(DeclRefExpr *E) {
10203       if (isReferenceType)
10204         HandleDeclRefExpr(E);
10205     }
10206 
10207     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10208       if (E->getCastKind() == CK_LValueToRValue) {
10209         HandleValue(E->getSubExpr());
10210         return;
10211       }
10212 
10213       Inherited::VisitImplicitCastExpr(E);
10214     }
10215 
10216     void VisitMemberExpr(MemberExpr *E) {
10217       if (isInitList) {
10218         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
10219           return;
10220       }
10221 
10222       // Don't warn on arrays since they can be treated as pointers.
10223       if (E->getType()->canDecayToPointerType()) return;
10224 
10225       // Warn when a non-static method call is followed by non-static member
10226       // field accesses, which is followed by a DeclRefExpr.
10227       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10228       bool Warn = (MD && !MD->isStatic());
10229       Expr *Base = E->getBase()->IgnoreParenImpCasts();
10230       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10231         if (!isa<FieldDecl>(ME->getMemberDecl()))
10232           Warn = false;
10233         Base = ME->getBase()->IgnoreParenImpCasts();
10234       }
10235 
10236       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10237         if (Warn)
10238           HandleDeclRefExpr(DRE);
10239         return;
10240       }
10241 
10242       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10243       // Visit that expression.
10244       Visit(Base);
10245     }
10246 
10247     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10248       Expr *Callee = E->getCallee();
10249 
10250       if (isa<UnresolvedLookupExpr>(Callee))
10251         return Inherited::VisitCXXOperatorCallExpr(E);
10252 
10253       Visit(Callee);
10254       for (auto Arg: E->arguments())
10255         HandleValue(Arg->IgnoreParenImpCasts());
10256     }
10257 
10258     void VisitUnaryOperator(UnaryOperator *E) {
10259       // For POD record types, addresses of its own members are well-defined.
10260       if (E->getOpcode() == UO_AddrOf && isRecordType &&
10261           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
10262         if (!isPODType)
10263           HandleValue(E->getSubExpr());
10264         return;
10265       }
10266 
10267       if (E->isIncrementDecrementOp()) {
10268         HandleValue(E->getSubExpr());
10269         return;
10270       }
10271 
10272       Inherited::VisitUnaryOperator(E);
10273     }
10274 
10275     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
10276 
10277     void VisitCXXConstructExpr(CXXConstructExpr *E) {
10278       if (E->getConstructor()->isCopyConstructor()) {
10279         Expr *ArgExpr = E->getArg(0);
10280         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
10281           if (ILE->getNumInits() == 1)
10282             ArgExpr = ILE->getInit(0);
10283         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
10284           if (ICE->getCastKind() == CK_NoOp)
10285             ArgExpr = ICE->getSubExpr();
10286         HandleValue(ArgExpr);
10287         return;
10288       }
10289       Inherited::VisitCXXConstructExpr(E);
10290     }
10291 
10292     void VisitCallExpr(CallExpr *E) {
10293       // Treat std::move as a use.
10294       if (E->isCallToStdMove()) {
10295         HandleValue(E->getArg(0));
10296         return;
10297       }
10298 
10299       Inherited::VisitCallExpr(E);
10300     }
10301 
10302     void VisitBinaryOperator(BinaryOperator *E) {
10303       if (E->isCompoundAssignmentOp()) {
10304         HandleValue(E->getLHS());
10305         Visit(E->getRHS());
10306         return;
10307       }
10308 
10309       Inherited::VisitBinaryOperator(E);
10310     }
10311 
10312     // A custom visitor for BinaryConditionalOperator is needed because the
10313     // regular visitor would check the condition and true expression separately
10314     // but both point to the same place giving duplicate diagnostics.
10315     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10316       Visit(E->getCond());
10317       Visit(E->getFalseExpr());
10318     }
10319 
10320     void HandleDeclRefExpr(DeclRefExpr *DRE) {
10321       Decl* ReferenceDecl = DRE->getDecl();
10322       if (OrigDecl != ReferenceDecl) return;
10323       unsigned diag;
10324       if (isReferenceType) {
10325         diag = diag::warn_uninit_self_reference_in_reference_init;
10326       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10327         diag = diag::warn_static_self_reference_in_init;
10328       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10329                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10330                  DRE->getDecl()->getType()->isRecordType()) {
10331         diag = diag::warn_uninit_self_reference_in_init;
10332       } else {
10333         // Local variables will be handled by the CFG analysis.
10334         return;
10335       }
10336 
10337       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
10338                             S.PDiag(diag)
10339                               << DRE->getNameInfo().getName()
10340                               << OrigDecl->getLocation()
10341                               << DRE->getSourceRange());
10342     }
10343   };
10344 
10345   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10346   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10347                                  bool DirectInit) {
10348     // Parameters arguments are occassionially constructed with itself,
10349     // for instance, in recursive functions.  Skip them.
10350     if (isa<ParmVarDecl>(OrigDecl))
10351       return;
10352 
10353     E = E->IgnoreParens();
10354 
10355     // Skip checking T a = a where T is not a record or reference type.
10356     // Doing so is a way to silence uninitialized warnings.
10357     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10358       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10359         if (ICE->getCastKind() == CK_LValueToRValue)
10360           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10361             if (DRE->getDecl() == OrigDecl)
10362               return;
10363 
10364     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10365   }
10366 } // end anonymous namespace
10367 
10368 namespace {
10369   // Simple wrapper to add the name of a variable or (if no variable is
10370   // available) a DeclarationName into a diagnostic.
10371   struct VarDeclOrName {
10372     VarDecl *VDecl;
10373     DeclarationName Name;
10374 
10375     friend const Sema::SemaDiagnosticBuilder &
10376     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10377       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10378     }
10379   };
10380 } // end anonymous namespace
10381 
10382 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10383                                             DeclarationName Name, QualType Type,
10384                                             TypeSourceInfo *TSI,
10385                                             SourceRange Range, bool DirectInit,
10386                                             Expr *Init) {
10387   bool IsInitCapture = !VDecl;
10388   assert((!VDecl || !VDecl->isInitCapture()) &&
10389          "init captures are expected to be deduced prior to initialization");
10390 
10391   VarDeclOrName VN{VDecl, Name};
10392 
10393   DeducedType *Deduced = Type->getContainedDeducedType();
10394   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10395 
10396   // C++11 [dcl.spec.auto]p3
10397   if (!Init) {
10398     assert(VDecl && "no init for init capture deduction?");
10399     Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10400       << VDecl->getDeclName() << Type;
10401     return QualType();
10402   }
10403 
10404   ArrayRef<Expr*> DeduceInits = Init;
10405   if (DirectInit) {
10406     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10407       DeduceInits = PL->exprs();
10408   }
10409 
10410   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10411     assert(VDecl && "non-auto type for init capture deduction?");
10412     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10413     InitializationKind Kind = InitializationKind::CreateForInit(
10414         VDecl->getLocation(), DirectInit, Init);
10415     // FIXME: Initialization should not be taking a mutable list of inits.
10416     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10417     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10418                                                        InitsCopy);
10419   }
10420 
10421   if (DirectInit) {
10422     if (auto *IL = dyn_cast<InitListExpr>(Init))
10423       DeduceInits = IL->inits();
10424   }
10425 
10426   // Deduction only works if we have exactly one source expression.
10427   if (DeduceInits.empty()) {
10428     // It isn't possible to write this directly, but it is possible to
10429     // end up in this situation with "auto x(some_pack...);"
10430     Diag(Init->getLocStart(), IsInitCapture
10431                                   ? diag::err_init_capture_no_expression
10432                                   : diag::err_auto_var_init_no_expression)
10433         << VN << Type << Range;
10434     return QualType();
10435   }
10436 
10437   if (DeduceInits.size() > 1) {
10438     Diag(DeduceInits[1]->getLocStart(),
10439          IsInitCapture ? diag::err_init_capture_multiple_expressions
10440                        : diag::err_auto_var_init_multiple_expressions)
10441         << VN << Type << Range;
10442     return QualType();
10443   }
10444 
10445   Expr *DeduceInit = DeduceInits[0];
10446   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10447     Diag(Init->getLocStart(), IsInitCapture
10448                                   ? diag::err_init_capture_paren_braces
10449                                   : diag::err_auto_var_init_paren_braces)
10450         << isa<InitListExpr>(Init) << VN << Type << Range;
10451     return QualType();
10452   }
10453 
10454   // Expressions default to 'id' when we're in a debugger.
10455   bool DefaultedAnyToId = false;
10456   if (getLangOpts().DebuggerCastResultToId &&
10457       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10458     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10459     if (Result.isInvalid()) {
10460       return QualType();
10461     }
10462     Init = Result.get();
10463     DefaultedAnyToId = true;
10464   }
10465 
10466   // C++ [dcl.decomp]p1:
10467   //   If the assignment-expression [...] has array type A and no ref-qualifier
10468   //   is present, e has type cv A
10469   if (VDecl && isa<DecompositionDecl>(VDecl) &&
10470       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10471       DeduceInit->getType()->isConstantArrayType())
10472     return Context.getQualifiedType(DeduceInit->getType(),
10473                                     Type.getQualifiers());
10474 
10475   QualType DeducedType;
10476   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
10477     if (!IsInitCapture)
10478       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
10479     else if (isa<InitListExpr>(Init))
10480       Diag(Range.getBegin(),
10481            diag::err_init_capture_deduction_failure_from_init_list)
10482           << VN
10483           << (DeduceInit->getType().isNull() ? TSI->getType()
10484                                              : DeduceInit->getType())
10485           << DeduceInit->getSourceRange();
10486     else
10487       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10488           << VN << TSI->getType()
10489           << (DeduceInit->getType().isNull() ? TSI->getType()
10490                                              : DeduceInit->getType())
10491           << DeduceInit->getSourceRange();
10492   }
10493 
10494   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10495   // 'id' instead of a specific object type prevents most of our usual
10496   // checks.
10497   // We only want to warn outside of template instantiations, though:
10498   // inside a template, the 'id' could have come from a parameter.
10499   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10500       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10501     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10502     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10503   }
10504 
10505   return DeducedType;
10506 }
10507 
10508 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
10509                                          Expr *Init) {
10510   QualType DeducedType = deduceVarTypeFromInitializer(
10511       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10512       VDecl->getSourceRange(), DirectInit, Init);
10513   if (DeducedType.isNull()) {
10514     VDecl->setInvalidDecl();
10515     return true;
10516   }
10517 
10518   VDecl->setType(DeducedType);
10519   assert(VDecl->isLinkageValid());
10520 
10521   // In ARC, infer lifetime.
10522   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10523     VDecl->setInvalidDecl();
10524 
10525   // If this is a redeclaration, check that the type we just deduced matches
10526   // the previously declared type.
10527   if (VarDecl *Old = VDecl->getPreviousDecl()) {
10528     // We never need to merge the type, because we cannot form an incomplete
10529     // array of auto, nor deduce such a type.
10530     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
10531   }
10532 
10533   // Check the deduced type is valid for a variable declaration.
10534   CheckVariableDeclarationType(VDecl);
10535   return VDecl->isInvalidDecl();
10536 }
10537 
10538 /// AddInitializerToDecl - Adds the initializer Init to the
10539 /// declaration dcl. If DirectInit is true, this is C++ direct
10540 /// initialization rather than copy initialization.
10541 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10542   // If there is no declaration, there was an error parsing it.  Just ignore
10543   // the initializer.
10544   if (!RealDecl || RealDecl->isInvalidDecl()) {
10545     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10546     return;
10547   }
10548 
10549   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10550     // Pure-specifiers are handled in ActOnPureSpecifier.
10551     Diag(Method->getLocation(), diag::err_member_function_initialization)
10552       << Method->getDeclName() << Init->getSourceRange();
10553     Method->setInvalidDecl();
10554     return;
10555   }
10556 
10557   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
10558   if (!VDecl) {
10559     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
10560     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
10561     RealDecl->setInvalidDecl();
10562     return;
10563   }
10564 
10565   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
10566   if (VDecl->getType()->isUndeducedType()) {
10567     // Attempt typo correction early so that the type of the init expression can
10568     // be deduced based on the chosen correction if the original init contains a
10569     // TypoExpr.
10570     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
10571     if (!Res.isUsable()) {
10572       RealDecl->setInvalidDecl();
10573       return;
10574     }
10575     Init = Res.get();
10576 
10577     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
10578       return;
10579   }
10580 
10581   // dllimport cannot be used on variable definitions.
10582   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
10583     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
10584     VDecl->setInvalidDecl();
10585     return;
10586   }
10587 
10588   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
10589     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
10590     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
10591     VDecl->setInvalidDecl();
10592     return;
10593   }
10594 
10595   if (!VDecl->getType()->isDependentType()) {
10596     // A definition must end up with a complete type, which means it must be
10597     // complete with the restriction that an array type might be completed by
10598     // the initializer; note that later code assumes this restriction.
10599     QualType BaseDeclType = VDecl->getType();
10600     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
10601       BaseDeclType = Array->getElementType();
10602     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
10603                             diag::err_typecheck_decl_incomplete_type)) {
10604       RealDecl->setInvalidDecl();
10605       return;
10606     }
10607 
10608     // The variable can not have an abstract class type.
10609     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
10610                                diag::err_abstract_type_in_decl,
10611                                AbstractVariableType))
10612       VDecl->setInvalidDecl();
10613   }
10614 
10615   // If adding the initializer will turn this declaration into a definition,
10616   // and we already have a definition for this variable, diagnose or otherwise
10617   // handle the situation.
10618   VarDecl *Def;
10619   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
10620       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
10621       !VDecl->isThisDeclarationADemotedDefinition() &&
10622       checkVarDeclRedefinition(Def, VDecl))
10623     return;
10624 
10625   if (getLangOpts().CPlusPlus) {
10626     // C++ [class.static.data]p4
10627     //   If a static data member is of const integral or const
10628     //   enumeration type, its declaration in the class definition can
10629     //   specify a constant-initializer which shall be an integral
10630     //   constant expression (5.19). In that case, the member can appear
10631     //   in integral constant expressions. The member shall still be
10632     //   defined in a namespace scope if it is used in the program and the
10633     //   namespace scope definition shall not contain an initializer.
10634     //
10635     // We already performed a redefinition check above, but for static
10636     // data members we also need to check whether there was an in-class
10637     // declaration with an initializer.
10638     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
10639       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
10640           << VDecl->getDeclName();
10641       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
10642            diag::note_previous_initializer)
10643           << 0;
10644       return;
10645     }
10646 
10647     if (VDecl->hasLocalStorage())
10648       getCurFunction()->setHasBranchProtectedScope();
10649 
10650     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
10651       VDecl->setInvalidDecl();
10652       return;
10653     }
10654   }
10655 
10656   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
10657   // a kernel function cannot be initialized."
10658   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
10659     Diag(VDecl->getLocation(), diag::err_local_cant_init);
10660     VDecl->setInvalidDecl();
10661     return;
10662   }
10663 
10664   // Get the decls type and save a reference for later, since
10665   // CheckInitializerTypes may change it.
10666   QualType DclT = VDecl->getType(), SavT = DclT;
10667 
10668   // Expressions default to 'id' when we're in a debugger
10669   // and we are assigning it to a variable of Objective-C pointer type.
10670   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
10671       Init->getType() == Context.UnknownAnyTy) {
10672     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10673     if (Result.isInvalid()) {
10674       VDecl->setInvalidDecl();
10675       return;
10676     }
10677     Init = Result.get();
10678   }
10679 
10680   // Perform the initialization.
10681   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
10682   if (!VDecl->isInvalidDecl()) {
10683     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10684     InitializationKind Kind = InitializationKind::CreateForInit(
10685         VDecl->getLocation(), DirectInit, Init);
10686 
10687     MultiExprArg Args = Init;
10688     if (CXXDirectInit)
10689       Args = MultiExprArg(CXXDirectInit->getExprs(),
10690                           CXXDirectInit->getNumExprs());
10691 
10692     // Try to correct any TypoExprs in the initialization arguments.
10693     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
10694       ExprResult Res = CorrectDelayedTyposInExpr(
10695           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
10696             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
10697             return Init.Failed() ? ExprError() : E;
10698           });
10699       if (Res.isInvalid()) {
10700         VDecl->setInvalidDecl();
10701       } else if (Res.get() != Args[Idx]) {
10702         Args[Idx] = Res.get();
10703       }
10704     }
10705     if (VDecl->isInvalidDecl())
10706       return;
10707 
10708     InitializationSequence InitSeq(*this, Entity, Kind, Args,
10709                                    /*TopLevelOfInitList=*/false,
10710                                    /*TreatUnavailableAsInvalid=*/false);
10711     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
10712     if (Result.isInvalid()) {
10713       VDecl->setInvalidDecl();
10714       return;
10715     }
10716 
10717     Init = Result.getAs<Expr>();
10718   }
10719 
10720   // Check for self-references within variable initializers.
10721   // Variables declared within a function/method body (except for references)
10722   // are handled by a dataflow analysis.
10723   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
10724       VDecl->getType()->isReferenceType()) {
10725     CheckSelfReference(*this, RealDecl, Init, DirectInit);
10726   }
10727 
10728   // If the type changed, it means we had an incomplete type that was
10729   // completed by the initializer. For example:
10730   //   int ary[] = { 1, 3, 5 };
10731   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
10732   if (!VDecl->isInvalidDecl() && (DclT != SavT))
10733     VDecl->setType(DclT);
10734 
10735   if (!VDecl->isInvalidDecl()) {
10736     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
10737 
10738     if (VDecl->hasAttr<BlocksAttr>())
10739       checkRetainCycles(VDecl, Init);
10740 
10741     // It is safe to assign a weak reference into a strong variable.
10742     // Although this code can still have problems:
10743     //   id x = self.weakProp;
10744     //   id y = self.weakProp;
10745     // we do not warn to warn spuriously when 'x' and 'y' are on separate
10746     // paths through the function. This should be revisited if
10747     // -Wrepeated-use-of-weak is made flow-sensitive.
10748     if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
10749          VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
10750         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10751                          Init->getLocStart()))
10752       getCurFunction()->markSafeWeakUse(Init);
10753   }
10754 
10755   // The initialization is usually a full-expression.
10756   //
10757   // FIXME: If this is a braced initialization of an aggregate, it is not
10758   // an expression, and each individual field initializer is a separate
10759   // full-expression. For instance, in:
10760   //
10761   //   struct Temp { ~Temp(); };
10762   //   struct S { S(Temp); };
10763   //   struct T { S a, b; } t = { Temp(), Temp() }
10764   //
10765   // we should destroy the first Temp before constructing the second.
10766   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10767                                           false,
10768                                           VDecl->isConstexpr());
10769   if (Result.isInvalid()) {
10770     VDecl->setInvalidDecl();
10771     return;
10772   }
10773   Init = Result.get();
10774 
10775   // Attach the initializer to the decl.
10776   VDecl->setInit(Init);
10777 
10778   if (VDecl->isLocalVarDecl()) {
10779     // Don't check the initializer if the declaration is malformed.
10780     if (VDecl->isInvalidDecl()) {
10781       // do nothing
10782 
10783     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
10784     // This is true even in OpenCL C++.
10785     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
10786       CheckForConstantInitializer(Init, DclT);
10787 
10788     // Otherwise, C++ does not restrict the initializer.
10789     } else if (getLangOpts().CPlusPlus) {
10790       // do nothing
10791 
10792     // C99 6.7.8p4: All the expressions in an initializer for an object that has
10793     // static storage duration shall be constant expressions or string literals.
10794     } else if (VDecl->getStorageClass() == SC_Static) {
10795       CheckForConstantInitializer(Init, DclT);
10796 
10797     // C89 is stricter than C99 for aggregate initializers.
10798     // C89 6.5.7p3: All the expressions [...] in an initializer list
10799     // for an object that has aggregate or union type shall be
10800     // constant expressions.
10801     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10802                isa<InitListExpr>(Init)) {
10803       const Expr *Culprit;
10804       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
10805         Diag(Culprit->getExprLoc(),
10806              diag::ext_aggregate_init_not_constant)
10807           << Culprit->getSourceRange();
10808       }
10809     }
10810   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10811              VDecl->getLexicalDeclContext()->isRecord()) {
10812     // This is an in-class initialization for a static data member, e.g.,
10813     //
10814     // struct S {
10815     //   static const int value = 17;
10816     // };
10817 
10818     // C++ [class.mem]p4:
10819     //   A member-declarator can contain a constant-initializer only
10820     //   if it declares a static member (9.4) of const integral or
10821     //   const enumeration type, see 9.4.2.
10822     //
10823     // C++11 [class.static.data]p3:
10824     //   If a non-volatile non-inline const static data member is of integral
10825     //   or enumeration type, its declaration in the class definition can
10826     //   specify a brace-or-equal-initializer in which every initializer-clause
10827     //   that is an assignment-expression is a constant expression. A static
10828     //   data member of literal type can be declared in the class definition
10829     //   with the constexpr specifier; if so, its declaration shall specify a
10830     //   brace-or-equal-initializer in which every initializer-clause that is
10831     //   an assignment-expression is a constant expression.
10832 
10833     // Do nothing on dependent types.
10834     if (DclT->isDependentType()) {
10835 
10836     // Allow any 'static constexpr' members, whether or not they are of literal
10837     // type. We separately check that every constexpr variable is of literal
10838     // type.
10839     } else if (VDecl->isConstexpr()) {
10840 
10841     // Require constness.
10842     } else if (!DclT.isConstQualified()) {
10843       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10844         << Init->getSourceRange();
10845       VDecl->setInvalidDecl();
10846 
10847     // We allow integer constant expressions in all cases.
10848     } else if (DclT->isIntegralOrEnumerationType()) {
10849       // Check whether the expression is a constant expression.
10850       SourceLocation Loc;
10851       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10852         // In C++11, a non-constexpr const static data member with an
10853         // in-class initializer cannot be volatile.
10854         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10855       else if (Init->isValueDependent())
10856         ; // Nothing to check.
10857       else if (Init->isIntegerConstantExpr(Context, &Loc))
10858         ; // Ok, it's an ICE!
10859       else if (Init->isEvaluatable(Context)) {
10860         // If we can constant fold the initializer through heroics, accept it,
10861         // but report this as a use of an extension for -pedantic.
10862         Diag(Loc, diag::ext_in_class_initializer_non_constant)
10863           << Init->getSourceRange();
10864       } else {
10865         // Otherwise, this is some crazy unknown case.  Report the issue at the
10866         // location provided by the isIntegerConstantExpr failed check.
10867         Diag(Loc, diag::err_in_class_initializer_non_constant)
10868           << Init->getSourceRange();
10869         VDecl->setInvalidDecl();
10870       }
10871 
10872     // We allow foldable floating-point constants as an extension.
10873     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10874       // In C++98, this is a GNU extension. In C++11, it is not, but we support
10875       // it anyway and provide a fixit to add the 'constexpr'.
10876       if (getLangOpts().CPlusPlus11) {
10877         Diag(VDecl->getLocation(),
10878              diag::ext_in_class_initializer_float_type_cxx11)
10879             << DclT << Init->getSourceRange();
10880         Diag(VDecl->getLocStart(),
10881              diag::note_in_class_initializer_float_type_cxx11)
10882             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10883       } else {
10884         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10885           << DclT << Init->getSourceRange();
10886 
10887         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10888           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10889             << Init->getSourceRange();
10890           VDecl->setInvalidDecl();
10891         }
10892       }
10893 
10894     // Suggest adding 'constexpr' in C++11 for literal types.
10895     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10896       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10897         << DclT << Init->getSourceRange()
10898         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10899       VDecl->setConstexpr(true);
10900 
10901     } else {
10902       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10903         << DclT << Init->getSourceRange();
10904       VDecl->setInvalidDecl();
10905     }
10906   } else if (VDecl->isFileVarDecl()) {
10907     // In C, extern is typically used to avoid tentative definitions when
10908     // declaring variables in headers, but adding an intializer makes it a
10909     // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
10910     // In C++, extern is often used to give implictly static const variables
10911     // external linkage, so don't warn in that case. If selectany is present,
10912     // this might be header code intended for C and C++ inclusion, so apply the
10913     // C++ rules.
10914     if (VDecl->getStorageClass() == SC_Extern &&
10915         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10916          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10917         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10918         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10919       Diag(VDecl->getLocation(), diag::warn_extern_init);
10920 
10921     // C99 6.7.8p4. All file scoped initializers need to be constant.
10922     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10923       CheckForConstantInitializer(Init, DclT);
10924   }
10925 
10926   // We will represent direct-initialization similarly to copy-initialization:
10927   //    int x(1);  -as-> int x = 1;
10928   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10929   //
10930   // Clients that want to distinguish between the two forms, can check for
10931   // direct initializer using VarDecl::getInitStyle().
10932   // A major benefit is that clients that don't particularly care about which
10933   // exactly form was it (like the CodeGen) can handle both cases without
10934   // special case code.
10935 
10936   // C++ 8.5p11:
10937   // The form of initialization (using parentheses or '=') is generally
10938   // insignificant, but does matter when the entity being initialized has a
10939   // class type.
10940   if (CXXDirectInit) {
10941     assert(DirectInit && "Call-style initializer must be direct init.");
10942     VDecl->setInitStyle(VarDecl::CallInit);
10943   } else if (DirectInit) {
10944     // This must be list-initialization. No other way is direct-initialization.
10945     VDecl->setInitStyle(VarDecl::ListInit);
10946   }
10947 
10948   CheckCompleteVariableDeclaration(VDecl);
10949 }
10950 
10951 /// ActOnInitializerError - Given that there was an error parsing an
10952 /// initializer for the given declaration, try to return to some form
10953 /// of sanity.
10954 void Sema::ActOnInitializerError(Decl *D) {
10955   // Our main concern here is re-establishing invariants like "a
10956   // variable's type is either dependent or complete".
10957   if (!D || D->isInvalidDecl()) return;
10958 
10959   VarDecl *VD = dyn_cast<VarDecl>(D);
10960   if (!VD) return;
10961 
10962   // Bindings are not usable if we can't make sense of the initializer.
10963   if (auto *DD = dyn_cast<DecompositionDecl>(D))
10964     for (auto *BD : DD->bindings())
10965       BD->setInvalidDecl();
10966 
10967   // Auto types are meaningless if we can't make sense of the initializer.
10968   if (ParsingInitForAutoVars.count(D)) {
10969     D->setInvalidDecl();
10970     return;
10971   }
10972 
10973   QualType Ty = VD->getType();
10974   if (Ty->isDependentType()) return;
10975 
10976   // Require a complete type.
10977   if (RequireCompleteType(VD->getLocation(),
10978                           Context.getBaseElementType(Ty),
10979                           diag::err_typecheck_decl_incomplete_type)) {
10980     VD->setInvalidDecl();
10981     return;
10982   }
10983 
10984   // Require a non-abstract type.
10985   if (RequireNonAbstractType(VD->getLocation(), Ty,
10986                              diag::err_abstract_type_in_decl,
10987                              AbstractVariableType)) {
10988     VD->setInvalidDecl();
10989     return;
10990   }
10991 
10992   // Don't bother complaining about constructors or destructors,
10993   // though.
10994 }
10995 
10996 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
10997   // If there is no declaration, there was an error parsing it. Just ignore it.
10998   if (!RealDecl)
10999     return;
11000 
11001   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
11002     QualType Type = Var->getType();
11003 
11004     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
11005     if (isa<DecompositionDecl>(RealDecl)) {
11006       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
11007       Var->setInvalidDecl();
11008       return;
11009     }
11010 
11011     if (Type->isUndeducedType() &&
11012         DeduceVariableDeclarationType(Var, false, nullptr))
11013       return;
11014 
11015     // C++11 [class.static.data]p3: A static data member can be declared with
11016     // the constexpr specifier; if so, its declaration shall specify
11017     // a brace-or-equal-initializer.
11018     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
11019     // the definition of a variable [...] or the declaration of a static data
11020     // member.
11021     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
11022         !Var->isThisDeclarationADemotedDefinition()) {
11023       if (Var->isStaticDataMember()) {
11024         // C++1z removes the relevant rule; the in-class declaration is always
11025         // a definition there.
11026         if (!getLangOpts().CPlusPlus17) {
11027           Diag(Var->getLocation(),
11028                diag::err_constexpr_static_mem_var_requires_init)
11029             << Var->getDeclName();
11030           Var->setInvalidDecl();
11031           return;
11032         }
11033       } else {
11034         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
11035         Var->setInvalidDecl();
11036         return;
11037       }
11038     }
11039 
11040     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
11041     // be initialized.
11042     if (!Var->isInvalidDecl() &&
11043         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
11044         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
11045       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
11046       Var->setInvalidDecl();
11047       return;
11048     }
11049 
11050     switch (Var->isThisDeclarationADefinition()) {
11051     case VarDecl::Definition:
11052       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
11053         break;
11054 
11055       // We have an out-of-line definition of a static data member
11056       // that has an in-class initializer, so we type-check this like
11057       // a declaration.
11058       //
11059       LLVM_FALLTHROUGH;
11060 
11061     case VarDecl::DeclarationOnly:
11062       // It's only a declaration.
11063 
11064       // Block scope. C99 6.7p7: If an identifier for an object is
11065       // declared with no linkage (C99 6.2.2p6), the type for the
11066       // object shall be complete.
11067       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
11068           !Var->hasLinkage() && !Var->isInvalidDecl() &&
11069           RequireCompleteType(Var->getLocation(), Type,
11070                               diag::err_typecheck_decl_incomplete_type))
11071         Var->setInvalidDecl();
11072 
11073       // Make sure that the type is not abstract.
11074       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11075           RequireNonAbstractType(Var->getLocation(), Type,
11076                                  diag::err_abstract_type_in_decl,
11077                                  AbstractVariableType))
11078         Var->setInvalidDecl();
11079       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11080           Var->getStorageClass() == SC_PrivateExtern) {
11081         Diag(Var->getLocation(), diag::warn_private_extern);
11082         Diag(Var->getLocation(), diag::note_private_extern);
11083       }
11084 
11085       return;
11086 
11087     case VarDecl::TentativeDefinition:
11088       // File scope. C99 6.9.2p2: A declaration of an identifier for an
11089       // object that has file scope without an initializer, and without a
11090       // storage-class specifier or with the storage-class specifier "static",
11091       // constitutes a tentative definition. Note: A tentative definition with
11092       // external linkage is valid (C99 6.2.2p5).
11093       if (!Var->isInvalidDecl()) {
11094         if (const IncompleteArrayType *ArrayT
11095                                     = Context.getAsIncompleteArrayType(Type)) {
11096           if (RequireCompleteType(Var->getLocation(),
11097                                   ArrayT->getElementType(),
11098                                   diag::err_illegal_decl_array_incomplete_type))
11099             Var->setInvalidDecl();
11100         } else if (Var->getStorageClass() == SC_Static) {
11101           // C99 6.9.2p3: If the declaration of an identifier for an object is
11102           // a tentative definition and has internal linkage (C99 6.2.2p3), the
11103           // declared type shall not be an incomplete type.
11104           // NOTE: code such as the following
11105           //     static struct s;
11106           //     struct s { int a; };
11107           // is accepted by gcc. Hence here we issue a warning instead of
11108           // an error and we do not invalidate the static declaration.
11109           // NOTE: to avoid multiple warnings, only check the first declaration.
11110           if (Var->isFirstDecl())
11111             RequireCompleteType(Var->getLocation(), Type,
11112                                 diag::ext_typecheck_decl_incomplete_type);
11113         }
11114       }
11115 
11116       // Record the tentative definition; we're done.
11117       if (!Var->isInvalidDecl())
11118         TentativeDefinitions.push_back(Var);
11119       return;
11120     }
11121 
11122     // Provide a specific diagnostic for uninitialized variable
11123     // definitions with incomplete array type.
11124     if (Type->isIncompleteArrayType()) {
11125       Diag(Var->getLocation(),
11126            diag::err_typecheck_incomplete_array_needs_initializer);
11127       Var->setInvalidDecl();
11128       return;
11129     }
11130 
11131     // Provide a specific diagnostic for uninitialized variable
11132     // definitions with reference type.
11133     if (Type->isReferenceType()) {
11134       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
11135         << Var->getDeclName()
11136         << SourceRange(Var->getLocation(), Var->getLocation());
11137       Var->setInvalidDecl();
11138       return;
11139     }
11140 
11141     // Do not attempt to type-check the default initializer for a
11142     // variable with dependent type.
11143     if (Type->isDependentType())
11144       return;
11145 
11146     if (Var->isInvalidDecl())
11147       return;
11148 
11149     if (!Var->hasAttr<AliasAttr>()) {
11150       if (RequireCompleteType(Var->getLocation(),
11151                               Context.getBaseElementType(Type),
11152                               diag::err_typecheck_decl_incomplete_type)) {
11153         Var->setInvalidDecl();
11154         return;
11155       }
11156     } else {
11157       return;
11158     }
11159 
11160     // The variable can not have an abstract class type.
11161     if (RequireNonAbstractType(Var->getLocation(), Type,
11162                                diag::err_abstract_type_in_decl,
11163                                AbstractVariableType)) {
11164       Var->setInvalidDecl();
11165       return;
11166     }
11167 
11168     // Check for jumps past the implicit initializer.  C++0x
11169     // clarifies that this applies to a "variable with automatic
11170     // storage duration", not a "local variable".
11171     // C++11 [stmt.dcl]p3
11172     //   A program that jumps from a point where a variable with automatic
11173     //   storage duration is not in scope to a point where it is in scope is
11174     //   ill-formed unless the variable has scalar type, class type with a
11175     //   trivial default constructor and a trivial destructor, a cv-qualified
11176     //   version of one of these types, or an array of one of the preceding
11177     //   types and is declared without an initializer.
11178     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
11179       if (const RecordType *Record
11180             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
11181         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
11182         // Mark the function for further checking even if the looser rules of
11183         // C++11 do not require such checks, so that we can diagnose
11184         // incompatibilities with C++98.
11185         if (!CXXRecord->isPOD())
11186           getCurFunction()->setHasBranchProtectedScope();
11187       }
11188     }
11189 
11190     // C++03 [dcl.init]p9:
11191     //   If no initializer is specified for an object, and the
11192     //   object is of (possibly cv-qualified) non-POD class type (or
11193     //   array thereof), the object shall be default-initialized; if
11194     //   the object is of const-qualified type, the underlying class
11195     //   type shall have a user-declared default
11196     //   constructor. Otherwise, if no initializer is specified for
11197     //   a non- static object, the object and its subobjects, if
11198     //   any, have an indeterminate initial value); if the object
11199     //   or any of its subobjects are of const-qualified type, the
11200     //   program is ill-formed.
11201     // C++0x [dcl.init]p11:
11202     //   If no initializer is specified for an object, the object is
11203     //   default-initialized; [...].
11204     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
11205     InitializationKind Kind
11206       = InitializationKind::CreateDefault(Var->getLocation());
11207 
11208     InitializationSequence InitSeq(*this, Entity, Kind, None);
11209     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
11210     if (Init.isInvalid())
11211       Var->setInvalidDecl();
11212     else if (Init.get()) {
11213       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
11214       // This is important for template substitution.
11215       Var->setInitStyle(VarDecl::CallInit);
11216     }
11217 
11218     CheckCompleteVariableDeclaration(Var);
11219   }
11220 }
11221 
11222 void Sema::ActOnCXXForRangeDecl(Decl *D) {
11223   // If there is no declaration, there was an error parsing it. Ignore it.
11224   if (!D)
11225     return;
11226 
11227   VarDecl *VD = dyn_cast<VarDecl>(D);
11228   if (!VD) {
11229     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
11230     D->setInvalidDecl();
11231     return;
11232   }
11233 
11234   VD->setCXXForRangeDecl(true);
11235 
11236   // for-range-declaration cannot be given a storage class specifier.
11237   int Error = -1;
11238   switch (VD->getStorageClass()) {
11239   case SC_None:
11240     break;
11241   case SC_Extern:
11242     Error = 0;
11243     break;
11244   case SC_Static:
11245     Error = 1;
11246     break;
11247   case SC_PrivateExtern:
11248     Error = 2;
11249     break;
11250   case SC_Auto:
11251     Error = 3;
11252     break;
11253   case SC_Register:
11254     Error = 4;
11255     break;
11256   }
11257   if (Error != -1) {
11258     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
11259       << VD->getDeclName() << Error;
11260     D->setInvalidDecl();
11261   }
11262 }
11263 
11264 StmtResult
11265 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
11266                                  IdentifierInfo *Ident,
11267                                  ParsedAttributes &Attrs,
11268                                  SourceLocation AttrEnd) {
11269   // C++1y [stmt.iter]p1:
11270   //   A range-based for statement of the form
11271   //      for ( for-range-identifier : for-range-initializer ) statement
11272   //   is equivalent to
11273   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
11274   DeclSpec DS(Attrs.getPool().getFactory());
11275 
11276   const char *PrevSpec;
11277   unsigned DiagID;
11278   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
11279                      getPrintingPolicy());
11280 
11281   Declarator D(DS, DeclaratorContext::ForContext);
11282   D.SetIdentifier(Ident, IdentLoc);
11283   D.takeAttributes(Attrs, AttrEnd);
11284 
11285   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
11286   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
11287                 EmptyAttrs, IdentLoc);
11288   Decl *Var = ActOnDeclarator(S, D);
11289   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
11290   FinalizeDeclaration(Var);
11291   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
11292                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
11293 }
11294 
11295 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
11296   if (var->isInvalidDecl()) return;
11297 
11298   if (getLangOpts().OpenCL) {
11299     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
11300     // initialiser
11301     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
11302         !var->hasInit()) {
11303       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
11304           << 1 /*Init*/;
11305       var->setInvalidDecl();
11306       return;
11307     }
11308   }
11309 
11310   // In Objective-C, don't allow jumps past the implicit initialization of a
11311   // local retaining variable.
11312   if (getLangOpts().ObjC1 &&
11313       var->hasLocalStorage()) {
11314     switch (var->getType().getObjCLifetime()) {
11315     case Qualifiers::OCL_None:
11316     case Qualifiers::OCL_ExplicitNone:
11317     case Qualifiers::OCL_Autoreleasing:
11318       break;
11319 
11320     case Qualifiers::OCL_Weak:
11321     case Qualifiers::OCL_Strong:
11322       getCurFunction()->setHasBranchProtectedScope();
11323       break;
11324     }
11325   }
11326 
11327   // Warn about externally-visible variables being defined without a
11328   // prior declaration.  We only want to do this for global
11329   // declarations, but we also specifically need to avoid doing it for
11330   // class members because the linkage of an anonymous class can
11331   // change if it's later given a typedef name.
11332   if (var->isThisDeclarationADefinition() &&
11333       var->getDeclContext()->getRedeclContext()->isFileContext() &&
11334       var->isExternallyVisible() && var->hasLinkage() &&
11335       !var->isInline() && !var->getDescribedVarTemplate() &&
11336       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
11337       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11338                                   var->getLocation())) {
11339     // Find a previous declaration that's not a definition.
11340     VarDecl *prev = var->getPreviousDecl();
11341     while (prev && prev->isThisDeclarationADefinition())
11342       prev = prev->getPreviousDecl();
11343 
11344     if (!prev)
11345       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11346   }
11347 
11348   // Cache the result of checking for constant initialization.
11349   Optional<bool> CacheHasConstInit;
11350   const Expr *CacheCulprit;
11351   auto checkConstInit = [&]() mutable {
11352     if (!CacheHasConstInit)
11353       CacheHasConstInit = var->getInit()->isConstantInitializer(
11354             Context, var->getType()->isReferenceType(), &CacheCulprit);
11355     return *CacheHasConstInit;
11356   };
11357 
11358   if (var->getTLSKind() == VarDecl::TLS_Static) {
11359     if (var->getType().isDestructedType()) {
11360       // GNU C++98 edits for __thread, [basic.start.term]p3:
11361       //   The type of an object with thread storage duration shall not
11362       //   have a non-trivial destructor.
11363       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11364       if (getLangOpts().CPlusPlus11)
11365         Diag(var->getLocation(), diag::note_use_thread_local);
11366     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11367       if (!checkConstInit()) {
11368         // GNU C++98 edits for __thread, [basic.start.init]p4:
11369         //   An object of thread storage duration shall not require dynamic
11370         //   initialization.
11371         // FIXME: Need strict checking here.
11372         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11373           << CacheCulprit->getSourceRange();
11374         if (getLangOpts().CPlusPlus11)
11375           Diag(var->getLocation(), diag::note_use_thread_local);
11376       }
11377     }
11378   }
11379 
11380   // Apply section attributes and pragmas to global variables.
11381   bool GlobalStorage = var->hasGlobalStorage();
11382   if (GlobalStorage && var->isThisDeclarationADefinition() &&
11383       !inTemplateInstantiation()) {
11384     PragmaStack<StringLiteral *> *Stack = nullptr;
11385     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11386     if (var->getType().isConstQualified())
11387       Stack = &ConstSegStack;
11388     else if (!var->getInit()) {
11389       Stack = &BSSSegStack;
11390       SectionFlags |= ASTContext::PSF_Write;
11391     } else {
11392       Stack = &DataSegStack;
11393       SectionFlags |= ASTContext::PSF_Write;
11394     }
11395     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11396       var->addAttr(SectionAttr::CreateImplicit(
11397           Context, SectionAttr::Declspec_allocate,
11398           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11399     }
11400     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11401       if (UnifySection(SA->getName(), SectionFlags, var))
11402         var->dropAttr<SectionAttr>();
11403 
11404     // Apply the init_seg attribute if this has an initializer.  If the
11405     // initializer turns out to not be dynamic, we'll end up ignoring this
11406     // attribute.
11407     if (CurInitSeg && var->getInit())
11408       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11409                                                CurInitSegLoc));
11410   }
11411 
11412   // All the following checks are C++ only.
11413   if (!getLangOpts().CPlusPlus) {
11414       // If this variable must be emitted, add it as an initializer for the
11415       // current module.
11416      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11417        Context.addModuleInitializer(ModuleScopes.back().Module, var);
11418      return;
11419   }
11420 
11421   if (auto *DD = dyn_cast<DecompositionDecl>(var))
11422     CheckCompleteDecompositionDeclaration(DD);
11423 
11424   QualType type = var->getType();
11425   if (type->isDependentType()) return;
11426 
11427   // __block variables might require us to capture a copy-initializer.
11428   if (var->hasAttr<BlocksAttr>()) {
11429     // It's currently invalid to ever have a __block variable with an
11430     // array type; should we diagnose that here?
11431 
11432     // Regardless, we don't want to ignore array nesting when
11433     // constructing this copy.
11434     if (type->isStructureOrClassType()) {
11435       EnterExpressionEvaluationContext scope(
11436           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
11437       SourceLocation poi = var->getLocation();
11438       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
11439       ExprResult result
11440         = PerformMoveOrCopyInitialization(
11441             InitializedEntity::InitializeBlock(poi, type, false),
11442             var, var->getType(), varRef, /*AllowNRVO=*/true);
11443       if (!result.isInvalid()) {
11444         result = MaybeCreateExprWithCleanups(result);
11445         Expr *init = result.getAs<Expr>();
11446         Context.setBlockVarCopyInits(var, init);
11447       }
11448     }
11449   }
11450 
11451   Expr *Init = var->getInit();
11452   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11453   QualType baseType = Context.getBaseElementType(type);
11454 
11455   if (Init && !Init->isValueDependent()) {
11456     if (var->isConstexpr()) {
11457       SmallVector<PartialDiagnosticAt, 8> Notes;
11458       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11459         SourceLocation DiagLoc = var->getLocation();
11460         // If the note doesn't add any useful information other than a source
11461         // location, fold it into the primary diagnostic.
11462         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11463               diag::note_invalid_subexpr_in_const_expr) {
11464           DiagLoc = Notes[0].first;
11465           Notes.clear();
11466         }
11467         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11468           << var << Init->getSourceRange();
11469         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11470           Diag(Notes[I].first, Notes[I].second);
11471       }
11472     } else if (var->isUsableInConstantExpressions(Context)) {
11473       // Check whether the initializer of a const variable of integral or
11474       // enumeration type is an ICE now, since we can't tell whether it was
11475       // initialized by a constant expression if we check later.
11476       var->checkInitIsICE();
11477     }
11478 
11479     // Don't emit further diagnostics about constexpr globals since they
11480     // were just diagnosed.
11481     if (!var->isConstexpr() && GlobalStorage &&
11482             var->hasAttr<RequireConstantInitAttr>()) {
11483       // FIXME: Need strict checking in C++03 here.
11484       bool DiagErr = getLangOpts().CPlusPlus11
11485           ? !var->checkInitIsICE() : !checkConstInit();
11486       if (DiagErr) {
11487         auto attr = var->getAttr<RequireConstantInitAttr>();
11488         Diag(var->getLocation(), diag::err_require_constant_init_failed)
11489           << Init->getSourceRange();
11490         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11491           << attr->getRange();
11492         if (getLangOpts().CPlusPlus11) {
11493           APValue Value;
11494           SmallVector<PartialDiagnosticAt, 8> Notes;
11495           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11496           for (auto &it : Notes)
11497             Diag(it.first, it.second);
11498         } else {
11499           Diag(CacheCulprit->getExprLoc(),
11500                diag::note_invalid_subexpr_in_const_expr)
11501               << CacheCulprit->getSourceRange();
11502         }
11503       }
11504     }
11505     else if (!var->isConstexpr() && IsGlobal &&
11506              !getDiagnostics().isIgnored(diag::warn_global_constructor,
11507                                     var->getLocation())) {
11508       // Warn about globals which don't have a constant initializer.  Don't
11509       // warn about globals with a non-trivial destructor because we already
11510       // warned about them.
11511       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11512       if (!(RD && !RD->hasTrivialDestructor())) {
11513         if (!checkConstInit())
11514           Diag(var->getLocation(), diag::warn_global_constructor)
11515             << Init->getSourceRange();
11516       }
11517     }
11518   }
11519 
11520   // Require the destructor.
11521   if (const RecordType *recordType = baseType->getAs<RecordType>())
11522     FinalizeVarWithDestructor(var, recordType);
11523 
11524   // If this variable must be emitted, add it as an initializer for the current
11525   // module.
11526   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11527     Context.addModuleInitializer(ModuleScopes.back().Module, var);
11528 }
11529 
11530 /// \brief Determines if a variable's alignment is dependent.
11531 static bool hasDependentAlignment(VarDecl *VD) {
11532   if (VD->getType()->isDependentType())
11533     return true;
11534   for (auto *I : VD->specific_attrs<AlignedAttr>())
11535     if (I->isAlignmentDependent())
11536       return true;
11537   return false;
11538 }
11539 
11540 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
11541 /// any semantic actions necessary after any initializer has been attached.
11542 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
11543   // Note that we are no longer parsing the initializer for this declaration.
11544   ParsingInitForAutoVars.erase(ThisDecl);
11545 
11546   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
11547   if (!VD)
11548     return;
11549 
11550   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
11551   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
11552       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
11553     if (PragmaClangBSSSection.Valid)
11554       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
11555                                                             PragmaClangBSSSection.SectionName,
11556                                                             PragmaClangBSSSection.PragmaLocation));
11557     if (PragmaClangDataSection.Valid)
11558       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
11559                                                              PragmaClangDataSection.SectionName,
11560                                                              PragmaClangDataSection.PragmaLocation));
11561     if (PragmaClangRodataSection.Valid)
11562       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
11563                                                                PragmaClangRodataSection.SectionName,
11564                                                                PragmaClangRodataSection.PragmaLocation));
11565   }
11566 
11567   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
11568     for (auto *BD : DD->bindings()) {
11569       FinalizeDeclaration(BD);
11570     }
11571   }
11572 
11573   checkAttributesAfterMerging(*this, *VD);
11574 
11575   // Perform TLS alignment check here after attributes attached to the variable
11576   // which may affect the alignment have been processed. Only perform the check
11577   // if the target has a maximum TLS alignment (zero means no constraints).
11578   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
11579     // Protect the check so that it's not performed on dependent types and
11580     // dependent alignments (we can't determine the alignment in that case).
11581     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
11582         !VD->isInvalidDecl()) {
11583       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
11584       if (Context.getDeclAlign(VD) > MaxAlignChars) {
11585         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
11586           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
11587           << (unsigned)MaxAlignChars.getQuantity();
11588       }
11589     }
11590   }
11591 
11592   if (VD->isStaticLocal()) {
11593     if (FunctionDecl *FD =
11594             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
11595       // Static locals inherit dll attributes from their function.
11596       if (Attr *A = getDLLAttr(FD)) {
11597         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11598         NewAttr->setInherited(true);
11599         VD->addAttr(NewAttr);
11600       }
11601       // CUDA E.2.9.4: Within the body of a __device__ or __global__
11602       // function, only __shared__ variables may be declared with
11603       // static storage class.
11604       if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
11605           CUDADiagIfDeviceCode(VD->getLocation(),
11606                                diag::err_device_static_local_var)
11607               << CurrentCUDATarget())
11608         VD->setInvalidDecl();
11609     }
11610   }
11611 
11612   // Perform check for initializers of device-side global variables.
11613   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
11614   // 7.5). We must also apply the same checks to all __shared__
11615   // variables whether they are local or not. CUDA also allows
11616   // constant initializers for __constant__ and __device__ variables.
11617   if (getLangOpts().CUDA) {
11618     const Expr *Init = VD->getInit();
11619     if (Init && VD->hasGlobalStorage()) {
11620       if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
11621           VD->hasAttr<CUDASharedAttr>()) {
11622         assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
11623         bool AllowedInit = false;
11624         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
11625           AllowedInit =
11626               isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
11627         // We'll allow constant initializers even if it's a non-empty
11628         // constructor according to CUDA rules. This deviates from NVCC,
11629         // but allows us to handle things like constexpr constructors.
11630         if (!AllowedInit &&
11631             (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
11632           AllowedInit = VD->getInit()->isConstantInitializer(
11633               Context, VD->getType()->isReferenceType());
11634 
11635         // Also make sure that destructor, if there is one, is empty.
11636         if (AllowedInit)
11637           if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
11638             AllowedInit =
11639                 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
11640 
11641         if (!AllowedInit) {
11642           Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
11643                                       ? diag::err_shared_var_init
11644                                       : diag::err_dynamic_var_init)
11645               << Init->getSourceRange();
11646           VD->setInvalidDecl();
11647         }
11648       } else {
11649         // This is a host-side global variable.  Check that the initializer is
11650         // callable from the host side.
11651         const FunctionDecl *InitFn = nullptr;
11652         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
11653           InitFn = CE->getConstructor();
11654         } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
11655           InitFn = CE->getDirectCallee();
11656         }
11657         if (InitFn) {
11658           CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
11659           if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
11660             Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
11661                 << InitFnTarget << InitFn;
11662             Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
11663             VD->setInvalidDecl();
11664           }
11665         }
11666       }
11667     }
11668   }
11669 
11670   // Grab the dllimport or dllexport attribute off of the VarDecl.
11671   const InheritableAttr *DLLAttr = getDLLAttr(VD);
11672 
11673   // Imported static data members cannot be defined out-of-line.
11674   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
11675     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
11676         VD->isThisDeclarationADefinition()) {
11677       // We allow definitions of dllimport class template static data members
11678       // with a warning.
11679       CXXRecordDecl *Context =
11680         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
11681       bool IsClassTemplateMember =
11682           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
11683           Context->getDescribedClassTemplate();
11684 
11685       Diag(VD->getLocation(),
11686            IsClassTemplateMember
11687                ? diag::warn_attribute_dllimport_static_field_definition
11688                : diag::err_attribute_dllimport_static_field_definition);
11689       Diag(IA->getLocation(), diag::note_attribute);
11690       if (!IsClassTemplateMember)
11691         VD->setInvalidDecl();
11692     }
11693   }
11694 
11695   // dllimport/dllexport variables cannot be thread local, their TLS index
11696   // isn't exported with the variable.
11697   if (DLLAttr && VD->getTLSKind()) {
11698     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11699     if (F && getDLLAttr(F)) {
11700       assert(VD->isStaticLocal());
11701       // But if this is a static local in a dlimport/dllexport function, the
11702       // function will never be inlined, which means the var would never be
11703       // imported, so having it marked import/export is safe.
11704     } else {
11705       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
11706                                                                     << DLLAttr;
11707       VD->setInvalidDecl();
11708     }
11709   }
11710 
11711   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
11712     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
11713       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11714       VD->dropAttr<UsedAttr>();
11715     }
11716   }
11717 
11718   const DeclContext *DC = VD->getDeclContext();
11719   // If there's a #pragma GCC visibility in scope, and this isn't a class
11720   // member, set the visibility of this variable.
11721   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11722     AddPushedVisibilityAttribute(VD);
11723 
11724   // FIXME: Warn on unused var template partial specializations.
11725   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
11726     MarkUnusedFileScopedDecl(VD);
11727 
11728   // Now we have parsed the initializer and can update the table of magic
11729   // tag values.
11730   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11731       !VD->getType()->isIntegralOrEnumerationType())
11732     return;
11733 
11734   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11735     const Expr *MagicValueExpr = VD->getInit();
11736     if (!MagicValueExpr) {
11737       continue;
11738     }
11739     llvm::APSInt MagicValueInt;
11740     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11741       Diag(I->getRange().getBegin(),
11742            diag::err_type_tag_for_datatype_not_ice)
11743         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11744       continue;
11745     }
11746     if (MagicValueInt.getActiveBits() > 64) {
11747       Diag(I->getRange().getBegin(),
11748            diag::err_type_tag_for_datatype_too_large)
11749         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11750       continue;
11751     }
11752     uint64_t MagicValue = MagicValueInt.getZExtValue();
11753     RegisterTypeTagForDatatype(I->getArgumentKind(),
11754                                MagicValue,
11755                                I->getMatchingCType(),
11756                                I->getLayoutCompatible(),
11757                                I->getMustBeNull());
11758   }
11759 }
11760 
11761 static bool hasDeducedAuto(DeclaratorDecl *DD) {
11762   auto *VD = dyn_cast<VarDecl>(DD);
11763   return VD && !VD->getType()->hasAutoForTrailingReturnType();
11764 }
11765 
11766 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
11767                                                    ArrayRef<Decl *> Group) {
11768   SmallVector<Decl*, 8> Decls;
11769 
11770   if (DS.isTypeSpecOwned())
11771     Decls.push_back(DS.getRepAsDecl());
11772 
11773   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11774   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11775   bool DiagnosedMultipleDecomps = false;
11776   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
11777   bool DiagnosedNonDeducedAuto = false;
11778 
11779   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11780     if (Decl *D = Group[i]) {
11781       // For declarators, there are some additional syntactic-ish checks we need
11782       // to perform.
11783       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11784         if (!FirstDeclaratorInGroup)
11785           FirstDeclaratorInGroup = DD;
11786         if (!FirstDecompDeclaratorInGroup)
11787           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
11788         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
11789             !hasDeducedAuto(DD))
11790           FirstNonDeducedAutoInGroup = DD;
11791 
11792         if (FirstDeclaratorInGroup != DD) {
11793           // A decomposition declaration cannot be combined with any other
11794           // declaration in the same group.
11795           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
11796             Diag(FirstDecompDeclaratorInGroup->getLocation(),
11797                  diag::err_decomp_decl_not_alone)
11798                 << FirstDeclaratorInGroup->getSourceRange()
11799                 << DD->getSourceRange();
11800             DiagnosedMultipleDecomps = true;
11801           }
11802 
11803           // A declarator that uses 'auto' in any way other than to declare a
11804           // variable with a deduced type cannot be combined with any other
11805           // declarator in the same group.
11806           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
11807             Diag(FirstNonDeducedAutoInGroup->getLocation(),
11808                  diag::err_auto_non_deduced_not_alone)
11809                 << FirstNonDeducedAutoInGroup->getType()
11810                        ->hasAutoForTrailingReturnType()
11811                 << FirstDeclaratorInGroup->getSourceRange()
11812                 << DD->getSourceRange();
11813             DiagnosedNonDeducedAuto = true;
11814           }
11815         }
11816       }
11817 
11818       Decls.push_back(D);
11819     }
11820   }
11821 
11822   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11823     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11824       handleTagNumbering(Tag, S);
11825       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11826           getLangOpts().CPlusPlus)
11827         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11828     }
11829   }
11830 
11831   return BuildDeclaratorGroup(Decls);
11832 }
11833 
11834 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11835 /// group, performing any necessary semantic checking.
11836 Sema::DeclGroupPtrTy
11837 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
11838   // C++14 [dcl.spec.auto]p7: (DR1347)
11839   //   If the type that replaces the placeholder type is not the same in each
11840   //   deduction, the program is ill-formed.
11841   if (Group.size() > 1) {
11842     QualType Deduced;
11843     VarDecl *DeducedDecl = nullptr;
11844     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11845       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
11846       if (!D || D->isInvalidDecl())
11847         break;
11848       DeducedType *DT = D->getType()->getContainedDeducedType();
11849       if (!DT || DT->getDeducedType().isNull())
11850         continue;
11851       if (Deduced.isNull()) {
11852         Deduced = DT->getDeducedType();
11853         DeducedDecl = D;
11854       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
11855         auto *AT = dyn_cast<AutoType>(DT);
11856         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11857              diag::err_auto_different_deductions)
11858           << (AT ? (unsigned)AT->getKeyword() : 3)
11859           << Deduced << DeducedDecl->getDeclName()
11860           << DT->getDeducedType() << D->getDeclName()
11861           << DeducedDecl->getInit()->getSourceRange()
11862           << D->getInit()->getSourceRange();
11863         D->setInvalidDecl();
11864         break;
11865       }
11866     }
11867   }
11868 
11869   ActOnDocumentableDecls(Group);
11870 
11871   return DeclGroupPtrTy::make(
11872       DeclGroupRef::Create(Context, Group.data(), Group.size()));
11873 }
11874 
11875 void Sema::ActOnDocumentableDecl(Decl *D) {
11876   ActOnDocumentableDecls(D);
11877 }
11878 
11879 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11880   // Don't parse the comment if Doxygen diagnostics are ignored.
11881   if (Group.empty() || !Group[0])
11882     return;
11883 
11884   if (Diags.isIgnored(diag::warn_doc_param_not_found,
11885                       Group[0]->getLocation()) &&
11886       Diags.isIgnored(diag::warn_unknown_comment_command_name,
11887                       Group[0]->getLocation()))
11888     return;
11889 
11890   if (Group.size() >= 2) {
11891     // This is a decl group.  Normally it will contain only declarations
11892     // produced from declarator list.  But in case we have any definitions or
11893     // additional declaration references:
11894     //   'typedef struct S {} S;'
11895     //   'typedef struct S *S;'
11896     //   'struct S *pS;'
11897     // FinalizeDeclaratorGroup adds these as separate declarations.
11898     Decl *MaybeTagDecl = Group[0];
11899     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11900       Group = Group.slice(1);
11901     }
11902   }
11903 
11904   // See if there are any new comments that are not attached to a decl.
11905   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11906   if (!Comments.empty() &&
11907       !Comments.back()->isAttached()) {
11908     // There is at least one comment that not attached to a decl.
11909     // Maybe it should be attached to one of these decls?
11910     //
11911     // Note that this way we pick up not only comments that precede the
11912     // declaration, but also comments that *follow* the declaration -- thanks to
11913     // the lookahead in the lexer: we've consumed the semicolon and looked
11914     // ahead through comments.
11915     for (unsigned i = 0, e = Group.size(); i != e; ++i)
11916       Context.getCommentForDecl(Group[i], &PP);
11917   }
11918 }
11919 
11920 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11921 /// to introduce parameters into function prototype scope.
11922 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11923   const DeclSpec &DS = D.getDeclSpec();
11924 
11925   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11926 
11927   // C++03 [dcl.stc]p2 also permits 'auto'.
11928   StorageClass SC = SC_None;
11929   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11930     SC = SC_Register;
11931     // In C++11, the 'register' storage class specifier is deprecated.
11932     // In C++17, it is not allowed, but we tolerate it as an extension.
11933     if (getLangOpts().CPlusPlus11) {
11934       Diag(DS.getStorageClassSpecLoc(),
11935            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
11936                                      : diag::warn_deprecated_register)
11937         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11938     }
11939   } else if (getLangOpts().CPlusPlus &&
11940              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11941     SC = SC_Auto;
11942   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11943     Diag(DS.getStorageClassSpecLoc(),
11944          diag::err_invalid_storage_class_in_func_decl);
11945     D.getMutableDeclSpec().ClearStorageClassSpecs();
11946   }
11947 
11948   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11949     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11950       << DeclSpec::getSpecifierName(TSCS);
11951   if (DS.isInlineSpecified())
11952     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11953         << getLangOpts().CPlusPlus17;
11954   if (DS.isConstexprSpecified())
11955     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11956       << 0;
11957 
11958   DiagnoseFunctionSpecifiers(DS);
11959 
11960   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11961   QualType parmDeclType = TInfo->getType();
11962 
11963   if (getLangOpts().CPlusPlus) {
11964     // Check that there are no default arguments inside the type of this
11965     // parameter.
11966     CheckExtraCXXDefaultArguments(D);
11967 
11968     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11969     if (D.getCXXScopeSpec().isSet()) {
11970       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11971         << D.getCXXScopeSpec().getRange();
11972       D.getCXXScopeSpec().clear();
11973     }
11974   }
11975 
11976   // Ensure we have a valid name
11977   IdentifierInfo *II = nullptr;
11978   if (D.hasName()) {
11979     II = D.getIdentifier();
11980     if (!II) {
11981       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11982         << GetNameForDeclarator(D).getName();
11983       D.setInvalidType(true);
11984     }
11985   }
11986 
11987   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11988   if (II) {
11989     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
11990                    ForVisibleRedeclaration);
11991     LookupName(R, S);
11992     if (R.isSingleResult()) {
11993       NamedDecl *PrevDecl = R.getFoundDecl();
11994       if (PrevDecl->isTemplateParameter()) {
11995         // Maybe we will complain about the shadowed template parameter.
11996         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11997         // Just pretend that we didn't see the previous declaration.
11998         PrevDecl = nullptr;
11999       } else if (S->isDeclScope(PrevDecl)) {
12000         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
12001         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12002 
12003         // Recover by removing the name
12004         II = nullptr;
12005         D.SetIdentifier(nullptr, D.getIdentifierLoc());
12006         D.setInvalidType(true);
12007       }
12008     }
12009   }
12010 
12011   // Temporarily put parameter variables in the translation unit, not
12012   // the enclosing context.  This prevents them from accidentally
12013   // looking like class members in C++.
12014   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
12015                                     D.getLocStart(),
12016                                     D.getIdentifierLoc(), II,
12017                                     parmDeclType, TInfo,
12018                                     SC);
12019 
12020   if (D.isInvalidType())
12021     New->setInvalidDecl();
12022 
12023   assert(S->isFunctionPrototypeScope());
12024   assert(S->getFunctionPrototypeDepth() >= 1);
12025   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
12026                     S->getNextFunctionPrototypeIndex());
12027 
12028   // Add the parameter declaration into this scope.
12029   S->AddDecl(New);
12030   if (II)
12031     IdResolver.AddDecl(New);
12032 
12033   ProcessDeclAttributes(S, New, D);
12034 
12035   if (D.getDeclSpec().isModulePrivateSpecified())
12036     Diag(New->getLocation(), diag::err_module_private_local)
12037       << 1 << New->getDeclName()
12038       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12039       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12040 
12041   if (New->hasAttr<BlocksAttr>()) {
12042     Diag(New->getLocation(), diag::err_block_on_nonlocal);
12043   }
12044   return New;
12045 }
12046 
12047 /// \brief Synthesizes a variable for a parameter arising from a
12048 /// typedef.
12049 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
12050                                               SourceLocation Loc,
12051                                               QualType T) {
12052   /* FIXME: setting StartLoc == Loc.
12053      Would it be worth to modify callers so as to provide proper source
12054      location for the unnamed parameters, embedding the parameter's type? */
12055   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
12056                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
12057                                            SC_None, nullptr);
12058   Param->setImplicit();
12059   return Param;
12060 }
12061 
12062 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
12063   // Don't diagnose unused-parameter errors in template instantiations; we
12064   // will already have done so in the template itself.
12065   if (inTemplateInstantiation())
12066     return;
12067 
12068   for (const ParmVarDecl *Parameter : Parameters) {
12069     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
12070         !Parameter->hasAttr<UnusedAttr>()) {
12071       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
12072         << Parameter->getDeclName();
12073     }
12074   }
12075 }
12076 
12077 void Sema::DiagnoseSizeOfParametersAndReturnValue(
12078     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
12079   if (LangOpts.NumLargeByValueCopy == 0) // No check.
12080     return;
12081 
12082   // Warn if the return value is pass-by-value and larger than the specified
12083   // threshold.
12084   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
12085     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
12086     if (Size > LangOpts.NumLargeByValueCopy)
12087       Diag(D->getLocation(), diag::warn_return_value_size)
12088           << D->getDeclName() << Size;
12089   }
12090 
12091   // Warn if any parameter is pass-by-value and larger than the specified
12092   // threshold.
12093   for (const ParmVarDecl *Parameter : Parameters) {
12094     QualType T = Parameter->getType();
12095     if (T->isDependentType() || !T.isPODType(Context))
12096       continue;
12097     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
12098     if (Size > LangOpts.NumLargeByValueCopy)
12099       Diag(Parameter->getLocation(), diag::warn_parameter_size)
12100           << Parameter->getDeclName() << Size;
12101   }
12102 }
12103 
12104 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
12105                                   SourceLocation NameLoc, IdentifierInfo *Name,
12106                                   QualType T, TypeSourceInfo *TSInfo,
12107                                   StorageClass SC) {
12108   // In ARC, infer a lifetime qualifier for appropriate parameter types.
12109   if (getLangOpts().ObjCAutoRefCount &&
12110       T.getObjCLifetime() == Qualifiers::OCL_None &&
12111       T->isObjCLifetimeType()) {
12112 
12113     Qualifiers::ObjCLifetime lifetime;
12114 
12115     // Special cases for arrays:
12116     //   - if it's const, use __unsafe_unretained
12117     //   - otherwise, it's an error
12118     if (T->isArrayType()) {
12119       if (!T.isConstQualified()) {
12120         DelayedDiagnostics.add(
12121             sema::DelayedDiagnostic::makeForbiddenType(
12122             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
12123       }
12124       lifetime = Qualifiers::OCL_ExplicitNone;
12125     } else {
12126       lifetime = T->getObjCARCImplicitLifetime();
12127     }
12128     T = Context.getLifetimeQualifiedType(T, lifetime);
12129   }
12130 
12131   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
12132                                          Context.getAdjustedParameterType(T),
12133                                          TSInfo, SC, nullptr);
12134 
12135   // Parameters can not be abstract class types.
12136   // For record types, this is done by the AbstractClassUsageDiagnoser once
12137   // the class has been completely parsed.
12138   if (!CurContext->isRecord() &&
12139       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
12140                              AbstractParamType))
12141     New->setInvalidDecl();
12142 
12143   // Parameter declarators cannot be interface types. All ObjC objects are
12144   // passed by reference.
12145   if (T->isObjCObjectType()) {
12146     SourceLocation TypeEndLoc =
12147         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
12148     Diag(NameLoc,
12149          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
12150       << FixItHint::CreateInsertion(TypeEndLoc, "*");
12151     T = Context.getObjCObjectPointerType(T);
12152     New->setType(T);
12153   }
12154 
12155   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
12156   // duration shall not be qualified by an address-space qualifier."
12157   // Since all parameters have automatic store duration, they can not have
12158   // an address space.
12159   if (T.getAddressSpace() != LangAS::Default &&
12160       // OpenCL allows function arguments declared to be an array of a type
12161       // to be qualified with an address space.
12162       !(getLangOpts().OpenCL &&
12163         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
12164     Diag(NameLoc, diag::err_arg_with_address_space);
12165     New->setInvalidDecl();
12166   }
12167 
12168   return New;
12169 }
12170 
12171 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
12172                                            SourceLocation LocAfterDecls) {
12173   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
12174 
12175   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
12176   // for a K&R function.
12177   if (!FTI.hasPrototype) {
12178     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
12179       --i;
12180       if (FTI.Params[i].Param == nullptr) {
12181         SmallString<256> Code;
12182         llvm::raw_svector_ostream(Code)
12183             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
12184         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
12185             << FTI.Params[i].Ident
12186             << FixItHint::CreateInsertion(LocAfterDecls, Code);
12187 
12188         // Implicitly declare the argument as type 'int' for lack of a better
12189         // type.
12190         AttributeFactory attrs;
12191         DeclSpec DS(attrs);
12192         const char* PrevSpec; // unused
12193         unsigned DiagID; // unused
12194         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
12195                            DiagID, Context.getPrintingPolicy());
12196         // Use the identifier location for the type source range.
12197         DS.SetRangeStart(FTI.Params[i].IdentLoc);
12198         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
12199         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
12200         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
12201         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
12202       }
12203     }
12204   }
12205 }
12206 
12207 Decl *
12208 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
12209                               MultiTemplateParamsArg TemplateParameterLists,
12210                               SkipBodyInfo *SkipBody) {
12211   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
12212   assert(D.isFunctionDeclarator() && "Not a function declarator!");
12213   Scope *ParentScope = FnBodyScope->getParent();
12214 
12215   D.setFunctionDefinitionKind(FDK_Definition);
12216   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
12217   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
12218 }
12219 
12220 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
12221   Consumer.HandleInlineFunctionDefinition(D);
12222 }
12223 
12224 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
12225                              const FunctionDecl*& PossibleZeroParamPrototype) {
12226   // Don't warn about invalid declarations.
12227   if (FD->isInvalidDecl())
12228     return false;
12229 
12230   // Or declarations that aren't global.
12231   if (!FD->isGlobal())
12232     return false;
12233 
12234   // Don't warn about C++ member functions.
12235   if (isa<CXXMethodDecl>(FD))
12236     return false;
12237 
12238   // Don't warn about 'main'.
12239   if (FD->isMain())
12240     return false;
12241 
12242   // Don't warn about inline functions.
12243   if (FD->isInlined())
12244     return false;
12245 
12246   // Don't warn about function templates.
12247   if (FD->getDescribedFunctionTemplate())
12248     return false;
12249 
12250   // Don't warn about function template specializations.
12251   if (FD->isFunctionTemplateSpecialization())
12252     return false;
12253 
12254   // Don't warn for OpenCL kernels.
12255   if (FD->hasAttr<OpenCLKernelAttr>())
12256     return false;
12257 
12258   // Don't warn on explicitly deleted functions.
12259   if (FD->isDeleted())
12260     return false;
12261 
12262   bool MissingPrototype = true;
12263   for (const FunctionDecl *Prev = FD->getPreviousDecl();
12264        Prev; Prev = Prev->getPreviousDecl()) {
12265     // Ignore any declarations that occur in function or method
12266     // scope, because they aren't visible from the header.
12267     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
12268       continue;
12269 
12270     MissingPrototype = !Prev->getType()->isFunctionProtoType();
12271     if (FD->getNumParams() == 0)
12272       PossibleZeroParamPrototype = Prev;
12273     break;
12274   }
12275 
12276   return MissingPrototype;
12277 }
12278 
12279 void
12280 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
12281                                    const FunctionDecl *EffectiveDefinition,
12282                                    SkipBodyInfo *SkipBody) {
12283   const FunctionDecl *Definition = EffectiveDefinition;
12284   if (!Definition)
12285     if (!FD->isDefined(Definition))
12286       return;
12287 
12288   if (canRedefineFunction(Definition, getLangOpts()))
12289     return;
12290 
12291   // Don't emit an error when this is redefinition of a typo-corrected
12292   // definition.
12293   if (TypoCorrectedFunctionDefinitions.count(Definition))
12294     return;
12295 
12296   // If we don't have a visible definition of the function, and it's inline or
12297   // a template, skip the new definition.
12298   if (SkipBody && !hasVisibleDefinition(Definition) &&
12299       (Definition->getFormalLinkage() == InternalLinkage ||
12300        Definition->isInlined() ||
12301        Definition->getDescribedFunctionTemplate() ||
12302        Definition->getNumTemplateParameterLists())) {
12303     SkipBody->ShouldSkip = true;
12304     if (auto *TD = Definition->getDescribedFunctionTemplate())
12305       makeMergedDefinitionVisible(TD);
12306     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
12307     return;
12308   }
12309 
12310   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
12311       Definition->getStorageClass() == SC_Extern)
12312     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
12313         << FD->getDeclName() << getLangOpts().CPlusPlus;
12314   else
12315     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12316 
12317   Diag(Definition->getLocation(), diag::note_previous_definition);
12318   FD->setInvalidDecl();
12319 }
12320 
12321 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12322                                    Sema &S) {
12323   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12324 
12325   LambdaScopeInfo *LSI = S.PushLambdaScope();
12326   LSI->CallOperator = CallOperator;
12327   LSI->Lambda = LambdaClass;
12328   LSI->ReturnType = CallOperator->getReturnType();
12329   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12330 
12331   if (LCD == LCD_None)
12332     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12333   else if (LCD == LCD_ByCopy)
12334     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12335   else if (LCD == LCD_ByRef)
12336     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12337   DeclarationNameInfo DNI = CallOperator->getNameInfo();
12338 
12339   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12340   LSI->Mutable = !CallOperator->isConst();
12341 
12342   // Add the captures to the LSI so they can be noted as already
12343   // captured within tryCaptureVar.
12344   auto I = LambdaClass->field_begin();
12345   for (const auto &C : LambdaClass->captures()) {
12346     if (C.capturesVariable()) {
12347       VarDecl *VD = C.getCapturedVar();
12348       if (VD->isInitCapture())
12349         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12350       QualType CaptureType = VD->getType();
12351       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12352       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12353           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12354           /*EllipsisLoc*/C.isPackExpansion()
12355                          ? C.getEllipsisLoc() : SourceLocation(),
12356           CaptureType, /*Expr*/ nullptr);
12357 
12358     } else if (C.capturesThis()) {
12359       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
12360                               /*Expr*/ nullptr,
12361                               C.getCaptureKind() == LCK_StarThis);
12362     } else {
12363       LSI->addVLATypeCapture(C.getLocation(), I->getType());
12364     }
12365     ++I;
12366   }
12367 }
12368 
12369 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12370                                     SkipBodyInfo *SkipBody) {
12371   if (!D)
12372     return D;
12373   FunctionDecl *FD = nullptr;
12374 
12375   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
12376     FD = FunTmpl->getTemplatedDecl();
12377   else
12378     FD = cast<FunctionDecl>(D);
12379 
12380   // Check for defining attributes before the check for redefinition.
12381   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
12382     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
12383     FD->dropAttr<AliasAttr>();
12384     FD->setInvalidDecl();
12385   }
12386   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12387     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12388     FD->dropAttr<IFuncAttr>();
12389     FD->setInvalidDecl();
12390   }
12391 
12392   // See if this is a redefinition. If 'will have body' is already set, then
12393   // these checks were already performed when it was set.
12394   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
12395     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
12396 
12397     // If we're skipping the body, we're done. Don't enter the scope.
12398     if (SkipBody && SkipBody->ShouldSkip)
12399       return D;
12400   }
12401 
12402   // Mark this function as "will have a body eventually".  This lets users to
12403   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12404   // this function.
12405   FD->setWillHaveBody();
12406 
12407   // If we are instantiating a generic lambda call operator, push
12408   // a LambdaScopeInfo onto the function stack.  But use the information
12409   // that's already been calculated (ActOnLambdaExpr) to prime the current
12410   // LambdaScopeInfo.
12411   // When the template operator is being specialized, the LambdaScopeInfo,
12412   // has to be properly restored so that tryCaptureVariable doesn't try
12413   // and capture any new variables. In addition when calculating potential
12414   // captures during transformation of nested lambdas, it is necessary to
12415   // have the LSI properly restored.
12416   if (isGenericLambdaCallOperatorSpecialization(FD)) {
12417     assert(inTemplateInstantiation() &&
12418            "There should be an active template instantiation on the stack "
12419            "when instantiating a generic lambda!");
12420     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12421   } else {
12422     // Enter a new function scope
12423     PushFunctionScope();
12424   }
12425 
12426   // Builtin functions cannot be defined.
12427   if (unsigned BuiltinID = FD->getBuiltinID()) {
12428     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12429         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12430       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12431       FD->setInvalidDecl();
12432     }
12433   }
12434 
12435   // The return type of a function definition must be complete
12436   // (C99 6.9.1p3, C++ [dcl.fct]p6).
12437   QualType ResultType = FD->getReturnType();
12438   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12439       !FD->isInvalidDecl() &&
12440       RequireCompleteType(FD->getLocation(), ResultType,
12441                           diag::err_func_def_incomplete_result))
12442     FD->setInvalidDecl();
12443 
12444   if (FnBodyScope)
12445     PushDeclContext(FnBodyScope, FD);
12446 
12447   // Check the validity of our function parameters
12448   CheckParmsForFunctionDef(FD->parameters(),
12449                            /*CheckParameterNames=*/true);
12450 
12451   // Add non-parameter declarations already in the function to the current
12452   // scope.
12453   if (FnBodyScope) {
12454     for (Decl *NPD : FD->decls()) {
12455       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
12456       if (!NonParmDecl)
12457         continue;
12458       assert(!isa<ParmVarDecl>(NonParmDecl) &&
12459              "parameters should not be in newly created FD yet");
12460 
12461       // If the decl has a name, make it accessible in the current scope.
12462       if (NonParmDecl->getDeclName())
12463         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
12464 
12465       // Similarly, dive into enums and fish their constants out, making them
12466       // accessible in this scope.
12467       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
12468         for (auto *EI : ED->enumerators())
12469           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
12470       }
12471     }
12472   }
12473 
12474   // Introduce our parameters into the function scope
12475   for (auto Param : FD->parameters()) {
12476     Param->setOwningFunction(FD);
12477 
12478     // If this has an identifier, add it to the scope stack.
12479     if (Param->getIdentifier() && FnBodyScope) {
12480       CheckShadow(FnBodyScope, Param);
12481 
12482       PushOnScopeChains(Param, FnBodyScope);
12483     }
12484   }
12485 
12486   // Ensure that the function's exception specification is instantiated.
12487   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
12488     ResolveExceptionSpec(D->getLocation(), FPT);
12489 
12490   // dllimport cannot be applied to non-inline function definitions.
12491   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
12492       !FD->isTemplateInstantiation()) {
12493     assert(!FD->hasAttr<DLLExportAttr>());
12494     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
12495     FD->setInvalidDecl();
12496     return D;
12497   }
12498   // We want to attach documentation to original Decl (which might be
12499   // a function template).
12500   ActOnDocumentableDecl(D);
12501   if (getCurLexicalContext()->isObjCContainer() &&
12502       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
12503       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
12504     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
12505 
12506   return D;
12507 }
12508 
12509 /// \brief Given the set of return statements within a function body,
12510 /// compute the variables that are subject to the named return value
12511 /// optimization.
12512 ///
12513 /// Each of the variables that is subject to the named return value
12514 /// optimization will be marked as NRVO variables in the AST, and any
12515 /// return statement that has a marked NRVO variable as its NRVO candidate can
12516 /// use the named return value optimization.
12517 ///
12518 /// This function applies a very simplistic algorithm for NRVO: if every return
12519 /// statement in the scope of a variable has the same NRVO candidate, that
12520 /// candidate is an NRVO variable.
12521 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
12522   ReturnStmt **Returns = Scope->Returns.data();
12523 
12524   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
12525     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
12526       if (!NRVOCandidate->isNRVOVariable())
12527         Returns[I]->setNRVOCandidate(nullptr);
12528     }
12529   }
12530 }
12531 
12532 bool Sema::canDelayFunctionBody(const Declarator &D) {
12533   // We can't delay parsing the body of a constexpr function template (yet).
12534   if (D.getDeclSpec().isConstexprSpecified())
12535     return false;
12536 
12537   // We can't delay parsing the body of a function template with a deduced
12538   // return type (yet).
12539   if (D.getDeclSpec().hasAutoTypeSpec()) {
12540     // If the placeholder introduces a non-deduced trailing return type,
12541     // we can still delay parsing it.
12542     if (D.getNumTypeObjects()) {
12543       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
12544       if (Outer.Kind == DeclaratorChunk::Function &&
12545           Outer.Fun.hasTrailingReturnType()) {
12546         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
12547         return Ty.isNull() || !Ty->isUndeducedType();
12548       }
12549     }
12550     return false;
12551   }
12552 
12553   return true;
12554 }
12555 
12556 bool Sema::canSkipFunctionBody(Decl *D) {
12557   // We cannot skip the body of a function (or function template) which is
12558   // constexpr, since we may need to evaluate its body in order to parse the
12559   // rest of the file.
12560   // We cannot skip the body of a function with an undeduced return type,
12561   // because any callers of that function need to know the type.
12562   if (const FunctionDecl *FD = D->getAsFunction())
12563     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
12564       return false;
12565   return Consumer.shouldSkipFunctionBody(D);
12566 }
12567 
12568 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
12569   if (!Decl)
12570     return nullptr;
12571   if (FunctionDecl *FD = Decl->getAsFunction())
12572     FD->setHasSkippedBody();
12573   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
12574     MD->setHasSkippedBody();
12575   return Decl;
12576 }
12577 
12578 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
12579   return ActOnFinishFunctionBody(D, BodyArg, false);
12580 }
12581 
12582 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
12583                                     bool IsInstantiation) {
12584   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
12585 
12586   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12587   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
12588 
12589   if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
12590     CheckCompletedCoroutineBody(FD, Body);
12591 
12592   if (FD) {
12593     FD->setBody(Body);
12594     FD->setWillHaveBody(false);
12595 
12596     if (getLangOpts().CPlusPlus14) {
12597       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
12598           FD->getReturnType()->isUndeducedType()) {
12599         // If the function has a deduced result type but contains no 'return'
12600         // statements, the result type as written must be exactly 'auto', and
12601         // the deduced result type is 'void'.
12602         if (!FD->getReturnType()->getAs<AutoType>()) {
12603           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
12604               << FD->getReturnType();
12605           FD->setInvalidDecl();
12606         } else {
12607           // Substitute 'void' for the 'auto' in the type.
12608           TypeLoc ResultType = getReturnTypeLoc(FD);
12609           Context.adjustDeducedFunctionResultType(
12610               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
12611         }
12612       }
12613     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
12614       // In C++11, we don't use 'auto' deduction rules for lambda call
12615       // operators because we don't support return type deduction.
12616       auto *LSI = getCurLambda();
12617       if (LSI->HasImplicitReturnType) {
12618         deduceClosureReturnType(*LSI);
12619 
12620         // C++11 [expr.prim.lambda]p4:
12621         //   [...] if there are no return statements in the compound-statement
12622         //   [the deduced type is] the type void
12623         QualType RetType =
12624             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
12625 
12626         // Update the return type to the deduced type.
12627         const FunctionProtoType *Proto =
12628             FD->getType()->getAs<FunctionProtoType>();
12629         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
12630                                             Proto->getExtProtoInfo()));
12631       }
12632     }
12633 
12634     // If the function implicitly returns zero (like 'main') or is naked,
12635     // don't complain about missing return statements.
12636     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
12637       WP.disableCheckFallThrough();
12638 
12639     // MSVC permits the use of pure specifier (=0) on function definition,
12640     // defined at class scope, warn about this non-standard construct.
12641     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
12642       Diag(FD->getLocation(), diag::ext_pure_function_definition);
12643 
12644     if (!FD->isInvalidDecl()) {
12645       // Don't diagnose unused parameters of defaulted or deleted functions.
12646       if (!FD->isDeleted() && !FD->isDefaulted())
12647         DiagnoseUnusedParameters(FD->parameters());
12648       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
12649                                              FD->getReturnType(), FD);
12650 
12651       // If this is a structor, we need a vtable.
12652       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
12653         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
12654       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
12655         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
12656 
12657       // Try to apply the named return value optimization. We have to check
12658       // if we can do this here because lambdas keep return statements around
12659       // to deduce an implicit return type.
12660       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
12661           !FD->isDependentContext())
12662         computeNRVO(Body, getCurFunction());
12663     }
12664 
12665     // GNU warning -Wmissing-prototypes:
12666     //   Warn if a global function is defined without a previous
12667     //   prototype declaration. This warning is issued even if the
12668     //   definition itself provides a prototype. The aim is to detect
12669     //   global functions that fail to be declared in header files.
12670     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
12671     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
12672       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
12673 
12674       if (PossibleZeroParamPrototype) {
12675         // We found a declaration that is not a prototype,
12676         // but that could be a zero-parameter prototype
12677         if (TypeSourceInfo *TI =
12678                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
12679           TypeLoc TL = TI->getTypeLoc();
12680           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
12681             Diag(PossibleZeroParamPrototype->getLocation(),
12682                  diag::note_declaration_not_a_prototype)
12683                 << PossibleZeroParamPrototype
12684                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
12685         }
12686       }
12687 
12688       // GNU warning -Wstrict-prototypes
12689       //   Warn if K&R function is defined without a previous declaration.
12690       //   This warning is issued only if the definition itself does not provide
12691       //   a prototype. Only K&R definitions do not provide a prototype.
12692       //   An empty list in a function declarator that is part of a definition
12693       //   of that function specifies that the function has no parameters
12694       //   (C99 6.7.5.3p14)
12695       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
12696           !LangOpts.CPlusPlus) {
12697         TypeSourceInfo *TI = FD->getTypeSourceInfo();
12698         TypeLoc TL = TI->getTypeLoc();
12699         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
12700         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
12701       }
12702     }
12703 
12704     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12705       const CXXMethodDecl *KeyFunction;
12706       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
12707           MD->isVirtual() &&
12708           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
12709           MD == KeyFunction->getCanonicalDecl()) {
12710         // Update the key-function state if necessary for this ABI.
12711         if (FD->isInlined() &&
12712             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12713           Context.setNonKeyFunction(MD);
12714 
12715           // If the newly-chosen key function is already defined, then we
12716           // need to mark the vtable as used retroactively.
12717           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
12718           const FunctionDecl *Definition;
12719           if (KeyFunction && KeyFunction->isDefined(Definition))
12720             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
12721         } else {
12722           // We just defined they key function; mark the vtable as used.
12723           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
12724         }
12725       }
12726     }
12727 
12728     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
12729            "Function parsing confused");
12730   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
12731     assert(MD == getCurMethodDecl() && "Method parsing confused");
12732     MD->setBody(Body);
12733     if (!MD->isInvalidDecl()) {
12734       DiagnoseUnusedParameters(MD->parameters());
12735       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
12736                                              MD->getReturnType(), MD);
12737 
12738       if (Body)
12739         computeNRVO(Body, getCurFunction());
12740     }
12741     if (getCurFunction()->ObjCShouldCallSuper) {
12742       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
12743         << MD->getSelector().getAsString();
12744       getCurFunction()->ObjCShouldCallSuper = false;
12745     }
12746     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12747       const ObjCMethodDecl *InitMethod = nullptr;
12748       bool isDesignated =
12749           MD->isDesignatedInitializerForTheInterface(&InitMethod);
12750       assert(isDesignated && InitMethod);
12751       (void)isDesignated;
12752 
12753       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12754         auto IFace = MD->getClassInterface();
12755         if (!IFace)
12756           return false;
12757         auto SuperD = IFace->getSuperClass();
12758         if (!SuperD)
12759           return false;
12760         return SuperD->getIdentifier() ==
12761             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12762       };
12763       // Don't issue this warning for unavailable inits or direct subclasses
12764       // of NSObject.
12765       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12766         Diag(MD->getLocation(),
12767              diag::warn_objc_designated_init_missing_super_call);
12768         Diag(InitMethod->getLocation(),
12769              diag::note_objc_designated_init_marked_here);
12770       }
12771       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12772     }
12773     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12774       // Don't issue this warning for unavaialable inits.
12775       if (!MD->isUnavailable())
12776         Diag(MD->getLocation(),
12777              diag::warn_objc_secondary_init_missing_init_call);
12778       getCurFunction()->ObjCWarnForNoInitDelegation = false;
12779     }
12780   } else {
12781     return nullptr;
12782   }
12783 
12784   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12785     DiagnoseUnguardedAvailabilityViolations(dcl);
12786 
12787   assert(!getCurFunction()->ObjCShouldCallSuper &&
12788          "This should only be set for ObjC methods, which should have been "
12789          "handled in the block above.");
12790 
12791   // Verify and clean out per-function state.
12792   if (Body && (!FD || !FD->isDefaulted())) {
12793     // C++ constructors that have function-try-blocks can't have return
12794     // statements in the handlers of that block. (C++ [except.handle]p14)
12795     // Verify this.
12796     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12797       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12798 
12799     // Verify that gotos and switch cases don't jump into scopes illegally.
12800     if (getCurFunction()->NeedsScopeChecking() &&
12801         !PP.isCodeCompletionEnabled())
12802       DiagnoseInvalidJumps(Body);
12803 
12804     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12805       if (!Destructor->getParent()->isDependentType())
12806         CheckDestructor(Destructor);
12807 
12808       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12809                                              Destructor->getParent());
12810     }
12811 
12812     // If any errors have occurred, clear out any temporaries that may have
12813     // been leftover. This ensures that these temporaries won't be picked up for
12814     // deletion in some later function.
12815     if (getDiagnostics().hasErrorOccurred() ||
12816         getDiagnostics().getSuppressAllDiagnostics()) {
12817       DiscardCleanupsInEvaluationContext();
12818     }
12819     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12820         !isa<FunctionTemplateDecl>(dcl)) {
12821       // Since the body is valid, issue any analysis-based warnings that are
12822       // enabled.
12823       ActivePolicy = &WP;
12824     }
12825 
12826     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12827         (!CheckConstexprFunctionDecl(FD) ||
12828          !CheckConstexprFunctionBody(FD, Body)))
12829       FD->setInvalidDecl();
12830 
12831     if (FD && FD->hasAttr<NakedAttr>()) {
12832       for (const Stmt *S : Body->children()) {
12833         // Allow local register variables without initializer as they don't
12834         // require prologue.
12835         bool RegisterVariables = false;
12836         if (auto *DS = dyn_cast<DeclStmt>(S)) {
12837           for (const auto *Decl : DS->decls()) {
12838             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12839               RegisterVariables =
12840                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12841               if (!RegisterVariables)
12842                 break;
12843             }
12844           }
12845         }
12846         if (RegisterVariables)
12847           continue;
12848         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12849           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12850           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12851           FD->setInvalidDecl();
12852           break;
12853         }
12854       }
12855     }
12856 
12857     assert(ExprCleanupObjects.size() ==
12858                ExprEvalContexts.back().NumCleanupObjects &&
12859            "Leftover temporaries in function");
12860     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12861     assert(MaybeODRUseExprs.empty() &&
12862            "Leftover expressions for odr-use checking");
12863   }
12864 
12865   if (!IsInstantiation)
12866     PopDeclContext();
12867 
12868   PopFunctionScopeInfo(ActivePolicy, dcl);
12869   // If any errors have occurred, clear out any temporaries that may have
12870   // been leftover. This ensures that these temporaries won't be picked up for
12871   // deletion in some later function.
12872   if (getDiagnostics().hasErrorOccurred()) {
12873     DiscardCleanupsInEvaluationContext();
12874   }
12875 
12876   return dcl;
12877 }
12878 
12879 /// When we finish delayed parsing of an attribute, we must attach it to the
12880 /// relevant Decl.
12881 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12882                                        ParsedAttributes &Attrs) {
12883   // Always attach attributes to the underlying decl.
12884   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12885     D = TD->getTemplatedDecl();
12886   ProcessDeclAttributeList(S, D, Attrs.getList());
12887 
12888   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12889     if (Method->isStatic())
12890       checkThisInStaticMemberFunctionAttributes(Method);
12891 }
12892 
12893 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12894 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12895 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12896                                           IdentifierInfo &II, Scope *S) {
12897   // Find the scope in which the identifier is injected and the corresponding
12898   // DeclContext.
12899   // FIXME: C89 does not say what happens if there is no enclosing block scope.
12900   // In that case, we inject the declaration into the translation unit scope
12901   // instead.
12902   Scope *BlockScope = S;
12903   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
12904     BlockScope = BlockScope->getParent();
12905 
12906   Scope *ContextScope = BlockScope;
12907   while (!ContextScope->getEntity())
12908     ContextScope = ContextScope->getParent();
12909   ContextRAII SavedContext(*this, ContextScope->getEntity());
12910 
12911   // Before we produce a declaration for an implicitly defined
12912   // function, see whether there was a locally-scoped declaration of
12913   // this name as a function or variable. If so, use that
12914   // (non-visible) declaration, and complain about it.
12915   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
12916   if (ExternCPrev) {
12917     // We still need to inject the function into the enclosing block scope so
12918     // that later (non-call) uses can see it.
12919     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
12920 
12921     // C89 footnote 38:
12922     //   If in fact it is not defined as having type "function returning int",
12923     //   the behavior is undefined.
12924     if (!isa<FunctionDecl>(ExternCPrev) ||
12925         !Context.typesAreCompatible(
12926             cast<FunctionDecl>(ExternCPrev)->getType(),
12927             Context.getFunctionNoProtoType(Context.IntTy))) {
12928       Diag(Loc, diag::ext_use_out_of_scope_declaration)
12929           << ExternCPrev << !getLangOpts().C99;
12930       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12931       return ExternCPrev;
12932     }
12933   }
12934 
12935   // Extension in C99.  Legal in C90, but warn about it.
12936   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
12937   unsigned diag_id;
12938   if (II.getName().startswith("__builtin_"))
12939     diag_id = diag::warn_builtin_unknown;
12940   else if (getLangOpts().C99 || getLangOpts().OpenCL)
12941     diag_id = diag::ext_implicit_function_decl;
12942   else
12943     diag_id = diag::warn_implicit_function_decl;
12944   Diag(Loc, diag_id) << &II << getLangOpts().OpenCL;
12945 
12946   // If we found a prior declaration of this function, don't bother building
12947   // another one. We've already pushed that one into scope, so there's nothing
12948   // more to do.
12949   if (ExternCPrev)
12950     return ExternCPrev;
12951 
12952   // Because typo correction is expensive, only do it if the implicit
12953   // function declaration is going to be treated as an error.
12954   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
12955     TypoCorrection Corrected;
12956     if (S &&
12957         (Corrected = CorrectTypo(
12958              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
12959              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
12960       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
12961                    /*ErrorRecovery*/false);
12962   }
12963 
12964   // Set a Declarator for the implicit definition: int foo();
12965   const char *Dummy;
12966   AttributeFactory attrFactory;
12967   DeclSpec DS(attrFactory);
12968   unsigned DiagID;
12969   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
12970                                   Context.getPrintingPolicy());
12971   (void)Error; // Silence warning.
12972   assert(!Error && "Error setting up implicit decl!");
12973   SourceLocation NoLoc;
12974   Declarator D(DS, DeclaratorContext::BlockContext);
12975   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
12976                                              /*IsAmbiguous=*/false,
12977                                              /*LParenLoc=*/NoLoc,
12978                                              /*Params=*/nullptr,
12979                                              /*NumParams=*/0,
12980                                              /*EllipsisLoc=*/NoLoc,
12981                                              /*RParenLoc=*/NoLoc,
12982                                              /*TypeQuals=*/0,
12983                                              /*RefQualifierIsLvalueRef=*/true,
12984                                              /*RefQualifierLoc=*/NoLoc,
12985                                              /*ConstQualifierLoc=*/NoLoc,
12986                                              /*VolatileQualifierLoc=*/NoLoc,
12987                                              /*RestrictQualifierLoc=*/NoLoc,
12988                                              /*MutableLoc=*/NoLoc,
12989                                              EST_None,
12990                                              /*ESpecRange=*/SourceRange(),
12991                                              /*Exceptions=*/nullptr,
12992                                              /*ExceptionRanges=*/nullptr,
12993                                              /*NumExceptions=*/0,
12994                                              /*NoexceptExpr=*/nullptr,
12995                                              /*ExceptionSpecTokens=*/nullptr,
12996                                              /*DeclsInPrototype=*/None,
12997                                              Loc, Loc, D),
12998                 DS.getAttributes(),
12999                 SourceLocation());
13000   D.SetIdentifier(&II, Loc);
13001 
13002   // Insert this function into the enclosing block scope.
13003   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
13004   FD->setImplicit();
13005 
13006   AddKnownFunctionAttributes(FD);
13007 
13008   return FD;
13009 }
13010 
13011 /// \brief Adds any function attributes that we know a priori based on
13012 /// the declaration of this function.
13013 ///
13014 /// These attributes can apply both to implicitly-declared builtins
13015 /// (like __builtin___printf_chk) or to library-declared functions
13016 /// like NSLog or printf.
13017 ///
13018 /// We need to check for duplicate attributes both here and where user-written
13019 /// attributes are applied to declarations.
13020 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
13021   if (FD->isInvalidDecl())
13022     return;
13023 
13024   // If this is a built-in function, map its builtin attributes to
13025   // actual attributes.
13026   if (unsigned BuiltinID = FD->getBuiltinID()) {
13027     // Handle printf-formatting attributes.
13028     unsigned FormatIdx;
13029     bool HasVAListArg;
13030     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
13031       if (!FD->hasAttr<FormatAttr>()) {
13032         const char *fmt = "printf";
13033         unsigned int NumParams = FD->getNumParams();
13034         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
13035             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
13036           fmt = "NSString";
13037         FD->addAttr(FormatAttr::CreateImplicit(Context,
13038                                                &Context.Idents.get(fmt),
13039                                                FormatIdx+1,
13040                                                HasVAListArg ? 0 : FormatIdx+2,
13041                                                FD->getLocation()));
13042       }
13043     }
13044     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
13045                                              HasVAListArg)) {
13046      if (!FD->hasAttr<FormatAttr>())
13047        FD->addAttr(FormatAttr::CreateImplicit(Context,
13048                                               &Context.Idents.get("scanf"),
13049                                               FormatIdx+1,
13050                                               HasVAListArg ? 0 : FormatIdx+2,
13051                                               FD->getLocation()));
13052     }
13053 
13054     // Mark const if we don't care about errno and that is the only thing
13055     // preventing the function from being const. This allows IRgen to use LLVM
13056     // intrinsics for such functions.
13057     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
13058         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
13059       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13060 
13061     // We make "fma" on GNU or Windows const because we know it does not set
13062     // errno in those environments even though it could set errno based on the
13063     // C standard.
13064     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
13065     if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
13066         !FD->hasAttr<ConstAttr>()) {
13067       switch (BuiltinID) {
13068       case Builtin::BI__builtin_fma:
13069       case Builtin::BI__builtin_fmaf:
13070       case Builtin::BI__builtin_fmal:
13071       case Builtin::BIfma:
13072       case Builtin::BIfmaf:
13073       case Builtin::BIfmal:
13074         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13075         break;
13076       default:
13077         break;
13078       }
13079     }
13080 
13081     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
13082         !FD->hasAttr<ReturnsTwiceAttr>())
13083       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
13084                                          FD->getLocation()));
13085     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
13086       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13087     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
13088       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
13089     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
13090       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13091     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
13092         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
13093       // Add the appropriate attribute, depending on the CUDA compilation mode
13094       // and which target the builtin belongs to. For example, during host
13095       // compilation, aux builtins are __device__, while the rest are __host__.
13096       if (getLangOpts().CUDAIsDevice !=
13097           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
13098         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
13099       else
13100         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
13101     }
13102   }
13103 
13104   // If C++ exceptions are enabled but we are told extern "C" functions cannot
13105   // throw, add an implicit nothrow attribute to any extern "C" function we come
13106   // across.
13107   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
13108       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
13109     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
13110     if (!FPT || FPT->getExceptionSpecType() == EST_None)
13111       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13112   }
13113 
13114   IdentifierInfo *Name = FD->getIdentifier();
13115   if (!Name)
13116     return;
13117   if ((!getLangOpts().CPlusPlus &&
13118        FD->getDeclContext()->isTranslationUnit()) ||
13119       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
13120        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
13121        LinkageSpecDecl::lang_c)) {
13122     // Okay: this could be a libc/libm/Objective-C function we know
13123     // about.
13124   } else
13125     return;
13126 
13127   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
13128     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
13129     // target-specific builtins, perhaps?
13130     if (!FD->hasAttr<FormatAttr>())
13131       FD->addAttr(FormatAttr::CreateImplicit(Context,
13132                                              &Context.Idents.get("printf"), 2,
13133                                              Name->isStr("vasprintf") ? 0 : 3,
13134                                              FD->getLocation()));
13135   }
13136 
13137   if (Name->isStr("__CFStringMakeConstantString")) {
13138     // We already have a __builtin___CFStringMakeConstantString,
13139     // but builds that use -fno-constant-cfstrings don't go through that.
13140     if (!FD->hasAttr<FormatArgAttr>())
13141       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
13142                                                 FD->getLocation()));
13143   }
13144 }
13145 
13146 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
13147                                     TypeSourceInfo *TInfo) {
13148   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
13149   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
13150 
13151   if (!TInfo) {
13152     assert(D.isInvalidType() && "no declarator info for valid type");
13153     TInfo = Context.getTrivialTypeSourceInfo(T);
13154   }
13155 
13156   // Scope manipulation handled by caller.
13157   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
13158                                            D.getLocStart(),
13159                                            D.getIdentifierLoc(),
13160                                            D.getIdentifier(),
13161                                            TInfo);
13162 
13163   // Bail out immediately if we have an invalid declaration.
13164   if (D.isInvalidType()) {
13165     NewTD->setInvalidDecl();
13166     return NewTD;
13167   }
13168 
13169   if (D.getDeclSpec().isModulePrivateSpecified()) {
13170     if (CurContext->isFunctionOrMethod())
13171       Diag(NewTD->getLocation(), diag::err_module_private_local)
13172         << 2 << NewTD->getDeclName()
13173         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13174         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13175     else
13176       NewTD->setModulePrivate();
13177   }
13178 
13179   // C++ [dcl.typedef]p8:
13180   //   If the typedef declaration defines an unnamed class (or
13181   //   enum), the first typedef-name declared by the declaration
13182   //   to be that class type (or enum type) is used to denote the
13183   //   class type (or enum type) for linkage purposes only.
13184   // We need to check whether the type was declared in the declaration.
13185   switch (D.getDeclSpec().getTypeSpecType()) {
13186   case TST_enum:
13187   case TST_struct:
13188   case TST_interface:
13189   case TST_union:
13190   case TST_class: {
13191     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
13192     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
13193     break;
13194   }
13195 
13196   default:
13197     break;
13198   }
13199 
13200   return NewTD;
13201 }
13202 
13203 /// \brief Check that this is a valid underlying type for an enum declaration.
13204 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
13205   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
13206   QualType T = TI->getType();
13207 
13208   if (T->isDependentType())
13209     return false;
13210 
13211   if (const BuiltinType *BT = T->getAs<BuiltinType>())
13212     if (BT->isInteger())
13213       return false;
13214 
13215   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
13216   return true;
13217 }
13218 
13219 /// Check whether this is a valid redeclaration of a previous enumeration.
13220 /// \return true if the redeclaration was invalid.
13221 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
13222                                   QualType EnumUnderlyingTy, bool IsFixed,
13223                                   const EnumDecl *Prev) {
13224   if (IsScoped != Prev->isScoped()) {
13225     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
13226       << Prev->isScoped();
13227     Diag(Prev->getLocation(), diag::note_previous_declaration);
13228     return true;
13229   }
13230 
13231   if (IsFixed && Prev->isFixed()) {
13232     if (!EnumUnderlyingTy->isDependentType() &&
13233         !Prev->getIntegerType()->isDependentType() &&
13234         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
13235                                         Prev->getIntegerType())) {
13236       // TODO: Highlight the underlying type of the redeclaration.
13237       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
13238         << EnumUnderlyingTy << Prev->getIntegerType();
13239       Diag(Prev->getLocation(), diag::note_previous_declaration)
13240           << Prev->getIntegerTypeRange();
13241       return true;
13242     }
13243   } else if (IsFixed != Prev->isFixed()) {
13244     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
13245       << Prev->isFixed();
13246     Diag(Prev->getLocation(), diag::note_previous_declaration);
13247     return true;
13248   }
13249 
13250   return false;
13251 }
13252 
13253 /// \brief Get diagnostic %select index for tag kind for
13254 /// redeclaration diagnostic message.
13255 /// WARNING: Indexes apply to particular diagnostics only!
13256 ///
13257 /// \returns diagnostic %select index.
13258 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
13259   switch (Tag) {
13260   case TTK_Struct: return 0;
13261   case TTK_Interface: return 1;
13262   case TTK_Class:  return 2;
13263   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
13264   }
13265 }
13266 
13267 /// \brief Determine if tag kind is a class-key compatible with
13268 /// class for redeclaration (class, struct, or __interface).
13269 ///
13270 /// \returns true iff the tag kind is compatible.
13271 static bool isClassCompatTagKind(TagTypeKind Tag)
13272 {
13273   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
13274 }
13275 
13276 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
13277                                              TagTypeKind TTK) {
13278   if (isa<TypedefDecl>(PrevDecl))
13279     return NTK_Typedef;
13280   else if (isa<TypeAliasDecl>(PrevDecl))
13281     return NTK_TypeAlias;
13282   else if (isa<ClassTemplateDecl>(PrevDecl))
13283     return NTK_Template;
13284   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
13285     return NTK_TypeAliasTemplate;
13286   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
13287     return NTK_TemplateTemplateArgument;
13288   switch (TTK) {
13289   case TTK_Struct:
13290   case TTK_Interface:
13291   case TTK_Class:
13292     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
13293   case TTK_Union:
13294     return NTK_NonUnion;
13295   case TTK_Enum:
13296     return NTK_NonEnum;
13297   }
13298   llvm_unreachable("invalid TTK");
13299 }
13300 
13301 /// \brief Determine whether a tag with a given kind is acceptable
13302 /// as a redeclaration of the given tag declaration.
13303 ///
13304 /// \returns true if the new tag kind is acceptable, false otherwise.
13305 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
13306                                         TagTypeKind NewTag, bool isDefinition,
13307                                         SourceLocation NewTagLoc,
13308                                         const IdentifierInfo *Name) {
13309   // C++ [dcl.type.elab]p3:
13310   //   The class-key or enum keyword present in the
13311   //   elaborated-type-specifier shall agree in kind with the
13312   //   declaration to which the name in the elaborated-type-specifier
13313   //   refers. This rule also applies to the form of
13314   //   elaborated-type-specifier that declares a class-name or
13315   //   friend class since it can be construed as referring to the
13316   //   definition of the class. Thus, in any
13317   //   elaborated-type-specifier, the enum keyword shall be used to
13318   //   refer to an enumeration (7.2), the union class-key shall be
13319   //   used to refer to a union (clause 9), and either the class or
13320   //   struct class-key shall be used to refer to a class (clause 9)
13321   //   declared using the class or struct class-key.
13322   TagTypeKind OldTag = Previous->getTagKind();
13323   if (!isDefinition || !isClassCompatTagKind(NewTag))
13324     if (OldTag == NewTag)
13325       return true;
13326 
13327   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
13328     // Warn about the struct/class tag mismatch.
13329     bool isTemplate = false;
13330     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
13331       isTemplate = Record->getDescribedClassTemplate();
13332 
13333     if (inTemplateInstantiation()) {
13334       // In a template instantiation, do not offer fix-its for tag mismatches
13335       // since they usually mess up the template instead of fixing the problem.
13336       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13337         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13338         << getRedeclDiagFromTagKind(OldTag);
13339       return true;
13340     }
13341 
13342     if (isDefinition) {
13343       // On definitions, check previous tags and issue a fix-it for each
13344       // one that doesn't match the current tag.
13345       if (Previous->getDefinition()) {
13346         // Don't suggest fix-its for redefinitions.
13347         return true;
13348       }
13349 
13350       bool previousMismatch = false;
13351       for (auto I : Previous->redecls()) {
13352         if (I->getTagKind() != NewTag) {
13353           if (!previousMismatch) {
13354             previousMismatch = true;
13355             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
13356               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13357               << getRedeclDiagFromTagKind(I->getTagKind());
13358           }
13359           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
13360             << getRedeclDiagFromTagKind(NewTag)
13361             << FixItHint::CreateReplacement(I->getInnerLocStart(),
13362                  TypeWithKeyword::getTagTypeKindName(NewTag));
13363         }
13364       }
13365       return true;
13366     }
13367 
13368     // Check for a previous definition.  If current tag and definition
13369     // are same type, do nothing.  If no definition, but disagree with
13370     // with previous tag type, give a warning, but no fix-it.
13371     const TagDecl *Redecl = Previous->getDefinition() ?
13372                             Previous->getDefinition() : Previous;
13373     if (Redecl->getTagKind() == NewTag) {
13374       return true;
13375     }
13376 
13377     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13378       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13379       << getRedeclDiagFromTagKind(OldTag);
13380     Diag(Redecl->getLocation(), diag::note_previous_use);
13381 
13382     // If there is a previous definition, suggest a fix-it.
13383     if (Previous->getDefinition()) {
13384         Diag(NewTagLoc, diag::note_struct_class_suggestion)
13385           << getRedeclDiagFromTagKind(Redecl->getTagKind())
13386           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
13387                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
13388     }
13389 
13390     return true;
13391   }
13392   return false;
13393 }
13394 
13395 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
13396 /// from an outer enclosing namespace or file scope inside a friend declaration.
13397 /// This should provide the commented out code in the following snippet:
13398 ///   namespace N {
13399 ///     struct X;
13400 ///     namespace M {
13401 ///       struct Y { friend struct /*N::*/ X; };
13402 ///     }
13403 ///   }
13404 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
13405                                          SourceLocation NameLoc) {
13406   // While the decl is in a namespace, do repeated lookup of that name and see
13407   // if we get the same namespace back.  If we do not, continue until
13408   // translation unit scope, at which point we have a fully qualified NNS.
13409   SmallVector<IdentifierInfo *, 4> Namespaces;
13410   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13411   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
13412     // This tag should be declared in a namespace, which can only be enclosed by
13413     // other namespaces.  Bail if there's an anonymous namespace in the chain.
13414     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
13415     if (!Namespace || Namespace->isAnonymousNamespace())
13416       return FixItHint();
13417     IdentifierInfo *II = Namespace->getIdentifier();
13418     Namespaces.push_back(II);
13419     NamedDecl *Lookup = SemaRef.LookupSingleName(
13420         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
13421     if (Lookup == Namespace)
13422       break;
13423   }
13424 
13425   // Once we have all the namespaces, reverse them to go outermost first, and
13426   // build an NNS.
13427   SmallString<64> Insertion;
13428   llvm::raw_svector_ostream OS(Insertion);
13429   if (DC->isTranslationUnit())
13430     OS << "::";
13431   std::reverse(Namespaces.begin(), Namespaces.end());
13432   for (auto *II : Namespaces)
13433     OS << II->getName() << "::";
13434   return FixItHint::CreateInsertion(NameLoc, Insertion);
13435 }
13436 
13437 /// \brief Determine whether a tag originally declared in context \p OldDC can
13438 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
13439 /// found a declaration in \p OldDC as a previous decl, perhaps through a
13440 /// using-declaration).
13441 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
13442                                          DeclContext *NewDC) {
13443   OldDC = OldDC->getRedeclContext();
13444   NewDC = NewDC->getRedeclContext();
13445 
13446   if (OldDC->Equals(NewDC))
13447     return true;
13448 
13449   // In MSVC mode, we allow a redeclaration if the contexts are related (either
13450   // encloses the other).
13451   if (S.getLangOpts().MSVCCompat &&
13452       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
13453     return true;
13454 
13455   return false;
13456 }
13457 
13458 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
13459 /// former case, Name will be non-null.  In the later case, Name will be null.
13460 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
13461 /// reference/declaration/definition of a tag.
13462 ///
13463 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
13464 /// trailing-type-specifier) other than one in an alias-declaration.
13465 ///
13466 /// \param SkipBody If non-null, will be set to indicate if the caller should
13467 /// skip the definition of this tag and treat it as if it were a declaration.
13468 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
13469                      SourceLocation KWLoc, CXXScopeSpec &SS,
13470                      IdentifierInfo *Name, SourceLocation NameLoc,
13471                      AttributeList *Attr, AccessSpecifier AS,
13472                      SourceLocation ModulePrivateLoc,
13473                      MultiTemplateParamsArg TemplateParameterLists,
13474                      bool &OwnedDecl, bool &IsDependent,
13475                      SourceLocation ScopedEnumKWLoc,
13476                      bool ScopedEnumUsesClassTag,
13477                      TypeResult UnderlyingType,
13478                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
13479                      SkipBodyInfo *SkipBody) {
13480   // If this is not a definition, it must have a name.
13481   IdentifierInfo *OrigName = Name;
13482   assert((Name != nullptr || TUK == TUK_Definition) &&
13483          "Nameless record must be a definition!");
13484   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
13485 
13486   OwnedDecl = false;
13487   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13488   bool ScopedEnum = ScopedEnumKWLoc.isValid();
13489 
13490   // FIXME: Check member specializations more carefully.
13491   bool isMemberSpecialization = false;
13492   bool Invalid = false;
13493 
13494   // We only need to do this matching if we have template parameters
13495   // or a scope specifier, which also conveniently avoids this work
13496   // for non-C++ cases.
13497   if (TemplateParameterLists.size() > 0 ||
13498       (SS.isNotEmpty() && TUK != TUK_Reference)) {
13499     if (TemplateParameterList *TemplateParams =
13500             MatchTemplateParametersToScopeSpecifier(
13501                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
13502                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
13503       if (Kind == TTK_Enum) {
13504         Diag(KWLoc, diag::err_enum_template);
13505         return nullptr;
13506       }
13507 
13508       if (TemplateParams->size() > 0) {
13509         // This is a declaration or definition of a class template (which may
13510         // be a member of another template).
13511 
13512         if (Invalid)
13513           return nullptr;
13514 
13515         OwnedDecl = false;
13516         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
13517                                                SS, Name, NameLoc, Attr,
13518                                                TemplateParams, AS,
13519                                                ModulePrivateLoc,
13520                                                /*FriendLoc*/SourceLocation(),
13521                                                TemplateParameterLists.size()-1,
13522                                                TemplateParameterLists.data(),
13523                                                SkipBody);
13524         return Result.get();
13525       } else {
13526         // The "template<>" header is extraneous.
13527         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13528           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13529         isMemberSpecialization = true;
13530       }
13531     }
13532   }
13533 
13534   // Figure out the underlying type if this a enum declaration. We need to do
13535   // this early, because it's needed to detect if this is an incompatible
13536   // redeclaration.
13537   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
13538   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
13539 
13540   if (Kind == TTK_Enum) {
13541     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
13542       // No underlying type explicitly specified, or we failed to parse the
13543       // type, default to int.
13544       EnumUnderlying = Context.IntTy.getTypePtr();
13545     } else if (UnderlyingType.get()) {
13546       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
13547       // integral type; any cv-qualification is ignored.
13548       TypeSourceInfo *TI = nullptr;
13549       GetTypeFromParser(UnderlyingType.get(), &TI);
13550       EnumUnderlying = TI;
13551 
13552       if (CheckEnumUnderlyingType(TI))
13553         // Recover by falling back to int.
13554         EnumUnderlying = Context.IntTy.getTypePtr();
13555 
13556       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
13557                                           UPPC_FixedUnderlyingType))
13558         EnumUnderlying = Context.IntTy.getTypePtr();
13559 
13560     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13561       // For MSVC ABI compatibility, unfixed enums must use an underlying type
13562       // of 'int'. However, if this is an unfixed forward declaration, don't set
13563       // the underlying type unless the user enables -fms-compatibility. This
13564       // makes unfixed forward declared enums incomplete and is more conforming.
13565       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
13566         EnumUnderlying = Context.IntTy.getTypePtr();
13567     }
13568   }
13569 
13570   DeclContext *SearchDC = CurContext;
13571   DeclContext *DC = CurContext;
13572   bool isStdBadAlloc = false;
13573   bool isStdAlignValT = false;
13574 
13575   RedeclarationKind Redecl = forRedeclarationInCurContext();
13576   if (TUK == TUK_Friend || TUK == TUK_Reference)
13577     Redecl = NotForRedeclaration;
13578 
13579   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
13580   /// implemented asks for structural equivalence checking, the returned decl
13581   /// here is passed back to the parser, allowing the tag body to be parsed.
13582   auto createTagFromNewDecl = [&]() -> TagDecl * {
13583     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
13584     // If there is an identifier, use the location of the identifier as the
13585     // location of the decl, otherwise use the location of the struct/union
13586     // keyword.
13587     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13588     TagDecl *New = nullptr;
13589 
13590     if (Kind == TTK_Enum) {
13591       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
13592                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
13593       // If this is an undefined enum, bail.
13594       if (TUK != TUK_Definition && !Invalid)
13595         return nullptr;
13596       if (EnumUnderlying) {
13597         EnumDecl *ED = cast<EnumDecl>(New);
13598         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
13599           ED->setIntegerTypeSourceInfo(TI);
13600         else
13601           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
13602         ED->setPromotionType(ED->getIntegerType());
13603       }
13604     } else { // struct/union
13605       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13606                                nullptr);
13607     }
13608 
13609     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13610       // Add alignment attributes if necessary; these attributes are checked
13611       // when the ASTContext lays out the structure.
13612       //
13613       // It is important for implementing the correct semantics that this
13614       // happen here (in ActOnTag). The #pragma pack stack is
13615       // maintained as a result of parser callbacks which can occur at
13616       // many points during the parsing of a struct declaration (because
13617       // the #pragma tokens are effectively skipped over during the
13618       // parsing of the struct).
13619       if (TUK == TUK_Definition) {
13620         AddAlignmentAttributesForRecord(RD);
13621         AddMsStructLayoutForRecord(RD);
13622       }
13623     }
13624     New->setLexicalDeclContext(CurContext);
13625     return New;
13626   };
13627 
13628   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
13629   if (Name && SS.isNotEmpty()) {
13630     // We have a nested-name tag ('struct foo::bar').
13631 
13632     // Check for invalid 'foo::'.
13633     if (SS.isInvalid()) {
13634       Name = nullptr;
13635       goto CreateNewDecl;
13636     }
13637 
13638     // If this is a friend or a reference to a class in a dependent
13639     // context, don't try to make a decl for it.
13640     if (TUK == TUK_Friend || TUK == TUK_Reference) {
13641       DC = computeDeclContext(SS, false);
13642       if (!DC) {
13643         IsDependent = true;
13644         return nullptr;
13645       }
13646     } else {
13647       DC = computeDeclContext(SS, true);
13648       if (!DC) {
13649         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
13650           << SS.getRange();
13651         return nullptr;
13652       }
13653     }
13654 
13655     if (RequireCompleteDeclContext(SS, DC))
13656       return nullptr;
13657 
13658     SearchDC = DC;
13659     // Look-up name inside 'foo::'.
13660     LookupQualifiedName(Previous, DC);
13661 
13662     if (Previous.isAmbiguous())
13663       return nullptr;
13664 
13665     if (Previous.empty()) {
13666       // Name lookup did not find anything. However, if the
13667       // nested-name-specifier refers to the current instantiation,
13668       // and that current instantiation has any dependent base
13669       // classes, we might find something at instantiation time: treat
13670       // this as a dependent elaborated-type-specifier.
13671       // But this only makes any sense for reference-like lookups.
13672       if (Previous.wasNotFoundInCurrentInstantiation() &&
13673           (TUK == TUK_Reference || TUK == TUK_Friend)) {
13674         IsDependent = true;
13675         return nullptr;
13676       }
13677 
13678       // A tag 'foo::bar' must already exist.
13679       Diag(NameLoc, diag::err_not_tag_in_scope)
13680         << Kind << Name << DC << SS.getRange();
13681       Name = nullptr;
13682       Invalid = true;
13683       goto CreateNewDecl;
13684     }
13685   } else if (Name) {
13686     // C++14 [class.mem]p14:
13687     //   If T is the name of a class, then each of the following shall have a
13688     //   name different from T:
13689     //    -- every member of class T that is itself a type
13690     if (TUK != TUK_Reference && TUK != TUK_Friend &&
13691         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
13692       return nullptr;
13693 
13694     // If this is a named struct, check to see if there was a previous forward
13695     // declaration or definition.
13696     // FIXME: We're looking into outer scopes here, even when we
13697     // shouldn't be. Doing so can result in ambiguities that we
13698     // shouldn't be diagnosing.
13699     LookupName(Previous, S);
13700 
13701     // When declaring or defining a tag, ignore ambiguities introduced
13702     // by types using'ed into this scope.
13703     if (Previous.isAmbiguous() &&
13704         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
13705       LookupResult::Filter F = Previous.makeFilter();
13706       while (F.hasNext()) {
13707         NamedDecl *ND = F.next();
13708         if (!ND->getDeclContext()->getRedeclContext()->Equals(
13709                 SearchDC->getRedeclContext()))
13710           F.erase();
13711       }
13712       F.done();
13713     }
13714 
13715     // C++11 [namespace.memdef]p3:
13716     //   If the name in a friend declaration is neither qualified nor
13717     //   a template-id and the declaration is a function or an
13718     //   elaborated-type-specifier, the lookup to determine whether
13719     //   the entity has been previously declared shall not consider
13720     //   any scopes outside the innermost enclosing namespace.
13721     //
13722     // MSVC doesn't implement the above rule for types, so a friend tag
13723     // declaration may be a redeclaration of a type declared in an enclosing
13724     // scope.  They do implement this rule for friend functions.
13725     //
13726     // Does it matter that this should be by scope instead of by
13727     // semantic context?
13728     if (!Previous.empty() && TUK == TUK_Friend) {
13729       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
13730       LookupResult::Filter F = Previous.makeFilter();
13731       bool FriendSawTagOutsideEnclosingNamespace = false;
13732       while (F.hasNext()) {
13733         NamedDecl *ND = F.next();
13734         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13735         if (DC->isFileContext() &&
13736             !EnclosingNS->Encloses(ND->getDeclContext())) {
13737           if (getLangOpts().MSVCCompat)
13738             FriendSawTagOutsideEnclosingNamespace = true;
13739           else
13740             F.erase();
13741         }
13742       }
13743       F.done();
13744 
13745       // Diagnose this MSVC extension in the easy case where lookup would have
13746       // unambiguously found something outside the enclosing namespace.
13747       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
13748         NamedDecl *ND = Previous.getFoundDecl();
13749         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
13750             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
13751       }
13752     }
13753 
13754     // Note:  there used to be some attempt at recovery here.
13755     if (Previous.isAmbiguous())
13756       return nullptr;
13757 
13758     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
13759       // FIXME: This makes sure that we ignore the contexts associated
13760       // with C structs, unions, and enums when looking for a matching
13761       // tag declaration or definition. See the similar lookup tweak
13762       // in Sema::LookupName; is there a better way to deal with this?
13763       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
13764         SearchDC = SearchDC->getParent();
13765     }
13766   }
13767 
13768   if (Previous.isSingleResult() &&
13769       Previous.getFoundDecl()->isTemplateParameter()) {
13770     // Maybe we will complain about the shadowed template parameter.
13771     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
13772     // Just pretend that we didn't see the previous declaration.
13773     Previous.clear();
13774   }
13775 
13776   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
13777       DC->Equals(getStdNamespace())) {
13778     if (Name->isStr("bad_alloc")) {
13779       // This is a declaration of or a reference to "std::bad_alloc".
13780       isStdBadAlloc = true;
13781 
13782       // If std::bad_alloc has been implicitly declared (but made invisible to
13783       // name lookup), fill in this implicit declaration as the previous
13784       // declaration, so that the declarations get chained appropriately.
13785       if (Previous.empty() && StdBadAlloc)
13786         Previous.addDecl(getStdBadAlloc());
13787     } else if (Name->isStr("align_val_t")) {
13788       isStdAlignValT = true;
13789       if (Previous.empty() && StdAlignValT)
13790         Previous.addDecl(getStdAlignValT());
13791     }
13792   }
13793 
13794   // If we didn't find a previous declaration, and this is a reference
13795   // (or friend reference), move to the correct scope.  In C++, we
13796   // also need to do a redeclaration lookup there, just in case
13797   // there's a shadow friend decl.
13798   if (Name && Previous.empty() &&
13799       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
13800     if (Invalid) goto CreateNewDecl;
13801     assert(SS.isEmpty());
13802 
13803     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
13804       // C++ [basic.scope.pdecl]p5:
13805       //   -- for an elaborated-type-specifier of the form
13806       //
13807       //          class-key identifier
13808       //
13809       //      if the elaborated-type-specifier is used in the
13810       //      decl-specifier-seq or parameter-declaration-clause of a
13811       //      function defined in namespace scope, the identifier is
13812       //      declared as a class-name in the namespace that contains
13813       //      the declaration; otherwise, except as a friend
13814       //      declaration, the identifier is declared in the smallest
13815       //      non-class, non-function-prototype scope that contains the
13816       //      declaration.
13817       //
13818       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
13819       // C structs and unions.
13820       //
13821       // It is an error in C++ to declare (rather than define) an enum
13822       // type, including via an elaborated type specifier.  We'll
13823       // diagnose that later; for now, declare the enum in the same
13824       // scope as we would have picked for any other tag type.
13825       //
13826       // GNU C also supports this behavior as part of its incomplete
13827       // enum types extension, while GNU C++ does not.
13828       //
13829       // Find the context where we'll be declaring the tag.
13830       // FIXME: We would like to maintain the current DeclContext as the
13831       // lexical context,
13832       SearchDC = getTagInjectionContext(SearchDC);
13833 
13834       // Find the scope where we'll be declaring the tag.
13835       S = getTagInjectionScope(S, getLangOpts());
13836     } else {
13837       assert(TUK == TUK_Friend);
13838       // C++ [namespace.memdef]p3:
13839       //   If a friend declaration in a non-local class first declares a
13840       //   class or function, the friend class or function is a member of
13841       //   the innermost enclosing namespace.
13842       SearchDC = SearchDC->getEnclosingNamespaceContext();
13843     }
13844 
13845     // In C++, we need to do a redeclaration lookup to properly
13846     // diagnose some problems.
13847     // FIXME: redeclaration lookup is also used (with and without C++) to find a
13848     // hidden declaration so that we don't get ambiguity errors when using a
13849     // type declared by an elaborated-type-specifier.  In C that is not correct
13850     // and we should instead merge compatible types found by lookup.
13851     if (getLangOpts().CPlusPlus) {
13852       Previous.setRedeclarationKind(forRedeclarationInCurContext());
13853       LookupQualifiedName(Previous, SearchDC);
13854     } else {
13855       Previous.setRedeclarationKind(forRedeclarationInCurContext());
13856       LookupName(Previous, S);
13857     }
13858   }
13859 
13860   // If we have a known previous declaration to use, then use it.
13861   if (Previous.empty() && SkipBody && SkipBody->Previous)
13862     Previous.addDecl(SkipBody->Previous);
13863 
13864   if (!Previous.empty()) {
13865     NamedDecl *PrevDecl = Previous.getFoundDecl();
13866     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13867 
13868     // It's okay to have a tag decl in the same scope as a typedef
13869     // which hides a tag decl in the same scope.  Finding this
13870     // insanity with a redeclaration lookup can only actually happen
13871     // in C++.
13872     //
13873     // This is also okay for elaborated-type-specifiers, which is
13874     // technically forbidden by the current standard but which is
13875     // okay according to the likely resolution of an open issue;
13876     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13877     if (getLangOpts().CPlusPlus) {
13878       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13879         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13880           TagDecl *Tag = TT->getDecl();
13881           if (Tag->getDeclName() == Name &&
13882               Tag->getDeclContext()->getRedeclContext()
13883                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
13884             PrevDecl = Tag;
13885             Previous.clear();
13886             Previous.addDecl(Tag);
13887             Previous.resolveKind();
13888           }
13889         }
13890       }
13891     }
13892 
13893     // If this is a redeclaration of a using shadow declaration, it must
13894     // declare a tag in the same context. In MSVC mode, we allow a
13895     // redefinition if either context is within the other.
13896     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13897       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13898       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13899           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
13900           !(OldTag && isAcceptableTagRedeclContext(
13901                           *this, OldTag->getDeclContext(), SearchDC))) {
13902         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13903         Diag(Shadow->getTargetDecl()->getLocation(),
13904              diag::note_using_decl_target);
13905         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13906             << 0;
13907         // Recover by ignoring the old declaration.
13908         Previous.clear();
13909         goto CreateNewDecl;
13910       }
13911     }
13912 
13913     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13914       // If this is a use of a previous tag, or if the tag is already declared
13915       // in the same scope (so that the definition/declaration completes or
13916       // rementions the tag), reuse the decl.
13917       if (TUK == TUK_Reference || TUK == TUK_Friend ||
13918           isDeclInScope(DirectPrevDecl, SearchDC, S,
13919                         SS.isNotEmpty() || isMemberSpecialization)) {
13920         // Make sure that this wasn't declared as an enum and now used as a
13921         // struct or something similar.
13922         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13923                                           TUK == TUK_Definition, KWLoc,
13924                                           Name)) {
13925           bool SafeToContinue
13926             = (PrevTagDecl->getTagKind() != TTK_Enum &&
13927                Kind != TTK_Enum);
13928           if (SafeToContinue)
13929             Diag(KWLoc, diag::err_use_with_wrong_tag)
13930               << Name
13931               << FixItHint::CreateReplacement(SourceRange(KWLoc),
13932                                               PrevTagDecl->getKindName());
13933           else
13934             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13935           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13936 
13937           if (SafeToContinue)
13938             Kind = PrevTagDecl->getTagKind();
13939           else {
13940             // Recover by making this an anonymous redefinition.
13941             Name = nullptr;
13942             Previous.clear();
13943             Invalid = true;
13944           }
13945         }
13946 
13947         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
13948           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
13949 
13950           // If this is an elaborated-type-specifier for a scoped enumeration,
13951           // the 'class' keyword is not necessary and not permitted.
13952           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13953             if (ScopedEnum)
13954               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
13955                 << PrevEnum->isScoped()
13956                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
13957             return PrevTagDecl;
13958           }
13959 
13960           QualType EnumUnderlyingTy;
13961           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13962             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
13963           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
13964             EnumUnderlyingTy = QualType(T, 0);
13965 
13966           // All conflicts with previous declarations are recovered by
13967           // returning the previous declaration, unless this is a definition,
13968           // in which case we want the caller to bail out.
13969           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
13970                                      ScopedEnum, EnumUnderlyingTy,
13971                                      IsFixed, PrevEnum))
13972             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
13973         }
13974 
13975         // C++11 [class.mem]p1:
13976         //   A member shall not be declared twice in the member-specification,
13977         //   except that a nested class or member class template can be declared
13978         //   and then later defined.
13979         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
13980             S->isDeclScope(PrevDecl)) {
13981           Diag(NameLoc, diag::ext_member_redeclared);
13982           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
13983         }
13984 
13985         if (!Invalid) {
13986           // If this is a use, just return the declaration we found, unless
13987           // we have attributes.
13988           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13989             if (Attr) {
13990               // FIXME: Diagnose these attributes. For now, we create a new
13991               // declaration to hold them.
13992             } else if (TUK == TUK_Reference &&
13993                        (PrevTagDecl->getFriendObjectKind() ==
13994                             Decl::FOK_Undeclared ||
13995                         PrevDecl->getOwningModule() != getCurrentModule()) &&
13996                        SS.isEmpty()) {
13997               // This declaration is a reference to an existing entity, but
13998               // has different visibility from that entity: it either makes
13999               // a friend visible or it makes a type visible in a new module.
14000               // In either case, create a new declaration. We only do this if
14001               // the declaration would have meant the same thing if no prior
14002               // declaration were found, that is, if it was found in the same
14003               // scope where we would have injected a declaration.
14004               if (!getTagInjectionContext(CurContext)->getRedeclContext()
14005                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
14006                 return PrevTagDecl;
14007               // This is in the injected scope, create a new declaration in
14008               // that scope.
14009               S = getTagInjectionScope(S, getLangOpts());
14010             } else {
14011               return PrevTagDecl;
14012             }
14013           }
14014 
14015           // Diagnose attempts to redefine a tag.
14016           if (TUK == TUK_Definition) {
14017             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
14018               // If we're defining a specialization and the previous definition
14019               // is from an implicit instantiation, don't emit an error
14020               // here; we'll catch this in the general case below.
14021               bool IsExplicitSpecializationAfterInstantiation = false;
14022               if (isMemberSpecialization) {
14023                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
14024                   IsExplicitSpecializationAfterInstantiation =
14025                     RD->getTemplateSpecializationKind() !=
14026                     TSK_ExplicitSpecialization;
14027                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
14028                   IsExplicitSpecializationAfterInstantiation =
14029                     ED->getTemplateSpecializationKind() !=
14030                     TSK_ExplicitSpecialization;
14031               }
14032 
14033               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
14034               // not keep more that one definition around (merge them). However,
14035               // ensure the decl passes the structural compatibility check in
14036               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
14037               NamedDecl *Hidden = nullptr;
14038               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
14039                 // There is a definition of this tag, but it is not visible. We
14040                 // explicitly make use of C++'s one definition rule here, and
14041                 // assume that this definition is identical to the hidden one
14042                 // we already have. Make the existing definition visible and
14043                 // use it in place of this one.
14044                 if (!getLangOpts().CPlusPlus) {
14045                   // Postpone making the old definition visible until after we
14046                   // complete parsing the new one and do the structural
14047                   // comparison.
14048                   SkipBody->CheckSameAsPrevious = true;
14049                   SkipBody->New = createTagFromNewDecl();
14050                   SkipBody->Previous = Hidden;
14051                 } else {
14052                   SkipBody->ShouldSkip = true;
14053                   makeMergedDefinitionVisible(Hidden);
14054                 }
14055                 return Def;
14056               } else if (!IsExplicitSpecializationAfterInstantiation) {
14057                 // A redeclaration in function prototype scope in C isn't
14058                 // visible elsewhere, so merely issue a warning.
14059                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
14060                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
14061                 else
14062                   Diag(NameLoc, diag::err_redefinition) << Name;
14063                 notePreviousDefinition(Def,
14064                                        NameLoc.isValid() ? NameLoc : KWLoc);
14065                 // If this is a redefinition, recover by making this
14066                 // struct be anonymous, which will make any later
14067                 // references get the previous definition.
14068                 Name = nullptr;
14069                 Previous.clear();
14070                 Invalid = true;
14071               }
14072             } else {
14073               // If the type is currently being defined, complain
14074               // about a nested redefinition.
14075               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
14076               if (TD->isBeingDefined()) {
14077                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
14078                 Diag(PrevTagDecl->getLocation(),
14079                      diag::note_previous_definition);
14080                 Name = nullptr;
14081                 Previous.clear();
14082                 Invalid = true;
14083               }
14084             }
14085 
14086             // Okay, this is definition of a previously declared or referenced
14087             // tag. We're going to create a new Decl for it.
14088           }
14089 
14090           // Okay, we're going to make a redeclaration.  If this is some kind
14091           // of reference, make sure we build the redeclaration in the same DC
14092           // as the original, and ignore the current access specifier.
14093           if (TUK == TUK_Friend || TUK == TUK_Reference) {
14094             SearchDC = PrevTagDecl->getDeclContext();
14095             AS = AS_none;
14096           }
14097         }
14098         // If we get here we have (another) forward declaration or we
14099         // have a definition.  Just create a new decl.
14100 
14101       } else {
14102         // If we get here, this is a definition of a new tag type in a nested
14103         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
14104         // new decl/type.  We set PrevDecl to NULL so that the entities
14105         // have distinct types.
14106         Previous.clear();
14107       }
14108       // If we get here, we're going to create a new Decl. If PrevDecl
14109       // is non-NULL, it's a definition of the tag declared by
14110       // PrevDecl. If it's NULL, we have a new definition.
14111 
14112     // Otherwise, PrevDecl is not a tag, but was found with tag
14113     // lookup.  This is only actually possible in C++, where a few
14114     // things like templates still live in the tag namespace.
14115     } else {
14116       // Use a better diagnostic if an elaborated-type-specifier
14117       // found the wrong kind of type on the first
14118       // (non-redeclaration) lookup.
14119       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
14120           !Previous.isForRedeclaration()) {
14121         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14122         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
14123                                                        << Kind;
14124         Diag(PrevDecl->getLocation(), diag::note_declared_at);
14125         Invalid = true;
14126 
14127       // Otherwise, only diagnose if the declaration is in scope.
14128       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
14129                                 SS.isNotEmpty() || isMemberSpecialization)) {
14130         // do nothing
14131 
14132       // Diagnose implicit declarations introduced by elaborated types.
14133       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
14134         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14135         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
14136         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14137         Invalid = true;
14138 
14139       // Otherwise it's a declaration.  Call out a particularly common
14140       // case here.
14141       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14142         unsigned Kind = 0;
14143         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
14144         Diag(NameLoc, diag::err_tag_definition_of_typedef)
14145           << Name << Kind << TND->getUnderlyingType();
14146         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14147         Invalid = true;
14148 
14149       // Otherwise, diagnose.
14150       } else {
14151         // The tag name clashes with something else in the target scope,
14152         // issue an error and recover by making this tag be anonymous.
14153         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
14154         notePreviousDefinition(PrevDecl, NameLoc);
14155         Name = nullptr;
14156         Invalid = true;
14157       }
14158 
14159       // The existing declaration isn't relevant to us; we're in a
14160       // new scope, so clear out the previous declaration.
14161       Previous.clear();
14162     }
14163   }
14164 
14165 CreateNewDecl:
14166 
14167   TagDecl *PrevDecl = nullptr;
14168   if (Previous.isSingleResult())
14169     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
14170 
14171   // If there is an identifier, use the location of the identifier as the
14172   // location of the decl, otherwise use the location of the struct/union
14173   // keyword.
14174   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14175 
14176   // Otherwise, create a new declaration. If there is a previous
14177   // declaration of the same entity, the two will be linked via
14178   // PrevDecl.
14179   TagDecl *New;
14180 
14181   bool IsForwardReference = false;
14182   if (Kind == TTK_Enum) {
14183     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14184     // enum X { A, B, C } D;    D should chain to X.
14185     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
14186                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
14187                            ScopedEnumUsesClassTag, IsFixed);
14188 
14189     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
14190       StdAlignValT = cast<EnumDecl>(New);
14191 
14192     // If this is an undefined enum, warn.
14193     if (TUK != TUK_Definition && !Invalid) {
14194       TagDecl *Def;
14195       if (IsFixed && (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
14196           cast<EnumDecl>(New)->isFixed()) {
14197         // C++0x: 7.2p2: opaque-enum-declaration.
14198         // Conflicts are diagnosed above. Do nothing.
14199       }
14200       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
14201         Diag(Loc, diag::ext_forward_ref_enum_def)
14202           << New;
14203         Diag(Def->getLocation(), diag::note_previous_definition);
14204       } else {
14205         unsigned DiagID = diag::ext_forward_ref_enum;
14206         if (getLangOpts().MSVCCompat)
14207           DiagID = diag::ext_ms_forward_ref_enum;
14208         else if (getLangOpts().CPlusPlus)
14209           DiagID = diag::err_forward_ref_enum;
14210         Diag(Loc, DiagID);
14211 
14212         // If this is a forward-declared reference to an enumeration, make a
14213         // note of it; we won't actually be introducing the declaration into
14214         // the declaration context.
14215         if (TUK == TUK_Reference)
14216           IsForwardReference = true;
14217       }
14218     }
14219 
14220     if (EnumUnderlying) {
14221       EnumDecl *ED = cast<EnumDecl>(New);
14222       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14223         ED->setIntegerTypeSourceInfo(TI);
14224       else
14225         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
14226       ED->setPromotionType(ED->getIntegerType());
14227       assert(ED->isComplete() && "enum with type should be complete");
14228     }
14229   } else {
14230     // struct/union/class
14231 
14232     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14233     // struct X { int A; } D;    D should chain to X.
14234     if (getLangOpts().CPlusPlus) {
14235       // FIXME: Look for a way to use RecordDecl for simple structs.
14236       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14237                                   cast_or_null<CXXRecordDecl>(PrevDecl));
14238 
14239       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
14240         StdBadAlloc = cast<CXXRecordDecl>(New);
14241     } else
14242       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14243                                cast_or_null<RecordDecl>(PrevDecl));
14244   }
14245 
14246   // C++11 [dcl.type]p3:
14247   //   A type-specifier-seq shall not define a class or enumeration [...].
14248   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
14249       TUK == TUK_Definition) {
14250     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
14251       << Context.getTagDeclType(New);
14252     Invalid = true;
14253   }
14254 
14255   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
14256       DC->getDeclKind() == Decl::Enum) {
14257     Diag(New->getLocation(), diag::err_type_defined_in_enum)
14258       << Context.getTagDeclType(New);
14259     Invalid = true;
14260   }
14261 
14262   // Maybe add qualifier info.
14263   if (SS.isNotEmpty()) {
14264     if (SS.isSet()) {
14265       // If this is either a declaration or a definition, check the
14266       // nested-name-specifier against the current context. We don't do this
14267       // for explicit specializations, because they have similar checking
14268       // (with more specific diagnostics) in the call to
14269       // CheckMemberSpecialization, below.
14270       if (!isMemberSpecialization &&
14271           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
14272           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
14273         Invalid = true;
14274 
14275       New->setQualifierInfo(SS.getWithLocInContext(Context));
14276       if (TemplateParameterLists.size() > 0) {
14277         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
14278       }
14279     }
14280     else
14281       Invalid = true;
14282   }
14283 
14284   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14285     // Add alignment attributes if necessary; these attributes are checked when
14286     // the ASTContext lays out the structure.
14287     //
14288     // It is important for implementing the correct semantics that this
14289     // happen here (in ActOnTag). The #pragma pack stack is
14290     // maintained as a result of parser callbacks which can occur at
14291     // many points during the parsing of a struct declaration (because
14292     // the #pragma tokens are effectively skipped over during the
14293     // parsing of the struct).
14294     if (TUK == TUK_Definition) {
14295       AddAlignmentAttributesForRecord(RD);
14296       AddMsStructLayoutForRecord(RD);
14297     }
14298   }
14299 
14300   if (ModulePrivateLoc.isValid()) {
14301     if (isMemberSpecialization)
14302       Diag(New->getLocation(), diag::err_module_private_specialization)
14303         << 2
14304         << FixItHint::CreateRemoval(ModulePrivateLoc);
14305     // __module_private__ does not apply to local classes. However, we only
14306     // diagnose this as an error when the declaration specifiers are
14307     // freestanding. Here, we just ignore the __module_private__.
14308     else if (!SearchDC->isFunctionOrMethod())
14309       New->setModulePrivate();
14310   }
14311 
14312   // If this is a specialization of a member class (of a class template),
14313   // check the specialization.
14314   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
14315     Invalid = true;
14316 
14317   // If we're declaring or defining a tag in function prototype scope in C,
14318   // note that this type can only be used within the function and add it to
14319   // the list of decls to inject into the function definition scope.
14320   if ((Name || Kind == TTK_Enum) &&
14321       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
14322     if (getLangOpts().CPlusPlus) {
14323       // C++ [dcl.fct]p6:
14324       //   Types shall not be defined in return or parameter types.
14325       if (TUK == TUK_Definition && !IsTypeSpecifier) {
14326         Diag(Loc, diag::err_type_defined_in_param_type)
14327             << Name;
14328         Invalid = true;
14329       }
14330     } else if (!PrevDecl) {
14331       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
14332     }
14333   }
14334 
14335   if (Invalid)
14336     New->setInvalidDecl();
14337 
14338   // Set the lexical context. If the tag has a C++ scope specifier, the
14339   // lexical context will be different from the semantic context.
14340   New->setLexicalDeclContext(CurContext);
14341 
14342   // Mark this as a friend decl if applicable.
14343   // In Microsoft mode, a friend declaration also acts as a forward
14344   // declaration so we always pass true to setObjectOfFriendDecl to make
14345   // the tag name visible.
14346   if (TUK == TUK_Friend)
14347     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
14348 
14349   // Set the access specifier.
14350   if (!Invalid && SearchDC->isRecord())
14351     SetMemberAccessSpecifier(New, PrevDecl, AS);
14352 
14353   if (PrevDecl)
14354     CheckRedeclarationModuleOwnership(New, PrevDecl);
14355 
14356   if (TUK == TUK_Definition)
14357     New->startDefinition();
14358 
14359   if (Attr)
14360     ProcessDeclAttributeList(S, New, Attr);
14361   AddPragmaAttributes(S, New);
14362 
14363   // If this has an identifier, add it to the scope stack.
14364   if (TUK == TUK_Friend) {
14365     // We might be replacing an existing declaration in the lookup tables;
14366     // if so, borrow its access specifier.
14367     if (PrevDecl)
14368       New->setAccess(PrevDecl->getAccess());
14369 
14370     DeclContext *DC = New->getDeclContext()->getRedeclContext();
14371     DC->makeDeclVisibleInContext(New);
14372     if (Name) // can be null along some error paths
14373       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14374         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
14375   } else if (Name) {
14376     S = getNonFieldDeclScope(S);
14377     PushOnScopeChains(New, S, !IsForwardReference);
14378     if (IsForwardReference)
14379       SearchDC->makeDeclVisibleInContext(New);
14380   } else {
14381     CurContext->addDecl(New);
14382   }
14383 
14384   // If this is the C FILE type, notify the AST context.
14385   if (IdentifierInfo *II = New->getIdentifier())
14386     if (!New->isInvalidDecl() &&
14387         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
14388         II->isStr("FILE"))
14389       Context.setFILEDecl(New);
14390 
14391   if (PrevDecl)
14392     mergeDeclAttributes(New, PrevDecl);
14393 
14394   // If there's a #pragma GCC visibility in scope, set the visibility of this
14395   // record.
14396   AddPushedVisibilityAttribute(New);
14397 
14398   if (isMemberSpecialization && !New->isInvalidDecl())
14399     CompleteMemberSpecialization(New, Previous);
14400 
14401   OwnedDecl = true;
14402   // In C++, don't return an invalid declaration. We can't recover well from
14403   // the cases where we make the type anonymous.
14404   if (Invalid && getLangOpts().CPlusPlus) {
14405     if (New->isBeingDefined())
14406       if (auto RD = dyn_cast<RecordDecl>(New))
14407         RD->completeDefinition();
14408     return nullptr;
14409   } else {
14410     return New;
14411   }
14412 }
14413 
14414 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
14415   AdjustDeclIfTemplate(TagD);
14416   TagDecl *Tag = cast<TagDecl>(TagD);
14417 
14418   // Enter the tag context.
14419   PushDeclContext(S, Tag);
14420 
14421   ActOnDocumentableDecl(TagD);
14422 
14423   // If there's a #pragma GCC visibility in scope, set the visibility of this
14424   // record.
14425   AddPushedVisibilityAttribute(Tag);
14426 }
14427 
14428 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
14429                                     SkipBodyInfo &SkipBody) {
14430   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
14431     return false;
14432 
14433   // Make the previous decl visible.
14434   makeMergedDefinitionVisible(SkipBody.Previous);
14435   return true;
14436 }
14437 
14438 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
14439   assert(isa<ObjCContainerDecl>(IDecl) &&
14440          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
14441   DeclContext *OCD = cast<DeclContext>(IDecl);
14442   assert(getContainingDC(OCD) == CurContext &&
14443       "The next DeclContext should be lexically contained in the current one.");
14444   CurContext = OCD;
14445   return IDecl;
14446 }
14447 
14448 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
14449                                            SourceLocation FinalLoc,
14450                                            bool IsFinalSpelledSealed,
14451                                            SourceLocation LBraceLoc) {
14452   AdjustDeclIfTemplate(TagD);
14453   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
14454 
14455   FieldCollector->StartClass();
14456 
14457   if (!Record->getIdentifier())
14458     return;
14459 
14460   if (FinalLoc.isValid())
14461     Record->addAttr(new (Context)
14462                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
14463 
14464   // C++ [class]p2:
14465   //   [...] The class-name is also inserted into the scope of the
14466   //   class itself; this is known as the injected-class-name. For
14467   //   purposes of access checking, the injected-class-name is treated
14468   //   as if it were a public member name.
14469   CXXRecordDecl *InjectedClassName
14470     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
14471                             Record->getLocStart(), Record->getLocation(),
14472                             Record->getIdentifier(),
14473                             /*PrevDecl=*/nullptr,
14474                             /*DelayTypeCreation=*/true);
14475   Context.getTypeDeclType(InjectedClassName, Record);
14476   InjectedClassName->setImplicit();
14477   InjectedClassName->setAccess(AS_public);
14478   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
14479       InjectedClassName->setDescribedClassTemplate(Template);
14480   PushOnScopeChains(InjectedClassName, S);
14481   assert(InjectedClassName->isInjectedClassName() &&
14482          "Broken injected-class-name");
14483 }
14484 
14485 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
14486                                     SourceRange BraceRange) {
14487   AdjustDeclIfTemplate(TagD);
14488   TagDecl *Tag = cast<TagDecl>(TagD);
14489   Tag->setBraceRange(BraceRange);
14490 
14491   // Make sure we "complete" the definition even it is invalid.
14492   if (Tag->isBeingDefined()) {
14493     assert(Tag->isInvalidDecl() && "We should already have completed it");
14494     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14495       RD->completeDefinition();
14496   }
14497 
14498   if (isa<CXXRecordDecl>(Tag)) {
14499     FieldCollector->FinishClass();
14500   }
14501 
14502   // Exit this scope of this tag's definition.
14503   PopDeclContext();
14504 
14505   if (getCurLexicalContext()->isObjCContainer() &&
14506       Tag->getDeclContext()->isFileContext())
14507     Tag->setTopLevelDeclInObjCContainer();
14508 
14509   // Notify the consumer that we've defined a tag.
14510   if (!Tag->isInvalidDecl())
14511     Consumer.HandleTagDeclDefinition(Tag);
14512 }
14513 
14514 void Sema::ActOnObjCContainerFinishDefinition() {
14515   // Exit this scope of this interface definition.
14516   PopDeclContext();
14517 }
14518 
14519 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
14520   assert(DC == CurContext && "Mismatch of container contexts");
14521   OriginalLexicalContext = DC;
14522   ActOnObjCContainerFinishDefinition();
14523 }
14524 
14525 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
14526   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
14527   OriginalLexicalContext = nullptr;
14528 }
14529 
14530 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
14531   AdjustDeclIfTemplate(TagD);
14532   TagDecl *Tag = cast<TagDecl>(TagD);
14533   Tag->setInvalidDecl();
14534 
14535   // Make sure we "complete" the definition even it is invalid.
14536   if (Tag->isBeingDefined()) {
14537     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14538       RD->completeDefinition();
14539   }
14540 
14541   // We're undoing ActOnTagStartDefinition here, not
14542   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
14543   // the FieldCollector.
14544 
14545   PopDeclContext();
14546 }
14547 
14548 // Note that FieldName may be null for anonymous bitfields.
14549 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
14550                                 IdentifierInfo *FieldName,
14551                                 QualType FieldTy, bool IsMsStruct,
14552                                 Expr *BitWidth, bool *ZeroWidth) {
14553   // Default to true; that shouldn't confuse checks for emptiness
14554   if (ZeroWidth)
14555     *ZeroWidth = true;
14556 
14557   // C99 6.7.2.1p4 - verify the field type.
14558   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
14559   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
14560     // Handle incomplete types with specific error.
14561     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
14562       return ExprError();
14563     if (FieldName)
14564       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
14565         << FieldName << FieldTy << BitWidth->getSourceRange();
14566     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
14567       << FieldTy << BitWidth->getSourceRange();
14568   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
14569                                              UPPC_BitFieldWidth))
14570     return ExprError();
14571 
14572   // If the bit-width is type- or value-dependent, don't try to check
14573   // it now.
14574   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
14575     return BitWidth;
14576 
14577   llvm::APSInt Value;
14578   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
14579   if (ICE.isInvalid())
14580     return ICE;
14581   BitWidth = ICE.get();
14582 
14583   if (Value != 0 && ZeroWidth)
14584     *ZeroWidth = false;
14585 
14586   // Zero-width bitfield is ok for anonymous field.
14587   if (Value == 0 && FieldName)
14588     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
14589 
14590   if (Value.isSigned() && Value.isNegative()) {
14591     if (FieldName)
14592       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
14593                << FieldName << Value.toString(10);
14594     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
14595       << Value.toString(10);
14596   }
14597 
14598   if (!FieldTy->isDependentType()) {
14599     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
14600     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
14601     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
14602 
14603     // Over-wide bitfields are an error in C or when using the MSVC bitfield
14604     // ABI.
14605     bool CStdConstraintViolation =
14606         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
14607     bool MSBitfieldViolation =
14608         Value.ugt(TypeStorageSize) &&
14609         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
14610     if (CStdConstraintViolation || MSBitfieldViolation) {
14611       unsigned DiagWidth =
14612           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
14613       if (FieldName)
14614         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
14615                << FieldName << (unsigned)Value.getZExtValue()
14616                << !CStdConstraintViolation << DiagWidth;
14617 
14618       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
14619              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
14620              << DiagWidth;
14621     }
14622 
14623     // Warn on types where the user might conceivably expect to get all
14624     // specified bits as value bits: that's all integral types other than
14625     // 'bool'.
14626     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
14627       if (FieldName)
14628         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
14629             << FieldName << (unsigned)Value.getZExtValue()
14630             << (unsigned)TypeWidth;
14631       else
14632         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
14633             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
14634     }
14635   }
14636 
14637   return BitWidth;
14638 }
14639 
14640 /// ActOnField - Each field of a C struct/union is passed into this in order
14641 /// to create a FieldDecl object for it.
14642 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
14643                        Declarator &D, Expr *BitfieldWidth) {
14644   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
14645                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
14646                                /*InitStyle=*/ICIS_NoInit, AS_public);
14647   return Res;
14648 }
14649 
14650 /// HandleField - Analyze a field of a C struct or a C++ data member.
14651 ///
14652 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
14653                              SourceLocation DeclStart,
14654                              Declarator &D, Expr *BitWidth,
14655                              InClassInitStyle InitStyle,
14656                              AccessSpecifier AS) {
14657   if (D.isDecompositionDeclarator()) {
14658     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
14659     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
14660       << Decomp.getSourceRange();
14661     return nullptr;
14662   }
14663 
14664   IdentifierInfo *II = D.getIdentifier();
14665   SourceLocation Loc = DeclStart;
14666   if (II) Loc = D.getIdentifierLoc();
14667 
14668   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14669   QualType T = TInfo->getType();
14670   if (getLangOpts().CPlusPlus) {
14671     CheckExtraCXXDefaultArguments(D);
14672 
14673     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14674                                         UPPC_DataMemberType)) {
14675       D.setInvalidType();
14676       T = Context.IntTy;
14677       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14678     }
14679   }
14680 
14681   // TR 18037 does not allow fields to be declared with address spaces.
14682   if (T.getQualifiers().hasAddressSpace() ||
14683       T->isDependentAddressSpaceType() ||
14684       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
14685     Diag(Loc, diag::err_field_with_address_space);
14686     D.setInvalidType();
14687   }
14688 
14689   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
14690   // used as structure or union field: image, sampler, event or block types.
14691   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
14692                           T->isSamplerT() || T->isBlockPointerType())) {
14693     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
14694     D.setInvalidType();
14695   }
14696 
14697   DiagnoseFunctionSpecifiers(D.getDeclSpec());
14698 
14699   if (D.getDeclSpec().isInlineSpecified())
14700     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14701         << getLangOpts().CPlusPlus17;
14702   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14703     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14704          diag::err_invalid_thread)
14705       << DeclSpec::getSpecifierName(TSCS);
14706 
14707   // Check to see if this name was declared as a member previously
14708   NamedDecl *PrevDecl = nullptr;
14709   LookupResult Previous(*this, II, Loc, LookupMemberName,
14710                         ForVisibleRedeclaration);
14711   LookupName(Previous, S);
14712   switch (Previous.getResultKind()) {
14713     case LookupResult::Found:
14714     case LookupResult::FoundUnresolvedValue:
14715       PrevDecl = Previous.getAsSingle<NamedDecl>();
14716       break;
14717 
14718     case LookupResult::FoundOverloaded:
14719       PrevDecl = Previous.getRepresentativeDecl();
14720       break;
14721 
14722     case LookupResult::NotFound:
14723     case LookupResult::NotFoundInCurrentInstantiation:
14724     case LookupResult::Ambiguous:
14725       break;
14726   }
14727   Previous.suppressDiagnostics();
14728 
14729   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14730     // Maybe we will complain about the shadowed template parameter.
14731     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14732     // Just pretend that we didn't see the previous declaration.
14733     PrevDecl = nullptr;
14734   }
14735 
14736   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14737     PrevDecl = nullptr;
14738 
14739   bool Mutable
14740     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
14741   SourceLocation TSSL = D.getLocStart();
14742   FieldDecl *NewFD
14743     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
14744                      TSSL, AS, PrevDecl, &D);
14745 
14746   if (NewFD->isInvalidDecl())
14747     Record->setInvalidDecl();
14748 
14749   if (D.getDeclSpec().isModulePrivateSpecified())
14750     NewFD->setModulePrivate();
14751 
14752   if (NewFD->isInvalidDecl() && PrevDecl) {
14753     // Don't introduce NewFD into scope; there's already something
14754     // with the same name in the same scope.
14755   } else if (II) {
14756     PushOnScopeChains(NewFD, S);
14757   } else
14758     Record->addDecl(NewFD);
14759 
14760   return NewFD;
14761 }
14762 
14763 /// \brief Build a new FieldDecl and check its well-formedness.
14764 ///
14765 /// This routine builds a new FieldDecl given the fields name, type,
14766 /// record, etc. \p PrevDecl should refer to any previous declaration
14767 /// with the same name and in the same scope as the field to be
14768 /// created.
14769 ///
14770 /// \returns a new FieldDecl.
14771 ///
14772 /// \todo The Declarator argument is a hack. It will be removed once
14773 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
14774                                 TypeSourceInfo *TInfo,
14775                                 RecordDecl *Record, SourceLocation Loc,
14776                                 bool Mutable, Expr *BitWidth,
14777                                 InClassInitStyle InitStyle,
14778                                 SourceLocation TSSL,
14779                                 AccessSpecifier AS, NamedDecl *PrevDecl,
14780                                 Declarator *D) {
14781   IdentifierInfo *II = Name.getAsIdentifierInfo();
14782   bool InvalidDecl = false;
14783   if (D) InvalidDecl = D->isInvalidType();
14784 
14785   // If we receive a broken type, recover by assuming 'int' and
14786   // marking this declaration as invalid.
14787   if (T.isNull()) {
14788     InvalidDecl = true;
14789     T = Context.IntTy;
14790   }
14791 
14792   QualType EltTy = Context.getBaseElementType(T);
14793   if (!EltTy->isDependentType()) {
14794     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
14795       // Fields of incomplete type force their record to be invalid.
14796       Record->setInvalidDecl();
14797       InvalidDecl = true;
14798     } else {
14799       NamedDecl *Def;
14800       EltTy->isIncompleteType(&Def);
14801       if (Def && Def->isInvalidDecl()) {
14802         Record->setInvalidDecl();
14803         InvalidDecl = true;
14804       }
14805     }
14806   }
14807 
14808   // OpenCL v1.2 s6.9.c: bitfields are not supported.
14809   if (BitWidth && getLangOpts().OpenCL) {
14810     Diag(Loc, diag::err_opencl_bitfields);
14811     InvalidDecl = true;
14812   }
14813 
14814   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14815   // than a variably modified type.
14816   if (!InvalidDecl && T->isVariablyModifiedType()) {
14817     bool SizeIsNegative;
14818     llvm::APSInt Oversized;
14819 
14820     TypeSourceInfo *FixedTInfo =
14821       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
14822                                                     SizeIsNegative,
14823                                                     Oversized);
14824     if (FixedTInfo) {
14825       Diag(Loc, diag::warn_illegal_constant_array_size);
14826       TInfo = FixedTInfo;
14827       T = FixedTInfo->getType();
14828     } else {
14829       if (SizeIsNegative)
14830         Diag(Loc, diag::err_typecheck_negative_array_size);
14831       else if (Oversized.getBoolValue())
14832         Diag(Loc, diag::err_array_too_large)
14833           << Oversized.toString(10);
14834       else
14835         Diag(Loc, diag::err_typecheck_field_variable_size);
14836       InvalidDecl = true;
14837     }
14838   }
14839 
14840   // Fields can not have abstract class types
14841   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
14842                                              diag::err_abstract_type_in_decl,
14843                                              AbstractFieldType))
14844     InvalidDecl = true;
14845 
14846   bool ZeroWidth = false;
14847   if (InvalidDecl)
14848     BitWidth = nullptr;
14849   // If this is declared as a bit-field, check the bit-field.
14850   if (BitWidth) {
14851     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
14852                               &ZeroWidth).get();
14853     if (!BitWidth) {
14854       InvalidDecl = true;
14855       BitWidth = nullptr;
14856       ZeroWidth = false;
14857     }
14858   }
14859 
14860   // Check that 'mutable' is consistent with the type of the declaration.
14861   if (!InvalidDecl && Mutable) {
14862     unsigned DiagID = 0;
14863     if (T->isReferenceType())
14864       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
14865                                         : diag::err_mutable_reference;
14866     else if (T.isConstQualified())
14867       DiagID = diag::err_mutable_const;
14868 
14869     if (DiagID) {
14870       SourceLocation ErrLoc = Loc;
14871       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
14872         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
14873       Diag(ErrLoc, DiagID);
14874       if (DiagID != diag::ext_mutable_reference) {
14875         Mutable = false;
14876         InvalidDecl = true;
14877       }
14878     }
14879   }
14880 
14881   // C++11 [class.union]p8 (DR1460):
14882   //   At most one variant member of a union may have a
14883   //   brace-or-equal-initializer.
14884   if (InitStyle != ICIS_NoInit)
14885     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14886 
14887   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14888                                        BitWidth, Mutable, InitStyle);
14889   if (InvalidDecl)
14890     NewFD->setInvalidDecl();
14891 
14892   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14893     Diag(Loc, diag::err_duplicate_member) << II;
14894     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14895     NewFD->setInvalidDecl();
14896   }
14897 
14898   if (!InvalidDecl && getLangOpts().CPlusPlus) {
14899     if (Record->isUnion()) {
14900       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14901         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14902         if (RDecl->getDefinition()) {
14903           // C++ [class.union]p1: An object of a class with a non-trivial
14904           // constructor, a non-trivial copy constructor, a non-trivial
14905           // destructor, or a non-trivial copy assignment operator
14906           // cannot be a member of a union, nor can an array of such
14907           // objects.
14908           if (CheckNontrivialField(NewFD))
14909             NewFD->setInvalidDecl();
14910         }
14911       }
14912 
14913       // C++ [class.union]p1: If a union contains a member of reference type,
14914       // the program is ill-formed, except when compiling with MSVC extensions
14915       // enabled.
14916       if (EltTy->isReferenceType()) {
14917         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14918                                     diag::ext_union_member_of_reference_type :
14919                                     diag::err_union_member_of_reference_type)
14920           << NewFD->getDeclName() << EltTy;
14921         if (!getLangOpts().MicrosoftExt)
14922           NewFD->setInvalidDecl();
14923       }
14924     }
14925   }
14926 
14927   // FIXME: We need to pass in the attributes given an AST
14928   // representation, not a parser representation.
14929   if (D) {
14930     // FIXME: The current scope is almost... but not entirely... correct here.
14931     ProcessDeclAttributes(getCurScope(), NewFD, *D);
14932 
14933     if (NewFD->hasAttrs())
14934       CheckAlignasUnderalignment(NewFD);
14935   }
14936 
14937   // In auto-retain/release, infer strong retension for fields of
14938   // retainable type.
14939   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
14940     NewFD->setInvalidDecl();
14941 
14942   if (T.isObjCGCWeak())
14943     Diag(Loc, diag::warn_attribute_weak_on_field);
14944 
14945   NewFD->setAccess(AS);
14946   return NewFD;
14947 }
14948 
14949 bool Sema::CheckNontrivialField(FieldDecl *FD) {
14950   assert(FD);
14951   assert(getLangOpts().CPlusPlus && "valid check only for C++");
14952 
14953   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
14954     return false;
14955 
14956   QualType EltTy = Context.getBaseElementType(FD->getType());
14957   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14958     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
14959     if (RDecl->getDefinition()) {
14960       // We check for copy constructors before constructors
14961       // because otherwise we'll never get complaints about
14962       // copy constructors.
14963 
14964       CXXSpecialMember member = CXXInvalid;
14965       // We're required to check for any non-trivial constructors. Since the
14966       // implicit default constructor is suppressed if there are any
14967       // user-declared constructors, we just need to check that there is a
14968       // trivial default constructor and a trivial copy constructor. (We don't
14969       // worry about move constructors here, since this is a C++98 check.)
14970       if (RDecl->hasNonTrivialCopyConstructor())
14971         member = CXXCopyConstructor;
14972       else if (!RDecl->hasTrivialDefaultConstructor())
14973         member = CXXDefaultConstructor;
14974       else if (RDecl->hasNonTrivialCopyAssignment())
14975         member = CXXCopyAssignment;
14976       else if (RDecl->hasNonTrivialDestructor())
14977         member = CXXDestructor;
14978 
14979       if (member != CXXInvalid) {
14980         if (!getLangOpts().CPlusPlus11 &&
14981             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
14982           // Objective-C++ ARC: it is an error to have a non-trivial field of
14983           // a union. However, system headers in Objective-C programs
14984           // occasionally have Objective-C lifetime objects within unions,
14985           // and rather than cause the program to fail, we make those
14986           // members unavailable.
14987           SourceLocation Loc = FD->getLocation();
14988           if (getSourceManager().isInSystemHeader(Loc)) {
14989             if (!FD->hasAttr<UnavailableAttr>())
14990               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14991                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
14992             return false;
14993           }
14994         }
14995 
14996         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
14997                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
14998                diag::err_illegal_union_or_anon_struct_member)
14999           << FD->getParent()->isUnion() << FD->getDeclName() << member;
15000         DiagnoseNontrivial(RDecl, member);
15001         return !getLangOpts().CPlusPlus11;
15002       }
15003     }
15004   }
15005 
15006   return false;
15007 }
15008 
15009 /// TranslateIvarVisibility - Translate visibility from a token ID to an
15010 ///  AST enum value.
15011 static ObjCIvarDecl::AccessControl
15012 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
15013   switch (ivarVisibility) {
15014   default: llvm_unreachable("Unknown visitibility kind");
15015   case tok::objc_private: return ObjCIvarDecl::Private;
15016   case tok::objc_public: return ObjCIvarDecl::Public;
15017   case tok::objc_protected: return ObjCIvarDecl::Protected;
15018   case tok::objc_package: return ObjCIvarDecl::Package;
15019   }
15020 }
15021 
15022 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
15023 /// in order to create an IvarDecl object for it.
15024 Decl *Sema::ActOnIvar(Scope *S,
15025                                 SourceLocation DeclStart,
15026                                 Declarator &D, Expr *BitfieldWidth,
15027                                 tok::ObjCKeywordKind Visibility) {
15028 
15029   IdentifierInfo *II = D.getIdentifier();
15030   Expr *BitWidth = (Expr*)BitfieldWidth;
15031   SourceLocation Loc = DeclStart;
15032   if (II) Loc = D.getIdentifierLoc();
15033 
15034   // FIXME: Unnamed fields can be handled in various different ways, for
15035   // example, unnamed unions inject all members into the struct namespace!
15036 
15037   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15038   QualType T = TInfo->getType();
15039 
15040   if (BitWidth) {
15041     // 6.7.2.1p3, 6.7.2.1p4
15042     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
15043     if (!BitWidth)
15044       D.setInvalidType();
15045   } else {
15046     // Not a bitfield.
15047 
15048     // validate II.
15049 
15050   }
15051   if (T->isReferenceType()) {
15052     Diag(Loc, diag::err_ivar_reference_type);
15053     D.setInvalidType();
15054   }
15055   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15056   // than a variably modified type.
15057   else if (T->isVariablyModifiedType()) {
15058     Diag(Loc, diag::err_typecheck_ivar_variable_size);
15059     D.setInvalidType();
15060   }
15061 
15062   // Get the visibility (access control) for this ivar.
15063   ObjCIvarDecl::AccessControl ac =
15064     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
15065                                         : ObjCIvarDecl::None;
15066   // Must set ivar's DeclContext to its enclosing interface.
15067   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
15068   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
15069     return nullptr;
15070   ObjCContainerDecl *EnclosingContext;
15071   if (ObjCImplementationDecl *IMPDecl =
15072       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15073     if (LangOpts.ObjCRuntime.isFragile()) {
15074     // Case of ivar declared in an implementation. Context is that of its class.
15075       EnclosingContext = IMPDecl->getClassInterface();
15076       assert(EnclosingContext && "Implementation has no class interface!");
15077     }
15078     else
15079       EnclosingContext = EnclosingDecl;
15080   } else {
15081     if (ObjCCategoryDecl *CDecl =
15082         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15083       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
15084         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
15085         return nullptr;
15086       }
15087     }
15088     EnclosingContext = EnclosingDecl;
15089   }
15090 
15091   // Construct the decl.
15092   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
15093                                              DeclStart, Loc, II, T,
15094                                              TInfo, ac, (Expr *)BitfieldWidth);
15095 
15096   if (II) {
15097     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
15098                                            ForVisibleRedeclaration);
15099     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
15100         && !isa<TagDecl>(PrevDecl)) {
15101       Diag(Loc, diag::err_duplicate_member) << II;
15102       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15103       NewID->setInvalidDecl();
15104     }
15105   }
15106 
15107   // Process attributes attached to the ivar.
15108   ProcessDeclAttributes(S, NewID, D);
15109 
15110   if (D.isInvalidType())
15111     NewID->setInvalidDecl();
15112 
15113   // In ARC, infer 'retaining' for ivars of retainable type.
15114   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
15115     NewID->setInvalidDecl();
15116 
15117   if (D.getDeclSpec().isModulePrivateSpecified())
15118     NewID->setModulePrivate();
15119 
15120   if (II) {
15121     // FIXME: When interfaces are DeclContexts, we'll need to add
15122     // these to the interface.
15123     S->AddDecl(NewID);
15124     IdResolver.AddDecl(NewID);
15125   }
15126 
15127   if (LangOpts.ObjCRuntime.isNonFragile() &&
15128       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
15129     Diag(Loc, diag::warn_ivars_in_interface);
15130 
15131   return NewID;
15132 }
15133 
15134 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
15135 /// class and class extensions. For every class \@interface and class
15136 /// extension \@interface, if the last ivar is a bitfield of any type,
15137 /// then add an implicit `char :0` ivar to the end of that interface.
15138 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
15139                              SmallVectorImpl<Decl *> &AllIvarDecls) {
15140   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
15141     return;
15142 
15143   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
15144   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
15145 
15146   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
15147     return;
15148   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
15149   if (!ID) {
15150     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
15151       if (!CD->IsClassExtension())
15152         return;
15153     }
15154     // No need to add this to end of @implementation.
15155     else
15156       return;
15157   }
15158   // All conditions are met. Add a new bitfield to the tail end of ivars.
15159   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
15160   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
15161 
15162   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
15163                               DeclLoc, DeclLoc, nullptr,
15164                               Context.CharTy,
15165                               Context.getTrivialTypeSourceInfo(Context.CharTy,
15166                                                                DeclLoc),
15167                               ObjCIvarDecl::Private, BW,
15168                               true);
15169   AllIvarDecls.push_back(Ivar);
15170 }
15171 
15172 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
15173                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
15174                        SourceLocation RBrac, AttributeList *Attr) {
15175   assert(EnclosingDecl && "missing record or interface decl");
15176 
15177   // If this is an Objective-C @implementation or category and we have
15178   // new fields here we should reset the layout of the interface since
15179   // it will now change.
15180   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
15181     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
15182     switch (DC->getKind()) {
15183     default: break;
15184     case Decl::ObjCCategory:
15185       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
15186       break;
15187     case Decl::ObjCImplementation:
15188       Context.
15189         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
15190       break;
15191     }
15192   }
15193 
15194   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
15195 
15196   // Start counting up the number of named members; make sure to include
15197   // members of anonymous structs and unions in the total.
15198   unsigned NumNamedMembers = 0;
15199   if (Record) {
15200     for (const auto *I : Record->decls()) {
15201       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
15202         if (IFD->getDeclName())
15203           ++NumNamedMembers;
15204     }
15205   }
15206 
15207   // Verify that all the fields are okay.
15208   SmallVector<FieldDecl*, 32> RecFields;
15209 
15210   bool ObjCFieldLifetimeErrReported = false;
15211   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
15212        i != end; ++i) {
15213     FieldDecl *FD = cast<FieldDecl>(*i);
15214 
15215     // Get the type for the field.
15216     const Type *FDTy = FD->getType().getTypePtr();
15217 
15218     if (!FD->isAnonymousStructOrUnion()) {
15219       // Remember all fields written by the user.
15220       RecFields.push_back(FD);
15221     }
15222 
15223     // If the field is already invalid for some reason, don't emit more
15224     // diagnostics about it.
15225     if (FD->isInvalidDecl()) {
15226       EnclosingDecl->setInvalidDecl();
15227       continue;
15228     }
15229 
15230     // C99 6.7.2.1p2:
15231     //   A structure or union shall not contain a member with
15232     //   incomplete or function type (hence, a structure shall not
15233     //   contain an instance of itself, but may contain a pointer to
15234     //   an instance of itself), except that the last member of a
15235     //   structure with more than one named member may have incomplete
15236     //   array type; such a structure (and any union containing,
15237     //   possibly recursively, a member that is such a structure)
15238     //   shall not be a member of a structure or an element of an
15239     //   array.
15240     bool IsLastField = (i + 1 == Fields.end());
15241     if (FDTy->isFunctionType()) {
15242       // Field declared as a function.
15243       Diag(FD->getLocation(), diag::err_field_declared_as_function)
15244         << FD->getDeclName();
15245       FD->setInvalidDecl();
15246       EnclosingDecl->setInvalidDecl();
15247       continue;
15248     } else if (FDTy->isIncompleteArrayType() &&
15249                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
15250       if (Record) {
15251         // Flexible array member.
15252         // Microsoft and g++ is more permissive regarding flexible array.
15253         // It will accept flexible array in union and also
15254         // as the sole element of a struct/class.
15255         unsigned DiagID = 0;
15256         if (!Record->isUnion() && !IsLastField) {
15257           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
15258             << FD->getDeclName() << FD->getType() << Record->getTagKind();
15259           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
15260           FD->setInvalidDecl();
15261           EnclosingDecl->setInvalidDecl();
15262           continue;
15263         } else if (Record->isUnion())
15264           DiagID = getLangOpts().MicrosoftExt
15265                        ? diag::ext_flexible_array_union_ms
15266                        : getLangOpts().CPlusPlus
15267                              ? diag::ext_flexible_array_union_gnu
15268                              : diag::err_flexible_array_union;
15269         else if (NumNamedMembers < 1)
15270           DiagID = getLangOpts().MicrosoftExt
15271                        ? diag::ext_flexible_array_empty_aggregate_ms
15272                        : getLangOpts().CPlusPlus
15273                              ? diag::ext_flexible_array_empty_aggregate_gnu
15274                              : diag::err_flexible_array_empty_aggregate;
15275 
15276         if (DiagID)
15277           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
15278                                           << Record->getTagKind();
15279         // While the layout of types that contain virtual bases is not specified
15280         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
15281         // virtual bases after the derived members.  This would make a flexible
15282         // array member declared at the end of an object not adjacent to the end
15283         // of the type.
15284         if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
15285           if (RD->getNumVBases() != 0)
15286             Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
15287               << FD->getDeclName() << Record->getTagKind();
15288         if (!getLangOpts().C99)
15289           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
15290             << FD->getDeclName() << Record->getTagKind();
15291 
15292         // If the element type has a non-trivial destructor, we would not
15293         // implicitly destroy the elements, so disallow it for now.
15294         //
15295         // FIXME: GCC allows this. We should probably either implicitly delete
15296         // the destructor of the containing class, or just allow this.
15297         QualType BaseElem = Context.getBaseElementType(FD->getType());
15298         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
15299           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
15300             << FD->getDeclName() << FD->getType();
15301           FD->setInvalidDecl();
15302           EnclosingDecl->setInvalidDecl();
15303           continue;
15304         }
15305         // Okay, we have a legal flexible array member at the end of the struct.
15306         Record->setHasFlexibleArrayMember(true);
15307       } else {
15308         // In ObjCContainerDecl ivars with incomplete array type are accepted,
15309         // unless they are followed by another ivar. That check is done
15310         // elsewhere, after synthesized ivars are known.
15311       }
15312     } else if (!FDTy->isDependentType() &&
15313                RequireCompleteType(FD->getLocation(), FD->getType(),
15314                                    diag::err_field_incomplete)) {
15315       // Incomplete type
15316       FD->setInvalidDecl();
15317       EnclosingDecl->setInvalidDecl();
15318       continue;
15319     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
15320       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
15321         // A type which contains a flexible array member is considered to be a
15322         // flexible array member.
15323         Record->setHasFlexibleArrayMember(true);
15324         if (!Record->isUnion()) {
15325           // If this is a struct/class and this is not the last element, reject
15326           // it.  Note that GCC supports variable sized arrays in the middle of
15327           // structures.
15328           if (!IsLastField)
15329             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
15330               << FD->getDeclName() << FD->getType();
15331           else {
15332             // We support flexible arrays at the end of structs in
15333             // other structs as an extension.
15334             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
15335               << FD->getDeclName();
15336           }
15337         }
15338       }
15339       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
15340           RequireNonAbstractType(FD->getLocation(), FD->getType(),
15341                                  diag::err_abstract_type_in_decl,
15342                                  AbstractIvarType)) {
15343         // Ivars can not have abstract class types
15344         FD->setInvalidDecl();
15345       }
15346       if (Record && FDTTy->getDecl()->hasObjectMember())
15347         Record->setHasObjectMember(true);
15348       if (Record && FDTTy->getDecl()->hasVolatileMember())
15349         Record->setHasVolatileMember(true);
15350     } else if (FDTy->isObjCObjectType()) {
15351       /// A field cannot be an Objective-c object
15352       Diag(FD->getLocation(), diag::err_statically_allocated_object)
15353         << FixItHint::CreateInsertion(FD->getLocation(), "*");
15354       QualType T = Context.getObjCObjectPointerType(FD->getType());
15355       FD->setType(T);
15356     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
15357                Record && !ObjCFieldLifetimeErrReported &&
15358                (!getLangOpts().CPlusPlus || Record->isUnion())) {
15359       // It's an error in ARC or Weak if a field has lifetime.
15360       // We don't want to report this in a system header, though,
15361       // so we just make the field unavailable.
15362       // FIXME: that's really not sufficient; we need to make the type
15363       // itself invalid to, say, initialize or copy.
15364       QualType T = FD->getType();
15365       if (T.hasNonTrivialObjCLifetime()) {
15366         SourceLocation loc = FD->getLocation();
15367         if (getSourceManager().isInSystemHeader(loc)) {
15368           if (!FD->hasAttr<UnavailableAttr>()) {
15369             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15370                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
15371           }
15372         } else {
15373           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
15374             << T->isBlockPointerType() << Record->getTagKind();
15375         }
15376         ObjCFieldLifetimeErrReported = true;
15377       }
15378     } else if (getLangOpts().ObjC1 &&
15379                getLangOpts().getGC() != LangOptions::NonGC &&
15380                Record && !Record->hasObjectMember()) {
15381       if (FD->getType()->isObjCObjectPointerType() ||
15382           FD->getType().isObjCGCStrong())
15383         Record->setHasObjectMember(true);
15384       else if (Context.getAsArrayType(FD->getType())) {
15385         QualType BaseType = Context.getBaseElementType(FD->getType());
15386         if (BaseType->isRecordType() &&
15387             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
15388           Record->setHasObjectMember(true);
15389         else if (BaseType->isObjCObjectPointerType() ||
15390                  BaseType.isObjCGCStrong())
15391                Record->setHasObjectMember(true);
15392       }
15393     }
15394     if (Record && FD->getType().isVolatileQualified())
15395       Record->setHasVolatileMember(true);
15396     // Keep track of the number of named members.
15397     if (FD->getIdentifier())
15398       ++NumNamedMembers;
15399   }
15400 
15401   // Okay, we successfully defined 'Record'.
15402   if (Record) {
15403     bool Completed = false;
15404     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15405       if (!CXXRecord->isInvalidDecl()) {
15406         // Set access bits correctly on the directly-declared conversions.
15407         for (CXXRecordDecl::conversion_iterator
15408                I = CXXRecord->conversion_begin(),
15409                E = CXXRecord->conversion_end(); I != E; ++I)
15410           I.setAccess((*I)->getAccess());
15411       }
15412 
15413       if (!CXXRecord->isDependentType()) {
15414         if (CXXRecord->hasUserDeclaredDestructor()) {
15415           // Adjust user-defined destructor exception spec.
15416           if (getLangOpts().CPlusPlus11)
15417             AdjustDestructorExceptionSpec(CXXRecord,
15418                                           CXXRecord->getDestructor());
15419         }
15420 
15421         // Add any implicitly-declared members to this class.
15422         AddImplicitlyDeclaredMembersToClass(CXXRecord);
15423 
15424         if (!CXXRecord->isInvalidDecl()) {
15425           // If we have virtual base classes, we may end up finding multiple
15426           // final overriders for a given virtual function. Check for this
15427           // problem now.
15428           if (CXXRecord->getNumVBases()) {
15429             CXXFinalOverriderMap FinalOverriders;
15430             CXXRecord->getFinalOverriders(FinalOverriders);
15431 
15432             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
15433                                              MEnd = FinalOverriders.end();
15434                  M != MEnd; ++M) {
15435               for (OverridingMethods::iterator SO = M->second.begin(),
15436                                             SOEnd = M->second.end();
15437                    SO != SOEnd; ++SO) {
15438                 assert(SO->second.size() > 0 &&
15439                        "Virtual function without overridding functions?");
15440                 if (SO->second.size() == 1)
15441                   continue;
15442 
15443                 // C++ [class.virtual]p2:
15444                 //   In a derived class, if a virtual member function of a base
15445                 //   class subobject has more than one final overrider the
15446                 //   program is ill-formed.
15447                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
15448                   << (const NamedDecl *)M->first << Record;
15449                 Diag(M->first->getLocation(),
15450                      diag::note_overridden_virtual_function);
15451                 for (OverridingMethods::overriding_iterator
15452                           OM = SO->second.begin(),
15453                        OMEnd = SO->second.end();
15454                      OM != OMEnd; ++OM)
15455                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
15456                     << (const NamedDecl *)M->first << OM->Method->getParent();
15457 
15458                 Record->setInvalidDecl();
15459               }
15460             }
15461             CXXRecord->completeDefinition(&FinalOverriders);
15462             Completed = true;
15463           }
15464         }
15465       }
15466     }
15467 
15468     if (!Completed)
15469       Record->completeDefinition();
15470 
15471     // We may have deferred checking for a deleted destructor. Check now.
15472     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15473       auto *Dtor = CXXRecord->getDestructor();
15474       if (Dtor && Dtor->isImplicit() &&
15475           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
15476         CXXRecord->setImplicitDestructorIsDeleted();
15477         SetDeclDeleted(Dtor, CXXRecord->getLocation());
15478       }
15479     }
15480 
15481     if (Record->hasAttrs()) {
15482       CheckAlignasUnderalignment(Record);
15483 
15484       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
15485         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
15486                                            IA->getRange(), IA->getBestCase(),
15487                                            IA->getSemanticSpelling());
15488     }
15489 
15490     // Check if the structure/union declaration is a type that can have zero
15491     // size in C. For C this is a language extension, for C++ it may cause
15492     // compatibility problems.
15493     bool CheckForZeroSize;
15494     if (!getLangOpts().CPlusPlus) {
15495       CheckForZeroSize = true;
15496     } else {
15497       // For C++ filter out types that cannot be referenced in C code.
15498       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
15499       CheckForZeroSize =
15500           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
15501           !CXXRecord->isDependentType() &&
15502           CXXRecord->isCLike();
15503     }
15504     if (CheckForZeroSize) {
15505       bool ZeroSize = true;
15506       bool IsEmpty = true;
15507       unsigned NonBitFields = 0;
15508       for (RecordDecl::field_iterator I = Record->field_begin(),
15509                                       E = Record->field_end();
15510            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
15511         IsEmpty = false;
15512         if (I->isUnnamedBitfield()) {
15513           if (I->getBitWidthValue(Context) > 0)
15514             ZeroSize = false;
15515         } else {
15516           ++NonBitFields;
15517           QualType FieldType = I->getType();
15518           if (FieldType->isIncompleteType() ||
15519               !Context.getTypeSizeInChars(FieldType).isZero())
15520             ZeroSize = false;
15521         }
15522       }
15523 
15524       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
15525       // allowed in C++, but warn if its declaration is inside
15526       // extern "C" block.
15527       if (ZeroSize) {
15528         Diag(RecLoc, getLangOpts().CPlusPlus ?
15529                          diag::warn_zero_size_struct_union_in_extern_c :
15530                          diag::warn_zero_size_struct_union_compat)
15531           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
15532       }
15533 
15534       // Structs without named members are extension in C (C99 6.7.2.1p7),
15535       // but are accepted by GCC.
15536       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
15537         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
15538                                diag::ext_no_named_members_in_struct_union)
15539           << Record->isUnion();
15540       }
15541     }
15542   } else {
15543     ObjCIvarDecl **ClsFields =
15544       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
15545     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
15546       ID->setEndOfDefinitionLoc(RBrac);
15547       // Add ivar's to class's DeclContext.
15548       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15549         ClsFields[i]->setLexicalDeclContext(ID);
15550         ID->addDecl(ClsFields[i]);
15551       }
15552       // Must enforce the rule that ivars in the base classes may not be
15553       // duplicates.
15554       if (ID->getSuperClass())
15555         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
15556     } else if (ObjCImplementationDecl *IMPDecl =
15557                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15558       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
15559       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
15560         // Ivar declared in @implementation never belongs to the implementation.
15561         // Only it is in implementation's lexical context.
15562         ClsFields[I]->setLexicalDeclContext(IMPDecl);
15563       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
15564       IMPDecl->setIvarLBraceLoc(LBrac);
15565       IMPDecl->setIvarRBraceLoc(RBrac);
15566     } else if (ObjCCategoryDecl *CDecl =
15567                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15568       // case of ivars in class extension; all other cases have been
15569       // reported as errors elsewhere.
15570       // FIXME. Class extension does not have a LocEnd field.
15571       // CDecl->setLocEnd(RBrac);
15572       // Add ivar's to class extension's DeclContext.
15573       // Diagnose redeclaration of private ivars.
15574       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
15575       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15576         if (IDecl) {
15577           if (const ObjCIvarDecl *ClsIvar =
15578               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
15579             Diag(ClsFields[i]->getLocation(),
15580                  diag::err_duplicate_ivar_declaration);
15581             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
15582             continue;
15583           }
15584           for (const auto *Ext : IDecl->known_extensions()) {
15585             if (const ObjCIvarDecl *ClsExtIvar
15586                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
15587               Diag(ClsFields[i]->getLocation(),
15588                    diag::err_duplicate_ivar_declaration);
15589               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
15590               continue;
15591             }
15592           }
15593         }
15594         ClsFields[i]->setLexicalDeclContext(CDecl);
15595         CDecl->addDecl(ClsFields[i]);
15596       }
15597       CDecl->setIvarLBraceLoc(LBrac);
15598       CDecl->setIvarRBraceLoc(RBrac);
15599     }
15600   }
15601 
15602   if (Attr)
15603     ProcessDeclAttributeList(S, Record, Attr);
15604 }
15605 
15606 /// \brief Determine whether the given integral value is representable within
15607 /// the given type T.
15608 static bool isRepresentableIntegerValue(ASTContext &Context,
15609                                         llvm::APSInt &Value,
15610                                         QualType T) {
15611   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
15612          "Integral type required!");
15613   unsigned BitWidth = Context.getIntWidth(T);
15614 
15615   if (Value.isUnsigned() || Value.isNonNegative()) {
15616     if (T->isSignedIntegerOrEnumerationType())
15617       --BitWidth;
15618     return Value.getActiveBits() <= BitWidth;
15619   }
15620   return Value.getMinSignedBits() <= BitWidth;
15621 }
15622 
15623 // \brief Given an integral type, return the next larger integral type
15624 // (or a NULL type of no such type exists).
15625 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
15626   // FIXME: Int128/UInt128 support, which also needs to be introduced into
15627   // enum checking below.
15628   assert((T->isIntegralType(Context) ||
15629          T->isEnumeralType()) && "Integral type required!");
15630   const unsigned NumTypes = 4;
15631   QualType SignedIntegralTypes[NumTypes] = {
15632     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
15633   };
15634   QualType UnsignedIntegralTypes[NumTypes] = {
15635     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
15636     Context.UnsignedLongLongTy
15637   };
15638 
15639   unsigned BitWidth = Context.getTypeSize(T);
15640   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
15641                                                         : UnsignedIntegralTypes;
15642   for (unsigned I = 0; I != NumTypes; ++I)
15643     if (Context.getTypeSize(Types[I]) > BitWidth)
15644       return Types[I];
15645 
15646   return QualType();
15647 }
15648 
15649 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
15650                                           EnumConstantDecl *LastEnumConst,
15651                                           SourceLocation IdLoc,
15652                                           IdentifierInfo *Id,
15653                                           Expr *Val) {
15654   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15655   llvm::APSInt EnumVal(IntWidth);
15656   QualType EltTy;
15657 
15658   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
15659     Val = nullptr;
15660 
15661   if (Val)
15662     Val = DefaultLvalueConversion(Val).get();
15663 
15664   if (Val) {
15665     if (Enum->isDependentType() || Val->isTypeDependent())
15666       EltTy = Context.DependentTy;
15667     else {
15668       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
15669           !getLangOpts().MSVCCompat) {
15670         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
15671         // constant-expression in the enumerator-definition shall be a converted
15672         // constant expression of the underlying type.
15673         EltTy = Enum->getIntegerType();
15674         ExprResult Converted =
15675           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
15676                                            CCEK_Enumerator);
15677         if (Converted.isInvalid())
15678           Val = nullptr;
15679         else
15680           Val = Converted.get();
15681       } else if (!Val->isValueDependent() &&
15682                  !(Val = VerifyIntegerConstantExpression(Val,
15683                                                          &EnumVal).get())) {
15684         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
15685       } else {
15686         if (Enum->isComplete()) {
15687           EltTy = Enum->getIntegerType();
15688 
15689           // In Obj-C and Microsoft mode, require the enumeration value to be
15690           // representable in the underlying type of the enumeration. In C++11,
15691           // we perform a non-narrowing conversion as part of converted constant
15692           // expression checking.
15693           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15694             if (getLangOpts().MSVCCompat) {
15695               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
15696               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
15697             } else
15698               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
15699           } else
15700             Val = ImpCastExprToType(Val, EltTy,
15701                                     EltTy->isBooleanType() ?
15702                                     CK_IntegralToBoolean : CK_IntegralCast)
15703                     .get();
15704         } else if (getLangOpts().CPlusPlus) {
15705           // C++11 [dcl.enum]p5:
15706           //   If the underlying type is not fixed, the type of each enumerator
15707           //   is the type of its initializing value:
15708           //     - If an initializer is specified for an enumerator, the
15709           //       initializing value has the same type as the expression.
15710           EltTy = Val->getType();
15711         } else {
15712           // C99 6.7.2.2p2:
15713           //   The expression that defines the value of an enumeration constant
15714           //   shall be an integer constant expression that has a value
15715           //   representable as an int.
15716 
15717           // Complain if the value is not representable in an int.
15718           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
15719             Diag(IdLoc, diag::ext_enum_value_not_int)
15720               << EnumVal.toString(10) << Val->getSourceRange()
15721               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
15722           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
15723             // Force the type of the expression to 'int'.
15724             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
15725           }
15726           EltTy = Val->getType();
15727         }
15728       }
15729     }
15730   }
15731 
15732   if (!Val) {
15733     if (Enum->isDependentType())
15734       EltTy = Context.DependentTy;
15735     else if (!LastEnumConst) {
15736       // C++0x [dcl.enum]p5:
15737       //   If the underlying type is not fixed, the type of each enumerator
15738       //   is the type of its initializing value:
15739       //     - If no initializer is specified for the first enumerator, the
15740       //       initializing value has an unspecified integral type.
15741       //
15742       // GCC uses 'int' for its unspecified integral type, as does
15743       // C99 6.7.2.2p3.
15744       if (Enum->isFixed()) {
15745         EltTy = Enum->getIntegerType();
15746       }
15747       else {
15748         EltTy = Context.IntTy;
15749       }
15750     } else {
15751       // Assign the last value + 1.
15752       EnumVal = LastEnumConst->getInitVal();
15753       ++EnumVal;
15754       EltTy = LastEnumConst->getType();
15755 
15756       // Check for overflow on increment.
15757       if (EnumVal < LastEnumConst->getInitVal()) {
15758         // C++0x [dcl.enum]p5:
15759         //   If the underlying type is not fixed, the type of each enumerator
15760         //   is the type of its initializing value:
15761         //
15762         //     - Otherwise the type of the initializing value is the same as
15763         //       the type of the initializing value of the preceding enumerator
15764         //       unless the incremented value is not representable in that type,
15765         //       in which case the type is an unspecified integral type
15766         //       sufficient to contain the incremented value. If no such type
15767         //       exists, the program is ill-formed.
15768         QualType T = getNextLargerIntegralType(Context, EltTy);
15769         if (T.isNull() || Enum->isFixed()) {
15770           // There is no integral type larger enough to represent this
15771           // value. Complain, then allow the value to wrap around.
15772           EnumVal = LastEnumConst->getInitVal();
15773           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
15774           ++EnumVal;
15775           if (Enum->isFixed())
15776             // When the underlying type is fixed, this is ill-formed.
15777             Diag(IdLoc, diag::err_enumerator_wrapped)
15778               << EnumVal.toString(10)
15779               << EltTy;
15780           else
15781             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
15782               << EnumVal.toString(10);
15783         } else {
15784           EltTy = T;
15785         }
15786 
15787         // Retrieve the last enumerator's value, extent that type to the
15788         // type that is supposed to be large enough to represent the incremented
15789         // value, then increment.
15790         EnumVal = LastEnumConst->getInitVal();
15791         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15792         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
15793         ++EnumVal;
15794 
15795         // If we're not in C++, diagnose the overflow of enumerator values,
15796         // which in C99 means that the enumerator value is not representable in
15797         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
15798         // permits enumerator values that are representable in some larger
15799         // integral type.
15800         if (!getLangOpts().CPlusPlus && !T.isNull())
15801           Diag(IdLoc, diag::warn_enum_value_overflow);
15802       } else if (!getLangOpts().CPlusPlus &&
15803                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15804         // Enforce C99 6.7.2.2p2 even when we compute the next value.
15805         Diag(IdLoc, diag::ext_enum_value_not_int)
15806           << EnumVal.toString(10) << 1;
15807       }
15808     }
15809   }
15810 
15811   if (!EltTy->isDependentType()) {
15812     // Make the enumerator value match the signedness and size of the
15813     // enumerator's type.
15814     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
15815     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15816   }
15817 
15818   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
15819                                   Val, EnumVal);
15820 }
15821 
15822 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
15823                                                 SourceLocation IILoc) {
15824   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
15825       !getLangOpts().CPlusPlus)
15826     return SkipBodyInfo();
15827 
15828   // We have an anonymous enum definition. Look up the first enumerator to
15829   // determine if we should merge the definition with an existing one and
15830   // skip the body.
15831   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
15832                                          forRedeclarationInCurContext());
15833   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
15834   if (!PrevECD)
15835     return SkipBodyInfo();
15836 
15837   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
15838   NamedDecl *Hidden;
15839   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
15840     SkipBodyInfo Skip;
15841     Skip.Previous = Hidden;
15842     return Skip;
15843   }
15844 
15845   return SkipBodyInfo();
15846 }
15847 
15848 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
15849                               SourceLocation IdLoc, IdentifierInfo *Id,
15850                               AttributeList *Attr,
15851                               SourceLocation EqualLoc, Expr *Val) {
15852   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
15853   EnumConstantDecl *LastEnumConst =
15854     cast_or_null<EnumConstantDecl>(lastEnumConst);
15855 
15856   // The scope passed in may not be a decl scope.  Zip up the scope tree until
15857   // we find one that is.
15858   S = getNonFieldDeclScope(S);
15859 
15860   // Verify that there isn't already something declared with this name in this
15861   // scope.
15862   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
15863                                          ForVisibleRedeclaration);
15864   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15865     // Maybe we will complain about the shadowed template parameter.
15866     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
15867     // Just pretend that we didn't see the previous declaration.
15868     PrevDecl = nullptr;
15869   }
15870 
15871   // C++ [class.mem]p15:
15872   // If T is the name of a class, then each of the following shall have a name
15873   // different from T:
15874   // - every enumerator of every member of class T that is an unscoped
15875   // enumerated type
15876   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
15877     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
15878                             DeclarationNameInfo(Id, IdLoc));
15879 
15880   EnumConstantDecl *New =
15881     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
15882   if (!New)
15883     return nullptr;
15884 
15885   if (PrevDecl) {
15886     // When in C++, we may get a TagDecl with the same name; in this case the
15887     // enum constant will 'hide' the tag.
15888     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
15889            "Received TagDecl when not in C++!");
15890     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
15891       if (isa<EnumConstantDecl>(PrevDecl))
15892         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15893       else
15894         Diag(IdLoc, diag::err_redefinition) << Id;
15895       notePreviousDefinition(PrevDecl, IdLoc);
15896       return nullptr;
15897     }
15898   }
15899 
15900   // Process attributes.
15901   if (Attr) ProcessDeclAttributeList(S, New, Attr);
15902   AddPragmaAttributes(S, New);
15903 
15904   // Register this decl in the current scope stack.
15905   New->setAccess(TheEnumDecl->getAccess());
15906   PushOnScopeChains(New, S);
15907 
15908   ActOnDocumentableDecl(New);
15909 
15910   return New;
15911 }
15912 
15913 // Returns true when the enum initial expression does not trigger the
15914 // duplicate enum warning.  A few common cases are exempted as follows:
15915 // Element2 = Element1
15916 // Element2 = Element1 + 1
15917 // Element2 = Element1 - 1
15918 // Where Element2 and Element1 are from the same enum.
15919 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
15920   Expr *InitExpr = ECD->getInitExpr();
15921   if (!InitExpr)
15922     return true;
15923   InitExpr = InitExpr->IgnoreImpCasts();
15924 
15925   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
15926     if (!BO->isAdditiveOp())
15927       return true;
15928     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
15929     if (!IL)
15930       return true;
15931     if (IL->getValue() != 1)
15932       return true;
15933 
15934     InitExpr = BO->getLHS();
15935   }
15936 
15937   // This checks if the elements are from the same enum.
15938   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
15939   if (!DRE)
15940     return true;
15941 
15942   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
15943   if (!EnumConstant)
15944     return true;
15945 
15946   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
15947       Enum)
15948     return true;
15949 
15950   return false;
15951 }
15952 
15953 namespace {
15954 struct DupKey {
15955   int64_t val;
15956   bool isTombstoneOrEmptyKey;
15957   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
15958     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
15959 };
15960 
15961 static DupKey GetDupKey(const llvm::APSInt& Val) {
15962   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
15963                 false);
15964 }
15965 
15966 struct DenseMapInfoDupKey {
15967   static DupKey getEmptyKey() { return DupKey(0, true); }
15968   static DupKey getTombstoneKey() { return DupKey(1, true); }
15969   static unsigned getHashValue(const DupKey Key) {
15970     return (unsigned)(Key.val * 37);
15971   }
15972   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
15973     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
15974            LHS.val == RHS.val;
15975   }
15976 };
15977 } // end anonymous namespace
15978 
15979 // Emits a warning when an element is implicitly set a value that
15980 // a previous element has already been set to.
15981 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
15982                                         EnumDecl *Enum,
15983                                         QualType EnumType) {
15984   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
15985     return;
15986   // Avoid anonymous enums
15987   if (!Enum->getIdentifier())
15988     return;
15989 
15990   // Only check for small enums.
15991   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
15992     return;
15993 
15994   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
15995   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
15996 
15997   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
15998   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
15999           ValueToVectorMap;
16000 
16001   DuplicatesVector DupVector;
16002   ValueToVectorMap EnumMap;
16003 
16004   // Populate the EnumMap with all values represented by enum constants without
16005   // an initialier.
16006   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16007     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
16008 
16009     // Null EnumConstantDecl means a previous diagnostic has been emitted for
16010     // this constant.  Skip this enum since it may be ill-formed.
16011     if (!ECD) {
16012       return;
16013     }
16014 
16015     if (ECD->getInitExpr())
16016       continue;
16017 
16018     DupKey Key = GetDupKey(ECD->getInitVal());
16019     DeclOrVector &Entry = EnumMap[Key];
16020 
16021     // First time encountering this value.
16022     if (Entry.isNull())
16023       Entry = ECD;
16024   }
16025 
16026   // Create vectors for any values that has duplicates.
16027   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16028     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
16029     if (!ValidDuplicateEnum(ECD, Enum))
16030       continue;
16031 
16032     DupKey Key = GetDupKey(ECD->getInitVal());
16033 
16034     DeclOrVector& Entry = EnumMap[Key];
16035     if (Entry.isNull())
16036       continue;
16037 
16038     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
16039       // Ensure constants are different.
16040       if (D == ECD)
16041         continue;
16042 
16043       // Create new vector and push values onto it.
16044       ECDVector *Vec = new ECDVector();
16045       Vec->push_back(D);
16046       Vec->push_back(ECD);
16047 
16048       // Update entry to point to the duplicates vector.
16049       Entry = Vec;
16050 
16051       // Store the vector somewhere we can consult later for quick emission of
16052       // diagnostics.
16053       DupVector.push_back(Vec);
16054       continue;
16055     }
16056 
16057     ECDVector *Vec = Entry.get<ECDVector*>();
16058     // Make sure constants are not added more than once.
16059     if (*Vec->begin() == ECD)
16060       continue;
16061 
16062     Vec->push_back(ECD);
16063   }
16064 
16065   // Emit diagnostics.
16066   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
16067                                   DupVectorEnd = DupVector.end();
16068        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
16069     ECDVector *Vec = *DupVectorIter;
16070     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
16071 
16072     // Emit warning for one enum constant.
16073     ECDVector::iterator I = Vec->begin();
16074     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
16075       << (*I)->getName() << (*I)->getInitVal().toString(10)
16076       << (*I)->getSourceRange();
16077     ++I;
16078 
16079     // Emit one note for each of the remaining enum constants with
16080     // the same value.
16081     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
16082       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
16083         << (*I)->getName() << (*I)->getInitVal().toString(10)
16084         << (*I)->getSourceRange();
16085     delete Vec;
16086   }
16087 }
16088 
16089 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
16090                              bool AllowMask) const {
16091   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
16092   assert(ED->isCompleteDefinition() && "expected enum definition");
16093 
16094   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
16095   llvm::APInt &FlagBits = R.first->second;
16096 
16097   if (R.second) {
16098     for (auto *E : ED->enumerators()) {
16099       const auto &EVal = E->getInitVal();
16100       // Only single-bit enumerators introduce new flag values.
16101       if (EVal.isPowerOf2())
16102         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
16103     }
16104   }
16105 
16106   // A value is in a flag enum if either its bits are a subset of the enum's
16107   // flag bits (the first condition) or we are allowing masks and the same is
16108   // true of its complement (the second condition). When masks are allowed, we
16109   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
16110   //
16111   // While it's true that any value could be used as a mask, the assumption is
16112   // that a mask will have all of the insignificant bits set. Anything else is
16113   // likely a logic error.
16114   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
16115   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
16116 }
16117 
16118 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
16119                          Decl *EnumDeclX,
16120                          ArrayRef<Decl *> Elements,
16121                          Scope *S, AttributeList *Attr) {
16122   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
16123   QualType EnumType = Context.getTypeDeclType(Enum);
16124 
16125   if (Attr)
16126     ProcessDeclAttributeList(S, Enum, Attr);
16127 
16128   if (Enum->isDependentType()) {
16129     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16130       EnumConstantDecl *ECD =
16131         cast_or_null<EnumConstantDecl>(Elements[i]);
16132       if (!ECD) continue;
16133 
16134       ECD->setType(EnumType);
16135     }
16136 
16137     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
16138     return;
16139   }
16140 
16141   // TODO: If the result value doesn't fit in an int, it must be a long or long
16142   // long value.  ISO C does not support this, but GCC does as an extension,
16143   // emit a warning.
16144   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16145   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
16146   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
16147 
16148   // Verify that all the values are okay, compute the size of the values, and
16149   // reverse the list.
16150   unsigned NumNegativeBits = 0;
16151   unsigned NumPositiveBits = 0;
16152 
16153   // Keep track of whether all elements have type int.
16154   bool AllElementsInt = true;
16155 
16156   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16157     EnumConstantDecl *ECD =
16158       cast_or_null<EnumConstantDecl>(Elements[i]);
16159     if (!ECD) continue;  // Already issued a diagnostic.
16160 
16161     const llvm::APSInt &InitVal = ECD->getInitVal();
16162 
16163     // Keep track of the size of positive and negative values.
16164     if (InitVal.isUnsigned() || InitVal.isNonNegative())
16165       NumPositiveBits = std::max(NumPositiveBits,
16166                                  (unsigned)InitVal.getActiveBits());
16167     else
16168       NumNegativeBits = std::max(NumNegativeBits,
16169                                  (unsigned)InitVal.getMinSignedBits());
16170 
16171     // Keep track of whether every enum element has type int (very commmon).
16172     if (AllElementsInt)
16173       AllElementsInt = ECD->getType() == Context.IntTy;
16174   }
16175 
16176   // Figure out the type that should be used for this enum.
16177   QualType BestType;
16178   unsigned BestWidth;
16179 
16180   // C++0x N3000 [conv.prom]p3:
16181   //   An rvalue of an unscoped enumeration type whose underlying
16182   //   type is not fixed can be converted to an rvalue of the first
16183   //   of the following types that can represent all the values of
16184   //   the enumeration: int, unsigned int, long int, unsigned long
16185   //   int, long long int, or unsigned long long int.
16186   // C99 6.4.4.3p2:
16187   //   An identifier declared as an enumeration constant has type int.
16188   // The C99 rule is modified by a gcc extension
16189   QualType BestPromotionType;
16190 
16191   bool Packed = Enum->hasAttr<PackedAttr>();
16192   // -fshort-enums is the equivalent to specifying the packed attribute on all
16193   // enum definitions.
16194   if (LangOpts.ShortEnums)
16195     Packed = true;
16196 
16197   // If the enum already has a type because it is fixed or dictated by the
16198   // target, promote that type instead of analyzing the enumerators.
16199   if (Enum->isComplete()) {
16200     BestType = Enum->getIntegerType();
16201     if (BestType->isPromotableIntegerType())
16202       BestPromotionType = Context.getPromotedIntegerType(BestType);
16203     else
16204       BestPromotionType = BestType;
16205 
16206     BestWidth = Context.getIntWidth(BestType);
16207   }
16208   else if (NumNegativeBits) {
16209     // If there is a negative value, figure out the smallest integer type (of
16210     // int/long/longlong) that fits.
16211     // If it's packed, check also if it fits a char or a short.
16212     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
16213       BestType = Context.SignedCharTy;
16214       BestWidth = CharWidth;
16215     } else if (Packed && NumNegativeBits <= ShortWidth &&
16216                NumPositiveBits < ShortWidth) {
16217       BestType = Context.ShortTy;
16218       BestWidth = ShortWidth;
16219     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
16220       BestType = Context.IntTy;
16221       BestWidth = IntWidth;
16222     } else {
16223       BestWidth = Context.getTargetInfo().getLongWidth();
16224 
16225       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
16226         BestType = Context.LongTy;
16227       } else {
16228         BestWidth = Context.getTargetInfo().getLongLongWidth();
16229 
16230         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
16231           Diag(Enum->getLocation(), diag::ext_enum_too_large);
16232         BestType = Context.LongLongTy;
16233       }
16234     }
16235     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
16236   } else {
16237     // If there is no negative value, figure out the smallest type that fits
16238     // all of the enumerator values.
16239     // If it's packed, check also if it fits a char or a short.
16240     if (Packed && NumPositiveBits <= CharWidth) {
16241       BestType = Context.UnsignedCharTy;
16242       BestPromotionType = Context.IntTy;
16243       BestWidth = CharWidth;
16244     } else if (Packed && NumPositiveBits <= ShortWidth) {
16245       BestType = Context.UnsignedShortTy;
16246       BestPromotionType = Context.IntTy;
16247       BestWidth = ShortWidth;
16248     } else if (NumPositiveBits <= IntWidth) {
16249       BestType = Context.UnsignedIntTy;
16250       BestWidth = IntWidth;
16251       BestPromotionType
16252         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16253                            ? Context.UnsignedIntTy : Context.IntTy;
16254     } else if (NumPositiveBits <=
16255                (BestWidth = Context.getTargetInfo().getLongWidth())) {
16256       BestType = Context.UnsignedLongTy;
16257       BestPromotionType
16258         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16259                            ? Context.UnsignedLongTy : Context.LongTy;
16260     } else {
16261       BestWidth = Context.getTargetInfo().getLongLongWidth();
16262       assert(NumPositiveBits <= BestWidth &&
16263              "How could an initializer get larger than ULL?");
16264       BestType = Context.UnsignedLongLongTy;
16265       BestPromotionType
16266         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16267                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
16268     }
16269   }
16270 
16271   // Loop over all of the enumerator constants, changing their types to match
16272   // the type of the enum if needed.
16273   for (auto *D : Elements) {
16274     auto *ECD = cast_or_null<EnumConstantDecl>(D);
16275     if (!ECD) continue;  // Already issued a diagnostic.
16276 
16277     // Standard C says the enumerators have int type, but we allow, as an
16278     // extension, the enumerators to be larger than int size.  If each
16279     // enumerator value fits in an int, type it as an int, otherwise type it the
16280     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
16281     // that X has type 'int', not 'unsigned'.
16282 
16283     // Determine whether the value fits into an int.
16284     llvm::APSInt InitVal = ECD->getInitVal();
16285 
16286     // If it fits into an integer type, force it.  Otherwise force it to match
16287     // the enum decl type.
16288     QualType NewTy;
16289     unsigned NewWidth;
16290     bool NewSign;
16291     if (!getLangOpts().CPlusPlus &&
16292         !Enum->isFixed() &&
16293         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
16294       NewTy = Context.IntTy;
16295       NewWidth = IntWidth;
16296       NewSign = true;
16297     } else if (ECD->getType() == BestType) {
16298       // Already the right type!
16299       if (getLangOpts().CPlusPlus)
16300         // C++ [dcl.enum]p4: Following the closing brace of an
16301         // enum-specifier, each enumerator has the type of its
16302         // enumeration.
16303         ECD->setType(EnumType);
16304       continue;
16305     } else {
16306       NewTy = BestType;
16307       NewWidth = BestWidth;
16308       NewSign = BestType->isSignedIntegerOrEnumerationType();
16309     }
16310 
16311     // Adjust the APSInt value.
16312     InitVal = InitVal.extOrTrunc(NewWidth);
16313     InitVal.setIsSigned(NewSign);
16314     ECD->setInitVal(InitVal);
16315 
16316     // Adjust the Expr initializer and type.
16317     if (ECD->getInitExpr() &&
16318         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
16319       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
16320                                                 CK_IntegralCast,
16321                                                 ECD->getInitExpr(),
16322                                                 /*base paths*/ nullptr,
16323                                                 VK_RValue));
16324     if (getLangOpts().CPlusPlus)
16325       // C++ [dcl.enum]p4: Following the closing brace of an
16326       // enum-specifier, each enumerator has the type of its
16327       // enumeration.
16328       ECD->setType(EnumType);
16329     else
16330       ECD->setType(NewTy);
16331   }
16332 
16333   Enum->completeDefinition(BestType, BestPromotionType,
16334                            NumPositiveBits, NumNegativeBits);
16335 
16336   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
16337 
16338   if (Enum->isClosedFlag()) {
16339     for (Decl *D : Elements) {
16340       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
16341       if (!ECD) continue;  // Already issued a diagnostic.
16342 
16343       llvm::APSInt InitVal = ECD->getInitVal();
16344       if (InitVal != 0 && !InitVal.isPowerOf2() &&
16345           !IsValueInFlagEnum(Enum, InitVal, true))
16346         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
16347           << ECD << Enum;
16348     }
16349   }
16350 
16351   // Now that the enum type is defined, ensure it's not been underaligned.
16352   if (Enum->hasAttrs())
16353     CheckAlignasUnderalignment(Enum);
16354 }
16355 
16356 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
16357                                   SourceLocation StartLoc,
16358                                   SourceLocation EndLoc) {
16359   StringLiteral *AsmString = cast<StringLiteral>(expr);
16360 
16361   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
16362                                                    AsmString, StartLoc,
16363                                                    EndLoc);
16364   CurContext->addDecl(New);
16365   return New;
16366 }
16367 
16368 static void checkModuleImportContext(Sema &S, Module *M,
16369                                      SourceLocation ImportLoc, DeclContext *DC,
16370                                      bool FromInclude = false) {
16371   SourceLocation ExternCLoc;
16372 
16373   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
16374     switch (LSD->getLanguage()) {
16375     case LinkageSpecDecl::lang_c:
16376       if (ExternCLoc.isInvalid())
16377         ExternCLoc = LSD->getLocStart();
16378       break;
16379     case LinkageSpecDecl::lang_cxx:
16380       break;
16381     }
16382     DC = LSD->getParent();
16383   }
16384 
16385   while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
16386     DC = DC->getParent();
16387 
16388   if (!isa<TranslationUnitDecl>(DC)) {
16389     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
16390                           ? diag::ext_module_import_not_at_top_level_noop
16391                           : diag::err_module_import_not_at_top_level_fatal)
16392         << M->getFullModuleName() << DC;
16393     S.Diag(cast<Decl>(DC)->getLocStart(),
16394            diag::note_module_import_not_at_top_level) << DC;
16395   } else if (!M->IsExternC && ExternCLoc.isValid()) {
16396     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
16397       << M->getFullModuleName();
16398     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
16399   }
16400 }
16401 
16402 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
16403                                            SourceLocation ModuleLoc,
16404                                            ModuleDeclKind MDK,
16405                                            ModuleIdPath Path) {
16406   assert(getLangOpts().ModulesTS &&
16407          "should only have module decl in modules TS");
16408 
16409   // A module implementation unit requires that we are not compiling a module
16410   // of any kind. A module interface unit requires that we are not compiling a
16411   // module map.
16412   switch (getLangOpts().getCompilingModule()) {
16413   case LangOptions::CMK_None:
16414     // It's OK to compile a module interface as a normal translation unit.
16415     break;
16416 
16417   case LangOptions::CMK_ModuleInterface:
16418     if (MDK != ModuleDeclKind::Implementation)
16419       break;
16420 
16421     // We were asked to compile a module interface unit but this is a module
16422     // implementation unit. That indicates the 'export' is missing.
16423     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
16424       << FixItHint::CreateInsertion(ModuleLoc, "export ");
16425     MDK = ModuleDeclKind::Interface;
16426     break;
16427 
16428   case LangOptions::CMK_ModuleMap:
16429     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
16430     return nullptr;
16431   }
16432 
16433   assert(ModuleScopes.size() == 1 && "expected to be at global module scope");
16434 
16435   // FIXME: Most of this work should be done by the preprocessor rather than
16436   // here, in order to support macro import.
16437 
16438   // Only one module-declaration is permitted per source file.
16439   if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) {
16440     Diag(ModuleLoc, diag::err_module_redeclaration);
16441     Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
16442          diag::note_prev_module_declaration);
16443     return nullptr;
16444   }
16445 
16446   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
16447   // modules, the dots here are just another character that can appear in a
16448   // module name.
16449   std::string ModuleName;
16450   for (auto &Piece : Path) {
16451     if (!ModuleName.empty())
16452       ModuleName += ".";
16453     ModuleName += Piece.first->getName();
16454   }
16455 
16456   // If a module name was explicitly specified on the command line, it must be
16457   // correct.
16458   if (!getLangOpts().CurrentModule.empty() &&
16459       getLangOpts().CurrentModule != ModuleName) {
16460     Diag(Path.front().second, diag::err_current_module_name_mismatch)
16461         << SourceRange(Path.front().second, Path.back().second)
16462         << getLangOpts().CurrentModule;
16463     return nullptr;
16464   }
16465   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
16466 
16467   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
16468   Module *Mod;
16469 
16470   switch (MDK) {
16471   case ModuleDeclKind::Interface: {
16472     // We can't have parsed or imported a definition of this module or parsed a
16473     // module map defining it already.
16474     if (auto *M = Map.findModule(ModuleName)) {
16475       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
16476       if (M->DefinitionLoc.isValid())
16477         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
16478       else if (const auto *FE = M->getASTFile())
16479         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
16480             << FE->getName();
16481       Mod = M;
16482       break;
16483     }
16484 
16485     // Create a Module for the module that we're defining.
16486     Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16487                                            ModuleScopes.front().Module);
16488     assert(Mod && "module creation should not fail");
16489     break;
16490   }
16491 
16492   case ModuleDeclKind::Partition:
16493     // FIXME: Check we are in a submodule of the named module.
16494     return nullptr;
16495 
16496   case ModuleDeclKind::Implementation:
16497     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
16498         PP.getIdentifierInfo(ModuleName), Path[0].second);
16499     Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible,
16500                                        /*IsIncludeDirective=*/false);
16501     if (!Mod) {
16502       Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
16503       // Create an empty module interface unit for error recovery.
16504       Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16505                                              ModuleScopes.front().Module);
16506     }
16507     break;
16508   }
16509 
16510   // Switch from the global module to the named module.
16511   ModuleScopes.back().Module = Mod;
16512   ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
16513   VisibleModules.setVisible(Mod, ModuleLoc);
16514 
16515   // From now on, we have an owning module for all declarations we see.
16516   // However, those declarations are module-private unless explicitly
16517   // exported.
16518   auto *TU = Context.getTranslationUnitDecl();
16519   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
16520   TU->setLocalOwningModule(Mod);
16521 
16522   // FIXME: Create a ModuleDecl.
16523   return nullptr;
16524 }
16525 
16526 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
16527                                    SourceLocation ImportLoc,
16528                                    ModuleIdPath Path) {
16529   Module *Mod =
16530       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
16531                                    /*IsIncludeDirective=*/false);
16532   if (!Mod)
16533     return true;
16534 
16535   VisibleModules.setVisible(Mod, ImportLoc);
16536 
16537   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
16538 
16539   // FIXME: we should support importing a submodule within a different submodule
16540   // of the same top-level module. Until we do, make it an error rather than
16541   // silently ignoring the import.
16542   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
16543   // warn on a redundant import of the current module?
16544   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
16545       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
16546     Diag(ImportLoc, getLangOpts().isCompilingModule()
16547                         ? diag::err_module_self_import
16548                         : diag::err_module_import_in_implementation)
16549         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
16550 
16551   SmallVector<SourceLocation, 2> IdentifierLocs;
16552   Module *ModCheck = Mod;
16553   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
16554     // If we've run out of module parents, just drop the remaining identifiers.
16555     // We need the length to be consistent.
16556     if (!ModCheck)
16557       break;
16558     ModCheck = ModCheck->Parent;
16559 
16560     IdentifierLocs.push_back(Path[I].second);
16561   }
16562 
16563   ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
16564                                           Mod, IdentifierLocs);
16565   if (!ModuleScopes.empty())
16566     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
16567   CurContext->addDecl(Import);
16568 
16569   // Re-export the module if needed.
16570   if (Import->isExported() &&
16571       !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface)
16572     getCurrentModule()->Exports.emplace_back(Mod, false);
16573 
16574   return Import;
16575 }
16576 
16577 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16578   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16579   BuildModuleInclude(DirectiveLoc, Mod);
16580 }
16581 
16582 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16583   // Determine whether we're in the #include buffer for a module. The #includes
16584   // in that buffer do not qualify as module imports; they're just an
16585   // implementation detail of us building the module.
16586   //
16587   // FIXME: Should we even get ActOnModuleInclude calls for those?
16588   bool IsInModuleIncludes =
16589       TUKind == TU_Module &&
16590       getSourceManager().isWrittenInMainFile(DirectiveLoc);
16591 
16592   bool ShouldAddImport = !IsInModuleIncludes;
16593 
16594   // If this module import was due to an inclusion directive, create an
16595   // implicit import declaration to capture it in the AST.
16596   if (ShouldAddImport) {
16597     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16598     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16599                                                      DirectiveLoc, Mod,
16600                                                      DirectiveLoc);
16601     if (!ModuleScopes.empty())
16602       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
16603     TU->addDecl(ImportD);
16604     Consumer.HandleImplicitImportDecl(ImportD);
16605   }
16606 
16607   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
16608   VisibleModules.setVisible(Mod, DirectiveLoc);
16609 }
16610 
16611 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
16612   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16613 
16614   ModuleScopes.push_back({});
16615   ModuleScopes.back().Module = Mod;
16616   if (getLangOpts().ModulesLocalVisibility)
16617     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
16618 
16619   VisibleModules.setVisible(Mod, DirectiveLoc);
16620 
16621   // The enclosing context is now part of this module.
16622   // FIXME: Consider creating a child DeclContext to hold the entities
16623   // lexically within the module.
16624   if (getLangOpts().trackLocalOwningModule()) {
16625     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16626       cast<Decl>(DC)->setModuleOwnershipKind(
16627           getLangOpts().ModulesLocalVisibility
16628               ? Decl::ModuleOwnershipKind::VisibleWhenImported
16629               : Decl::ModuleOwnershipKind::Visible);
16630       cast<Decl>(DC)->setLocalOwningModule(Mod);
16631     }
16632   }
16633 }
16634 
16635 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
16636   if (getLangOpts().ModulesLocalVisibility) {
16637     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
16638     // Leaving a module hides namespace names, so our visible namespace cache
16639     // is now out of date.
16640     VisibleNamespaceCache.clear();
16641   }
16642 
16643   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
16644          "left the wrong module scope");
16645   ModuleScopes.pop_back();
16646 
16647   // We got to the end of processing a local module. Create an
16648   // ImportDecl as we would for an imported module.
16649   FileID File = getSourceManager().getFileID(EomLoc);
16650   SourceLocation DirectiveLoc;
16651   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
16652     // We reached the end of a #included module header. Use the #include loc.
16653     assert(File != getSourceManager().getMainFileID() &&
16654            "end of submodule in main source file");
16655     DirectiveLoc = getSourceManager().getIncludeLoc(File);
16656   } else {
16657     // We reached an EOM pragma. Use the pragma location.
16658     DirectiveLoc = EomLoc;
16659   }
16660   BuildModuleInclude(DirectiveLoc, Mod);
16661 
16662   // Any further declarations are in whatever module we returned to.
16663   if (getLangOpts().trackLocalOwningModule()) {
16664     // The parser guarantees that this is the same context that we entered
16665     // the module within.
16666     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16667       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
16668       if (!getCurrentModule())
16669         cast<Decl>(DC)->setModuleOwnershipKind(
16670             Decl::ModuleOwnershipKind::Unowned);
16671     }
16672   }
16673 }
16674 
16675 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
16676                                                       Module *Mod) {
16677   // Bail if we're not allowed to implicitly import a module here.
16678   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
16679       VisibleModules.isVisible(Mod))
16680     return;
16681 
16682   // Create the implicit import declaration.
16683   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16684   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16685                                                    Loc, Mod, Loc);
16686   TU->addDecl(ImportD);
16687   Consumer.HandleImplicitImportDecl(ImportD);
16688 
16689   // Make the module visible.
16690   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
16691   VisibleModules.setVisible(Mod, Loc);
16692 }
16693 
16694 /// We have parsed the start of an export declaration, including the '{'
16695 /// (if present).
16696 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
16697                                  SourceLocation LBraceLoc) {
16698   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
16699 
16700   // C++ Modules TS draft:
16701   //   An export-declaration shall appear in the purview of a module other than
16702   //   the global module.
16703   if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface)
16704     Diag(ExportLoc, diag::err_export_not_in_module_interface);
16705 
16706   //   An export-declaration [...] shall not contain more than one
16707   //   export keyword.
16708   //
16709   // The intent here is that an export-declaration cannot appear within another
16710   // export-declaration.
16711   if (D->isExported())
16712     Diag(ExportLoc, diag::err_export_within_export);
16713 
16714   CurContext->addDecl(D);
16715   PushDeclContext(S, D);
16716   D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
16717   return D;
16718 }
16719 
16720 /// Complete the definition of an export declaration.
16721 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
16722   auto *ED = cast<ExportDecl>(D);
16723   if (RBraceLoc.isValid())
16724     ED->setRBraceLoc(RBraceLoc);
16725 
16726   // FIXME: Diagnose export of internal-linkage declaration (including
16727   // anonymous namespace).
16728 
16729   PopDeclContext();
16730   return D;
16731 }
16732 
16733 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
16734                                       IdentifierInfo* AliasName,
16735                                       SourceLocation PragmaLoc,
16736                                       SourceLocation NameLoc,
16737                                       SourceLocation AliasNameLoc) {
16738   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
16739                                          LookupOrdinaryName);
16740   AsmLabelAttr *Attr =
16741       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
16742 
16743   // If a declaration that:
16744   // 1) declares a function or a variable
16745   // 2) has external linkage
16746   // already exists, add a label attribute to it.
16747   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16748     if (isDeclExternC(PrevDecl))
16749       PrevDecl->addAttr(Attr);
16750     else
16751       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
16752           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
16753   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
16754   } else
16755     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
16756 }
16757 
16758 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
16759                              SourceLocation PragmaLoc,
16760                              SourceLocation NameLoc) {
16761   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
16762 
16763   if (PrevDecl) {
16764     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
16765   } else {
16766     (void)WeakUndeclaredIdentifiers.insert(
16767       std::pair<IdentifierInfo*,WeakInfo>
16768         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
16769   }
16770 }
16771 
16772 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
16773                                 IdentifierInfo* AliasName,
16774                                 SourceLocation PragmaLoc,
16775                                 SourceLocation NameLoc,
16776                                 SourceLocation AliasNameLoc) {
16777   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
16778                                     LookupOrdinaryName);
16779   WeakInfo W = WeakInfo(Name, NameLoc);
16780 
16781   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16782     if (!PrevDecl->hasAttr<AliasAttr>())
16783       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
16784         DeclApplyPragmaWeak(TUScope, ND, W);
16785   } else {
16786     (void)WeakUndeclaredIdentifiers.insert(
16787       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
16788   }
16789 }
16790 
16791 Decl *Sema::getObjCDeclContext() const {
16792   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
16793 }
16794