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   return D->isCopyAssignmentOperator();
1523 }
1524 
1525 // We need this to handle
1526 //
1527 // typedef struct {
1528 //   void *foo() { return 0; }
1529 // } A;
1530 //
1531 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1532 // for example. If 'A', foo will have external linkage. If we have '*A',
1533 // foo will have no linkage. Since we can't know until we get to the end
1534 // of the typedef, this function finds out if D might have non-external linkage.
1535 // Callers should verify at the end of the TU if it D has external linkage or
1536 // not.
1537 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1538   const DeclContext *DC = D->getDeclContext();
1539   while (!DC->isTranslationUnit()) {
1540     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1541       if (!RD->hasNameForLinkage())
1542         return true;
1543     }
1544     DC = DC->getParent();
1545   }
1546 
1547   return !D->isExternallyVisible();
1548 }
1549 
1550 // FIXME: This needs to be refactored; some other isInMainFile users want
1551 // these semantics.
1552 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1553   if (S.TUKind != TU_Complete)
1554     return false;
1555   return S.SourceMgr.isInMainFile(Loc);
1556 }
1557 
1558 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1559   assert(D);
1560 
1561   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1562     return false;
1563 
1564   // Ignore all entities declared within templates, and out-of-line definitions
1565   // of members of class templates.
1566   if (D->getDeclContext()->isDependentContext() ||
1567       D->getLexicalDeclContext()->isDependentContext())
1568     return false;
1569 
1570   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1571     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1572       return false;
1573     // A non-out-of-line declaration of a member specialization was implicitly
1574     // instantiated; it's the out-of-line declaration that we're interested in.
1575     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1576         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1577       return false;
1578 
1579     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1580       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1581         return false;
1582     } else {
1583       // 'static inline' functions are defined in headers; don't warn.
1584       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1585         return false;
1586     }
1587 
1588     if (FD->doesThisDeclarationHaveABody() &&
1589         Context.DeclMustBeEmitted(FD))
1590       return false;
1591   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1592     // Constants and utility variables are defined in headers with internal
1593     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1594     // like "inline".)
1595     if (!isMainFileLoc(*this, VD->getLocation()))
1596       return false;
1597 
1598     if (Context.DeclMustBeEmitted(VD))
1599       return false;
1600 
1601     if (VD->isStaticDataMember() &&
1602         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1603       return false;
1604     if (VD->isStaticDataMember() &&
1605         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1606         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1607       return false;
1608 
1609     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1610       return false;
1611   } else {
1612     return false;
1613   }
1614 
1615   // Only warn for unused decls internal to the translation unit.
1616   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1617   // for inline functions defined in the main source file, for instance.
1618   return mightHaveNonExternalLinkage(D);
1619 }
1620 
1621 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1622   if (!D)
1623     return;
1624 
1625   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1626     const FunctionDecl *First = FD->getFirstDecl();
1627     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1628       return; // First should already be in the vector.
1629   }
1630 
1631   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1632     const VarDecl *First = VD->getFirstDecl();
1633     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1634       return; // First should already be in the vector.
1635   }
1636 
1637   if (ShouldWarnIfUnusedFileScopedDecl(D))
1638     UnusedFileScopedDecls.push_back(D);
1639 }
1640 
1641 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1642   if (D->isInvalidDecl())
1643     return false;
1644 
1645   bool Referenced = false;
1646   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1647     // For a decomposition declaration, warn if none of the bindings are
1648     // referenced, instead of if the variable itself is referenced (which
1649     // it is, by the bindings' expressions).
1650     for (auto *BD : DD->bindings()) {
1651       if (BD->isReferenced()) {
1652         Referenced = true;
1653         break;
1654       }
1655     }
1656   } else if (!D->getDeclName()) {
1657     return false;
1658   } else if (D->isReferenced() || D->isUsed()) {
1659     Referenced = true;
1660   }
1661 
1662   if (Referenced || D->hasAttr<UnusedAttr>() ||
1663       D->hasAttr<ObjCPreciseLifetimeAttr>())
1664     return false;
1665 
1666   if (isa<LabelDecl>(D))
1667     return true;
1668 
1669   // Except for labels, we only care about unused decls that are local to
1670   // functions.
1671   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1672   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1673     // For dependent types, the diagnostic is deferred.
1674     WithinFunction =
1675         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1676   if (!WithinFunction)
1677     return false;
1678 
1679   if (isa<TypedefNameDecl>(D))
1680     return true;
1681 
1682   // White-list anything that isn't a local variable.
1683   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1684     return false;
1685 
1686   // Types of valid local variables should be complete, so this should succeed.
1687   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1688 
1689     // White-list anything with an __attribute__((unused)) type.
1690     const auto *Ty = VD->getType().getTypePtr();
1691 
1692     // Only look at the outermost level of typedef.
1693     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1694       if (TT->getDecl()->hasAttr<UnusedAttr>())
1695         return false;
1696     }
1697 
1698     // If we failed to complete the type for some reason, or if the type is
1699     // dependent, don't diagnose the variable.
1700     if (Ty->isIncompleteType() || Ty->isDependentType())
1701       return false;
1702 
1703     // Look at the element type to ensure that the warning behaviour is
1704     // consistent for both scalars and arrays.
1705     Ty = Ty->getBaseElementTypeUnsafe();
1706 
1707     if (const TagType *TT = Ty->getAs<TagType>()) {
1708       const TagDecl *Tag = TT->getDecl();
1709       if (Tag->hasAttr<UnusedAttr>())
1710         return false;
1711 
1712       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1713         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1714           return false;
1715 
1716         if (const Expr *Init = VD->getInit()) {
1717           if (const ExprWithCleanups *Cleanups =
1718                   dyn_cast<ExprWithCleanups>(Init))
1719             Init = Cleanups->getSubExpr();
1720           const CXXConstructExpr *Construct =
1721             dyn_cast<CXXConstructExpr>(Init);
1722           if (Construct && !Construct->isElidable()) {
1723             CXXConstructorDecl *CD = Construct->getConstructor();
1724             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1725                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1726               return false;
1727           }
1728         }
1729       }
1730     }
1731 
1732     // TODO: __attribute__((unused)) templates?
1733   }
1734 
1735   return true;
1736 }
1737 
1738 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1739                                      FixItHint &Hint) {
1740   if (isa<LabelDecl>(D)) {
1741     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1742                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1743     if (AfterColon.isInvalid())
1744       return;
1745     Hint = FixItHint::CreateRemoval(CharSourceRange::
1746                                     getCharRange(D->getLocStart(), AfterColon));
1747   }
1748 }
1749 
1750 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1751   if (D->getTypeForDecl()->isDependentType())
1752     return;
1753 
1754   for (auto *TmpD : D->decls()) {
1755     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1756       DiagnoseUnusedDecl(T);
1757     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1758       DiagnoseUnusedNestedTypedefs(R);
1759   }
1760 }
1761 
1762 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1763 /// unless they are marked attr(unused).
1764 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1765   if (!ShouldDiagnoseUnusedDecl(D))
1766     return;
1767 
1768   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1769     // typedefs can be referenced later on, so the diagnostics are emitted
1770     // at end-of-translation-unit.
1771     UnusedLocalTypedefNameCandidates.insert(TD);
1772     return;
1773   }
1774 
1775   FixItHint Hint;
1776   GenerateFixForUnusedDecl(D, Context, Hint);
1777 
1778   unsigned DiagID;
1779   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1780     DiagID = diag::warn_unused_exception_param;
1781   else if (isa<LabelDecl>(D))
1782     DiagID = diag::warn_unused_label;
1783   else
1784     DiagID = diag::warn_unused_variable;
1785 
1786   Diag(D->getLocation(), DiagID) << D << Hint;
1787 }
1788 
1789 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1790   // Verify that we have no forward references left.  If so, there was a goto
1791   // or address of a label taken, but no definition of it.  Label fwd
1792   // definitions are indicated with a null substmt which is also not a resolved
1793   // MS inline assembly label name.
1794   bool Diagnose = false;
1795   if (L->isMSAsmLabel())
1796     Diagnose = !L->isResolvedMSAsmLabel();
1797   else
1798     Diagnose = L->getStmt() == nullptr;
1799   if (Diagnose)
1800     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1801 }
1802 
1803 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1804   S->mergeNRVOIntoParent();
1805 
1806   if (S->decl_empty()) return;
1807   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1808          "Scope shouldn't contain decls!");
1809 
1810   for (auto *TmpD : S->decls()) {
1811     assert(TmpD && "This decl didn't get pushed??");
1812 
1813     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1814     NamedDecl *D = cast<NamedDecl>(TmpD);
1815 
1816     // Diagnose unused variables in this scope.
1817     if (!S->hasUnrecoverableErrorOccurred()) {
1818       DiagnoseUnusedDecl(D);
1819       if (const auto *RD = dyn_cast<RecordDecl>(D))
1820         DiagnoseUnusedNestedTypedefs(RD);
1821     }
1822 
1823     if (!D->getDeclName()) continue;
1824 
1825     // If this was a forward reference to a label, verify it was defined.
1826     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1827       CheckPoppedLabel(LD, *this);
1828 
1829     // Remove this name from our lexical scope, and warn on it if we haven't
1830     // already.
1831     IdResolver.RemoveDecl(D);
1832     auto ShadowI = ShadowingDecls.find(D);
1833     if (ShadowI != ShadowingDecls.end()) {
1834       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1835         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1836             << D << FD << FD->getParent();
1837         Diag(FD->getLocation(), diag::note_previous_declaration);
1838       }
1839       ShadowingDecls.erase(ShadowI);
1840     }
1841   }
1842 }
1843 
1844 /// \brief Look for an Objective-C class in the translation unit.
1845 ///
1846 /// \param Id The name of the Objective-C class we're looking for. If
1847 /// typo-correction fixes this name, the Id will be updated
1848 /// to the fixed name.
1849 ///
1850 /// \param IdLoc The location of the name in the translation unit.
1851 ///
1852 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1853 /// if there is no class with the given name.
1854 ///
1855 /// \returns The declaration of the named Objective-C class, or NULL if the
1856 /// class could not be found.
1857 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1858                                               SourceLocation IdLoc,
1859                                               bool DoTypoCorrection) {
1860   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1861   // creation from this context.
1862   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1863 
1864   if (!IDecl && DoTypoCorrection) {
1865     // Perform typo correction at the given location, but only if we
1866     // find an Objective-C class name.
1867     if (TypoCorrection C = CorrectTypo(
1868             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1869             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1870             CTK_ErrorRecovery)) {
1871       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1872       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1873       Id = IDecl->getIdentifier();
1874     }
1875   }
1876   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1877   // This routine must always return a class definition, if any.
1878   if (Def && Def->getDefinition())
1879       Def = Def->getDefinition();
1880   return Def;
1881 }
1882 
1883 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1884 /// from S, where a non-field would be declared. This routine copes
1885 /// with the difference between C and C++ scoping rules in structs and
1886 /// unions. For example, the following code is well-formed in C but
1887 /// ill-formed in C++:
1888 /// @code
1889 /// struct S6 {
1890 ///   enum { BAR } e;
1891 /// };
1892 ///
1893 /// void test_S6() {
1894 ///   struct S6 a;
1895 ///   a.e = BAR;
1896 /// }
1897 /// @endcode
1898 /// For the declaration of BAR, this routine will return a different
1899 /// scope. The scope S will be the scope of the unnamed enumeration
1900 /// within S6. In C++, this routine will return the scope associated
1901 /// with S6, because the enumeration's scope is a transparent
1902 /// context but structures can contain non-field names. In C, this
1903 /// routine will return the translation unit scope, since the
1904 /// enumeration's scope is a transparent context and structures cannot
1905 /// contain non-field names.
1906 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1907   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1908          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1909          (S->isClassScope() && !getLangOpts().CPlusPlus))
1910     S = S->getParent();
1911   return S;
1912 }
1913 
1914 /// \brief Looks up the declaration of "struct objc_super" and
1915 /// saves it for later use in building builtin declaration of
1916 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1917 /// pre-existing declaration exists no action takes place.
1918 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1919                                         IdentifierInfo *II) {
1920   if (!II->isStr("objc_msgSendSuper"))
1921     return;
1922   ASTContext &Context = ThisSema.Context;
1923 
1924   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1925                       SourceLocation(), Sema::LookupTagName);
1926   ThisSema.LookupName(Result, S);
1927   if (Result.getResultKind() == LookupResult::Found)
1928     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1929       Context.setObjCSuperType(Context.getTagDeclType(TD));
1930 }
1931 
1932 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1933   switch (Error) {
1934   case ASTContext::GE_None:
1935     return "";
1936   case ASTContext::GE_Missing_stdio:
1937     return "stdio.h";
1938   case ASTContext::GE_Missing_setjmp:
1939     return "setjmp.h";
1940   case ASTContext::GE_Missing_ucontext:
1941     return "ucontext.h";
1942   }
1943   llvm_unreachable("unhandled error kind");
1944 }
1945 
1946 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1947 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1948 /// if we're creating this built-in in anticipation of redeclaring the
1949 /// built-in.
1950 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1951                                      Scope *S, bool ForRedeclaration,
1952                                      SourceLocation Loc) {
1953   LookupPredefedObjCSuperType(*this, S, II);
1954 
1955   ASTContext::GetBuiltinTypeError Error;
1956   QualType R = Context.GetBuiltinType(ID, Error);
1957   if (Error) {
1958     if (ForRedeclaration)
1959       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1960           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1961     return nullptr;
1962   }
1963 
1964   if (!ForRedeclaration &&
1965       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1966        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1967     Diag(Loc, diag::ext_implicit_lib_function_decl)
1968         << Context.BuiltinInfo.getName(ID) << R;
1969     if (Context.BuiltinInfo.getHeaderName(ID) &&
1970         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1971       Diag(Loc, diag::note_include_header_or_declare)
1972           << Context.BuiltinInfo.getHeaderName(ID)
1973           << Context.BuiltinInfo.getName(ID);
1974   }
1975 
1976   if (R.isNull())
1977     return nullptr;
1978 
1979   DeclContext *Parent = Context.getTranslationUnitDecl();
1980   if (getLangOpts().CPlusPlus) {
1981     LinkageSpecDecl *CLinkageDecl =
1982         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1983                                 LinkageSpecDecl::lang_c, false);
1984     CLinkageDecl->setImplicit();
1985     Parent->addDecl(CLinkageDecl);
1986     Parent = CLinkageDecl;
1987   }
1988 
1989   FunctionDecl *New = FunctionDecl::Create(Context,
1990                                            Parent,
1991                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1992                                            SC_Extern,
1993                                            false,
1994                                            R->isFunctionProtoType());
1995   New->setImplicit();
1996 
1997   // Create Decl objects for each parameter, adding them to the
1998   // FunctionDecl.
1999   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2000     SmallVector<ParmVarDecl*, 16> Params;
2001     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2002       ParmVarDecl *parm =
2003           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2004                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2005                               SC_None, nullptr);
2006       parm->setScopeInfo(0, i);
2007       Params.push_back(parm);
2008     }
2009     New->setParams(Params);
2010   }
2011 
2012   AddKnownFunctionAttributes(New);
2013   RegisterLocallyScopedExternCDecl(New, S);
2014 
2015   // TUScope is the translation-unit scope to insert this function into.
2016   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2017   // relate Scopes to DeclContexts, and probably eliminate CurContext
2018   // entirely, but we're not there yet.
2019   DeclContext *SavedContext = CurContext;
2020   CurContext = Parent;
2021   PushOnScopeChains(New, TUScope);
2022   CurContext = SavedContext;
2023   return New;
2024 }
2025 
2026 /// Typedef declarations don't have linkage, but they still denote the same
2027 /// entity if their types are the same.
2028 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2029 /// isSameEntity.
2030 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2031                                                      TypedefNameDecl *Decl,
2032                                                      LookupResult &Previous) {
2033   // This is only interesting when modules are enabled.
2034   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2035     return;
2036 
2037   // Empty sets are uninteresting.
2038   if (Previous.empty())
2039     return;
2040 
2041   LookupResult::Filter Filter = Previous.makeFilter();
2042   while (Filter.hasNext()) {
2043     NamedDecl *Old = Filter.next();
2044 
2045     // Non-hidden declarations are never ignored.
2046     if (S.isVisible(Old))
2047       continue;
2048 
2049     // Declarations of the same entity are not ignored, even if they have
2050     // different linkages.
2051     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2052       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2053                                 Decl->getUnderlyingType()))
2054         continue;
2055 
2056       // If both declarations give a tag declaration a typedef name for linkage
2057       // purposes, then they declare the same entity.
2058       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2059           Decl->getAnonDeclWithTypedefName())
2060         continue;
2061     }
2062 
2063     Filter.erase();
2064   }
2065 
2066   Filter.done();
2067 }
2068 
2069 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2070   QualType OldType;
2071   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2072     OldType = OldTypedef->getUnderlyingType();
2073   else
2074     OldType = Context.getTypeDeclType(Old);
2075   QualType NewType = New->getUnderlyingType();
2076 
2077   if (NewType->isVariablyModifiedType()) {
2078     // Must not redefine a typedef with a variably-modified type.
2079     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2080     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2081       << Kind << NewType;
2082     if (Old->getLocation().isValid())
2083       notePreviousDefinition(Old, New->getLocation());
2084     New->setInvalidDecl();
2085     return true;
2086   }
2087 
2088   if (OldType != NewType &&
2089       !OldType->isDependentType() &&
2090       !NewType->isDependentType() &&
2091       !Context.hasSameType(OldType, NewType)) {
2092     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2093     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2094       << Kind << NewType << OldType;
2095     if (Old->getLocation().isValid())
2096       notePreviousDefinition(Old, New->getLocation());
2097     New->setInvalidDecl();
2098     return true;
2099   }
2100   return false;
2101 }
2102 
2103 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2104 /// same name and scope as a previous declaration 'Old'.  Figure out
2105 /// how to resolve this situation, merging decls or emitting
2106 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2107 ///
2108 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2109                                 LookupResult &OldDecls) {
2110   // If the new decl is known invalid already, don't bother doing any
2111   // merging checks.
2112   if (New->isInvalidDecl()) return;
2113 
2114   // Allow multiple definitions for ObjC built-in typedefs.
2115   // FIXME: Verify the underlying types are equivalent!
2116   if (getLangOpts().ObjC1) {
2117     const IdentifierInfo *TypeID = New->getIdentifier();
2118     switch (TypeID->getLength()) {
2119     default: break;
2120     case 2:
2121       {
2122         if (!TypeID->isStr("id"))
2123           break;
2124         QualType T = New->getUnderlyingType();
2125         if (!T->isPointerType())
2126           break;
2127         if (!T->isVoidPointerType()) {
2128           QualType PT = T->getAs<PointerType>()->getPointeeType();
2129           if (!PT->isStructureType())
2130             break;
2131         }
2132         Context.setObjCIdRedefinitionType(T);
2133         // Install the built-in type for 'id', ignoring the current definition.
2134         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2135         return;
2136       }
2137     case 5:
2138       if (!TypeID->isStr("Class"))
2139         break;
2140       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2141       // Install the built-in type for 'Class', ignoring the current definition.
2142       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2143       return;
2144     case 3:
2145       if (!TypeID->isStr("SEL"))
2146         break;
2147       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2148       // Install the built-in type for 'SEL', ignoring the current definition.
2149       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2150       return;
2151     }
2152     // Fall through - the typedef name was not a builtin type.
2153   }
2154 
2155   // Verify the old decl was also a type.
2156   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2157   if (!Old) {
2158     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2159       << New->getDeclName();
2160 
2161     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2162     if (OldD->getLocation().isValid())
2163       notePreviousDefinition(OldD, New->getLocation());
2164 
2165     return New->setInvalidDecl();
2166   }
2167 
2168   // If the old declaration is invalid, just give up here.
2169   if (Old->isInvalidDecl())
2170     return New->setInvalidDecl();
2171 
2172   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2173     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2174     auto *NewTag = New->getAnonDeclWithTypedefName();
2175     NamedDecl *Hidden = nullptr;
2176     if (OldTag && NewTag &&
2177         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2178         !hasVisibleDefinition(OldTag, &Hidden)) {
2179       // There is a definition of this tag, but it is not visible. Use it
2180       // instead of our tag.
2181       New->setTypeForDecl(OldTD->getTypeForDecl());
2182       if (OldTD->isModed())
2183         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2184                                     OldTD->getUnderlyingType());
2185       else
2186         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2187 
2188       // Make the old tag definition visible.
2189       makeMergedDefinitionVisible(Hidden);
2190 
2191       // If this was an unscoped enumeration, yank all of its enumerators
2192       // out of the scope.
2193       if (isa<EnumDecl>(NewTag)) {
2194         Scope *EnumScope = getNonFieldDeclScope(S);
2195         for (auto *D : NewTag->decls()) {
2196           auto *ED = cast<EnumConstantDecl>(D);
2197           assert(EnumScope->isDeclScope(ED));
2198           EnumScope->RemoveDecl(ED);
2199           IdResolver.RemoveDecl(ED);
2200           ED->getLexicalDeclContext()->removeDecl(ED);
2201         }
2202       }
2203     }
2204   }
2205 
2206   // If the typedef types are not identical, reject them in all languages and
2207   // with any extensions enabled.
2208   if (isIncompatibleTypedef(Old, New))
2209     return;
2210 
2211   // The types match.  Link up the redeclaration chain and merge attributes if
2212   // the old declaration was a typedef.
2213   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2214     New->setPreviousDecl(Typedef);
2215     mergeDeclAttributes(New, Old);
2216   }
2217 
2218   if (getLangOpts().MicrosoftExt)
2219     return;
2220 
2221   if (getLangOpts().CPlusPlus) {
2222     // C++ [dcl.typedef]p2:
2223     //   In a given non-class scope, a typedef specifier can be used to
2224     //   redefine the name of any type declared in that scope to refer
2225     //   to the type to which it already refers.
2226     if (!isa<CXXRecordDecl>(CurContext))
2227       return;
2228 
2229     // C++0x [dcl.typedef]p4:
2230     //   In a given class scope, a typedef specifier can be used to redefine
2231     //   any class-name declared in that scope that is not also a typedef-name
2232     //   to refer to the type to which it already refers.
2233     //
2234     // This wording came in via DR424, which was a correction to the
2235     // wording in DR56, which accidentally banned code like:
2236     //
2237     //   struct S {
2238     //     typedef struct A { } A;
2239     //   };
2240     //
2241     // in the C++03 standard. We implement the C++0x semantics, which
2242     // allow the above but disallow
2243     //
2244     //   struct S {
2245     //     typedef int I;
2246     //     typedef int I;
2247     //   };
2248     //
2249     // since that was the intent of DR56.
2250     if (!isa<TypedefNameDecl>(Old))
2251       return;
2252 
2253     Diag(New->getLocation(), diag::err_redefinition)
2254       << New->getDeclName();
2255     notePreviousDefinition(Old, New->getLocation());
2256     return New->setInvalidDecl();
2257   }
2258 
2259   // Modules always permit redefinition of typedefs, as does C11.
2260   if (getLangOpts().Modules || getLangOpts().C11)
2261     return;
2262 
2263   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2264   // is normally mapped to an error, but can be controlled with
2265   // -Wtypedef-redefinition.  If either the original or the redefinition is
2266   // in a system header, don't emit this for compatibility with GCC.
2267   if (getDiagnostics().getSuppressSystemWarnings() &&
2268       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2269       (Old->isImplicit() ||
2270        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2271        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2272     return;
2273 
2274   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2275     << New->getDeclName();
2276   notePreviousDefinition(Old, New->getLocation());
2277 }
2278 
2279 /// DeclhasAttr - returns true if decl Declaration already has the target
2280 /// attribute.
2281 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2282   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2283   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2284   for (const auto *i : D->attrs())
2285     if (i->getKind() == A->getKind()) {
2286       if (Ann) {
2287         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2288           return true;
2289         continue;
2290       }
2291       // FIXME: Don't hardcode this check
2292       if (OA && isa<OwnershipAttr>(i))
2293         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2294       return true;
2295     }
2296 
2297   return false;
2298 }
2299 
2300 static bool isAttributeTargetADefinition(Decl *D) {
2301   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2302     return VD->isThisDeclarationADefinition();
2303   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2304     return TD->isCompleteDefinition() || TD->isBeingDefined();
2305   return true;
2306 }
2307 
2308 /// Merge alignment attributes from \p Old to \p New, taking into account the
2309 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2310 ///
2311 /// \return \c true if any attributes were added to \p New.
2312 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2313   // Look for alignas attributes on Old, and pick out whichever attribute
2314   // specifies the strictest alignment requirement.
2315   AlignedAttr *OldAlignasAttr = nullptr;
2316   AlignedAttr *OldStrictestAlignAttr = nullptr;
2317   unsigned OldAlign = 0;
2318   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2319     // FIXME: We have no way of representing inherited dependent alignments
2320     // in a case like:
2321     //   template<int A, int B> struct alignas(A) X;
2322     //   template<int A, int B> struct alignas(B) X {};
2323     // For now, we just ignore any alignas attributes which are not on the
2324     // definition in such a case.
2325     if (I->isAlignmentDependent())
2326       return false;
2327 
2328     if (I->isAlignas())
2329       OldAlignasAttr = I;
2330 
2331     unsigned Align = I->getAlignment(S.Context);
2332     if (Align > OldAlign) {
2333       OldAlign = Align;
2334       OldStrictestAlignAttr = I;
2335     }
2336   }
2337 
2338   // Look for alignas attributes on New.
2339   AlignedAttr *NewAlignasAttr = nullptr;
2340   unsigned NewAlign = 0;
2341   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2342     if (I->isAlignmentDependent())
2343       return false;
2344 
2345     if (I->isAlignas())
2346       NewAlignasAttr = I;
2347 
2348     unsigned Align = I->getAlignment(S.Context);
2349     if (Align > NewAlign)
2350       NewAlign = Align;
2351   }
2352 
2353   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2354     // Both declarations have 'alignas' attributes. We require them to match.
2355     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2356     // fall short. (If two declarations both have alignas, they must both match
2357     // every definition, and so must match each other if there is a definition.)
2358 
2359     // If either declaration only contains 'alignas(0)' specifiers, then it
2360     // specifies the natural alignment for the type.
2361     if (OldAlign == 0 || NewAlign == 0) {
2362       QualType Ty;
2363       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2364         Ty = VD->getType();
2365       else
2366         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2367 
2368       if (OldAlign == 0)
2369         OldAlign = S.Context.getTypeAlign(Ty);
2370       if (NewAlign == 0)
2371         NewAlign = S.Context.getTypeAlign(Ty);
2372     }
2373 
2374     if (OldAlign != NewAlign) {
2375       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2376         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2377         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2378       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2379     }
2380   }
2381 
2382   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2383     // C++11 [dcl.align]p6:
2384     //   if any declaration of an entity has an alignment-specifier,
2385     //   every defining declaration of that entity shall specify an
2386     //   equivalent alignment.
2387     // C11 6.7.5/7:
2388     //   If the definition of an object does not have an alignment
2389     //   specifier, any other declaration of that object shall also
2390     //   have no alignment specifier.
2391     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2392       << OldAlignasAttr;
2393     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2394       << OldAlignasAttr;
2395   }
2396 
2397   bool AnyAdded = false;
2398 
2399   // Ensure we have an attribute representing the strictest alignment.
2400   if (OldAlign > NewAlign) {
2401     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2402     Clone->setInherited(true);
2403     New->addAttr(Clone);
2404     AnyAdded = true;
2405   }
2406 
2407   // Ensure we have an alignas attribute if the old declaration had one.
2408   if (OldAlignasAttr && !NewAlignasAttr &&
2409       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2410     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2411     Clone->setInherited(true);
2412     New->addAttr(Clone);
2413     AnyAdded = true;
2414   }
2415 
2416   return AnyAdded;
2417 }
2418 
2419 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2420                                const InheritableAttr *Attr,
2421                                Sema::AvailabilityMergeKind AMK) {
2422   // This function copies an attribute Attr from a previous declaration to the
2423   // new declaration D if the new declaration doesn't itself have that attribute
2424   // yet or if that attribute allows duplicates.
2425   // If you're adding a new attribute that requires logic different from
2426   // "use explicit attribute on decl if present, else use attribute from
2427   // previous decl", for example if the attribute needs to be consistent
2428   // between redeclarations, you need to call a custom merge function here.
2429   InheritableAttr *NewAttr = nullptr;
2430   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2431   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2432     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2433                                       AA->isImplicit(), AA->getIntroduced(),
2434                                       AA->getDeprecated(),
2435                                       AA->getObsoleted(), AA->getUnavailable(),
2436                                       AA->getMessage(), AA->getStrict(),
2437                                       AA->getReplacement(), AMK,
2438                                       AttrSpellingListIndex);
2439   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2440     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2441                                     AttrSpellingListIndex);
2442   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2443     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2444                                         AttrSpellingListIndex);
2445   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2446     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2447                                    AttrSpellingListIndex);
2448   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2449     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2450                                    AttrSpellingListIndex);
2451   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2452     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2453                                 FA->getFormatIdx(), FA->getFirstArg(),
2454                                 AttrSpellingListIndex);
2455   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2456     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2457                                  AttrSpellingListIndex);
2458   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2459     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2460                                        AttrSpellingListIndex,
2461                                        IA->getSemanticSpelling());
2462   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2463     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2464                                       &S.Context.Idents.get(AA->getSpelling()),
2465                                       AttrSpellingListIndex);
2466   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2467            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2468             isa<CUDAGlobalAttr>(Attr))) {
2469     // CUDA target attributes are part of function signature for
2470     // overloading purposes and must not be merged.
2471     return false;
2472   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2473     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2474   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2475     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2476   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2477     NewAttr = S.mergeInternalLinkageAttr(
2478         D, InternalLinkageA->getRange(),
2479         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2480         AttrSpellingListIndex);
2481   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2482     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2483                                 &S.Context.Idents.get(CommonA->getSpelling()),
2484                                 AttrSpellingListIndex);
2485   else if (isa<AlignedAttr>(Attr))
2486     // AlignedAttrs are handled separately, because we need to handle all
2487     // such attributes on a declaration at the same time.
2488     NewAttr = nullptr;
2489   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2490            (AMK == Sema::AMK_Override ||
2491             AMK == Sema::AMK_ProtocolImplementation))
2492     NewAttr = nullptr;
2493   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2494     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2495                               UA->getGuid());
2496   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2497     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2498 
2499   if (NewAttr) {
2500     NewAttr->setInherited(true);
2501     D->addAttr(NewAttr);
2502     if (isa<MSInheritanceAttr>(NewAttr))
2503       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2504     return true;
2505   }
2506 
2507   return false;
2508 }
2509 
2510 static const NamedDecl *getDefinition(const Decl *D) {
2511   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2512     return TD->getDefinition();
2513   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2514     const VarDecl *Def = VD->getDefinition();
2515     if (Def)
2516       return Def;
2517     return VD->getActingDefinition();
2518   }
2519   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2520     return FD->getDefinition();
2521   return nullptr;
2522 }
2523 
2524 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2525   for (const auto *Attribute : D->attrs())
2526     if (Attribute->getKind() == Kind)
2527       return true;
2528   return false;
2529 }
2530 
2531 /// checkNewAttributesAfterDef - If we already have a definition, check that
2532 /// there are no new attributes in this declaration.
2533 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2534   if (!New->hasAttrs())
2535     return;
2536 
2537   const NamedDecl *Def = getDefinition(Old);
2538   if (!Def || Def == New)
2539     return;
2540 
2541   AttrVec &NewAttributes = New->getAttrs();
2542   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2543     const Attr *NewAttribute = NewAttributes[I];
2544 
2545     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2546       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2547         Sema::SkipBodyInfo SkipBody;
2548         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2549 
2550         // If we're skipping this definition, drop the "alias" attribute.
2551         if (SkipBody.ShouldSkip) {
2552           NewAttributes.erase(NewAttributes.begin() + I);
2553           --E;
2554           continue;
2555         }
2556       } else {
2557         VarDecl *VD = cast<VarDecl>(New);
2558         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2559                                 VarDecl::TentativeDefinition
2560                             ? diag::err_alias_after_tentative
2561                             : diag::err_redefinition;
2562         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2563         if (Diag == diag::err_redefinition)
2564           S.notePreviousDefinition(Def, VD->getLocation());
2565         else
2566           S.Diag(Def->getLocation(), diag::note_previous_definition);
2567         VD->setInvalidDecl();
2568       }
2569       ++I;
2570       continue;
2571     }
2572 
2573     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2574       // Tentative definitions are only interesting for the alias check above.
2575       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2576         ++I;
2577         continue;
2578       }
2579     }
2580 
2581     if (hasAttribute(Def, NewAttribute->getKind())) {
2582       ++I;
2583       continue; // regular attr merging will take care of validating this.
2584     }
2585 
2586     if (isa<C11NoReturnAttr>(NewAttribute)) {
2587       // C's _Noreturn is allowed to be added to a function after it is defined.
2588       ++I;
2589       continue;
2590     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2591       if (AA->isAlignas()) {
2592         // C++11 [dcl.align]p6:
2593         //   if any declaration of an entity has an alignment-specifier,
2594         //   every defining declaration of that entity shall specify an
2595         //   equivalent alignment.
2596         // C11 6.7.5/7:
2597         //   If the definition of an object does not have an alignment
2598         //   specifier, any other declaration of that object shall also
2599         //   have no alignment specifier.
2600         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2601           << AA;
2602         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2603           << AA;
2604         NewAttributes.erase(NewAttributes.begin() + I);
2605         --E;
2606         continue;
2607       }
2608     }
2609 
2610     S.Diag(NewAttribute->getLocation(),
2611            diag::warn_attribute_precede_definition);
2612     S.Diag(Def->getLocation(), diag::note_previous_definition);
2613     NewAttributes.erase(NewAttributes.begin() + I);
2614     --E;
2615   }
2616 }
2617 
2618 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2619 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2620                                AvailabilityMergeKind AMK) {
2621   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2622     UsedAttr *NewAttr = OldAttr->clone(Context);
2623     NewAttr->setInherited(true);
2624     New->addAttr(NewAttr);
2625   }
2626 
2627   if (!Old->hasAttrs() && !New->hasAttrs())
2628     return;
2629 
2630   // Attributes declared post-definition are currently ignored.
2631   checkNewAttributesAfterDef(*this, New, Old);
2632 
2633   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2634     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2635       if (OldA->getLabel() != NewA->getLabel()) {
2636         // This redeclaration changes __asm__ label.
2637         Diag(New->getLocation(), diag::err_different_asm_label);
2638         Diag(OldA->getLocation(), diag::note_previous_declaration);
2639       }
2640     } else if (Old->isUsed()) {
2641       // This redeclaration adds an __asm__ label to a declaration that has
2642       // already been ODR-used.
2643       Diag(New->getLocation(), diag::err_late_asm_label_name)
2644         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2645     }
2646   }
2647 
2648   // Re-declaration cannot add abi_tag's.
2649   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2650     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2651       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2652         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2653                       NewTag) == OldAbiTagAttr->tags_end()) {
2654           Diag(NewAbiTagAttr->getLocation(),
2655                diag::err_new_abi_tag_on_redeclaration)
2656               << NewTag;
2657           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2658         }
2659       }
2660     } else {
2661       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2662       Diag(Old->getLocation(), diag::note_previous_declaration);
2663     }
2664   }
2665 
2666   // This redeclaration adds a section attribute.
2667   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2668     if (auto *VD = dyn_cast<VarDecl>(New)) {
2669       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2670         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2671         Diag(Old->getLocation(), diag::note_previous_declaration);
2672       }
2673     }
2674   }
2675 
2676   if (!Old->hasAttrs())
2677     return;
2678 
2679   bool foundAny = New->hasAttrs();
2680 
2681   // Ensure that any moving of objects within the allocated map is done before
2682   // we process them.
2683   if (!foundAny) New->setAttrs(AttrVec());
2684 
2685   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2686     // Ignore deprecated/unavailable/availability attributes if requested.
2687     AvailabilityMergeKind LocalAMK = AMK_None;
2688     if (isa<DeprecatedAttr>(I) ||
2689         isa<UnavailableAttr>(I) ||
2690         isa<AvailabilityAttr>(I)) {
2691       switch (AMK) {
2692       case AMK_None:
2693         continue;
2694 
2695       case AMK_Redeclaration:
2696       case AMK_Override:
2697       case AMK_ProtocolImplementation:
2698         LocalAMK = AMK;
2699         break;
2700       }
2701     }
2702 
2703     // Already handled.
2704     if (isa<UsedAttr>(I))
2705       continue;
2706 
2707     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2708       foundAny = true;
2709   }
2710 
2711   if (mergeAlignedAttrs(*this, New, Old))
2712     foundAny = true;
2713 
2714   if (!foundAny) New->dropAttrs();
2715 }
2716 
2717 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2718 /// to the new one.
2719 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2720                                      const ParmVarDecl *oldDecl,
2721                                      Sema &S) {
2722   // C++11 [dcl.attr.depend]p2:
2723   //   The first declaration of a function shall specify the
2724   //   carries_dependency attribute for its declarator-id if any declaration
2725   //   of the function specifies the carries_dependency attribute.
2726   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2727   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2728     S.Diag(CDA->getLocation(),
2729            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2730     // Find the first declaration of the parameter.
2731     // FIXME: Should we build redeclaration chains for function parameters?
2732     const FunctionDecl *FirstFD =
2733       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2734     const ParmVarDecl *FirstVD =
2735       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2736     S.Diag(FirstVD->getLocation(),
2737            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2738   }
2739 
2740   if (!oldDecl->hasAttrs())
2741     return;
2742 
2743   bool foundAny = newDecl->hasAttrs();
2744 
2745   // Ensure that any moving of objects within the allocated map is
2746   // done before we process them.
2747   if (!foundAny) newDecl->setAttrs(AttrVec());
2748 
2749   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2750     if (!DeclHasAttr(newDecl, I)) {
2751       InheritableAttr *newAttr =
2752         cast<InheritableParamAttr>(I->clone(S.Context));
2753       newAttr->setInherited(true);
2754       newDecl->addAttr(newAttr);
2755       foundAny = true;
2756     }
2757   }
2758 
2759   if (!foundAny) newDecl->dropAttrs();
2760 }
2761 
2762 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2763                                 const ParmVarDecl *OldParam,
2764                                 Sema &S) {
2765   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2766     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2767       if (*Oldnullability != *Newnullability) {
2768         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2769           << DiagNullabilityKind(
2770                *Newnullability,
2771                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2772                 != 0))
2773           << DiagNullabilityKind(
2774                *Oldnullability,
2775                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2776                 != 0));
2777         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2778       }
2779     } else {
2780       QualType NewT = NewParam->getType();
2781       NewT = S.Context.getAttributedType(
2782                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2783                          NewT, NewT);
2784       NewParam->setType(NewT);
2785     }
2786   }
2787 }
2788 
2789 namespace {
2790 
2791 /// Used in MergeFunctionDecl to keep track of function parameters in
2792 /// C.
2793 struct GNUCompatibleParamWarning {
2794   ParmVarDecl *OldParm;
2795   ParmVarDecl *NewParm;
2796   QualType PromotedType;
2797 };
2798 
2799 } // end anonymous namespace
2800 
2801 /// getSpecialMember - get the special member enum for a method.
2802 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2803   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2804     if (Ctor->isDefaultConstructor())
2805       return Sema::CXXDefaultConstructor;
2806 
2807     if (Ctor->isCopyConstructor())
2808       return Sema::CXXCopyConstructor;
2809 
2810     if (Ctor->isMoveConstructor())
2811       return Sema::CXXMoveConstructor;
2812   } else if (isa<CXXDestructorDecl>(MD)) {
2813     return Sema::CXXDestructor;
2814   } else if (MD->isCopyAssignmentOperator()) {
2815     return Sema::CXXCopyAssignment;
2816   } else if (MD->isMoveAssignmentOperator()) {
2817     return Sema::CXXMoveAssignment;
2818   }
2819 
2820   return Sema::CXXInvalid;
2821 }
2822 
2823 // Determine whether the previous declaration was a definition, implicit
2824 // declaration, or a declaration.
2825 template <typename T>
2826 static std::pair<diag::kind, SourceLocation>
2827 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2828   diag::kind PrevDiag;
2829   SourceLocation OldLocation = Old->getLocation();
2830   if (Old->isThisDeclarationADefinition())
2831     PrevDiag = diag::note_previous_definition;
2832   else if (Old->isImplicit()) {
2833     PrevDiag = diag::note_previous_implicit_declaration;
2834     if (OldLocation.isInvalid())
2835       OldLocation = New->getLocation();
2836   } else
2837     PrevDiag = diag::note_previous_declaration;
2838   return std::make_pair(PrevDiag, OldLocation);
2839 }
2840 
2841 /// canRedefineFunction - checks if a function can be redefined. Currently,
2842 /// only extern inline functions can be redefined, and even then only in
2843 /// GNU89 mode.
2844 static bool canRedefineFunction(const FunctionDecl *FD,
2845                                 const LangOptions& LangOpts) {
2846   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2847           !LangOpts.CPlusPlus &&
2848           FD->isInlineSpecified() &&
2849           FD->getStorageClass() == SC_Extern);
2850 }
2851 
2852 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2853   const AttributedType *AT = T->getAs<AttributedType>();
2854   while (AT && !AT->isCallingConv())
2855     AT = AT->getModifiedType()->getAs<AttributedType>();
2856   return AT;
2857 }
2858 
2859 template <typename T>
2860 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2861   const DeclContext *DC = Old->getDeclContext();
2862   if (DC->isRecord())
2863     return false;
2864 
2865   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2866   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2867     return true;
2868   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2869     return true;
2870   return false;
2871 }
2872 
2873 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2874 static bool isExternC(VarTemplateDecl *) { return false; }
2875 
2876 /// \brief Check whether a redeclaration of an entity introduced by a
2877 /// using-declaration is valid, given that we know it's not an overload
2878 /// (nor a hidden tag declaration).
2879 template<typename ExpectedDecl>
2880 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2881                                    ExpectedDecl *New) {
2882   // C++11 [basic.scope.declarative]p4:
2883   //   Given a set of declarations in a single declarative region, each of
2884   //   which specifies the same unqualified name,
2885   //   -- they shall all refer to the same entity, or all refer to functions
2886   //      and function templates; or
2887   //   -- exactly one declaration shall declare a class name or enumeration
2888   //      name that is not a typedef name and the other declarations shall all
2889   //      refer to the same variable or enumerator, or all refer to functions
2890   //      and function templates; in this case the class name or enumeration
2891   //      name is hidden (3.3.10).
2892 
2893   // C++11 [namespace.udecl]p14:
2894   //   If a function declaration in namespace scope or block scope has the
2895   //   same name and the same parameter-type-list as a function introduced
2896   //   by a using-declaration, and the declarations do not declare the same
2897   //   function, the program is ill-formed.
2898 
2899   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2900   if (Old &&
2901       !Old->getDeclContext()->getRedeclContext()->Equals(
2902           New->getDeclContext()->getRedeclContext()) &&
2903       !(isExternC(Old) && isExternC(New)))
2904     Old = nullptr;
2905 
2906   if (!Old) {
2907     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2908     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2909     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2910     return true;
2911   }
2912   return false;
2913 }
2914 
2915 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2916                                             const FunctionDecl *B) {
2917   assert(A->getNumParams() == B->getNumParams());
2918 
2919   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2920     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2921     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2922     if (AttrA == AttrB)
2923       return true;
2924     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2925   };
2926 
2927   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2928 }
2929 
2930 /// If necessary, adjust the semantic declaration context for a qualified
2931 /// declaration to name the correct inline namespace within the qualifier.
2932 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
2933                                                DeclaratorDecl *OldD) {
2934   // The only case where we need to update the DeclContext is when
2935   // redeclaration lookup for a qualified name finds a declaration
2936   // in an inline namespace within the context named by the qualifier:
2937   //
2938   //   inline namespace N { int f(); }
2939   //   int ::f(); // Sema DC needs adjusting from :: to N::.
2940   //
2941   // For unqualified declarations, the semantic context *can* change
2942   // along the redeclaration chain (for local extern declarations,
2943   // extern "C" declarations, and friend declarations in particular).
2944   if (!NewD->getQualifier())
2945     return;
2946 
2947   // NewD is probably already in the right context.
2948   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
2949   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
2950   if (NamedDC->Equals(SemaDC))
2951     return;
2952 
2953   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
2954           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
2955          "unexpected context for redeclaration");
2956 
2957   auto *LexDC = NewD->getLexicalDeclContext();
2958   auto FixSemaDC = [=](NamedDecl *D) {
2959     if (!D)
2960       return;
2961     D->setDeclContext(SemaDC);
2962     D->setLexicalDeclContext(LexDC);
2963   };
2964 
2965   FixSemaDC(NewD);
2966   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
2967     FixSemaDC(FD->getDescribedFunctionTemplate());
2968   else if (auto *VD = dyn_cast<VarDecl>(NewD))
2969     FixSemaDC(VD->getDescribedVarTemplate());
2970 }
2971 
2972 /// MergeFunctionDecl - We just parsed a function 'New' from
2973 /// declarator D which has the same name and scope as a previous
2974 /// declaration 'Old'.  Figure out how to resolve this situation,
2975 /// merging decls or emitting diagnostics as appropriate.
2976 ///
2977 /// In C++, New and Old must be declarations that are not
2978 /// overloaded. Use IsOverload to determine whether New and Old are
2979 /// overloaded, and to select the Old declaration that New should be
2980 /// merged with.
2981 ///
2982 /// Returns true if there was an error, false otherwise.
2983 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2984                              Scope *S, bool MergeTypeWithOld) {
2985   // Verify the old decl was also a function.
2986   FunctionDecl *Old = OldD->getAsFunction();
2987   if (!Old) {
2988     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2989       if (New->getFriendObjectKind()) {
2990         Diag(New->getLocation(), diag::err_using_decl_friend);
2991         Diag(Shadow->getTargetDecl()->getLocation(),
2992              diag::note_using_decl_target);
2993         Diag(Shadow->getUsingDecl()->getLocation(),
2994              diag::note_using_decl) << 0;
2995         return true;
2996       }
2997 
2998       // Check whether the two declarations might declare the same function.
2999       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3000         return true;
3001       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3002     } else {
3003       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3004         << New->getDeclName();
3005       notePreviousDefinition(OldD, New->getLocation());
3006       return true;
3007     }
3008   }
3009 
3010   // If the old declaration is invalid, just give up here.
3011   if (Old->isInvalidDecl())
3012     return true;
3013 
3014   diag::kind PrevDiag;
3015   SourceLocation OldLocation;
3016   std::tie(PrevDiag, OldLocation) =
3017       getNoteDiagForInvalidRedeclaration(Old, New);
3018 
3019   // Don't complain about this if we're in GNU89 mode and the old function
3020   // is an extern inline function.
3021   // Don't complain about specializations. They are not supposed to have
3022   // storage classes.
3023   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3024       New->getStorageClass() == SC_Static &&
3025       Old->hasExternalFormalLinkage() &&
3026       !New->getTemplateSpecializationInfo() &&
3027       !canRedefineFunction(Old, getLangOpts())) {
3028     if (getLangOpts().MicrosoftExt) {
3029       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3030       Diag(OldLocation, PrevDiag);
3031     } else {
3032       Diag(New->getLocation(), diag::err_static_non_static) << New;
3033       Diag(OldLocation, PrevDiag);
3034       return true;
3035     }
3036   }
3037 
3038   if (New->hasAttr<InternalLinkageAttr>() &&
3039       !Old->hasAttr<InternalLinkageAttr>()) {
3040     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3041         << New->getDeclName();
3042     notePreviousDefinition(Old, New->getLocation());
3043     New->dropAttr<InternalLinkageAttr>();
3044   }
3045 
3046   if (CheckRedeclarationModuleOwnership(New, Old))
3047     return true;
3048 
3049   if (!getLangOpts().CPlusPlus) {
3050     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3051     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3052       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3053         << New << OldOvl;
3054 
3055       // Try our best to find a decl that actually has the overloadable
3056       // attribute for the note. In most cases (e.g. programs with only one
3057       // broken declaration/definition), this won't matter.
3058       //
3059       // FIXME: We could do this if we juggled some extra state in
3060       // OverloadableAttr, rather than just removing it.
3061       const Decl *DiagOld = Old;
3062       if (OldOvl) {
3063         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3064           const auto *A = D->getAttr<OverloadableAttr>();
3065           return A && !A->isImplicit();
3066         });
3067         // If we've implicitly added *all* of the overloadable attrs to this
3068         // chain, emitting a "previous redecl" note is pointless.
3069         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3070       }
3071 
3072       if (DiagOld)
3073         Diag(DiagOld->getLocation(),
3074              diag::note_attribute_overloadable_prev_overload)
3075           << OldOvl;
3076 
3077       if (OldOvl)
3078         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3079       else
3080         New->dropAttr<OverloadableAttr>();
3081     }
3082   }
3083 
3084   // If a function is first declared with a calling convention, but is later
3085   // declared or defined without one, all following decls assume the calling
3086   // convention of the first.
3087   //
3088   // It's OK if a function is first declared without a calling convention,
3089   // but is later declared or defined with the default calling convention.
3090   //
3091   // To test if either decl has an explicit calling convention, we look for
3092   // AttributedType sugar nodes on the type as written.  If they are missing or
3093   // were canonicalized away, we assume the calling convention was implicit.
3094   //
3095   // Note also that we DO NOT return at this point, because we still have
3096   // other tests to run.
3097   QualType OldQType = Context.getCanonicalType(Old->getType());
3098   QualType NewQType = Context.getCanonicalType(New->getType());
3099   const FunctionType *OldType = cast<FunctionType>(OldQType);
3100   const FunctionType *NewType = cast<FunctionType>(NewQType);
3101   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3102   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3103   bool RequiresAdjustment = false;
3104 
3105   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3106     FunctionDecl *First = Old->getFirstDecl();
3107     const FunctionType *FT =
3108         First->getType().getCanonicalType()->castAs<FunctionType>();
3109     FunctionType::ExtInfo FI = FT->getExtInfo();
3110     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3111     if (!NewCCExplicit) {
3112       // Inherit the CC from the previous declaration if it was specified
3113       // there but not here.
3114       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3115       RequiresAdjustment = true;
3116     } else {
3117       // Calling conventions aren't compatible, so complain.
3118       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3119       Diag(New->getLocation(), diag::err_cconv_change)
3120         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3121         << !FirstCCExplicit
3122         << (!FirstCCExplicit ? "" :
3123             FunctionType::getNameForCallConv(FI.getCC()));
3124 
3125       // Put the note on the first decl, since it is the one that matters.
3126       Diag(First->getLocation(), diag::note_previous_declaration);
3127       return true;
3128     }
3129   }
3130 
3131   // FIXME: diagnose the other way around?
3132   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3133     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3134     RequiresAdjustment = true;
3135   }
3136 
3137   // Merge regparm attribute.
3138   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3139       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3140     if (NewTypeInfo.getHasRegParm()) {
3141       Diag(New->getLocation(), diag::err_regparm_mismatch)
3142         << NewType->getRegParmType()
3143         << OldType->getRegParmType();
3144       Diag(OldLocation, diag::note_previous_declaration);
3145       return true;
3146     }
3147 
3148     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3149     RequiresAdjustment = true;
3150   }
3151 
3152   // Merge ns_returns_retained attribute.
3153   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3154     if (NewTypeInfo.getProducesResult()) {
3155       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3156           << "'ns_returns_retained'";
3157       Diag(OldLocation, diag::note_previous_declaration);
3158       return true;
3159     }
3160 
3161     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3162     RequiresAdjustment = true;
3163   }
3164 
3165   if (OldTypeInfo.getNoCallerSavedRegs() !=
3166       NewTypeInfo.getNoCallerSavedRegs()) {
3167     if (NewTypeInfo.getNoCallerSavedRegs()) {
3168       AnyX86NoCallerSavedRegistersAttr *Attr =
3169         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3170       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3171       Diag(OldLocation, diag::note_previous_declaration);
3172       return true;
3173     }
3174 
3175     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3176     RequiresAdjustment = true;
3177   }
3178 
3179   if (RequiresAdjustment) {
3180     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3181     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3182     New->setType(QualType(AdjustedType, 0));
3183     NewQType = Context.getCanonicalType(New->getType());
3184     NewType = cast<FunctionType>(NewQType);
3185   }
3186 
3187   // If this redeclaration makes the function inline, we may need to add it to
3188   // UndefinedButUsed.
3189   if (!Old->isInlined() && New->isInlined() &&
3190       !New->hasAttr<GNUInlineAttr>() &&
3191       !getLangOpts().GNUInline &&
3192       Old->isUsed(false) &&
3193       !Old->isDefined() && !New->isThisDeclarationADefinition())
3194     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3195                                            SourceLocation()));
3196 
3197   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3198   // about it.
3199   if (New->hasAttr<GNUInlineAttr>() &&
3200       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3201     UndefinedButUsed.erase(Old->getCanonicalDecl());
3202   }
3203 
3204   // If pass_object_size params don't match up perfectly, this isn't a valid
3205   // redeclaration.
3206   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3207       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3208     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3209         << New->getDeclName();
3210     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3211     return true;
3212   }
3213 
3214   if (getLangOpts().CPlusPlus) {
3215     // C++1z [over.load]p2
3216     //   Certain function declarations cannot be overloaded:
3217     //     -- Function declarations that differ only in the return type,
3218     //        the exception specification, or both cannot be overloaded.
3219 
3220     // Check the exception specifications match. This may recompute the type of
3221     // both Old and New if it resolved exception specifications, so grab the
3222     // types again after this. Because this updates the type, we do this before
3223     // any of the other checks below, which may update the "de facto" NewQType
3224     // but do not necessarily update the type of New.
3225     if (CheckEquivalentExceptionSpec(Old, New))
3226       return true;
3227     OldQType = Context.getCanonicalType(Old->getType());
3228     NewQType = Context.getCanonicalType(New->getType());
3229 
3230     // Go back to the type source info to compare the declared return types,
3231     // per C++1y [dcl.type.auto]p13:
3232     //   Redeclarations or specializations of a function or function template
3233     //   with a declared return type that uses a placeholder type shall also
3234     //   use that placeholder, not a deduced type.
3235     QualType OldDeclaredReturnType =
3236         (Old->getTypeSourceInfo()
3237              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3238              : OldType)->getReturnType();
3239     QualType NewDeclaredReturnType =
3240         (New->getTypeSourceInfo()
3241              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3242              : NewType)->getReturnType();
3243     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3244         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3245           New->isLocalExternDecl())) {
3246       QualType ResQT;
3247       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3248           OldDeclaredReturnType->isObjCObjectPointerType())
3249         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3250       if (ResQT.isNull()) {
3251         if (New->isCXXClassMember() && New->isOutOfLine())
3252           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3253               << New << New->getReturnTypeSourceRange();
3254         else
3255           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3256               << New->getReturnTypeSourceRange();
3257         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3258                                     << Old->getReturnTypeSourceRange();
3259         return true;
3260       }
3261       else
3262         NewQType = ResQT;
3263     }
3264 
3265     QualType OldReturnType = OldType->getReturnType();
3266     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3267     if (OldReturnType != NewReturnType) {
3268       // If this function has a deduced return type and has already been
3269       // defined, copy the deduced value from the old declaration.
3270       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3271       if (OldAT && OldAT->isDeduced()) {
3272         New->setType(
3273             SubstAutoType(New->getType(),
3274                           OldAT->isDependentType() ? Context.DependentTy
3275                                                    : OldAT->getDeducedType()));
3276         NewQType = Context.getCanonicalType(
3277             SubstAutoType(NewQType,
3278                           OldAT->isDependentType() ? Context.DependentTy
3279                                                    : OldAT->getDeducedType()));
3280       }
3281     }
3282 
3283     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3284     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3285     if (OldMethod && NewMethod) {
3286       // Preserve triviality.
3287       NewMethod->setTrivial(OldMethod->isTrivial());
3288 
3289       // MSVC allows explicit template specialization at class scope:
3290       // 2 CXXMethodDecls referring to the same function will be injected.
3291       // We don't want a redeclaration error.
3292       bool IsClassScopeExplicitSpecialization =
3293                               OldMethod->isFunctionTemplateSpecialization() &&
3294                               NewMethod->isFunctionTemplateSpecialization();
3295       bool isFriend = NewMethod->getFriendObjectKind();
3296 
3297       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3298           !IsClassScopeExplicitSpecialization) {
3299         //    -- Member function declarations with the same name and the
3300         //       same parameter types cannot be overloaded if any of them
3301         //       is a static member function declaration.
3302         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3303           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3304           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3305           return true;
3306         }
3307 
3308         // C++ [class.mem]p1:
3309         //   [...] A member shall not be declared twice in the
3310         //   member-specification, except that a nested class or member
3311         //   class template can be declared and then later defined.
3312         if (!inTemplateInstantiation()) {
3313           unsigned NewDiag;
3314           if (isa<CXXConstructorDecl>(OldMethod))
3315             NewDiag = diag::err_constructor_redeclared;
3316           else if (isa<CXXDestructorDecl>(NewMethod))
3317             NewDiag = diag::err_destructor_redeclared;
3318           else if (isa<CXXConversionDecl>(NewMethod))
3319             NewDiag = diag::err_conv_function_redeclared;
3320           else
3321             NewDiag = diag::err_member_redeclared;
3322 
3323           Diag(New->getLocation(), NewDiag);
3324         } else {
3325           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3326             << New << New->getType();
3327         }
3328         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3329         return true;
3330 
3331       // Complain if this is an explicit declaration of a special
3332       // member that was initially declared implicitly.
3333       //
3334       // As an exception, it's okay to befriend such methods in order
3335       // to permit the implicit constructor/destructor/operator calls.
3336       } else if (OldMethod->isImplicit()) {
3337         if (isFriend) {
3338           NewMethod->setImplicit();
3339         } else {
3340           Diag(NewMethod->getLocation(),
3341                diag::err_definition_of_implicitly_declared_member)
3342             << New << getSpecialMember(OldMethod);
3343           return true;
3344         }
3345       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3346         Diag(NewMethod->getLocation(),
3347              diag::err_definition_of_explicitly_defaulted_member)
3348           << getSpecialMember(OldMethod);
3349         return true;
3350       }
3351     }
3352 
3353     // C++11 [dcl.attr.noreturn]p1:
3354     //   The first declaration of a function shall specify the noreturn
3355     //   attribute if any declaration of that function specifies the noreturn
3356     //   attribute.
3357     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3358     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3359       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3360       Diag(Old->getFirstDecl()->getLocation(),
3361            diag::note_noreturn_missing_first_decl);
3362     }
3363 
3364     // C++11 [dcl.attr.depend]p2:
3365     //   The first declaration of a function shall specify the
3366     //   carries_dependency attribute for its declarator-id if any declaration
3367     //   of the function specifies the carries_dependency attribute.
3368     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3369     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3370       Diag(CDA->getLocation(),
3371            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3372       Diag(Old->getFirstDecl()->getLocation(),
3373            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3374     }
3375 
3376     // (C++98 8.3.5p3):
3377     //   All declarations for a function shall agree exactly in both the
3378     //   return type and the parameter-type-list.
3379     // We also want to respect all the extended bits except noreturn.
3380 
3381     // noreturn should now match unless the old type info didn't have it.
3382     QualType OldQTypeForComparison = OldQType;
3383     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3384       auto *OldType = OldQType->castAs<FunctionProtoType>();
3385       const FunctionType *OldTypeForComparison
3386         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3387       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3388       assert(OldQTypeForComparison.isCanonical());
3389     }
3390 
3391     if (haveIncompatibleLanguageLinkages(Old, New)) {
3392       // As a special case, retain the language linkage from previous
3393       // declarations of a friend function as an extension.
3394       //
3395       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3396       // and is useful because there's otherwise no way to specify language
3397       // linkage within class scope.
3398       //
3399       // Check cautiously as the friend object kind isn't yet complete.
3400       if (New->getFriendObjectKind() != Decl::FOK_None) {
3401         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3402         Diag(OldLocation, PrevDiag);
3403       } else {
3404         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3405         Diag(OldLocation, PrevDiag);
3406         return true;
3407       }
3408     }
3409 
3410     if (OldQTypeForComparison == NewQType)
3411       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3412 
3413     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3414         New->isLocalExternDecl()) {
3415       // It's OK if we couldn't merge types for a local function declaraton
3416       // if either the old or new type is dependent. We'll merge the types
3417       // when we instantiate the function.
3418       return false;
3419     }
3420 
3421     // Fall through for conflicting redeclarations and redefinitions.
3422   }
3423 
3424   // C: Function types need to be compatible, not identical. This handles
3425   // duplicate function decls like "void f(int); void f(enum X);" properly.
3426   if (!getLangOpts().CPlusPlus &&
3427       Context.typesAreCompatible(OldQType, NewQType)) {
3428     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3429     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3430     const FunctionProtoType *OldProto = nullptr;
3431     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3432         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3433       // The old declaration provided a function prototype, but the
3434       // new declaration does not. Merge in the prototype.
3435       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3436       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3437       NewQType =
3438           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3439                                   OldProto->getExtProtoInfo());
3440       New->setType(NewQType);
3441       New->setHasInheritedPrototype();
3442 
3443       // Synthesize parameters with the same types.
3444       SmallVector<ParmVarDecl*, 16> Params;
3445       for (const auto &ParamType : OldProto->param_types()) {
3446         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3447                                                  SourceLocation(), nullptr,
3448                                                  ParamType, /*TInfo=*/nullptr,
3449                                                  SC_None, nullptr);
3450         Param->setScopeInfo(0, Params.size());
3451         Param->setImplicit();
3452         Params.push_back(Param);
3453       }
3454 
3455       New->setParams(Params);
3456     }
3457 
3458     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3459   }
3460 
3461   // GNU C permits a K&R definition to follow a prototype declaration
3462   // if the declared types of the parameters in the K&R definition
3463   // match the types in the prototype declaration, even when the
3464   // promoted types of the parameters from the K&R definition differ
3465   // from the types in the prototype. GCC then keeps the types from
3466   // the prototype.
3467   //
3468   // If a variadic prototype is followed by a non-variadic K&R definition,
3469   // the K&R definition becomes variadic.  This is sort of an edge case, but
3470   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3471   // C99 6.9.1p8.
3472   if (!getLangOpts().CPlusPlus &&
3473       Old->hasPrototype() && !New->hasPrototype() &&
3474       New->getType()->getAs<FunctionProtoType>() &&
3475       Old->getNumParams() == New->getNumParams()) {
3476     SmallVector<QualType, 16> ArgTypes;
3477     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3478     const FunctionProtoType *OldProto
3479       = Old->getType()->getAs<FunctionProtoType>();
3480     const FunctionProtoType *NewProto
3481       = New->getType()->getAs<FunctionProtoType>();
3482 
3483     // Determine whether this is the GNU C extension.
3484     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3485                                                NewProto->getReturnType());
3486     bool LooseCompatible = !MergedReturn.isNull();
3487     for (unsigned Idx = 0, End = Old->getNumParams();
3488          LooseCompatible && Idx != End; ++Idx) {
3489       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3490       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3491       if (Context.typesAreCompatible(OldParm->getType(),
3492                                      NewProto->getParamType(Idx))) {
3493         ArgTypes.push_back(NewParm->getType());
3494       } else if (Context.typesAreCompatible(OldParm->getType(),
3495                                             NewParm->getType(),
3496                                             /*CompareUnqualified=*/true)) {
3497         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3498                                            NewProto->getParamType(Idx) };
3499         Warnings.push_back(Warn);
3500         ArgTypes.push_back(NewParm->getType());
3501       } else
3502         LooseCompatible = false;
3503     }
3504 
3505     if (LooseCompatible) {
3506       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3507         Diag(Warnings[Warn].NewParm->getLocation(),
3508              diag::ext_param_promoted_not_compatible_with_prototype)
3509           << Warnings[Warn].PromotedType
3510           << Warnings[Warn].OldParm->getType();
3511         if (Warnings[Warn].OldParm->getLocation().isValid())
3512           Diag(Warnings[Warn].OldParm->getLocation(),
3513                diag::note_previous_declaration);
3514       }
3515 
3516       if (MergeTypeWithOld)
3517         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3518                                              OldProto->getExtProtoInfo()));
3519       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3520     }
3521 
3522     // Fall through to diagnose conflicting types.
3523   }
3524 
3525   // A function that has already been declared has been redeclared or
3526   // defined with a different type; show an appropriate diagnostic.
3527 
3528   // If the previous declaration was an implicitly-generated builtin
3529   // declaration, then at the very least we should use a specialized note.
3530   unsigned BuiltinID;
3531   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3532     // If it's actually a library-defined builtin function like 'malloc'
3533     // or 'printf', just warn about the incompatible redeclaration.
3534     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3535       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3536       Diag(OldLocation, diag::note_previous_builtin_declaration)
3537         << Old << Old->getType();
3538 
3539       // If this is a global redeclaration, just forget hereafter
3540       // about the "builtin-ness" of the function.
3541       //
3542       // Doing this for local extern declarations is problematic.  If
3543       // the builtin declaration remains visible, a second invalid
3544       // local declaration will produce a hard error; if it doesn't
3545       // remain visible, a single bogus local redeclaration (which is
3546       // actually only a warning) could break all the downstream code.
3547       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3548         New->getIdentifier()->revertBuiltin();
3549 
3550       return false;
3551     }
3552 
3553     PrevDiag = diag::note_previous_builtin_declaration;
3554   }
3555 
3556   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3557   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3558   return true;
3559 }
3560 
3561 /// \brief Completes the merge of two function declarations that are
3562 /// known to be compatible.
3563 ///
3564 /// This routine handles the merging of attributes and other
3565 /// properties of function declarations from the old declaration to
3566 /// the new declaration, once we know that New is in fact a
3567 /// redeclaration of Old.
3568 ///
3569 /// \returns false
3570 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3571                                         Scope *S, bool MergeTypeWithOld) {
3572   // Merge the attributes
3573   mergeDeclAttributes(New, Old);
3574 
3575   // Merge "pure" flag.
3576   if (Old->isPure())
3577     New->setPure();
3578 
3579   // Merge "used" flag.
3580   if (Old->getMostRecentDecl()->isUsed(false))
3581     New->setIsUsed();
3582 
3583   // Merge attributes from the parameters.  These can mismatch with K&R
3584   // declarations.
3585   if (New->getNumParams() == Old->getNumParams())
3586       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3587         ParmVarDecl *NewParam = New->getParamDecl(i);
3588         ParmVarDecl *OldParam = Old->getParamDecl(i);
3589         mergeParamDeclAttributes(NewParam, OldParam, *this);
3590         mergeParamDeclTypes(NewParam, OldParam, *this);
3591       }
3592 
3593   if (getLangOpts().CPlusPlus)
3594     return MergeCXXFunctionDecl(New, Old, S);
3595 
3596   // Merge the function types so the we get the composite types for the return
3597   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3598   // was visible.
3599   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3600   if (!Merged.isNull() && MergeTypeWithOld)
3601     New->setType(Merged);
3602 
3603   return false;
3604 }
3605 
3606 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3607                                 ObjCMethodDecl *oldMethod) {
3608   // Merge the attributes, including deprecated/unavailable
3609   AvailabilityMergeKind MergeKind =
3610     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3611       ? AMK_ProtocolImplementation
3612       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3613                                                        : AMK_Override;
3614 
3615   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3616 
3617   // Merge attributes from the parameters.
3618   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3619                                        oe = oldMethod->param_end();
3620   for (ObjCMethodDecl::param_iterator
3621          ni = newMethod->param_begin(), ne = newMethod->param_end();
3622        ni != ne && oi != oe; ++ni, ++oi)
3623     mergeParamDeclAttributes(*ni, *oi, *this);
3624 
3625   CheckObjCMethodOverride(newMethod, oldMethod);
3626 }
3627 
3628 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3629   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3630 
3631   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3632          ? diag::err_redefinition_different_type
3633          : diag::err_redeclaration_different_type)
3634     << New->getDeclName() << New->getType() << Old->getType();
3635 
3636   diag::kind PrevDiag;
3637   SourceLocation OldLocation;
3638   std::tie(PrevDiag, OldLocation)
3639     = getNoteDiagForInvalidRedeclaration(Old, New);
3640   S.Diag(OldLocation, PrevDiag);
3641   New->setInvalidDecl();
3642 }
3643 
3644 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3645 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3646 /// emitting diagnostics as appropriate.
3647 ///
3648 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3649 /// to here in AddInitializerToDecl. We can't check them before the initializer
3650 /// is attached.
3651 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3652                              bool MergeTypeWithOld) {
3653   if (New->isInvalidDecl() || Old->isInvalidDecl())
3654     return;
3655 
3656   QualType MergedT;
3657   if (getLangOpts().CPlusPlus) {
3658     if (New->getType()->isUndeducedType()) {
3659       // We don't know what the new type is until the initializer is attached.
3660       return;
3661     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3662       // These could still be something that needs exception specs checked.
3663       return MergeVarDeclExceptionSpecs(New, Old);
3664     }
3665     // C++ [basic.link]p10:
3666     //   [...] the types specified by all declarations referring to a given
3667     //   object or function shall be identical, except that declarations for an
3668     //   array object can specify array types that differ by the presence or
3669     //   absence of a major array bound (8.3.4).
3670     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3671       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3672       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3673 
3674       // We are merging a variable declaration New into Old. If it has an array
3675       // bound, and that bound differs from Old's bound, we should diagnose the
3676       // mismatch.
3677       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3678         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3679              PrevVD = PrevVD->getPreviousDecl()) {
3680           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3681           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3682             continue;
3683 
3684           if (!Context.hasSameType(NewArray, PrevVDTy))
3685             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3686         }
3687       }
3688 
3689       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3690         if (Context.hasSameType(OldArray->getElementType(),
3691                                 NewArray->getElementType()))
3692           MergedT = New->getType();
3693       }
3694       // FIXME: Check visibility. New is hidden but has a complete type. If New
3695       // has no array bound, it should not inherit one from Old, if Old is not
3696       // visible.
3697       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3698         if (Context.hasSameType(OldArray->getElementType(),
3699                                 NewArray->getElementType()))
3700           MergedT = Old->getType();
3701       }
3702     }
3703     else if (New->getType()->isObjCObjectPointerType() &&
3704                Old->getType()->isObjCObjectPointerType()) {
3705       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3706                                               Old->getType());
3707     }
3708   } else {
3709     // C 6.2.7p2:
3710     //   All declarations that refer to the same object or function shall have
3711     //   compatible type.
3712     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3713   }
3714   if (MergedT.isNull()) {
3715     // It's OK if we couldn't merge types if either type is dependent, for a
3716     // block-scope variable. In other cases (static data members of class
3717     // templates, variable templates, ...), we require the types to be
3718     // equivalent.
3719     // FIXME: The C++ standard doesn't say anything about this.
3720     if ((New->getType()->isDependentType() ||
3721          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3722       // If the old type was dependent, we can't merge with it, so the new type
3723       // becomes dependent for now. We'll reproduce the original type when we
3724       // instantiate the TypeSourceInfo for the variable.
3725       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3726         New->setType(Context.DependentTy);
3727       return;
3728     }
3729     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3730   }
3731 
3732   // Don't actually update the type on the new declaration if the old
3733   // declaration was an extern declaration in a different scope.
3734   if (MergeTypeWithOld)
3735     New->setType(MergedT);
3736 }
3737 
3738 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3739                                   LookupResult &Previous) {
3740   // C11 6.2.7p4:
3741   //   For an identifier with internal or external linkage declared
3742   //   in a scope in which a prior declaration of that identifier is
3743   //   visible, if the prior declaration specifies internal or
3744   //   external linkage, the type of the identifier at the later
3745   //   declaration becomes the composite type.
3746   //
3747   // If the variable isn't visible, we do not merge with its type.
3748   if (Previous.isShadowed())
3749     return false;
3750 
3751   if (S.getLangOpts().CPlusPlus) {
3752     // C++11 [dcl.array]p3:
3753     //   If there is a preceding declaration of the entity in the same
3754     //   scope in which the bound was specified, an omitted array bound
3755     //   is taken to be the same as in that earlier declaration.
3756     return NewVD->isPreviousDeclInSameBlockScope() ||
3757            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3758             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3759   } else {
3760     // If the old declaration was function-local, don't merge with its
3761     // type unless we're in the same function.
3762     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3763            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3764   }
3765 }
3766 
3767 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3768 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3769 /// situation, merging decls or emitting diagnostics as appropriate.
3770 ///
3771 /// Tentative definition rules (C99 6.9.2p2) are checked by
3772 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3773 /// definitions here, since the initializer hasn't been attached.
3774 ///
3775 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3776   // If the new decl is already invalid, don't do any other checking.
3777   if (New->isInvalidDecl())
3778     return;
3779 
3780   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3781     return;
3782 
3783   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3784 
3785   // Verify the old decl was also a variable or variable template.
3786   VarDecl *Old = nullptr;
3787   VarTemplateDecl *OldTemplate = nullptr;
3788   if (Previous.isSingleResult()) {
3789     if (NewTemplate) {
3790       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3791       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3792 
3793       if (auto *Shadow =
3794               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3795         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3796           return New->setInvalidDecl();
3797     } else {
3798       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3799 
3800       if (auto *Shadow =
3801               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3802         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3803           return New->setInvalidDecl();
3804     }
3805   }
3806   if (!Old) {
3807     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3808         << New->getDeclName();
3809     notePreviousDefinition(Previous.getRepresentativeDecl(),
3810                            New->getLocation());
3811     return New->setInvalidDecl();
3812   }
3813 
3814   // Ensure the template parameters are compatible.
3815   if (NewTemplate &&
3816       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3817                                       OldTemplate->getTemplateParameters(),
3818                                       /*Complain=*/true, TPL_TemplateMatch))
3819     return New->setInvalidDecl();
3820 
3821   // C++ [class.mem]p1:
3822   //   A member shall not be declared twice in the member-specification [...]
3823   //
3824   // Here, we need only consider static data members.
3825   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3826     Diag(New->getLocation(), diag::err_duplicate_member)
3827       << New->getIdentifier();
3828     Diag(Old->getLocation(), diag::note_previous_declaration);
3829     New->setInvalidDecl();
3830   }
3831 
3832   mergeDeclAttributes(New, Old);
3833   // Warn if an already-declared variable is made a weak_import in a subsequent
3834   // declaration
3835   if (New->hasAttr<WeakImportAttr>() &&
3836       Old->getStorageClass() == SC_None &&
3837       !Old->hasAttr<WeakImportAttr>()) {
3838     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3839     notePreviousDefinition(Old, New->getLocation());
3840     // Remove weak_import attribute on new declaration.
3841     New->dropAttr<WeakImportAttr>();
3842   }
3843 
3844   if (New->hasAttr<InternalLinkageAttr>() &&
3845       !Old->hasAttr<InternalLinkageAttr>()) {
3846     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3847         << New->getDeclName();
3848     notePreviousDefinition(Old, New->getLocation());
3849     New->dropAttr<InternalLinkageAttr>();
3850   }
3851 
3852   // Merge the types.
3853   VarDecl *MostRecent = Old->getMostRecentDecl();
3854   if (MostRecent != Old) {
3855     MergeVarDeclTypes(New, MostRecent,
3856                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3857     if (New->isInvalidDecl())
3858       return;
3859   }
3860 
3861   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3862   if (New->isInvalidDecl())
3863     return;
3864 
3865   diag::kind PrevDiag;
3866   SourceLocation OldLocation;
3867   std::tie(PrevDiag, OldLocation) =
3868       getNoteDiagForInvalidRedeclaration(Old, New);
3869 
3870   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3871   if (New->getStorageClass() == SC_Static &&
3872       !New->isStaticDataMember() &&
3873       Old->hasExternalFormalLinkage()) {
3874     if (getLangOpts().MicrosoftExt) {
3875       Diag(New->getLocation(), diag::ext_static_non_static)
3876           << New->getDeclName();
3877       Diag(OldLocation, PrevDiag);
3878     } else {
3879       Diag(New->getLocation(), diag::err_static_non_static)
3880           << New->getDeclName();
3881       Diag(OldLocation, PrevDiag);
3882       return New->setInvalidDecl();
3883     }
3884   }
3885   // C99 6.2.2p4:
3886   //   For an identifier declared with the storage-class specifier
3887   //   extern in a scope in which a prior declaration of that
3888   //   identifier is visible,23) if the prior declaration specifies
3889   //   internal or external linkage, the linkage of the identifier at
3890   //   the later declaration is the same as the linkage specified at
3891   //   the prior declaration. If no prior declaration is visible, or
3892   //   if the prior declaration specifies no linkage, then the
3893   //   identifier has external linkage.
3894   if (New->hasExternalStorage() && Old->hasLinkage())
3895     /* Okay */;
3896   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3897            !New->isStaticDataMember() &&
3898            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3899     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3900     Diag(OldLocation, PrevDiag);
3901     return New->setInvalidDecl();
3902   }
3903 
3904   // Check if extern is followed by non-extern and vice-versa.
3905   if (New->hasExternalStorage() &&
3906       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3907     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3908     Diag(OldLocation, PrevDiag);
3909     return New->setInvalidDecl();
3910   }
3911   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3912       !New->hasExternalStorage()) {
3913     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3914     Diag(OldLocation, PrevDiag);
3915     return New->setInvalidDecl();
3916   }
3917 
3918   if (CheckRedeclarationModuleOwnership(New, Old))
3919     return;
3920 
3921   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3922 
3923   // FIXME: The test for external storage here seems wrong? We still
3924   // need to check for mismatches.
3925   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3926       // Don't complain about out-of-line definitions of static members.
3927       !(Old->getLexicalDeclContext()->isRecord() &&
3928         !New->getLexicalDeclContext()->isRecord())) {
3929     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3930     Diag(OldLocation, PrevDiag);
3931     return New->setInvalidDecl();
3932   }
3933 
3934   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3935     if (VarDecl *Def = Old->getDefinition()) {
3936       // C++1z [dcl.fcn.spec]p4:
3937       //   If the definition of a variable appears in a translation unit before
3938       //   its first declaration as inline, the program is ill-formed.
3939       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3940       Diag(Def->getLocation(), diag::note_previous_definition);
3941     }
3942   }
3943 
3944   // If this redeclaration makes the variable inline, we may need to add it to
3945   // UndefinedButUsed.
3946   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3947       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3948     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3949                                            SourceLocation()));
3950 
3951   if (New->getTLSKind() != Old->getTLSKind()) {
3952     if (!Old->getTLSKind()) {
3953       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3954       Diag(OldLocation, PrevDiag);
3955     } else if (!New->getTLSKind()) {
3956       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3957       Diag(OldLocation, PrevDiag);
3958     } else {
3959       // Do not allow redeclaration to change the variable between requiring
3960       // static and dynamic initialization.
3961       // FIXME: GCC allows this, but uses the TLS keyword on the first
3962       // declaration to determine the kind. Do we need to be compatible here?
3963       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3964         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3965       Diag(OldLocation, PrevDiag);
3966     }
3967   }
3968 
3969   // C++ doesn't have tentative definitions, so go right ahead and check here.
3970   if (getLangOpts().CPlusPlus &&
3971       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3972     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3973         Old->getCanonicalDecl()->isConstexpr()) {
3974       // This definition won't be a definition any more once it's been merged.
3975       Diag(New->getLocation(),
3976            diag::warn_deprecated_redundant_constexpr_static_def);
3977     } else if (VarDecl *Def = Old->getDefinition()) {
3978       if (checkVarDeclRedefinition(Def, New))
3979         return;
3980     }
3981   }
3982 
3983   if (haveIncompatibleLanguageLinkages(Old, New)) {
3984     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3985     Diag(OldLocation, PrevDiag);
3986     New->setInvalidDecl();
3987     return;
3988   }
3989 
3990   // Merge "used" flag.
3991   if (Old->getMostRecentDecl()->isUsed(false))
3992     New->setIsUsed();
3993 
3994   // Keep a chain of previous declarations.
3995   New->setPreviousDecl(Old);
3996   if (NewTemplate)
3997     NewTemplate->setPreviousDecl(OldTemplate);
3998   adjustDeclContextForDeclaratorDecl(New, Old);
3999 
4000   // Inherit access appropriately.
4001   New->setAccess(Old->getAccess());
4002   if (NewTemplate)
4003     NewTemplate->setAccess(New->getAccess());
4004 
4005   if (Old->isInline())
4006     New->setImplicitlyInline();
4007 }
4008 
4009 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4010   SourceManager &SrcMgr = getSourceManager();
4011   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4012   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4013   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4014   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4015   auto &HSI = PP.getHeaderSearchInfo();
4016   StringRef HdrFilename =
4017       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4018 
4019   auto noteFromModuleOrInclude = [&](Module *Mod,
4020                                      SourceLocation IncLoc) -> bool {
4021     // Redefinition errors with modules are common with non modular mapped
4022     // headers, example: a non-modular header H in module A that also gets
4023     // included directly in a TU. Pointing twice to the same header/definition
4024     // is confusing, try to get better diagnostics when modules is on.
4025     if (IncLoc.isValid()) {
4026       if (Mod) {
4027         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4028             << HdrFilename.str() << Mod->getFullModuleName();
4029         if (!Mod->DefinitionLoc.isInvalid())
4030           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4031               << Mod->getFullModuleName();
4032       } else {
4033         Diag(IncLoc, diag::note_redefinition_include_same_file)
4034             << HdrFilename.str();
4035       }
4036       return true;
4037     }
4038 
4039     return false;
4040   };
4041 
4042   // Is it the same file and same offset? Provide more information on why
4043   // this leads to a redefinition error.
4044   bool EmittedDiag = false;
4045   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4046     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4047     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4048     EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4049     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4050 
4051     // If the header has no guards, emit a note suggesting one.
4052     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4053       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4054 
4055     if (EmittedDiag)
4056       return;
4057   }
4058 
4059   // Redefinition coming from different files or couldn't do better above.
4060   Diag(Old->getLocation(), diag::note_previous_definition);
4061 }
4062 
4063 /// We've just determined that \p Old and \p New both appear to be definitions
4064 /// of the same variable. Either diagnose or fix the problem.
4065 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4066   if (!hasVisibleDefinition(Old) &&
4067       (New->getFormalLinkage() == InternalLinkage ||
4068        New->isInline() ||
4069        New->getDescribedVarTemplate() ||
4070        New->getNumTemplateParameterLists() ||
4071        New->getDeclContext()->isDependentContext())) {
4072     // The previous definition is hidden, and multiple definitions are
4073     // permitted (in separate TUs). Demote this to a declaration.
4074     New->demoteThisDefinitionToDeclaration();
4075 
4076     // Make the canonical definition visible.
4077     if (auto *OldTD = Old->getDescribedVarTemplate())
4078       makeMergedDefinitionVisible(OldTD);
4079     makeMergedDefinitionVisible(Old);
4080     return false;
4081   } else {
4082     Diag(New->getLocation(), diag::err_redefinition) << New;
4083     notePreviousDefinition(Old, New->getLocation());
4084     New->setInvalidDecl();
4085     return true;
4086   }
4087 }
4088 
4089 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4090 /// no declarator (e.g. "struct foo;") is parsed.
4091 Decl *
4092 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4093                                  RecordDecl *&AnonRecord) {
4094   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4095                                     AnonRecord);
4096 }
4097 
4098 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4099 // disambiguate entities defined in different scopes.
4100 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4101 // compatibility.
4102 // We will pick our mangling number depending on which version of MSVC is being
4103 // targeted.
4104 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4105   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4106              ? S->getMSCurManglingNumber()
4107              : S->getMSLastManglingNumber();
4108 }
4109 
4110 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4111   if (!Context.getLangOpts().CPlusPlus)
4112     return;
4113 
4114   if (isa<CXXRecordDecl>(Tag->getParent())) {
4115     // If this tag is the direct child of a class, number it if
4116     // it is anonymous.
4117     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4118       return;
4119     MangleNumberingContext &MCtx =
4120         Context.getManglingNumberContext(Tag->getParent());
4121     Context.setManglingNumber(
4122         Tag, MCtx.getManglingNumber(
4123                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4124     return;
4125   }
4126 
4127   // If this tag isn't a direct child of a class, number it if it is local.
4128   Decl *ManglingContextDecl;
4129   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4130           Tag->getDeclContext(), ManglingContextDecl)) {
4131     Context.setManglingNumber(
4132         Tag, MCtx->getManglingNumber(
4133                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4134   }
4135 }
4136 
4137 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4138                                         TypedefNameDecl *NewTD) {
4139   if (TagFromDeclSpec->isInvalidDecl())
4140     return;
4141 
4142   // Do nothing if the tag already has a name for linkage purposes.
4143   if (TagFromDeclSpec->hasNameForLinkage())
4144     return;
4145 
4146   // A well-formed anonymous tag must always be a TUK_Definition.
4147   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4148 
4149   // The type must match the tag exactly;  no qualifiers allowed.
4150   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4151                            Context.getTagDeclType(TagFromDeclSpec))) {
4152     if (getLangOpts().CPlusPlus)
4153       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4154     return;
4155   }
4156 
4157   // If we've already computed linkage for the anonymous tag, then
4158   // adding a typedef name for the anonymous decl can change that
4159   // linkage, which might be a serious problem.  Diagnose this as
4160   // unsupported and ignore the typedef name.  TODO: we should
4161   // pursue this as a language defect and establish a formal rule
4162   // for how to handle it.
4163   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4164     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4165 
4166     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4167     tagLoc = getLocForEndOfToken(tagLoc);
4168 
4169     llvm::SmallString<40> textToInsert;
4170     textToInsert += ' ';
4171     textToInsert += NewTD->getIdentifier()->getName();
4172     Diag(tagLoc, diag::note_typedef_changes_linkage)
4173         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4174     return;
4175   }
4176 
4177   // Otherwise, set this is the anon-decl typedef for the tag.
4178   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4179 }
4180 
4181 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4182   switch (T) {
4183   case DeclSpec::TST_class:
4184     return 0;
4185   case DeclSpec::TST_struct:
4186     return 1;
4187   case DeclSpec::TST_interface:
4188     return 2;
4189   case DeclSpec::TST_union:
4190     return 3;
4191   case DeclSpec::TST_enum:
4192     return 4;
4193   default:
4194     llvm_unreachable("unexpected type specifier");
4195   }
4196 }
4197 
4198 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4199 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4200 /// parameters to cope with template friend declarations.
4201 Decl *
4202 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4203                                  MultiTemplateParamsArg TemplateParams,
4204                                  bool IsExplicitInstantiation,
4205                                  RecordDecl *&AnonRecord) {
4206   Decl *TagD = nullptr;
4207   TagDecl *Tag = nullptr;
4208   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4209       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4210       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4211       DS.getTypeSpecType() == DeclSpec::TST_union ||
4212       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4213     TagD = DS.getRepAsDecl();
4214 
4215     if (!TagD) // We probably had an error
4216       return nullptr;
4217 
4218     // Note that the above type specs guarantee that the
4219     // type rep is a Decl, whereas in many of the others
4220     // it's a Type.
4221     if (isa<TagDecl>(TagD))
4222       Tag = cast<TagDecl>(TagD);
4223     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4224       Tag = CTD->getTemplatedDecl();
4225   }
4226 
4227   if (Tag) {
4228     handleTagNumbering(Tag, S);
4229     Tag->setFreeStanding();
4230     if (Tag->isInvalidDecl())
4231       return Tag;
4232   }
4233 
4234   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4235     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4236     // or incomplete types shall not be restrict-qualified."
4237     if (TypeQuals & DeclSpec::TQ_restrict)
4238       Diag(DS.getRestrictSpecLoc(),
4239            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4240            << DS.getSourceRange();
4241   }
4242 
4243   if (DS.isInlineSpecified())
4244     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4245         << getLangOpts().CPlusPlus17;
4246 
4247   if (DS.isConstexprSpecified()) {
4248     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4249     // and definitions of functions and variables.
4250     if (Tag)
4251       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4252           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4253     else
4254       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4255     // Don't emit warnings after this error.
4256     return TagD;
4257   }
4258 
4259   DiagnoseFunctionSpecifiers(DS);
4260 
4261   if (DS.isFriendSpecified()) {
4262     // If we're dealing with a decl but not a TagDecl, assume that
4263     // whatever routines created it handled the friendship aspect.
4264     if (TagD && !Tag)
4265       return nullptr;
4266     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4267   }
4268 
4269   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4270   bool IsExplicitSpecialization =
4271     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4272   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4273       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4274       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4275     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4276     // nested-name-specifier unless it is an explicit instantiation
4277     // or an explicit specialization.
4278     //
4279     // FIXME: We allow class template partial specializations here too, per the
4280     // obvious intent of DR1819.
4281     //
4282     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4283     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4284         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4285     return nullptr;
4286   }
4287 
4288   // Track whether this decl-specifier declares anything.
4289   bool DeclaresAnything = true;
4290 
4291   // Handle anonymous struct definitions.
4292   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4293     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4294         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4295       if (getLangOpts().CPlusPlus ||
4296           Record->getDeclContext()->isRecord()) {
4297         // If CurContext is a DeclContext that can contain statements,
4298         // RecursiveASTVisitor won't visit the decls that
4299         // BuildAnonymousStructOrUnion() will put into CurContext.
4300         // Also store them here so that they can be part of the
4301         // DeclStmt that gets created in this case.
4302         // FIXME: Also return the IndirectFieldDecls created by
4303         // BuildAnonymousStructOr union, for the same reason?
4304         if (CurContext->isFunctionOrMethod())
4305           AnonRecord = Record;
4306         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4307                                            Context.getPrintingPolicy());
4308       }
4309 
4310       DeclaresAnything = false;
4311     }
4312   }
4313 
4314   // C11 6.7.2.1p2:
4315   //   A struct-declaration that does not declare an anonymous structure or
4316   //   anonymous union shall contain a struct-declarator-list.
4317   //
4318   // This rule also existed in C89 and C99; the grammar for struct-declaration
4319   // did not permit a struct-declaration without a struct-declarator-list.
4320   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4321       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4322     // Check for Microsoft C extension: anonymous struct/union member.
4323     // Handle 2 kinds of anonymous struct/union:
4324     //   struct STRUCT;
4325     //   union UNION;
4326     // and
4327     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4328     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4329     if ((Tag && Tag->getDeclName()) ||
4330         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4331       RecordDecl *Record = nullptr;
4332       if (Tag)
4333         Record = dyn_cast<RecordDecl>(Tag);
4334       else if (const RecordType *RT =
4335                    DS.getRepAsType().get()->getAsStructureType())
4336         Record = RT->getDecl();
4337       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4338         Record = UT->getDecl();
4339 
4340       if (Record && getLangOpts().MicrosoftExt) {
4341         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4342           << Record->isUnion() << DS.getSourceRange();
4343         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4344       }
4345 
4346       DeclaresAnything = false;
4347     }
4348   }
4349 
4350   // Skip all the checks below if we have a type error.
4351   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4352       (TagD && TagD->isInvalidDecl()))
4353     return TagD;
4354 
4355   if (getLangOpts().CPlusPlus &&
4356       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4357     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4358       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4359           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4360         DeclaresAnything = false;
4361 
4362   if (!DS.isMissingDeclaratorOk()) {
4363     // Customize diagnostic for a typedef missing a name.
4364     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4365       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4366         << DS.getSourceRange();
4367     else
4368       DeclaresAnything = false;
4369   }
4370 
4371   if (DS.isModulePrivateSpecified() &&
4372       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4373     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4374       << Tag->getTagKind()
4375       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4376 
4377   ActOnDocumentableDecl(TagD);
4378 
4379   // C 6.7/2:
4380   //   A declaration [...] shall declare at least a declarator [...], a tag,
4381   //   or the members of an enumeration.
4382   // C++ [dcl.dcl]p3:
4383   //   [If there are no declarators], and except for the declaration of an
4384   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4385   //   names into the program, or shall redeclare a name introduced by a
4386   //   previous declaration.
4387   if (!DeclaresAnything) {
4388     // In C, we allow this as a (popular) extension / bug. Don't bother
4389     // producing further diagnostics for redundant qualifiers after this.
4390     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4391     return TagD;
4392   }
4393 
4394   // C++ [dcl.stc]p1:
4395   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4396   //   init-declarator-list of the declaration shall not be empty.
4397   // C++ [dcl.fct.spec]p1:
4398   //   If a cv-qualifier appears in a decl-specifier-seq, the
4399   //   init-declarator-list of the declaration shall not be empty.
4400   //
4401   // Spurious qualifiers here appear to be valid in C.
4402   unsigned DiagID = diag::warn_standalone_specifier;
4403   if (getLangOpts().CPlusPlus)
4404     DiagID = diag::ext_standalone_specifier;
4405 
4406   // Note that a linkage-specification sets a storage class, but
4407   // 'extern "C" struct foo;' is actually valid and not theoretically
4408   // useless.
4409   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4410     if (SCS == DeclSpec::SCS_mutable)
4411       // Since mutable is not a viable storage class specifier in C, there is
4412       // no reason to treat it as an extension. Instead, diagnose as an error.
4413       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4414     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4415       Diag(DS.getStorageClassSpecLoc(), DiagID)
4416         << DeclSpec::getSpecifierName(SCS);
4417   }
4418 
4419   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4420     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4421       << DeclSpec::getSpecifierName(TSCS);
4422   if (DS.getTypeQualifiers()) {
4423     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4424       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4425     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4426       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4427     // Restrict is covered above.
4428     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4429       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4430     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4431       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4432   }
4433 
4434   // Warn about ignored type attributes, for example:
4435   // __attribute__((aligned)) struct A;
4436   // Attributes should be placed after tag to apply to type declaration.
4437   if (!DS.getAttributes().empty()) {
4438     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4439     if (TypeSpecType == DeclSpec::TST_class ||
4440         TypeSpecType == DeclSpec::TST_struct ||
4441         TypeSpecType == DeclSpec::TST_interface ||
4442         TypeSpecType == DeclSpec::TST_union ||
4443         TypeSpecType == DeclSpec::TST_enum) {
4444       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4445            attrs = attrs->getNext())
4446         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4447             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4448     }
4449   }
4450 
4451   return TagD;
4452 }
4453 
4454 /// We are trying to inject an anonymous member into the given scope;
4455 /// check if there's an existing declaration that can't be overloaded.
4456 ///
4457 /// \return true if this is a forbidden redeclaration
4458 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4459                                          Scope *S,
4460                                          DeclContext *Owner,
4461                                          DeclarationName Name,
4462                                          SourceLocation NameLoc,
4463                                          bool IsUnion) {
4464   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4465                  Sema::ForVisibleRedeclaration);
4466   if (!SemaRef.LookupName(R, S)) return false;
4467 
4468   // Pick a representative declaration.
4469   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4470   assert(PrevDecl && "Expected a non-null Decl");
4471 
4472   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4473     return false;
4474 
4475   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4476     << IsUnion << Name;
4477   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4478 
4479   return true;
4480 }
4481 
4482 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4483 /// anonymous struct or union AnonRecord into the owning context Owner
4484 /// and scope S. This routine will be invoked just after we realize
4485 /// that an unnamed union or struct is actually an anonymous union or
4486 /// struct, e.g.,
4487 ///
4488 /// @code
4489 /// union {
4490 ///   int i;
4491 ///   float f;
4492 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4493 ///    // f into the surrounding scope.x
4494 /// @endcode
4495 ///
4496 /// This routine is recursive, injecting the names of nested anonymous
4497 /// structs/unions into the owning context and scope as well.
4498 static bool
4499 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4500                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4501                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4502   bool Invalid = false;
4503 
4504   // Look every FieldDecl and IndirectFieldDecl with a name.
4505   for (auto *D : AnonRecord->decls()) {
4506     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4507         cast<NamedDecl>(D)->getDeclName()) {
4508       ValueDecl *VD = cast<ValueDecl>(D);
4509       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4510                                        VD->getLocation(),
4511                                        AnonRecord->isUnion())) {
4512         // C++ [class.union]p2:
4513         //   The names of the members of an anonymous union shall be
4514         //   distinct from the names of any other entity in the
4515         //   scope in which the anonymous union is declared.
4516         Invalid = true;
4517       } else {
4518         // C++ [class.union]p2:
4519         //   For the purpose of name lookup, after the anonymous union
4520         //   definition, the members of the anonymous union are
4521         //   considered to have been defined in the scope in which the
4522         //   anonymous union is declared.
4523         unsigned OldChainingSize = Chaining.size();
4524         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4525           Chaining.append(IF->chain_begin(), IF->chain_end());
4526         else
4527           Chaining.push_back(VD);
4528 
4529         assert(Chaining.size() >= 2);
4530         NamedDecl **NamedChain =
4531           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4532         for (unsigned i = 0; i < Chaining.size(); i++)
4533           NamedChain[i] = Chaining[i];
4534 
4535         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4536             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4537             VD->getType(), {NamedChain, Chaining.size()});
4538 
4539         for (const auto *Attr : VD->attrs())
4540           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4541 
4542         IndirectField->setAccess(AS);
4543         IndirectField->setImplicit();
4544         SemaRef.PushOnScopeChains(IndirectField, S);
4545 
4546         // That includes picking up the appropriate access specifier.
4547         if (AS != AS_none) IndirectField->setAccess(AS);
4548 
4549         Chaining.resize(OldChainingSize);
4550       }
4551     }
4552   }
4553 
4554   return Invalid;
4555 }
4556 
4557 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4558 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4559 /// illegal input values are mapped to SC_None.
4560 static StorageClass
4561 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4562   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4563   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4564          "Parser allowed 'typedef' as storage class VarDecl.");
4565   switch (StorageClassSpec) {
4566   case DeclSpec::SCS_unspecified:    return SC_None;
4567   case DeclSpec::SCS_extern:
4568     if (DS.isExternInLinkageSpec())
4569       return SC_None;
4570     return SC_Extern;
4571   case DeclSpec::SCS_static:         return SC_Static;
4572   case DeclSpec::SCS_auto:           return SC_Auto;
4573   case DeclSpec::SCS_register:       return SC_Register;
4574   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4575     // Illegal SCSs map to None: error reporting is up to the caller.
4576   case DeclSpec::SCS_mutable:        // Fall through.
4577   case DeclSpec::SCS_typedef:        return SC_None;
4578   }
4579   llvm_unreachable("unknown storage class specifier");
4580 }
4581 
4582 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4583   assert(Record->hasInClassInitializer());
4584 
4585   for (const auto *I : Record->decls()) {
4586     const auto *FD = dyn_cast<FieldDecl>(I);
4587     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4588       FD = IFD->getAnonField();
4589     if (FD && FD->hasInClassInitializer())
4590       return FD->getLocation();
4591   }
4592 
4593   llvm_unreachable("couldn't find in-class initializer");
4594 }
4595 
4596 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4597                                       SourceLocation DefaultInitLoc) {
4598   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4599     return;
4600 
4601   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4602   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4603 }
4604 
4605 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4606                                       CXXRecordDecl *AnonUnion) {
4607   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4608     return;
4609 
4610   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4611 }
4612 
4613 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4614 /// anonymous structure or union. Anonymous unions are a C++ feature
4615 /// (C++ [class.union]) and a C11 feature; anonymous structures
4616 /// are a C11 feature and GNU C++ extension.
4617 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4618                                         AccessSpecifier AS,
4619                                         RecordDecl *Record,
4620                                         const PrintingPolicy &Policy) {
4621   DeclContext *Owner = Record->getDeclContext();
4622 
4623   // Diagnose whether this anonymous struct/union is an extension.
4624   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4625     Diag(Record->getLocation(), diag::ext_anonymous_union);
4626   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4627     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4628   else if (!Record->isUnion() && !getLangOpts().C11)
4629     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4630 
4631   // C and C++ require different kinds of checks for anonymous
4632   // structs/unions.
4633   bool Invalid = false;
4634   if (getLangOpts().CPlusPlus) {
4635     const char *PrevSpec = nullptr;
4636     unsigned DiagID;
4637     if (Record->isUnion()) {
4638       // C++ [class.union]p6:
4639       //   Anonymous unions declared in a named namespace or in the
4640       //   global namespace shall be declared static.
4641       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4642           (isa<TranslationUnitDecl>(Owner) ||
4643            (isa<NamespaceDecl>(Owner) &&
4644             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4645         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4646           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4647 
4648         // Recover by adding 'static'.
4649         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4650                                PrevSpec, DiagID, Policy);
4651       }
4652       // C++ [class.union]p6:
4653       //   A storage class is not allowed in a declaration of an
4654       //   anonymous union in a class scope.
4655       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4656                isa<RecordDecl>(Owner)) {
4657         Diag(DS.getStorageClassSpecLoc(),
4658              diag::err_anonymous_union_with_storage_spec)
4659           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4660 
4661         // Recover by removing the storage specifier.
4662         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4663                                SourceLocation(),
4664                                PrevSpec, DiagID, Context.getPrintingPolicy());
4665       }
4666     }
4667 
4668     // Ignore const/volatile/restrict qualifiers.
4669     if (DS.getTypeQualifiers()) {
4670       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4671         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4672           << Record->isUnion() << "const"
4673           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4674       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4675         Diag(DS.getVolatileSpecLoc(),
4676              diag::ext_anonymous_struct_union_qualified)
4677           << Record->isUnion() << "volatile"
4678           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4679       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4680         Diag(DS.getRestrictSpecLoc(),
4681              diag::ext_anonymous_struct_union_qualified)
4682           << Record->isUnion() << "restrict"
4683           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4684       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4685         Diag(DS.getAtomicSpecLoc(),
4686              diag::ext_anonymous_struct_union_qualified)
4687           << Record->isUnion() << "_Atomic"
4688           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4689       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4690         Diag(DS.getUnalignedSpecLoc(),
4691              diag::ext_anonymous_struct_union_qualified)
4692           << Record->isUnion() << "__unaligned"
4693           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4694 
4695       DS.ClearTypeQualifiers();
4696     }
4697 
4698     // C++ [class.union]p2:
4699     //   The member-specification of an anonymous union shall only
4700     //   define non-static data members. [Note: nested types and
4701     //   functions cannot be declared within an anonymous union. ]
4702     for (auto *Mem : Record->decls()) {
4703       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4704         // C++ [class.union]p3:
4705         //   An anonymous union shall not have private or protected
4706         //   members (clause 11).
4707         assert(FD->getAccess() != AS_none);
4708         if (FD->getAccess() != AS_public) {
4709           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4710             << Record->isUnion() << (FD->getAccess() == AS_protected);
4711           Invalid = true;
4712         }
4713 
4714         // C++ [class.union]p1
4715         //   An object of a class with a non-trivial constructor, a non-trivial
4716         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4717         //   assignment operator cannot be a member of a union, nor can an
4718         //   array of such objects.
4719         if (CheckNontrivialField(FD))
4720           Invalid = true;
4721       } else if (Mem->isImplicit()) {
4722         // Any implicit members are fine.
4723       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4724         // This is a type that showed up in an
4725         // elaborated-type-specifier inside the anonymous struct or
4726         // union, but which actually declares a type outside of the
4727         // anonymous struct or union. It's okay.
4728       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4729         if (!MemRecord->isAnonymousStructOrUnion() &&
4730             MemRecord->getDeclName()) {
4731           // Visual C++ allows type definition in anonymous struct or union.
4732           if (getLangOpts().MicrosoftExt)
4733             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4734               << Record->isUnion();
4735           else {
4736             // This is a nested type declaration.
4737             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4738               << Record->isUnion();
4739             Invalid = true;
4740           }
4741         } else {
4742           // This is an anonymous type definition within another anonymous type.
4743           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4744           // not part of standard C++.
4745           Diag(MemRecord->getLocation(),
4746                diag::ext_anonymous_record_with_anonymous_type)
4747             << Record->isUnion();
4748         }
4749       } else if (isa<AccessSpecDecl>(Mem)) {
4750         // Any access specifier is fine.
4751       } else if (isa<StaticAssertDecl>(Mem)) {
4752         // In C++1z, static_assert declarations are also fine.
4753       } else {
4754         // We have something that isn't a non-static data
4755         // member. Complain about it.
4756         unsigned DK = diag::err_anonymous_record_bad_member;
4757         if (isa<TypeDecl>(Mem))
4758           DK = diag::err_anonymous_record_with_type;
4759         else if (isa<FunctionDecl>(Mem))
4760           DK = diag::err_anonymous_record_with_function;
4761         else if (isa<VarDecl>(Mem))
4762           DK = diag::err_anonymous_record_with_static;
4763 
4764         // Visual C++ allows type definition in anonymous struct or union.
4765         if (getLangOpts().MicrosoftExt &&
4766             DK == diag::err_anonymous_record_with_type)
4767           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4768             << Record->isUnion();
4769         else {
4770           Diag(Mem->getLocation(), DK) << Record->isUnion();
4771           Invalid = true;
4772         }
4773       }
4774     }
4775 
4776     // C++11 [class.union]p8 (DR1460):
4777     //   At most one variant member of a union may have a
4778     //   brace-or-equal-initializer.
4779     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4780         Owner->isRecord())
4781       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4782                                 cast<CXXRecordDecl>(Record));
4783   }
4784 
4785   if (!Record->isUnion() && !Owner->isRecord()) {
4786     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4787       << getLangOpts().CPlusPlus;
4788     Invalid = true;
4789   }
4790 
4791   // Mock up a declarator.
4792   Declarator Dc(DS, DeclaratorContext::MemberContext);
4793   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4794   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4795 
4796   // Create a declaration for this anonymous struct/union.
4797   NamedDecl *Anon = nullptr;
4798   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4799     Anon = FieldDecl::Create(Context, OwningClass,
4800                              DS.getLocStart(),
4801                              Record->getLocation(),
4802                              /*IdentifierInfo=*/nullptr,
4803                              Context.getTypeDeclType(Record),
4804                              TInfo,
4805                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4806                              /*InitStyle=*/ICIS_NoInit);
4807     Anon->setAccess(AS);
4808     if (getLangOpts().CPlusPlus)
4809       FieldCollector->Add(cast<FieldDecl>(Anon));
4810   } else {
4811     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4812     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4813     if (SCSpec == DeclSpec::SCS_mutable) {
4814       // mutable can only appear on non-static class members, so it's always
4815       // an error here
4816       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4817       Invalid = true;
4818       SC = SC_None;
4819     }
4820 
4821     Anon = VarDecl::Create(Context, Owner,
4822                            DS.getLocStart(),
4823                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4824                            Context.getTypeDeclType(Record),
4825                            TInfo, SC);
4826 
4827     // Default-initialize the implicit variable. This initialization will be
4828     // trivial in almost all cases, except if a union member has an in-class
4829     // initializer:
4830     //   union { int n = 0; };
4831     ActOnUninitializedDecl(Anon);
4832   }
4833   Anon->setImplicit();
4834 
4835   // Mark this as an anonymous struct/union type.
4836   Record->setAnonymousStructOrUnion(true);
4837 
4838   // Add the anonymous struct/union object to the current
4839   // context. We'll be referencing this object when we refer to one of
4840   // its members.
4841   Owner->addDecl(Anon);
4842 
4843   // Inject the members of the anonymous struct/union into the owning
4844   // context and into the identifier resolver chain for name lookup
4845   // purposes.
4846   SmallVector<NamedDecl*, 2> Chain;
4847   Chain.push_back(Anon);
4848 
4849   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4850     Invalid = true;
4851 
4852   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4853     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4854       Decl *ManglingContextDecl;
4855       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4856               NewVD->getDeclContext(), ManglingContextDecl)) {
4857         Context.setManglingNumber(
4858             NewVD, MCtx->getManglingNumber(
4859                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4860         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4861       }
4862     }
4863   }
4864 
4865   if (Invalid)
4866     Anon->setInvalidDecl();
4867 
4868   return Anon;
4869 }
4870 
4871 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4872 /// Microsoft C anonymous structure.
4873 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4874 /// Example:
4875 ///
4876 /// struct A { int a; };
4877 /// struct B { struct A; int b; };
4878 ///
4879 /// void foo() {
4880 ///   B var;
4881 ///   var.a = 3;
4882 /// }
4883 ///
4884 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4885                                            RecordDecl *Record) {
4886   assert(Record && "expected a record!");
4887 
4888   // Mock up a declarator.
4889   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
4890   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4891   assert(TInfo && "couldn't build declarator info for anonymous struct");
4892 
4893   auto *ParentDecl = cast<RecordDecl>(CurContext);
4894   QualType RecTy = Context.getTypeDeclType(Record);
4895 
4896   // Create a declaration for this anonymous struct.
4897   NamedDecl *Anon = FieldDecl::Create(Context,
4898                              ParentDecl,
4899                              DS.getLocStart(),
4900                              DS.getLocStart(),
4901                              /*IdentifierInfo=*/nullptr,
4902                              RecTy,
4903                              TInfo,
4904                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4905                              /*InitStyle=*/ICIS_NoInit);
4906   Anon->setImplicit();
4907 
4908   // Add the anonymous struct object to the current context.
4909   CurContext->addDecl(Anon);
4910 
4911   // Inject the members of the anonymous struct into the current
4912   // context and into the identifier resolver chain for name lookup
4913   // purposes.
4914   SmallVector<NamedDecl*, 2> Chain;
4915   Chain.push_back(Anon);
4916 
4917   RecordDecl *RecordDef = Record->getDefinition();
4918   if (RequireCompleteType(Anon->getLocation(), RecTy,
4919                           diag::err_field_incomplete) ||
4920       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4921                                           AS_none, Chain)) {
4922     Anon->setInvalidDecl();
4923     ParentDecl->setInvalidDecl();
4924   }
4925 
4926   return Anon;
4927 }
4928 
4929 /// GetNameForDeclarator - Determine the full declaration name for the
4930 /// given Declarator.
4931 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4932   return GetNameFromUnqualifiedId(D.getName());
4933 }
4934 
4935 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4936 DeclarationNameInfo
4937 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4938   DeclarationNameInfo NameInfo;
4939   NameInfo.setLoc(Name.StartLocation);
4940 
4941   switch (Name.getKind()) {
4942 
4943   case UnqualifiedIdKind::IK_ImplicitSelfParam:
4944   case UnqualifiedIdKind::IK_Identifier:
4945     NameInfo.setName(Name.Identifier);
4946     NameInfo.setLoc(Name.StartLocation);
4947     return NameInfo;
4948 
4949   case UnqualifiedIdKind::IK_DeductionGuideName: {
4950     // C++ [temp.deduct.guide]p3:
4951     //   The simple-template-id shall name a class template specialization.
4952     //   The template-name shall be the same identifier as the template-name
4953     //   of the simple-template-id.
4954     // These together intend to imply that the template-name shall name a
4955     // class template.
4956     // FIXME: template<typename T> struct X {};
4957     //        template<typename T> using Y = X<T>;
4958     //        Y(int) -> Y<int>;
4959     //   satisfies these rules but does not name a class template.
4960     TemplateName TN = Name.TemplateName.get().get();
4961     auto *Template = TN.getAsTemplateDecl();
4962     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4963       Diag(Name.StartLocation,
4964            diag::err_deduction_guide_name_not_class_template)
4965         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4966       if (Template)
4967         Diag(Template->getLocation(), diag::note_template_decl_here);
4968       return DeclarationNameInfo();
4969     }
4970 
4971     NameInfo.setName(
4972         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4973     NameInfo.setLoc(Name.StartLocation);
4974     return NameInfo;
4975   }
4976 
4977   case UnqualifiedIdKind::IK_OperatorFunctionId:
4978     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4979                                            Name.OperatorFunctionId.Operator));
4980     NameInfo.setLoc(Name.StartLocation);
4981     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4982       = Name.OperatorFunctionId.SymbolLocations[0];
4983     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4984       = Name.EndLocation.getRawEncoding();
4985     return NameInfo;
4986 
4987   case UnqualifiedIdKind::IK_LiteralOperatorId:
4988     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4989                                                            Name.Identifier));
4990     NameInfo.setLoc(Name.StartLocation);
4991     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4992     return NameInfo;
4993 
4994   case UnqualifiedIdKind::IK_ConversionFunctionId: {
4995     TypeSourceInfo *TInfo;
4996     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4997     if (Ty.isNull())
4998       return DeclarationNameInfo();
4999     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5000                                                Context.getCanonicalType(Ty)));
5001     NameInfo.setLoc(Name.StartLocation);
5002     NameInfo.setNamedTypeInfo(TInfo);
5003     return NameInfo;
5004   }
5005 
5006   case UnqualifiedIdKind::IK_ConstructorName: {
5007     TypeSourceInfo *TInfo;
5008     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5009     if (Ty.isNull())
5010       return DeclarationNameInfo();
5011     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5012                                               Context.getCanonicalType(Ty)));
5013     NameInfo.setLoc(Name.StartLocation);
5014     NameInfo.setNamedTypeInfo(TInfo);
5015     return NameInfo;
5016   }
5017 
5018   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5019     // In well-formed code, we can only have a constructor
5020     // template-id that refers to the current context, so go there
5021     // to find the actual type being constructed.
5022     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5023     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5024       return DeclarationNameInfo();
5025 
5026     // Determine the type of the class being constructed.
5027     QualType CurClassType = Context.getTypeDeclType(CurClass);
5028 
5029     // FIXME: Check two things: that the template-id names the same type as
5030     // CurClassType, and that the template-id does not occur when the name
5031     // was qualified.
5032 
5033     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5034                                     Context.getCanonicalType(CurClassType)));
5035     NameInfo.setLoc(Name.StartLocation);
5036     // FIXME: should we retrieve TypeSourceInfo?
5037     NameInfo.setNamedTypeInfo(nullptr);
5038     return NameInfo;
5039   }
5040 
5041   case UnqualifiedIdKind::IK_DestructorName: {
5042     TypeSourceInfo *TInfo;
5043     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5044     if (Ty.isNull())
5045       return DeclarationNameInfo();
5046     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5047                                               Context.getCanonicalType(Ty)));
5048     NameInfo.setLoc(Name.StartLocation);
5049     NameInfo.setNamedTypeInfo(TInfo);
5050     return NameInfo;
5051   }
5052 
5053   case UnqualifiedIdKind::IK_TemplateId: {
5054     TemplateName TName = Name.TemplateId->Template.get();
5055     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5056     return Context.getNameForTemplate(TName, TNameLoc);
5057   }
5058 
5059   } // switch (Name.getKind())
5060 
5061   llvm_unreachable("Unknown name kind");
5062 }
5063 
5064 static QualType getCoreType(QualType Ty) {
5065   do {
5066     if (Ty->isPointerType() || Ty->isReferenceType())
5067       Ty = Ty->getPointeeType();
5068     else if (Ty->isArrayType())
5069       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5070     else
5071       return Ty.withoutLocalFastQualifiers();
5072   } while (true);
5073 }
5074 
5075 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5076 /// and Definition have "nearly" matching parameters. This heuristic is
5077 /// used to improve diagnostics in the case where an out-of-line function
5078 /// definition doesn't match any declaration within the class or namespace.
5079 /// Also sets Params to the list of indices to the parameters that differ
5080 /// between the declaration and the definition. If hasSimilarParameters
5081 /// returns true and Params is empty, then all of the parameters match.
5082 static bool hasSimilarParameters(ASTContext &Context,
5083                                      FunctionDecl *Declaration,
5084                                      FunctionDecl *Definition,
5085                                      SmallVectorImpl<unsigned> &Params) {
5086   Params.clear();
5087   if (Declaration->param_size() != Definition->param_size())
5088     return false;
5089   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5090     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5091     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5092 
5093     // The parameter types are identical
5094     if (Context.hasSameType(DefParamTy, DeclParamTy))
5095       continue;
5096 
5097     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5098     QualType DefParamBaseTy = getCoreType(DefParamTy);
5099     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5100     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5101 
5102     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5103         (DeclTyName && DeclTyName == DefTyName))
5104       Params.push_back(Idx);
5105     else  // The two parameters aren't even close
5106       return false;
5107   }
5108 
5109   return true;
5110 }
5111 
5112 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5113 /// declarator needs to be rebuilt in the current instantiation.
5114 /// Any bits of declarator which appear before the name are valid for
5115 /// consideration here.  That's specifically the type in the decl spec
5116 /// and the base type in any member-pointer chunks.
5117 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5118                                                     DeclarationName Name) {
5119   // The types we specifically need to rebuild are:
5120   //   - typenames, typeofs, and decltypes
5121   //   - types which will become injected class names
5122   // Of course, we also need to rebuild any type referencing such a
5123   // type.  It's safest to just say "dependent", but we call out a
5124   // few cases here.
5125 
5126   DeclSpec &DS = D.getMutableDeclSpec();
5127   switch (DS.getTypeSpecType()) {
5128   case DeclSpec::TST_typename:
5129   case DeclSpec::TST_typeofType:
5130   case DeclSpec::TST_underlyingType:
5131   case DeclSpec::TST_atomic: {
5132     // Grab the type from the parser.
5133     TypeSourceInfo *TSI = nullptr;
5134     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5135     if (T.isNull() || !T->isDependentType()) break;
5136 
5137     // Make sure there's a type source info.  This isn't really much
5138     // of a waste; most dependent types should have type source info
5139     // attached already.
5140     if (!TSI)
5141       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5142 
5143     // Rebuild the type in the current instantiation.
5144     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5145     if (!TSI) return true;
5146 
5147     // Store the new type back in the decl spec.
5148     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5149     DS.UpdateTypeRep(LocType);
5150     break;
5151   }
5152 
5153   case DeclSpec::TST_decltype:
5154   case DeclSpec::TST_typeofExpr: {
5155     Expr *E = DS.getRepAsExpr();
5156     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5157     if (Result.isInvalid()) return true;
5158     DS.UpdateExprRep(Result.get());
5159     break;
5160   }
5161 
5162   default:
5163     // Nothing to do for these decl specs.
5164     break;
5165   }
5166 
5167   // It doesn't matter what order we do this in.
5168   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5169     DeclaratorChunk &Chunk = D.getTypeObject(I);
5170 
5171     // The only type information in the declarator which can come
5172     // before the declaration name is the base type of a member
5173     // pointer.
5174     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5175       continue;
5176 
5177     // Rebuild the scope specifier in-place.
5178     CXXScopeSpec &SS = Chunk.Mem.Scope();
5179     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5180       return true;
5181   }
5182 
5183   return false;
5184 }
5185 
5186 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5187   D.setFunctionDefinitionKind(FDK_Declaration);
5188   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5189 
5190   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5191       Dcl && Dcl->getDeclContext()->isFileContext())
5192     Dcl->setTopLevelDeclInObjCContainer();
5193 
5194   if (getLangOpts().OpenCL)
5195     setCurrentOpenCLExtensionForDecl(Dcl);
5196 
5197   return Dcl;
5198 }
5199 
5200 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5201 ///   If T is the name of a class, then each of the following shall have a
5202 ///   name different from T:
5203 ///     - every static data member of class T;
5204 ///     - every member function of class T
5205 ///     - every member of class T that is itself a type;
5206 /// \returns true if the declaration name violates these rules.
5207 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5208                                    DeclarationNameInfo NameInfo) {
5209   DeclarationName Name = NameInfo.getName();
5210 
5211   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5212   while (Record && Record->isAnonymousStructOrUnion())
5213     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5214   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5215     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5216     return true;
5217   }
5218 
5219   return false;
5220 }
5221 
5222 /// \brief Diagnose a declaration whose declarator-id has the given
5223 /// nested-name-specifier.
5224 ///
5225 /// \param SS The nested-name-specifier of the declarator-id.
5226 ///
5227 /// \param DC The declaration context to which the nested-name-specifier
5228 /// resolves.
5229 ///
5230 /// \param Name The name of the entity being declared.
5231 ///
5232 /// \param Loc The location of the name of the entity being declared.
5233 ///
5234 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5235 /// we're declaring an explicit / partial specialization / instantiation.
5236 ///
5237 /// \returns true if we cannot safely recover from this error, false otherwise.
5238 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5239                                         DeclarationName Name,
5240                                         SourceLocation Loc, bool IsTemplateId) {
5241   DeclContext *Cur = CurContext;
5242   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5243     Cur = Cur->getParent();
5244 
5245   // If the user provided a superfluous scope specifier that refers back to the
5246   // class in which the entity is already declared, diagnose and ignore it.
5247   //
5248   // class X {
5249   //   void X::f();
5250   // };
5251   //
5252   // Note, it was once ill-formed to give redundant qualification in all
5253   // contexts, but that rule was removed by DR482.
5254   if (Cur->Equals(DC)) {
5255     if (Cur->isRecord()) {
5256       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5257                                       : diag::err_member_extra_qualification)
5258         << Name << FixItHint::CreateRemoval(SS.getRange());
5259       SS.clear();
5260     } else {
5261       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5262     }
5263     return false;
5264   }
5265 
5266   // Check whether the qualifying scope encloses the scope of the original
5267   // declaration. For a template-id, we perform the checks in
5268   // CheckTemplateSpecializationScope.
5269   if (!Cur->Encloses(DC) && !IsTemplateId) {
5270     if (Cur->isRecord())
5271       Diag(Loc, diag::err_member_qualification)
5272         << Name << SS.getRange();
5273     else if (isa<TranslationUnitDecl>(DC))
5274       Diag(Loc, diag::err_invalid_declarator_global_scope)
5275         << Name << SS.getRange();
5276     else if (isa<FunctionDecl>(Cur))
5277       Diag(Loc, diag::err_invalid_declarator_in_function)
5278         << Name << SS.getRange();
5279     else if (isa<BlockDecl>(Cur))
5280       Diag(Loc, diag::err_invalid_declarator_in_block)
5281         << Name << SS.getRange();
5282     else
5283       Diag(Loc, diag::err_invalid_declarator_scope)
5284       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5285 
5286     return true;
5287   }
5288 
5289   if (Cur->isRecord()) {
5290     // Cannot qualify members within a class.
5291     Diag(Loc, diag::err_member_qualification)
5292       << Name << SS.getRange();
5293     SS.clear();
5294 
5295     // C++ constructors and destructors with incorrect scopes can break
5296     // our AST invariants by having the wrong underlying types. If
5297     // that's the case, then drop this declaration entirely.
5298     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5299          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5300         !Context.hasSameType(Name.getCXXNameType(),
5301                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5302       return true;
5303 
5304     return false;
5305   }
5306 
5307   // C++11 [dcl.meaning]p1:
5308   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5309   //   not begin with a decltype-specifer"
5310   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5311   while (SpecLoc.getPrefix())
5312     SpecLoc = SpecLoc.getPrefix();
5313   if (dyn_cast_or_null<DecltypeType>(
5314         SpecLoc.getNestedNameSpecifier()->getAsType()))
5315     Diag(Loc, diag::err_decltype_in_declarator)
5316       << SpecLoc.getTypeLoc().getSourceRange();
5317 
5318   return false;
5319 }
5320 
5321 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5322                                   MultiTemplateParamsArg TemplateParamLists) {
5323   // TODO: consider using NameInfo for diagnostic.
5324   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5325   DeclarationName Name = NameInfo.getName();
5326 
5327   // All of these full declarators require an identifier.  If it doesn't have
5328   // one, the ParsedFreeStandingDeclSpec action should be used.
5329   if (D.isDecompositionDeclarator()) {
5330     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5331   } else if (!Name) {
5332     if (!D.isInvalidType())  // Reject this if we think it is valid.
5333       Diag(D.getDeclSpec().getLocStart(),
5334            diag::err_declarator_need_ident)
5335         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5336     return nullptr;
5337   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5338     return nullptr;
5339 
5340   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5341   // we find one that is.
5342   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5343          (S->getFlags() & Scope::TemplateParamScope) != 0)
5344     S = S->getParent();
5345 
5346   DeclContext *DC = CurContext;
5347   if (D.getCXXScopeSpec().isInvalid())
5348     D.setInvalidType();
5349   else if (D.getCXXScopeSpec().isSet()) {
5350     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5351                                         UPPC_DeclarationQualifier))
5352       return nullptr;
5353 
5354     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5355     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5356     if (!DC || isa<EnumDecl>(DC)) {
5357       // If we could not compute the declaration context, it's because the
5358       // declaration context is dependent but does not refer to a class,
5359       // class template, or class template partial specialization. Complain
5360       // and return early, to avoid the coming semantic disaster.
5361       Diag(D.getIdentifierLoc(),
5362            diag::err_template_qualified_declarator_no_match)
5363         << D.getCXXScopeSpec().getScopeRep()
5364         << D.getCXXScopeSpec().getRange();
5365       return nullptr;
5366     }
5367     bool IsDependentContext = DC->isDependentContext();
5368 
5369     if (!IsDependentContext &&
5370         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5371       return nullptr;
5372 
5373     // If a class is incomplete, do not parse entities inside it.
5374     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5375       Diag(D.getIdentifierLoc(),
5376            diag::err_member_def_undefined_record)
5377         << Name << DC << D.getCXXScopeSpec().getRange();
5378       return nullptr;
5379     }
5380     if (!D.getDeclSpec().isFriendSpecified()) {
5381       if (diagnoseQualifiedDeclaration(
5382               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5383               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5384         if (DC->isRecord())
5385           return nullptr;
5386 
5387         D.setInvalidType();
5388       }
5389     }
5390 
5391     // Check whether we need to rebuild the type of the given
5392     // declaration in the current instantiation.
5393     if (EnteringContext && IsDependentContext &&
5394         TemplateParamLists.size() != 0) {
5395       ContextRAII SavedContext(*this, DC);
5396       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5397         D.setInvalidType();
5398     }
5399   }
5400 
5401   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5402   QualType R = TInfo->getType();
5403 
5404   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5405                                       UPPC_DeclarationType))
5406     D.setInvalidType();
5407 
5408   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5409                         forRedeclarationInCurContext());
5410 
5411   // See if this is a redefinition of a variable in the same scope.
5412   if (!D.getCXXScopeSpec().isSet()) {
5413     bool IsLinkageLookup = false;
5414     bool CreateBuiltins = false;
5415 
5416     // If the declaration we're planning to build will be a function
5417     // or object with linkage, then look for another declaration with
5418     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5419     //
5420     // If the declaration we're planning to build will be declared with
5421     // external linkage in the translation unit, create any builtin with
5422     // the same name.
5423     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5424       /* Do nothing*/;
5425     else if (CurContext->isFunctionOrMethod() &&
5426              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5427               R->isFunctionType())) {
5428       IsLinkageLookup = true;
5429       CreateBuiltins =
5430           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5431     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5432                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5433       CreateBuiltins = true;
5434 
5435     if (IsLinkageLookup) {
5436       Previous.clear(LookupRedeclarationWithLinkage);
5437       Previous.setRedeclarationKind(ForExternalRedeclaration);
5438     }
5439 
5440     LookupName(Previous, S, CreateBuiltins);
5441   } else { // Something like "int foo::x;"
5442     LookupQualifiedName(Previous, DC);
5443 
5444     // C++ [dcl.meaning]p1:
5445     //   When the declarator-id is qualified, the declaration shall refer to a
5446     //  previously declared member of the class or namespace to which the
5447     //  qualifier refers (or, in the case of a namespace, of an element of the
5448     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5449     //  thereof; [...]
5450     //
5451     // Note that we already checked the context above, and that we do not have
5452     // enough information to make sure that Previous contains the declaration
5453     // we want to match. For example, given:
5454     //
5455     //   class X {
5456     //     void f();
5457     //     void f(float);
5458     //   };
5459     //
5460     //   void X::f(int) { } // ill-formed
5461     //
5462     // In this case, Previous will point to the overload set
5463     // containing the two f's declared in X, but neither of them
5464     // matches.
5465 
5466     // C++ [dcl.meaning]p1:
5467     //   [...] the member shall not merely have been introduced by a
5468     //   using-declaration in the scope of the class or namespace nominated by
5469     //   the nested-name-specifier of the declarator-id.
5470     RemoveUsingDecls(Previous);
5471   }
5472 
5473   if (Previous.isSingleResult() &&
5474       Previous.getFoundDecl()->isTemplateParameter()) {
5475     // Maybe we will complain about the shadowed template parameter.
5476     if (!D.isInvalidType())
5477       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5478                                       Previous.getFoundDecl());
5479 
5480     // Just pretend that we didn't see the previous declaration.
5481     Previous.clear();
5482   }
5483 
5484   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5485     // Forget that the previous declaration is the injected-class-name.
5486     Previous.clear();
5487 
5488   // In C++, the previous declaration we find might be a tag type
5489   // (class or enum). In this case, the new declaration will hide the
5490   // tag type. Note that this applies to functions, function templates, and
5491   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5492   if (Previous.isSingleTagDecl() &&
5493       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5494       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5495     Previous.clear();
5496 
5497   // Check that there are no default arguments other than in the parameters
5498   // of a function declaration (C++ only).
5499   if (getLangOpts().CPlusPlus)
5500     CheckExtraCXXDefaultArguments(D);
5501 
5502   NamedDecl *New;
5503 
5504   bool AddToScope = true;
5505   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5506     if (TemplateParamLists.size()) {
5507       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5508       return nullptr;
5509     }
5510 
5511     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5512   } else if (R->isFunctionType()) {
5513     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5514                                   TemplateParamLists,
5515                                   AddToScope);
5516   } else {
5517     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5518                                   AddToScope);
5519   }
5520 
5521   if (!New)
5522     return nullptr;
5523 
5524   // If this has an identifier and is not a function template specialization,
5525   // add it to the scope stack.
5526   if (New->getDeclName() && AddToScope) {
5527     // Only make a locally-scoped extern declaration visible if it is the first
5528     // declaration of this entity. Qualified lookup for such an entity should
5529     // only find this declaration if there is no visible declaration of it.
5530     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5531     PushOnScopeChains(New, S, AddToContext);
5532     if (!AddToContext)
5533       CurContext->addHiddenDecl(New);
5534   }
5535 
5536   if (isInOpenMPDeclareTargetContext())
5537     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5538 
5539   return New;
5540 }
5541 
5542 /// Helper method to turn variable array types into constant array
5543 /// types in certain situations which would otherwise be errors (for
5544 /// GCC compatibility).
5545 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5546                                                     ASTContext &Context,
5547                                                     bool &SizeIsNegative,
5548                                                     llvm::APSInt &Oversized) {
5549   // This method tries to turn a variable array into a constant
5550   // array even when the size isn't an ICE.  This is necessary
5551   // for compatibility with code that depends on gcc's buggy
5552   // constant expression folding, like struct {char x[(int)(char*)2];}
5553   SizeIsNegative = false;
5554   Oversized = 0;
5555 
5556   if (T->isDependentType())
5557     return QualType();
5558 
5559   QualifierCollector Qs;
5560   const Type *Ty = Qs.strip(T);
5561 
5562   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5563     QualType Pointee = PTy->getPointeeType();
5564     QualType FixedType =
5565         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5566                                             Oversized);
5567     if (FixedType.isNull()) return FixedType;
5568     FixedType = Context.getPointerType(FixedType);
5569     return Qs.apply(Context, FixedType);
5570   }
5571   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5572     QualType Inner = PTy->getInnerType();
5573     QualType FixedType =
5574         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5575                                             Oversized);
5576     if (FixedType.isNull()) return FixedType;
5577     FixedType = Context.getParenType(FixedType);
5578     return Qs.apply(Context, FixedType);
5579   }
5580 
5581   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5582   if (!VLATy)
5583     return QualType();
5584   // FIXME: We should probably handle this case
5585   if (VLATy->getElementType()->isVariablyModifiedType())
5586     return QualType();
5587 
5588   llvm::APSInt Res;
5589   if (!VLATy->getSizeExpr() ||
5590       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5591     return QualType();
5592 
5593   // Check whether the array size is negative.
5594   if (Res.isSigned() && Res.isNegative()) {
5595     SizeIsNegative = true;
5596     return QualType();
5597   }
5598 
5599   // Check whether the array is too large to be addressed.
5600   unsigned ActiveSizeBits
5601     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5602                                               Res);
5603   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5604     Oversized = Res;
5605     return QualType();
5606   }
5607 
5608   return Context.getConstantArrayType(VLATy->getElementType(),
5609                                       Res, ArrayType::Normal, 0);
5610 }
5611 
5612 static void
5613 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5614   SrcTL = SrcTL.getUnqualifiedLoc();
5615   DstTL = DstTL.getUnqualifiedLoc();
5616   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5617     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5618     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5619                                       DstPTL.getPointeeLoc());
5620     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5621     return;
5622   }
5623   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5624     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5625     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5626                                       DstPTL.getInnerLoc());
5627     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5628     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5629     return;
5630   }
5631   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5632   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5633   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5634   TypeLoc DstElemTL = DstATL.getElementLoc();
5635   DstElemTL.initializeFullCopy(SrcElemTL);
5636   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5637   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5638   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5639 }
5640 
5641 /// Helper method to turn variable array types into constant array
5642 /// types in certain situations which would otherwise be errors (for
5643 /// GCC compatibility).
5644 static TypeSourceInfo*
5645 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5646                                               ASTContext &Context,
5647                                               bool &SizeIsNegative,
5648                                               llvm::APSInt &Oversized) {
5649   QualType FixedTy
5650     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5651                                           SizeIsNegative, Oversized);
5652   if (FixedTy.isNull())
5653     return nullptr;
5654   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5655   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5656                                     FixedTInfo->getTypeLoc());
5657   return FixedTInfo;
5658 }
5659 
5660 /// \brief Register the given locally-scoped extern "C" declaration so
5661 /// that it can be found later for redeclarations. We include any extern "C"
5662 /// declaration that is not visible in the translation unit here, not just
5663 /// function-scope declarations.
5664 void
5665 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5666   if (!getLangOpts().CPlusPlus &&
5667       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5668     // Don't need to track declarations in the TU in C.
5669     return;
5670 
5671   // Note that we have a locally-scoped external with this name.
5672   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5673 }
5674 
5675 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5676   // FIXME: We can have multiple results via __attribute__((overloadable)).
5677   auto Result = Context.getExternCContextDecl()->lookup(Name);
5678   return Result.empty() ? nullptr : *Result.begin();
5679 }
5680 
5681 /// \brief Diagnose function specifiers on a declaration of an identifier that
5682 /// does not identify a function.
5683 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5684   // FIXME: We should probably indicate the identifier in question to avoid
5685   // confusion for constructs like "virtual int a(), b;"
5686   if (DS.isVirtualSpecified())
5687     Diag(DS.getVirtualSpecLoc(),
5688          diag::err_virtual_non_function);
5689 
5690   if (DS.isExplicitSpecified())
5691     Diag(DS.getExplicitSpecLoc(),
5692          diag::err_explicit_non_function);
5693 
5694   if (DS.isNoreturnSpecified())
5695     Diag(DS.getNoreturnSpecLoc(),
5696          diag::err_noreturn_non_function);
5697 }
5698 
5699 NamedDecl*
5700 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5701                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5702   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5703   if (D.getCXXScopeSpec().isSet()) {
5704     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5705       << D.getCXXScopeSpec().getRange();
5706     D.setInvalidType();
5707     // Pretend we didn't see the scope specifier.
5708     DC = CurContext;
5709     Previous.clear();
5710   }
5711 
5712   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5713 
5714   if (D.getDeclSpec().isInlineSpecified())
5715     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5716         << getLangOpts().CPlusPlus17;
5717   if (D.getDeclSpec().isConstexprSpecified())
5718     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5719       << 1;
5720 
5721   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5722     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5723       Diag(D.getName().StartLocation,
5724            diag::err_deduction_guide_invalid_specifier)
5725           << "typedef";
5726     else
5727       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5728           << D.getName().getSourceRange();
5729     return nullptr;
5730   }
5731 
5732   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5733   if (!NewTD) return nullptr;
5734 
5735   // Handle attributes prior to checking for duplicates in MergeVarDecl
5736   ProcessDeclAttributes(S, NewTD, D);
5737 
5738   CheckTypedefForVariablyModifiedType(S, NewTD);
5739 
5740   bool Redeclaration = D.isRedeclaration();
5741   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5742   D.setRedeclaration(Redeclaration);
5743   return ND;
5744 }
5745 
5746 void
5747 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5748   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5749   // then it shall have block scope.
5750   // Note that variably modified types must be fixed before merging the decl so
5751   // that redeclarations will match.
5752   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5753   QualType T = TInfo->getType();
5754   if (T->isVariablyModifiedType()) {
5755     setFunctionHasBranchProtectedScope();
5756 
5757     if (S->getFnParent() == nullptr) {
5758       bool SizeIsNegative;
5759       llvm::APSInt Oversized;
5760       TypeSourceInfo *FixedTInfo =
5761         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5762                                                       SizeIsNegative,
5763                                                       Oversized);
5764       if (FixedTInfo) {
5765         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5766         NewTD->setTypeSourceInfo(FixedTInfo);
5767       } else {
5768         if (SizeIsNegative)
5769           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5770         else if (T->isVariableArrayType())
5771           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5772         else if (Oversized.getBoolValue())
5773           Diag(NewTD->getLocation(), diag::err_array_too_large)
5774             << Oversized.toString(10);
5775         else
5776           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5777         NewTD->setInvalidDecl();
5778       }
5779     }
5780   }
5781 }
5782 
5783 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5784 /// declares a typedef-name, either using the 'typedef' type specifier or via
5785 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5786 NamedDecl*
5787 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5788                            LookupResult &Previous, bool &Redeclaration) {
5789 
5790   // Find the shadowed declaration before filtering for scope.
5791   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5792 
5793   // Merge the decl with the existing one if appropriate. If the decl is
5794   // in an outer scope, it isn't the same thing.
5795   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5796                        /*AllowInlineNamespace*/false);
5797   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5798   if (!Previous.empty()) {
5799     Redeclaration = true;
5800     MergeTypedefNameDecl(S, NewTD, Previous);
5801   }
5802 
5803   if (ShadowedDecl && !Redeclaration)
5804     CheckShadow(NewTD, ShadowedDecl, Previous);
5805 
5806   // If this is the C FILE type, notify the AST context.
5807   if (IdentifierInfo *II = NewTD->getIdentifier())
5808     if (!NewTD->isInvalidDecl() &&
5809         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5810       if (II->isStr("FILE"))
5811         Context.setFILEDecl(NewTD);
5812       else if (II->isStr("jmp_buf"))
5813         Context.setjmp_bufDecl(NewTD);
5814       else if (II->isStr("sigjmp_buf"))
5815         Context.setsigjmp_bufDecl(NewTD);
5816       else if (II->isStr("ucontext_t"))
5817         Context.setucontext_tDecl(NewTD);
5818     }
5819 
5820   return NewTD;
5821 }
5822 
5823 /// \brief Determines whether the given declaration is an out-of-scope
5824 /// previous declaration.
5825 ///
5826 /// This routine should be invoked when name lookup has found a
5827 /// previous declaration (PrevDecl) that is not in the scope where a
5828 /// new declaration by the same name is being introduced. If the new
5829 /// declaration occurs in a local scope, previous declarations with
5830 /// linkage may still be considered previous declarations (C99
5831 /// 6.2.2p4-5, C++ [basic.link]p6).
5832 ///
5833 /// \param PrevDecl the previous declaration found by name
5834 /// lookup
5835 ///
5836 /// \param DC the context in which the new declaration is being
5837 /// declared.
5838 ///
5839 /// \returns true if PrevDecl is an out-of-scope previous declaration
5840 /// for a new delcaration with the same name.
5841 static bool
5842 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5843                                 ASTContext &Context) {
5844   if (!PrevDecl)
5845     return false;
5846 
5847   if (!PrevDecl->hasLinkage())
5848     return false;
5849 
5850   if (Context.getLangOpts().CPlusPlus) {
5851     // C++ [basic.link]p6:
5852     //   If there is a visible declaration of an entity with linkage
5853     //   having the same name and type, ignoring entities declared
5854     //   outside the innermost enclosing namespace scope, the block
5855     //   scope declaration declares that same entity and receives the
5856     //   linkage of the previous declaration.
5857     DeclContext *OuterContext = DC->getRedeclContext();
5858     if (!OuterContext->isFunctionOrMethod())
5859       // This rule only applies to block-scope declarations.
5860       return false;
5861 
5862     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5863     if (PrevOuterContext->isRecord())
5864       // We found a member function: ignore it.
5865       return false;
5866 
5867     // Find the innermost enclosing namespace for the new and
5868     // previous declarations.
5869     OuterContext = OuterContext->getEnclosingNamespaceContext();
5870     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5871 
5872     // The previous declaration is in a different namespace, so it
5873     // isn't the same function.
5874     if (!OuterContext->Equals(PrevOuterContext))
5875       return false;
5876   }
5877 
5878   return true;
5879 }
5880 
5881 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5882   CXXScopeSpec &SS = D.getCXXScopeSpec();
5883   if (!SS.isSet()) return;
5884   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5885 }
5886 
5887 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5888   QualType type = decl->getType();
5889   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5890   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5891     // Various kinds of declaration aren't allowed to be __autoreleasing.
5892     unsigned kind = -1U;
5893     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5894       if (var->hasAttr<BlocksAttr>())
5895         kind = 0; // __block
5896       else if (!var->hasLocalStorage())
5897         kind = 1; // global
5898     } else if (isa<ObjCIvarDecl>(decl)) {
5899       kind = 3; // ivar
5900     } else if (isa<FieldDecl>(decl)) {
5901       kind = 2; // field
5902     }
5903 
5904     if (kind != -1U) {
5905       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5906         << kind;
5907     }
5908   } else if (lifetime == Qualifiers::OCL_None) {
5909     // Try to infer lifetime.
5910     if (!type->isObjCLifetimeType())
5911       return false;
5912 
5913     lifetime = type->getObjCARCImplicitLifetime();
5914     type = Context.getLifetimeQualifiedType(type, lifetime);
5915     decl->setType(type);
5916   }
5917 
5918   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5919     // Thread-local variables cannot have lifetime.
5920     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5921         var->getTLSKind()) {
5922       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5923         << var->getType();
5924       return true;
5925     }
5926   }
5927 
5928   return false;
5929 }
5930 
5931 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5932   // Ensure that an auto decl is deduced otherwise the checks below might cache
5933   // the wrong linkage.
5934   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5935 
5936   // 'weak' only applies to declarations with external linkage.
5937   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5938     if (!ND.isExternallyVisible()) {
5939       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5940       ND.dropAttr<WeakAttr>();
5941     }
5942   }
5943   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5944     if (ND.isExternallyVisible()) {
5945       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5946       ND.dropAttr<WeakRefAttr>();
5947       ND.dropAttr<AliasAttr>();
5948     }
5949   }
5950 
5951   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5952     if (VD->hasInit()) {
5953       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5954         assert(VD->isThisDeclarationADefinition() &&
5955                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5956         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5957         VD->dropAttr<AliasAttr>();
5958       }
5959     }
5960   }
5961 
5962   // 'selectany' only applies to externally visible variable declarations.
5963   // It does not apply to functions.
5964   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5965     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5966       S.Diag(Attr->getLocation(),
5967              diag::err_attribute_selectany_non_extern_data);
5968       ND.dropAttr<SelectAnyAttr>();
5969     }
5970   }
5971 
5972   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5973     // dll attributes require external linkage. Static locals may have external
5974     // linkage but still cannot be explicitly imported or exported.
5975     auto *VD = dyn_cast<VarDecl>(&ND);
5976     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5977       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5978         << &ND << Attr;
5979       ND.setInvalidDecl();
5980     }
5981   }
5982 
5983   // Virtual functions cannot be marked as 'notail'.
5984   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5985     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5986       if (MD->isVirtual()) {
5987         S.Diag(ND.getLocation(),
5988                diag::err_invalid_attribute_on_virtual_function)
5989             << Attr;
5990         ND.dropAttr<NotTailCalledAttr>();
5991       }
5992 }
5993 
5994 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5995                                            NamedDecl *NewDecl,
5996                                            bool IsSpecialization,
5997                                            bool IsDefinition) {
5998   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
5999     return;
6000 
6001   bool IsTemplate = false;
6002   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6003     OldDecl = OldTD->getTemplatedDecl();
6004     IsTemplate = true;
6005     if (!IsSpecialization)
6006       IsDefinition = false;
6007   }
6008   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6009     NewDecl = NewTD->getTemplatedDecl();
6010     IsTemplate = true;
6011   }
6012 
6013   if (!OldDecl || !NewDecl)
6014     return;
6015 
6016   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6017   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6018   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6019   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6020 
6021   // dllimport and dllexport are inheritable attributes so we have to exclude
6022   // inherited attribute instances.
6023   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6024                     (NewExportAttr && !NewExportAttr->isInherited());
6025 
6026   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6027   // the only exception being explicit specializations.
6028   // Implicitly generated declarations are also excluded for now because there
6029   // is no other way to switch these to use dllimport or dllexport.
6030   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6031 
6032   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6033     // Allow with a warning for free functions and global variables.
6034     bool JustWarn = false;
6035     if (!OldDecl->isCXXClassMember()) {
6036       auto *VD = dyn_cast<VarDecl>(OldDecl);
6037       if (VD && !VD->getDescribedVarTemplate())
6038         JustWarn = true;
6039       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6040       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6041         JustWarn = true;
6042     }
6043 
6044     // We cannot change a declaration that's been used because IR has already
6045     // been emitted. Dllimported functions will still work though (modulo
6046     // address equality) as they can use the thunk.
6047     if (OldDecl->isUsed())
6048       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6049         JustWarn = false;
6050 
6051     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6052                                : diag::err_attribute_dll_redeclaration;
6053     S.Diag(NewDecl->getLocation(), DiagID)
6054         << NewDecl
6055         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6056     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6057     if (!JustWarn) {
6058       NewDecl->setInvalidDecl();
6059       return;
6060     }
6061   }
6062 
6063   // A redeclaration is not allowed to drop a dllimport attribute, the only
6064   // exceptions being inline function definitions (except for function
6065   // templates), local extern declarations, qualified friend declarations or
6066   // special MSVC extension: in the last case, the declaration is treated as if
6067   // it were marked dllexport.
6068   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6069   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6070   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6071     // Ignore static data because out-of-line definitions are diagnosed
6072     // separately.
6073     IsStaticDataMember = VD->isStaticDataMember();
6074     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6075                    VarDecl::DeclarationOnly;
6076   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6077     IsInline = FD->isInlined();
6078     IsQualifiedFriend = FD->getQualifier() &&
6079                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6080   }
6081 
6082   if (OldImportAttr && !HasNewAttr &&
6083       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6084       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6085     if (IsMicrosoft && IsDefinition) {
6086       S.Diag(NewDecl->getLocation(),
6087              diag::warn_redeclaration_without_import_attribute)
6088           << NewDecl;
6089       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6090       NewDecl->dropAttr<DLLImportAttr>();
6091       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6092           NewImportAttr->getRange(), S.Context,
6093           NewImportAttr->getSpellingListIndex()));
6094     } else {
6095       S.Diag(NewDecl->getLocation(),
6096              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6097           << NewDecl << OldImportAttr;
6098       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6099       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6100       OldDecl->dropAttr<DLLImportAttr>();
6101       NewDecl->dropAttr<DLLImportAttr>();
6102     }
6103   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6104     // In MinGW, seeing a function declared inline drops the dllimport
6105     // attribute.
6106     OldDecl->dropAttr<DLLImportAttr>();
6107     NewDecl->dropAttr<DLLImportAttr>();
6108     S.Diag(NewDecl->getLocation(),
6109            diag::warn_dllimport_dropped_from_inline_function)
6110         << NewDecl << OldImportAttr;
6111   }
6112 
6113   // A specialization of a class template member function is processed here
6114   // since it's a redeclaration. If the parent class is dllexport, the
6115   // specialization inherits that attribute. This doesn't happen automatically
6116   // since the parent class isn't instantiated until later.
6117   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6118     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6119         !NewImportAttr && !NewExportAttr) {
6120       if (const DLLExportAttr *ParentExportAttr =
6121               MD->getParent()->getAttr<DLLExportAttr>()) {
6122         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6123         NewAttr->setInherited(true);
6124         NewDecl->addAttr(NewAttr);
6125       }
6126     }
6127   }
6128 }
6129 
6130 /// Given that we are within the definition of the given function,
6131 /// will that definition behave like C99's 'inline', where the
6132 /// definition is discarded except for optimization purposes?
6133 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6134   // Try to avoid calling GetGVALinkageForFunction.
6135 
6136   // All cases of this require the 'inline' keyword.
6137   if (!FD->isInlined()) return false;
6138 
6139   // This is only possible in C++ with the gnu_inline attribute.
6140   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6141     return false;
6142 
6143   // Okay, go ahead and call the relatively-more-expensive function.
6144   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6145 }
6146 
6147 /// Determine whether a variable is extern "C" prior to attaching
6148 /// an initializer. We can't just call isExternC() here, because that
6149 /// will also compute and cache whether the declaration is externally
6150 /// visible, which might change when we attach the initializer.
6151 ///
6152 /// This can only be used if the declaration is known to not be a
6153 /// redeclaration of an internal linkage declaration.
6154 ///
6155 /// For instance:
6156 ///
6157 ///   auto x = []{};
6158 ///
6159 /// Attaching the initializer here makes this declaration not externally
6160 /// visible, because its type has internal linkage.
6161 ///
6162 /// FIXME: This is a hack.
6163 template<typename T>
6164 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6165   if (S.getLangOpts().CPlusPlus) {
6166     // In C++, the overloadable attribute negates the effects of extern "C".
6167     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6168       return false;
6169 
6170     // So do CUDA's host/device attributes.
6171     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6172                                  D->template hasAttr<CUDAHostAttr>()))
6173       return false;
6174   }
6175   return D->isExternC();
6176 }
6177 
6178 static bool shouldConsiderLinkage(const VarDecl *VD) {
6179   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6180   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
6181     return VD->hasExternalStorage();
6182   if (DC->isFileContext())
6183     return true;
6184   if (DC->isRecord())
6185     return false;
6186   llvm_unreachable("Unexpected context");
6187 }
6188 
6189 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6190   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6191   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6192       isa<OMPDeclareReductionDecl>(DC))
6193     return true;
6194   if (DC->isRecord())
6195     return false;
6196   llvm_unreachable("Unexpected context");
6197 }
6198 
6199 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
6200                           AttributeList::Kind Kind) {
6201   for (const AttributeList *L = AttrList; L; L = L->getNext())
6202     if (L->getKind() == Kind)
6203       return true;
6204   return false;
6205 }
6206 
6207 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6208                           AttributeList::Kind Kind) {
6209   // Check decl attributes on the DeclSpec.
6210   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
6211     return true;
6212 
6213   // Walk the declarator structure, checking decl attributes that were in a type
6214   // position to the decl itself.
6215   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6216     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
6217       return true;
6218   }
6219 
6220   // Finally, check attributes on the decl itself.
6221   return hasParsedAttr(S, PD.getAttributes(), Kind);
6222 }
6223 
6224 /// Adjust the \c DeclContext for a function or variable that might be a
6225 /// function-local external declaration.
6226 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6227   if (!DC->isFunctionOrMethod())
6228     return false;
6229 
6230   // If this is a local extern function or variable declared within a function
6231   // template, don't add it into the enclosing namespace scope until it is
6232   // instantiated; it might have a dependent type right now.
6233   if (DC->isDependentContext())
6234     return true;
6235 
6236   // C++11 [basic.link]p7:
6237   //   When a block scope declaration of an entity with linkage is not found to
6238   //   refer to some other declaration, then that entity is a member of the
6239   //   innermost enclosing namespace.
6240   //
6241   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6242   // semantically-enclosing namespace, not a lexically-enclosing one.
6243   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6244     DC = DC->getParent();
6245   return true;
6246 }
6247 
6248 /// \brief Returns true if given declaration has external C language linkage.
6249 static bool isDeclExternC(const Decl *D) {
6250   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6251     return FD->isExternC();
6252   if (const auto *VD = dyn_cast<VarDecl>(D))
6253     return VD->isExternC();
6254 
6255   llvm_unreachable("Unknown type of decl!");
6256 }
6257 
6258 NamedDecl *Sema::ActOnVariableDeclarator(
6259     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6260     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6261     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6262   QualType R = TInfo->getType();
6263   DeclarationName Name = GetNameForDeclarator(D).getName();
6264 
6265   IdentifierInfo *II = Name.getAsIdentifierInfo();
6266 
6267   if (D.isDecompositionDeclarator()) {
6268     // Take the name of the first declarator as our name for diagnostic
6269     // purposes.
6270     auto &Decomp = D.getDecompositionDeclarator();
6271     if (!Decomp.bindings().empty()) {
6272       II = Decomp.bindings()[0].Name;
6273       Name = II;
6274     }
6275   } else if (!II) {
6276     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6277     return nullptr;
6278   }
6279 
6280   if (getLangOpts().OpenCL) {
6281     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6282     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6283     // argument.
6284     if (R->isImageType() || R->isPipeType()) {
6285       Diag(D.getIdentifierLoc(),
6286            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6287           << R;
6288       D.setInvalidType();
6289       return nullptr;
6290     }
6291 
6292     // OpenCL v1.2 s6.9.r:
6293     // The event type cannot be used to declare a program scope variable.
6294     // OpenCL v2.0 s6.9.q:
6295     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6296     if (NULL == S->getParent()) {
6297       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6298         Diag(D.getIdentifierLoc(),
6299              diag::err_invalid_type_for_program_scope_var) << R;
6300         D.setInvalidType();
6301         return nullptr;
6302       }
6303     }
6304 
6305     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6306     QualType NR = R;
6307     while (NR->isPointerType()) {
6308       if (NR->isFunctionPointerType()) {
6309         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6310         D.setInvalidType();
6311         break;
6312       }
6313       NR = NR->getPointeeType();
6314     }
6315 
6316     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6317       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6318       // half array type (unless the cl_khr_fp16 extension is enabled).
6319       if (Context.getBaseElementType(R)->isHalfType()) {
6320         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6321         D.setInvalidType();
6322       }
6323     }
6324 
6325     if (R->isSamplerT()) {
6326       // OpenCL v1.2 s6.9.b p4:
6327       // The sampler type cannot be used with the __local and __global address
6328       // space qualifiers.
6329       if (R.getAddressSpace() == LangAS::opencl_local ||
6330           R.getAddressSpace() == LangAS::opencl_global) {
6331         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6332       }
6333 
6334       // OpenCL v1.2 s6.12.14.1:
6335       // A global sampler must be declared with either the constant address
6336       // space qualifier or with the const qualifier.
6337       if (DC->isTranslationUnit() &&
6338           !(R.getAddressSpace() == LangAS::opencl_constant ||
6339           R.isConstQualified())) {
6340         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6341         D.setInvalidType();
6342       }
6343     }
6344 
6345     // OpenCL v1.2 s6.9.r:
6346     // The event type cannot be used with the __local, __constant and __global
6347     // address space qualifiers.
6348     if (R->isEventT()) {
6349       if (R.getAddressSpace() != LangAS::opencl_private) {
6350         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6351         D.setInvalidType();
6352       }
6353     }
6354   }
6355 
6356   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6357   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6358 
6359   // dllimport globals without explicit storage class are treated as extern. We
6360   // have to change the storage class this early to get the right DeclContext.
6361   if (SC == SC_None && !DC->isRecord() &&
6362       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
6363       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
6364     SC = SC_Extern;
6365 
6366   DeclContext *OriginalDC = DC;
6367   bool IsLocalExternDecl = SC == SC_Extern &&
6368                            adjustContextForLocalExternDecl(DC);
6369 
6370   if (SCSpec == DeclSpec::SCS_mutable) {
6371     // mutable can only appear on non-static class members, so it's always
6372     // an error here
6373     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6374     D.setInvalidType();
6375     SC = SC_None;
6376   }
6377 
6378   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6379       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6380                               D.getDeclSpec().getStorageClassSpecLoc())) {
6381     // In C++11, the 'register' storage class specifier is deprecated.
6382     // Suppress the warning in system macros, it's used in macros in some
6383     // popular C system headers, such as in glibc's htonl() macro.
6384     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6385          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6386                                    : diag::warn_deprecated_register)
6387       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6388   }
6389 
6390   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6391 
6392   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6393     // C99 6.9p2: The storage-class specifiers auto and register shall not
6394     // appear in the declaration specifiers in an external declaration.
6395     // Global Register+Asm is a GNU extension we support.
6396     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6397       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6398       D.setInvalidType();
6399     }
6400   }
6401 
6402   bool IsMemberSpecialization = false;
6403   bool IsVariableTemplateSpecialization = false;
6404   bool IsPartialSpecialization = false;
6405   bool IsVariableTemplate = false;
6406   VarDecl *NewVD = nullptr;
6407   VarTemplateDecl *NewTemplate = nullptr;
6408   TemplateParameterList *TemplateParams = nullptr;
6409   if (!getLangOpts().CPlusPlus) {
6410     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6411                             D.getIdentifierLoc(), II,
6412                             R, TInfo, SC);
6413 
6414     if (R->getContainedDeducedType())
6415       ParsingInitForAutoVars.insert(NewVD);
6416 
6417     if (D.isInvalidType())
6418       NewVD->setInvalidDecl();
6419   } else {
6420     bool Invalid = false;
6421 
6422     if (DC->isRecord() && !CurContext->isRecord()) {
6423       // This is an out-of-line definition of a static data member.
6424       switch (SC) {
6425       case SC_None:
6426         break;
6427       case SC_Static:
6428         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6429              diag::err_static_out_of_line)
6430           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6431         break;
6432       case SC_Auto:
6433       case SC_Register:
6434       case SC_Extern:
6435         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6436         // to names of variables declared in a block or to function parameters.
6437         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6438         // of class members
6439 
6440         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6441              diag::err_storage_class_for_static_member)
6442           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6443         break;
6444       case SC_PrivateExtern:
6445         llvm_unreachable("C storage class in c++!");
6446       }
6447     }
6448 
6449     if (SC == SC_Static && CurContext->isRecord()) {
6450       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6451         if (RD->isLocalClass())
6452           Diag(D.getIdentifierLoc(),
6453                diag::err_static_data_member_not_allowed_in_local_class)
6454             << Name << RD->getDeclName();
6455 
6456         // C++98 [class.union]p1: If a union contains a static data member,
6457         // the program is ill-formed. C++11 drops this restriction.
6458         if (RD->isUnion())
6459           Diag(D.getIdentifierLoc(),
6460                getLangOpts().CPlusPlus11
6461                  ? diag::warn_cxx98_compat_static_data_member_in_union
6462                  : diag::ext_static_data_member_in_union) << Name;
6463         // We conservatively disallow static data members in anonymous structs.
6464         else if (!RD->getDeclName())
6465           Diag(D.getIdentifierLoc(),
6466                diag::err_static_data_member_not_allowed_in_anon_struct)
6467             << Name << RD->isUnion();
6468       }
6469     }
6470 
6471     // Match up the template parameter lists with the scope specifier, then
6472     // determine whether we have a template or a template specialization.
6473     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6474         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6475         D.getCXXScopeSpec(),
6476         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6477             ? D.getName().TemplateId
6478             : nullptr,
6479         TemplateParamLists,
6480         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6481 
6482     if (TemplateParams) {
6483       if (!TemplateParams->size() &&
6484           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6485         // There is an extraneous 'template<>' for this variable. Complain
6486         // about it, but allow the declaration of the variable.
6487         Diag(TemplateParams->getTemplateLoc(),
6488              diag::err_template_variable_noparams)
6489           << II
6490           << SourceRange(TemplateParams->getTemplateLoc(),
6491                          TemplateParams->getRAngleLoc());
6492         TemplateParams = nullptr;
6493       } else {
6494         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6495           // This is an explicit specialization or a partial specialization.
6496           // FIXME: Check that we can declare a specialization here.
6497           IsVariableTemplateSpecialization = true;
6498           IsPartialSpecialization = TemplateParams->size() > 0;
6499         } else { // if (TemplateParams->size() > 0)
6500           // This is a template declaration.
6501           IsVariableTemplate = true;
6502 
6503           // Check that we can declare a template here.
6504           if (CheckTemplateDeclScope(S, TemplateParams))
6505             return nullptr;
6506 
6507           // Only C++1y supports variable templates (N3651).
6508           Diag(D.getIdentifierLoc(),
6509                getLangOpts().CPlusPlus14
6510                    ? diag::warn_cxx11_compat_variable_template
6511                    : diag::ext_variable_template);
6512         }
6513       }
6514     } else {
6515       assert((Invalid ||
6516               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6517              "should have a 'template<>' for this decl");
6518     }
6519 
6520     if (IsVariableTemplateSpecialization) {
6521       SourceLocation TemplateKWLoc =
6522           TemplateParamLists.size() > 0
6523               ? TemplateParamLists[0]->getTemplateLoc()
6524               : SourceLocation();
6525       DeclResult Res = ActOnVarTemplateSpecialization(
6526           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6527           IsPartialSpecialization);
6528       if (Res.isInvalid())
6529         return nullptr;
6530       NewVD = cast<VarDecl>(Res.get());
6531       AddToScope = false;
6532     } else if (D.isDecompositionDeclarator()) {
6533       NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6534                                         D.getIdentifierLoc(), R, TInfo, SC,
6535                                         Bindings);
6536     } else
6537       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6538                               D.getIdentifierLoc(), II, R, TInfo, SC);
6539 
6540     // If this is supposed to be a variable template, create it as such.
6541     if (IsVariableTemplate) {
6542       NewTemplate =
6543           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6544                                   TemplateParams, NewVD);
6545       NewVD->setDescribedVarTemplate(NewTemplate);
6546     }
6547 
6548     // If this decl has an auto type in need of deduction, make a note of the
6549     // Decl so we can diagnose uses of it in its own initializer.
6550     if (R->getContainedDeducedType())
6551       ParsingInitForAutoVars.insert(NewVD);
6552 
6553     if (D.isInvalidType() || Invalid) {
6554       NewVD->setInvalidDecl();
6555       if (NewTemplate)
6556         NewTemplate->setInvalidDecl();
6557     }
6558 
6559     SetNestedNameSpecifier(NewVD, D);
6560 
6561     // If we have any template parameter lists that don't directly belong to
6562     // the variable (matching the scope specifier), store them.
6563     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6564     if (TemplateParamLists.size() > VDTemplateParamLists)
6565       NewVD->setTemplateParameterListsInfo(
6566           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6567 
6568     if (D.getDeclSpec().isConstexprSpecified()) {
6569       NewVD->setConstexpr(true);
6570       // C++1z [dcl.spec.constexpr]p1:
6571       //   A static data member declared with the constexpr specifier is
6572       //   implicitly an inline variable.
6573       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
6574         NewVD->setImplicitlyInline();
6575     }
6576   }
6577 
6578   if (D.getDeclSpec().isInlineSpecified()) {
6579     if (!getLangOpts().CPlusPlus) {
6580       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6581           << 0;
6582     } else if (CurContext->isFunctionOrMethod()) {
6583       // 'inline' is not allowed on block scope variable declaration.
6584       Diag(D.getDeclSpec().getInlineSpecLoc(),
6585            diag::err_inline_declaration_block_scope) << Name
6586         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6587     } else {
6588       Diag(D.getDeclSpec().getInlineSpecLoc(),
6589            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6590                                      : diag::ext_inline_variable);
6591       NewVD->setInlineSpecified();
6592     }
6593   }
6594 
6595   // Set the lexical context. If the declarator has a C++ scope specifier, the
6596   // lexical context will be different from the semantic context.
6597   NewVD->setLexicalDeclContext(CurContext);
6598   if (NewTemplate)
6599     NewTemplate->setLexicalDeclContext(CurContext);
6600 
6601   if (IsLocalExternDecl) {
6602     if (D.isDecompositionDeclarator())
6603       for (auto *B : Bindings)
6604         B->setLocalExternDecl();
6605     else
6606       NewVD->setLocalExternDecl();
6607   }
6608 
6609   bool EmitTLSUnsupportedError = false;
6610   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6611     // C++11 [dcl.stc]p4:
6612     //   When thread_local is applied to a variable of block scope the
6613     //   storage-class-specifier static is implied if it does not appear
6614     //   explicitly.
6615     // Core issue: 'static' is not implied if the variable is declared
6616     //   'extern'.
6617     if (NewVD->hasLocalStorage() &&
6618         (SCSpec != DeclSpec::SCS_unspecified ||
6619          TSCS != DeclSpec::TSCS_thread_local ||
6620          !DC->isFunctionOrMethod()))
6621       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6622            diag::err_thread_non_global)
6623         << DeclSpec::getSpecifierName(TSCS);
6624     else if (!Context.getTargetInfo().isTLSSupported()) {
6625       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6626         // Postpone error emission until we've collected attributes required to
6627         // figure out whether it's a host or device variable and whether the
6628         // error should be ignored.
6629         EmitTLSUnsupportedError = true;
6630         // We still need to mark the variable as TLS so it shows up in AST with
6631         // proper storage class for other tools to use even if we're not going
6632         // to emit any code for it.
6633         NewVD->setTSCSpec(TSCS);
6634       } else
6635         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6636              diag::err_thread_unsupported);
6637     } else
6638       NewVD->setTSCSpec(TSCS);
6639   }
6640 
6641   // C99 6.7.4p3
6642   //   An inline definition of a function with external linkage shall
6643   //   not contain a definition of a modifiable object with static or
6644   //   thread storage duration...
6645   // We only apply this when the function is required to be defined
6646   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6647   // that a local variable with thread storage duration still has to
6648   // be marked 'static'.  Also note that it's possible to get these
6649   // semantics in C++ using __attribute__((gnu_inline)).
6650   if (SC == SC_Static && S->getFnParent() != nullptr &&
6651       !NewVD->getType().isConstQualified()) {
6652     FunctionDecl *CurFD = getCurFunctionDecl();
6653     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6654       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6655            diag::warn_static_local_in_extern_inline);
6656       MaybeSuggestAddingStaticToDecl(CurFD);
6657     }
6658   }
6659 
6660   if (D.getDeclSpec().isModulePrivateSpecified()) {
6661     if (IsVariableTemplateSpecialization)
6662       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6663           << (IsPartialSpecialization ? 1 : 0)
6664           << FixItHint::CreateRemoval(
6665                  D.getDeclSpec().getModulePrivateSpecLoc());
6666     else if (IsMemberSpecialization)
6667       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6668         << 2
6669         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6670     else if (NewVD->hasLocalStorage())
6671       Diag(NewVD->getLocation(), diag::err_module_private_local)
6672         << 0 << NewVD->getDeclName()
6673         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6674         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6675     else {
6676       NewVD->setModulePrivate();
6677       if (NewTemplate)
6678         NewTemplate->setModulePrivate();
6679       for (auto *B : Bindings)
6680         B->setModulePrivate();
6681     }
6682   }
6683 
6684   // Handle attributes prior to checking for duplicates in MergeVarDecl
6685   ProcessDeclAttributes(S, NewVD, D);
6686 
6687   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6688     if (EmitTLSUnsupportedError &&
6689         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6690          (getLangOpts().OpenMPIsDevice &&
6691           NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6692       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6693            diag::err_thread_unsupported);
6694     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6695     // storage [duration]."
6696     if (SC == SC_None && S->getFnParent() != nullptr &&
6697         (NewVD->hasAttr<CUDASharedAttr>() ||
6698          NewVD->hasAttr<CUDAConstantAttr>())) {
6699       NewVD->setStorageClass(SC_Static);
6700     }
6701   }
6702 
6703   // Ensure that dllimport globals without explicit storage class are treated as
6704   // extern. The storage class is set above using parsed attributes. Now we can
6705   // check the VarDecl itself.
6706   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6707          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6708          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6709 
6710   // In auto-retain/release, infer strong retension for variables of
6711   // retainable type.
6712   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6713     NewVD->setInvalidDecl();
6714 
6715   // Handle GNU asm-label extension (encoded as an attribute).
6716   if (Expr *E = (Expr*)D.getAsmLabel()) {
6717     // The parser guarantees this is a string.
6718     StringLiteral *SE = cast<StringLiteral>(E);
6719     StringRef Label = SE->getString();
6720     if (S->getFnParent() != nullptr) {
6721       switch (SC) {
6722       case SC_None:
6723       case SC_Auto:
6724         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6725         break;
6726       case SC_Register:
6727         // Local Named register
6728         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6729             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6730           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6731         break;
6732       case SC_Static:
6733       case SC_Extern:
6734       case SC_PrivateExtern:
6735         break;
6736       }
6737     } else if (SC == SC_Register) {
6738       // Global Named register
6739       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6740         const auto &TI = Context.getTargetInfo();
6741         bool HasSizeMismatch;
6742 
6743         if (!TI.isValidGCCRegisterName(Label))
6744           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6745         else if (!TI.validateGlobalRegisterVariable(Label,
6746                                                     Context.getTypeSize(R),
6747                                                     HasSizeMismatch))
6748           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6749         else if (HasSizeMismatch)
6750           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6751       }
6752 
6753       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6754         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6755         NewVD->setInvalidDecl(true);
6756       }
6757     }
6758 
6759     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6760                                                 Context, Label, 0));
6761   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6762     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6763       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6764     if (I != ExtnameUndeclaredIdentifiers.end()) {
6765       if (isDeclExternC(NewVD)) {
6766         NewVD->addAttr(I->second);
6767         ExtnameUndeclaredIdentifiers.erase(I);
6768       } else
6769         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6770             << /*Variable*/1 << NewVD;
6771     }
6772   }
6773 
6774   // Find the shadowed declaration before filtering for scope.
6775   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6776                                 ? getShadowedDeclaration(NewVD, Previous)
6777                                 : nullptr;
6778 
6779   // Don't consider existing declarations that are in a different
6780   // scope and are out-of-semantic-context declarations (if the new
6781   // declaration has linkage).
6782   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6783                        D.getCXXScopeSpec().isNotEmpty() ||
6784                        IsMemberSpecialization ||
6785                        IsVariableTemplateSpecialization);
6786 
6787   // Check whether the previous declaration is in the same block scope. This
6788   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6789   if (getLangOpts().CPlusPlus &&
6790       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6791     NewVD->setPreviousDeclInSameBlockScope(
6792         Previous.isSingleResult() && !Previous.isShadowed() &&
6793         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6794 
6795   if (!getLangOpts().CPlusPlus) {
6796     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6797   } else {
6798     // If this is an explicit specialization of a static data member, check it.
6799     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6800         CheckMemberSpecialization(NewVD, Previous))
6801       NewVD->setInvalidDecl();
6802 
6803     // Merge the decl with the existing one if appropriate.
6804     if (!Previous.empty()) {
6805       if (Previous.isSingleResult() &&
6806           isa<FieldDecl>(Previous.getFoundDecl()) &&
6807           D.getCXXScopeSpec().isSet()) {
6808         // The user tried to define a non-static data member
6809         // out-of-line (C++ [dcl.meaning]p1).
6810         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6811           << D.getCXXScopeSpec().getRange();
6812         Previous.clear();
6813         NewVD->setInvalidDecl();
6814       }
6815     } else if (D.getCXXScopeSpec().isSet()) {
6816       // No previous declaration in the qualifying scope.
6817       Diag(D.getIdentifierLoc(), diag::err_no_member)
6818         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6819         << D.getCXXScopeSpec().getRange();
6820       NewVD->setInvalidDecl();
6821     }
6822 
6823     if (!IsVariableTemplateSpecialization)
6824       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6825 
6826     if (NewTemplate) {
6827       VarTemplateDecl *PrevVarTemplate =
6828           NewVD->getPreviousDecl()
6829               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6830               : nullptr;
6831 
6832       // Check the template parameter list of this declaration, possibly
6833       // merging in the template parameter list from the previous variable
6834       // template declaration.
6835       if (CheckTemplateParameterList(
6836               TemplateParams,
6837               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6838                               : nullptr,
6839               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6840                DC->isDependentContext())
6841                   ? TPC_ClassTemplateMember
6842                   : TPC_VarTemplate))
6843         NewVD->setInvalidDecl();
6844 
6845       // If we are providing an explicit specialization of a static variable
6846       // template, make a note of that.
6847       if (PrevVarTemplate &&
6848           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6849         PrevVarTemplate->setMemberSpecialization();
6850     }
6851   }
6852 
6853   // Diagnose shadowed variables iff this isn't a redeclaration.
6854   if (ShadowedDecl && !D.isRedeclaration())
6855     CheckShadow(NewVD, ShadowedDecl, Previous);
6856 
6857   ProcessPragmaWeak(S, NewVD);
6858 
6859   // If this is the first declaration of an extern C variable, update
6860   // the map of such variables.
6861   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6862       isIncompleteDeclExternC(*this, NewVD))
6863     RegisterLocallyScopedExternCDecl(NewVD, S);
6864 
6865   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6866     Decl *ManglingContextDecl;
6867     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6868             NewVD->getDeclContext(), ManglingContextDecl)) {
6869       Context.setManglingNumber(
6870           NewVD, MCtx->getManglingNumber(
6871                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6872       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6873     }
6874   }
6875 
6876   // Special handling of variable named 'main'.
6877   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6878       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6879       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6880 
6881     // C++ [basic.start.main]p3
6882     // A program that declares a variable main at global scope is ill-formed.
6883     if (getLangOpts().CPlusPlus)
6884       Diag(D.getLocStart(), diag::err_main_global_variable);
6885 
6886     // In C, and external-linkage variable named main results in undefined
6887     // behavior.
6888     else if (NewVD->hasExternalFormalLinkage())
6889       Diag(D.getLocStart(), diag::warn_main_redefined);
6890   }
6891 
6892   if (D.isRedeclaration() && !Previous.empty()) {
6893     NamedDecl *Prev = Previous.getRepresentativeDecl();
6894     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
6895                                    D.isFunctionDefinition());
6896   }
6897 
6898   if (NewTemplate) {
6899     if (NewVD->isInvalidDecl())
6900       NewTemplate->setInvalidDecl();
6901     ActOnDocumentableDecl(NewTemplate);
6902     return NewTemplate;
6903   }
6904 
6905   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6906     CompleteMemberSpecialization(NewVD, Previous);
6907 
6908   return NewVD;
6909 }
6910 
6911 /// Enum describing the %select options in diag::warn_decl_shadow.
6912 enum ShadowedDeclKind {
6913   SDK_Local,
6914   SDK_Global,
6915   SDK_StaticMember,
6916   SDK_Field,
6917   SDK_Typedef,
6918   SDK_Using
6919 };
6920 
6921 /// Determine what kind of declaration we're shadowing.
6922 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6923                                                 const DeclContext *OldDC) {
6924   if (isa<TypeAliasDecl>(ShadowedDecl))
6925     return SDK_Using;
6926   else if (isa<TypedefDecl>(ShadowedDecl))
6927     return SDK_Typedef;
6928   else if (isa<RecordDecl>(OldDC))
6929     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6930 
6931   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6932 }
6933 
6934 /// Return the location of the capture if the given lambda captures the given
6935 /// variable \p VD, or an invalid source location otherwise.
6936 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6937                                          const VarDecl *VD) {
6938   for (const Capture &Capture : LSI->Captures) {
6939     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6940       return Capture.getLocation();
6941   }
6942   return SourceLocation();
6943 }
6944 
6945 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6946                                      const LookupResult &R) {
6947   // Only diagnose if we're shadowing an unambiguous field or variable.
6948   if (R.getResultKind() != LookupResult::Found)
6949     return false;
6950 
6951   // Return false if warning is ignored.
6952   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6953 }
6954 
6955 /// \brief Return the declaration shadowed by the given variable \p D, or null
6956 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6957 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6958                                         const LookupResult &R) {
6959   if (!shouldWarnIfShadowedDecl(Diags, R))
6960     return nullptr;
6961 
6962   // Don't diagnose declarations at file scope.
6963   if (D->hasGlobalStorage())
6964     return nullptr;
6965 
6966   NamedDecl *ShadowedDecl = R.getFoundDecl();
6967   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6968              ? ShadowedDecl
6969              : nullptr;
6970 }
6971 
6972 /// \brief Return the declaration shadowed by the given typedef \p D, or null
6973 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6974 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
6975                                         const LookupResult &R) {
6976   // Don't warn if typedef declaration is part of a class
6977   if (D->getDeclContext()->isRecord())
6978     return nullptr;
6979 
6980   if (!shouldWarnIfShadowedDecl(Diags, R))
6981     return nullptr;
6982 
6983   NamedDecl *ShadowedDecl = R.getFoundDecl();
6984   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
6985 }
6986 
6987 /// \brief Diagnose variable or built-in function shadowing.  Implements
6988 /// -Wshadow.
6989 ///
6990 /// This method is called whenever a VarDecl is added to a "useful"
6991 /// scope.
6992 ///
6993 /// \param ShadowedDecl the declaration that is shadowed by the given variable
6994 /// \param R the lookup of the name
6995 ///
6996 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
6997                        const LookupResult &R) {
6998   DeclContext *NewDC = D->getDeclContext();
6999 
7000   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7001     // Fields are not shadowed by variables in C++ static methods.
7002     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7003       if (MD->isStatic())
7004         return;
7005 
7006     // Fields shadowed by constructor parameters are a special case. Usually
7007     // the constructor initializes the field with the parameter.
7008     if (isa<CXXConstructorDecl>(NewDC))
7009       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7010         // Remember that this was shadowed so we can either warn about its
7011         // modification or its existence depending on warning settings.
7012         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7013         return;
7014       }
7015   }
7016 
7017   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7018     if (shadowedVar->isExternC()) {
7019       // For shadowing external vars, make sure that we point to the global
7020       // declaration, not a locally scoped extern declaration.
7021       for (auto I : shadowedVar->redecls())
7022         if (I->isFileVarDecl()) {
7023           ShadowedDecl = I;
7024           break;
7025         }
7026     }
7027 
7028   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7029 
7030   unsigned WarningDiag = diag::warn_decl_shadow;
7031   SourceLocation CaptureLoc;
7032   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7033       isa<CXXMethodDecl>(NewDC)) {
7034     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7035       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7036         if (RD->getLambdaCaptureDefault() == LCD_None) {
7037           // Try to avoid warnings for lambdas with an explicit capture list.
7038           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7039           // Warn only when the lambda captures the shadowed decl explicitly.
7040           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7041           if (CaptureLoc.isInvalid())
7042             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7043         } else {
7044           // Remember that this was shadowed so we can avoid the warning if the
7045           // shadowed decl isn't captured and the warning settings allow it.
7046           cast<LambdaScopeInfo>(getCurFunction())
7047               ->ShadowingDecls.push_back(
7048                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7049           return;
7050         }
7051       }
7052 
7053       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7054         // A variable can't shadow a local variable in an enclosing scope, if
7055         // they are separated by a non-capturing declaration context.
7056         for (DeclContext *ParentDC = NewDC;
7057              ParentDC && !ParentDC->Equals(OldDC);
7058              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7059           // Only block literals, captured statements, and lambda expressions
7060           // can capture; other scopes don't.
7061           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7062               !isLambdaCallOperator(ParentDC)) {
7063             return;
7064           }
7065         }
7066       }
7067     }
7068   }
7069 
7070   // Only warn about certain kinds of shadowing for class members.
7071   if (NewDC && NewDC->isRecord()) {
7072     // In particular, don't warn about shadowing non-class members.
7073     if (!OldDC->isRecord())
7074       return;
7075 
7076     // TODO: should we warn about static data members shadowing
7077     // static data members from base classes?
7078 
7079     // TODO: don't diagnose for inaccessible shadowed members.
7080     // This is hard to do perfectly because we might friend the
7081     // shadowing context, but that's just a false negative.
7082   }
7083 
7084 
7085   DeclarationName Name = R.getLookupName();
7086 
7087   // Emit warning and note.
7088   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7089     return;
7090   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7091   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7092   if (!CaptureLoc.isInvalid())
7093     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7094         << Name << /*explicitly*/ 1;
7095   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7096 }
7097 
7098 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7099 /// when these variables are captured by the lambda.
7100 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7101   for (const auto &Shadow : LSI->ShadowingDecls) {
7102     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7103     // Try to avoid the warning when the shadowed decl isn't captured.
7104     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7105     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7106     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7107                                        ? diag::warn_decl_shadow_uncaptured_local
7108                                        : diag::warn_decl_shadow)
7109         << Shadow.VD->getDeclName()
7110         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7111     if (!CaptureLoc.isInvalid())
7112       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7113           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7114     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7115   }
7116 }
7117 
7118 /// \brief Check -Wshadow without the advantage of a previous lookup.
7119 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7120   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7121     return;
7122 
7123   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7124                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7125   LookupName(R, S);
7126   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7127     CheckShadow(D, ShadowedDecl, R);
7128 }
7129 
7130 /// Check if 'E', which is an expression that is about to be modified, refers
7131 /// to a constructor parameter that shadows a field.
7132 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7133   // Quickly ignore expressions that can't be shadowing ctor parameters.
7134   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7135     return;
7136   E = E->IgnoreParenImpCasts();
7137   auto *DRE = dyn_cast<DeclRefExpr>(E);
7138   if (!DRE)
7139     return;
7140   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7141   auto I = ShadowingDecls.find(D);
7142   if (I == ShadowingDecls.end())
7143     return;
7144   const NamedDecl *ShadowedDecl = I->second;
7145   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7146   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7147   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7148   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7149 
7150   // Avoid issuing multiple warnings about the same decl.
7151   ShadowingDecls.erase(I);
7152 }
7153 
7154 /// Check for conflict between this global or extern "C" declaration and
7155 /// previous global or extern "C" declarations. This is only used in C++.
7156 template<typename T>
7157 static bool checkGlobalOrExternCConflict(
7158     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7159   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7160   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7161 
7162   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7163     // The common case: this global doesn't conflict with any extern "C"
7164     // declaration.
7165     return false;
7166   }
7167 
7168   if (Prev) {
7169     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7170       // Both the old and new declarations have C language linkage. This is a
7171       // redeclaration.
7172       Previous.clear();
7173       Previous.addDecl(Prev);
7174       return true;
7175     }
7176 
7177     // This is a global, non-extern "C" declaration, and there is a previous
7178     // non-global extern "C" declaration. Diagnose if this is a variable
7179     // declaration.
7180     if (!isa<VarDecl>(ND))
7181       return false;
7182   } else {
7183     // The declaration is extern "C". Check for any declaration in the
7184     // translation unit which might conflict.
7185     if (IsGlobal) {
7186       // We have already performed the lookup into the translation unit.
7187       IsGlobal = false;
7188       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7189            I != E; ++I) {
7190         if (isa<VarDecl>(*I)) {
7191           Prev = *I;
7192           break;
7193         }
7194       }
7195     } else {
7196       DeclContext::lookup_result R =
7197           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7198       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7199            I != E; ++I) {
7200         if (isa<VarDecl>(*I)) {
7201           Prev = *I;
7202           break;
7203         }
7204         // FIXME: If we have any other entity with this name in global scope,
7205         // the declaration is ill-formed, but that is a defect: it breaks the
7206         // 'stat' hack, for instance. Only variables can have mangled name
7207         // clashes with extern "C" declarations, so only they deserve a
7208         // diagnostic.
7209       }
7210     }
7211 
7212     if (!Prev)
7213       return false;
7214   }
7215 
7216   // Use the first declaration's location to ensure we point at something which
7217   // is lexically inside an extern "C" linkage-spec.
7218   assert(Prev && "should have found a previous declaration to diagnose");
7219   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7220     Prev = FD->getFirstDecl();
7221   else
7222     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7223 
7224   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7225     << IsGlobal << ND;
7226   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7227     << IsGlobal;
7228   return false;
7229 }
7230 
7231 /// Apply special rules for handling extern "C" declarations. Returns \c true
7232 /// if we have found that this is a redeclaration of some prior entity.
7233 ///
7234 /// Per C++ [dcl.link]p6:
7235 ///   Two declarations [for a function or variable] with C language linkage
7236 ///   with the same name that appear in different scopes refer to the same
7237 ///   [entity]. An entity with C language linkage shall not be declared with
7238 ///   the same name as an entity in global scope.
7239 template<typename T>
7240 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7241                                                   LookupResult &Previous) {
7242   if (!S.getLangOpts().CPlusPlus) {
7243     // In C, when declaring a global variable, look for a corresponding 'extern'
7244     // variable declared in function scope. We don't need this in C++, because
7245     // we find local extern decls in the surrounding file-scope DeclContext.
7246     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7247       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7248         Previous.clear();
7249         Previous.addDecl(Prev);
7250         return true;
7251       }
7252     }
7253     return false;
7254   }
7255 
7256   // A declaration in the translation unit can conflict with an extern "C"
7257   // declaration.
7258   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7259     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7260 
7261   // An extern "C" declaration can conflict with a declaration in the
7262   // translation unit or can be a redeclaration of an extern "C" declaration
7263   // in another scope.
7264   if (isIncompleteDeclExternC(S,ND))
7265     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7266 
7267   // Neither global nor extern "C": nothing to do.
7268   return false;
7269 }
7270 
7271 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7272   // If the decl is already known invalid, don't check it.
7273   if (NewVD->isInvalidDecl())
7274     return;
7275 
7276   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
7277   QualType T = TInfo->getType();
7278 
7279   // Defer checking an 'auto' type until its initializer is attached.
7280   if (T->isUndeducedType())
7281     return;
7282 
7283   if (NewVD->hasAttrs())
7284     CheckAlignasUnderalignment(NewVD);
7285 
7286   if (T->isObjCObjectType()) {
7287     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7288       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7289     T = Context.getObjCObjectPointerType(T);
7290     NewVD->setType(T);
7291   }
7292 
7293   // Emit an error if an address space was applied to decl with local storage.
7294   // This includes arrays of objects with address space qualifiers, but not
7295   // automatic variables that point to other address spaces.
7296   // ISO/IEC TR 18037 S5.1.2
7297   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7298       T.getAddressSpace() != LangAS::Default) {
7299     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7300     NewVD->setInvalidDecl();
7301     return;
7302   }
7303 
7304   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7305   // scope.
7306   if (getLangOpts().OpenCLVersion == 120 &&
7307       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7308       NewVD->isStaticLocal()) {
7309     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7310     NewVD->setInvalidDecl();
7311     return;
7312   }
7313 
7314   if (getLangOpts().OpenCL) {
7315     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7316     if (NewVD->hasAttr<BlocksAttr>()) {
7317       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7318       return;
7319     }
7320 
7321     if (T->isBlockPointerType()) {
7322       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7323       // can't use 'extern' storage class.
7324       if (!T.isConstQualified()) {
7325         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7326             << 0 /*const*/;
7327         NewVD->setInvalidDecl();
7328         return;
7329       }
7330       if (NewVD->hasExternalStorage()) {
7331         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7332         NewVD->setInvalidDecl();
7333         return;
7334       }
7335     }
7336     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7337     // __constant address space.
7338     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7339     // variables inside a function can also be declared in the global
7340     // address space.
7341     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7342         NewVD->hasExternalStorage()) {
7343       if (!T->isSamplerT() &&
7344           !(T.getAddressSpace() == LangAS::opencl_constant ||
7345             (T.getAddressSpace() == LangAS::opencl_global &&
7346              getLangOpts().OpenCLVersion == 200))) {
7347         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7348         if (getLangOpts().OpenCLVersion == 200)
7349           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7350               << Scope << "global or constant";
7351         else
7352           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7353               << Scope << "constant";
7354         NewVD->setInvalidDecl();
7355         return;
7356       }
7357     } else {
7358       if (T.getAddressSpace() == LangAS::opencl_global) {
7359         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7360             << 1 /*is any function*/ << "global";
7361         NewVD->setInvalidDecl();
7362         return;
7363       }
7364       if (T.getAddressSpace() == LangAS::opencl_constant ||
7365           T.getAddressSpace() == LangAS::opencl_local) {
7366         FunctionDecl *FD = getCurFunctionDecl();
7367         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7368         // in functions.
7369         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7370           if (T.getAddressSpace() == LangAS::opencl_constant)
7371             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7372                 << 0 /*non-kernel only*/ << "constant";
7373           else
7374             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7375                 << 0 /*non-kernel only*/ << "local";
7376           NewVD->setInvalidDecl();
7377           return;
7378         }
7379         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7380         // in the outermost scope of a kernel function.
7381         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7382           if (!getCurScope()->isFunctionScope()) {
7383             if (T.getAddressSpace() == LangAS::opencl_constant)
7384               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7385                   << "constant";
7386             else
7387               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7388                   << "local";
7389             NewVD->setInvalidDecl();
7390             return;
7391           }
7392         }
7393       } else if (T.getAddressSpace() != LangAS::opencl_private) {
7394         // Do not allow other address spaces on automatic variable.
7395         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7396         NewVD->setInvalidDecl();
7397         return;
7398       }
7399     }
7400   }
7401 
7402   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7403       && !NewVD->hasAttr<BlocksAttr>()) {
7404     if (getLangOpts().getGC() != LangOptions::NonGC)
7405       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7406     else {
7407       assert(!getLangOpts().ObjCAutoRefCount);
7408       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7409     }
7410   }
7411 
7412   bool isVM = T->isVariablyModifiedType();
7413   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7414       NewVD->hasAttr<BlocksAttr>())
7415     setFunctionHasBranchProtectedScope();
7416 
7417   if ((isVM && NewVD->hasLinkage()) ||
7418       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7419     bool SizeIsNegative;
7420     llvm::APSInt Oversized;
7421     TypeSourceInfo *FixedTInfo =
7422       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7423                                                     SizeIsNegative, Oversized);
7424     if (!FixedTInfo && T->isVariableArrayType()) {
7425       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7426       // FIXME: This won't give the correct result for
7427       // int a[10][n];
7428       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7429 
7430       if (NewVD->isFileVarDecl())
7431         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7432         << SizeRange;
7433       else if (NewVD->isStaticLocal())
7434         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7435         << SizeRange;
7436       else
7437         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7438         << SizeRange;
7439       NewVD->setInvalidDecl();
7440       return;
7441     }
7442 
7443     if (!FixedTInfo) {
7444       if (NewVD->isFileVarDecl())
7445         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7446       else
7447         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7448       NewVD->setInvalidDecl();
7449       return;
7450     }
7451 
7452     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7453     NewVD->setType(FixedTInfo->getType());
7454     NewVD->setTypeSourceInfo(FixedTInfo);
7455   }
7456 
7457   if (T->isVoidType()) {
7458     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7459     //                    of objects and functions.
7460     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7461       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7462         << T;
7463       NewVD->setInvalidDecl();
7464       return;
7465     }
7466   }
7467 
7468   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7469     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7470     NewVD->setInvalidDecl();
7471     return;
7472   }
7473 
7474   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7475     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7476     NewVD->setInvalidDecl();
7477     return;
7478   }
7479 
7480   if (NewVD->isConstexpr() && !T->isDependentType() &&
7481       RequireLiteralType(NewVD->getLocation(), T,
7482                          diag::err_constexpr_var_non_literal)) {
7483     NewVD->setInvalidDecl();
7484     return;
7485   }
7486 }
7487 
7488 /// \brief Perform semantic checking on a newly-created variable
7489 /// declaration.
7490 ///
7491 /// This routine performs all of the type-checking required for a
7492 /// variable declaration once it has been built. It is used both to
7493 /// check variables after they have been parsed and their declarators
7494 /// have been translated into a declaration, and to check variables
7495 /// that have been instantiated from a template.
7496 ///
7497 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7498 ///
7499 /// Returns true if the variable declaration is a redeclaration.
7500 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7501   CheckVariableDeclarationType(NewVD);
7502 
7503   // If the decl is already known invalid, don't check it.
7504   if (NewVD->isInvalidDecl())
7505     return false;
7506 
7507   // If we did not find anything by this name, look for a non-visible
7508   // extern "C" declaration with the same name.
7509   if (Previous.empty() &&
7510       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7511     Previous.setShadowed();
7512 
7513   if (!Previous.empty()) {
7514     MergeVarDecl(NewVD, Previous);
7515     return true;
7516   }
7517   return false;
7518 }
7519 
7520 namespace {
7521 struct FindOverriddenMethod {
7522   Sema *S;
7523   CXXMethodDecl *Method;
7524 
7525   /// Member lookup function that determines whether a given C++
7526   /// method overrides a method in a base class, to be used with
7527   /// CXXRecordDecl::lookupInBases().
7528   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7529     RecordDecl *BaseRecord =
7530         Specifier->getType()->getAs<RecordType>()->getDecl();
7531 
7532     DeclarationName Name = Method->getDeclName();
7533 
7534     // FIXME: Do we care about other names here too?
7535     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7536       // We really want to find the base class destructor here.
7537       QualType T = S->Context.getTypeDeclType(BaseRecord);
7538       CanQualType CT = S->Context.getCanonicalType(T);
7539 
7540       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7541     }
7542 
7543     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7544          Path.Decls = Path.Decls.slice(1)) {
7545       NamedDecl *D = Path.Decls.front();
7546       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7547         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7548           return true;
7549       }
7550     }
7551 
7552     return false;
7553   }
7554 };
7555 
7556 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7557 } // end anonymous namespace
7558 
7559 /// \brief Report an error regarding overriding, along with any relevant
7560 /// overriden methods.
7561 ///
7562 /// \param DiagID the primary error to report.
7563 /// \param MD the overriding method.
7564 /// \param OEK which overrides to include as notes.
7565 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7566                             OverrideErrorKind OEK = OEK_All) {
7567   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7568   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7569     // This check (& the OEK parameter) could be replaced by a predicate, but
7570     // without lambdas that would be overkill. This is still nicer than writing
7571     // out the diag loop 3 times.
7572     if ((OEK == OEK_All) ||
7573         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7574         (OEK == OEK_Deleted && O->isDeleted()))
7575       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7576   }
7577 }
7578 
7579 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7580 /// and if so, check that it's a valid override and remember it.
7581 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7582   // Look for methods in base classes that this method might override.
7583   CXXBasePaths Paths;
7584   FindOverriddenMethod FOM;
7585   FOM.Method = MD;
7586   FOM.S = this;
7587   bool hasDeletedOverridenMethods = false;
7588   bool hasNonDeletedOverridenMethods = false;
7589   bool AddedAny = false;
7590   if (DC->lookupInBases(FOM, Paths)) {
7591     for (auto *I : Paths.found_decls()) {
7592       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7593         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7594         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7595             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7596             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7597             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7598           hasDeletedOverridenMethods |= OldMD->isDeleted();
7599           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7600           AddedAny = true;
7601         }
7602       }
7603     }
7604   }
7605 
7606   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7607     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7608   }
7609   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7610     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7611   }
7612 
7613   return AddedAny;
7614 }
7615 
7616 namespace {
7617   // Struct for holding all of the extra arguments needed by
7618   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7619   struct ActOnFDArgs {
7620     Scope *S;
7621     Declarator &D;
7622     MultiTemplateParamsArg TemplateParamLists;
7623     bool AddToScope;
7624   };
7625 } // end anonymous namespace
7626 
7627 namespace {
7628 
7629 // Callback to only accept typo corrections that have a non-zero edit distance.
7630 // Also only accept corrections that have the same parent decl.
7631 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7632  public:
7633   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7634                             CXXRecordDecl *Parent)
7635       : Context(Context), OriginalFD(TypoFD),
7636         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7637 
7638   bool ValidateCandidate(const TypoCorrection &candidate) override {
7639     if (candidate.getEditDistance() == 0)
7640       return false;
7641 
7642     SmallVector<unsigned, 1> MismatchedParams;
7643     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7644                                           CDeclEnd = candidate.end();
7645          CDecl != CDeclEnd; ++CDecl) {
7646       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7647 
7648       if (FD && !FD->hasBody() &&
7649           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7650         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7651           CXXRecordDecl *Parent = MD->getParent();
7652           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7653             return true;
7654         } else if (!ExpectedParent) {
7655           return true;
7656         }
7657       }
7658     }
7659 
7660     return false;
7661   }
7662 
7663  private:
7664   ASTContext &Context;
7665   FunctionDecl *OriginalFD;
7666   CXXRecordDecl *ExpectedParent;
7667 };
7668 
7669 } // end anonymous namespace
7670 
7671 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7672   TypoCorrectedFunctionDefinitions.insert(F);
7673 }
7674 
7675 /// \brief Generate diagnostics for an invalid function redeclaration.
7676 ///
7677 /// This routine handles generating the diagnostic messages for an invalid
7678 /// function redeclaration, including finding possible similar declarations
7679 /// or performing typo correction if there are no previous declarations with
7680 /// the same name.
7681 ///
7682 /// Returns a NamedDecl iff typo correction was performed and substituting in
7683 /// the new declaration name does not cause new errors.
7684 static NamedDecl *DiagnoseInvalidRedeclaration(
7685     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7686     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7687   DeclarationName Name = NewFD->getDeclName();
7688   DeclContext *NewDC = NewFD->getDeclContext();
7689   SmallVector<unsigned, 1> MismatchedParams;
7690   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7691   TypoCorrection Correction;
7692   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7693   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7694                                    : diag::err_member_decl_does_not_match;
7695   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7696                     IsLocalFriend ? Sema::LookupLocalFriendName
7697                                   : Sema::LookupOrdinaryName,
7698                     Sema::ForVisibleRedeclaration);
7699 
7700   NewFD->setInvalidDecl();
7701   if (IsLocalFriend)
7702     SemaRef.LookupName(Prev, S);
7703   else
7704     SemaRef.LookupQualifiedName(Prev, NewDC);
7705   assert(!Prev.isAmbiguous() &&
7706          "Cannot have an ambiguity in previous-declaration lookup");
7707   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7708   if (!Prev.empty()) {
7709     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7710          Func != FuncEnd; ++Func) {
7711       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7712       if (FD &&
7713           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7714         // Add 1 to the index so that 0 can mean the mismatch didn't
7715         // involve a parameter
7716         unsigned ParamNum =
7717             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7718         NearMatches.push_back(std::make_pair(FD, ParamNum));
7719       }
7720     }
7721   // If the qualified name lookup yielded nothing, try typo correction
7722   } else if ((Correction = SemaRef.CorrectTypo(
7723                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7724                   &ExtraArgs.D.getCXXScopeSpec(),
7725                   llvm::make_unique<DifferentNameValidatorCCC>(
7726                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7727                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7728     // Set up everything for the call to ActOnFunctionDeclarator
7729     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7730                               ExtraArgs.D.getIdentifierLoc());
7731     Previous.clear();
7732     Previous.setLookupName(Correction.getCorrection());
7733     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7734                                     CDeclEnd = Correction.end();
7735          CDecl != CDeclEnd; ++CDecl) {
7736       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7737       if (FD && !FD->hasBody() &&
7738           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7739         Previous.addDecl(FD);
7740       }
7741     }
7742     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7743 
7744     NamedDecl *Result;
7745     // Retry building the function declaration with the new previous
7746     // declarations, and with errors suppressed.
7747     {
7748       // Trap errors.
7749       Sema::SFINAETrap Trap(SemaRef);
7750 
7751       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7752       // pieces need to verify the typo-corrected C++ declaration and hopefully
7753       // eliminate the need for the parameter pack ExtraArgs.
7754       Result = SemaRef.ActOnFunctionDeclarator(
7755           ExtraArgs.S, ExtraArgs.D,
7756           Correction.getCorrectionDecl()->getDeclContext(),
7757           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7758           ExtraArgs.AddToScope);
7759 
7760       if (Trap.hasErrorOccurred())
7761         Result = nullptr;
7762     }
7763 
7764     if (Result) {
7765       // Determine which correction we picked.
7766       Decl *Canonical = Result->getCanonicalDecl();
7767       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7768            I != E; ++I)
7769         if ((*I)->getCanonicalDecl() == Canonical)
7770           Correction.setCorrectionDecl(*I);
7771 
7772       // Let Sema know about the correction.
7773       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7774       SemaRef.diagnoseTypo(
7775           Correction,
7776           SemaRef.PDiag(IsLocalFriend
7777                           ? diag::err_no_matching_local_friend_suggest
7778                           : diag::err_member_decl_does_not_match_suggest)
7779             << Name << NewDC << IsDefinition);
7780       return Result;
7781     }
7782 
7783     // Pretend the typo correction never occurred
7784     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7785                               ExtraArgs.D.getIdentifierLoc());
7786     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7787     Previous.clear();
7788     Previous.setLookupName(Name);
7789   }
7790 
7791   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7792       << Name << NewDC << IsDefinition << NewFD->getLocation();
7793 
7794   bool NewFDisConst = false;
7795   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7796     NewFDisConst = NewMD->isConst();
7797 
7798   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7799        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7800        NearMatch != NearMatchEnd; ++NearMatch) {
7801     FunctionDecl *FD = NearMatch->first;
7802     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7803     bool FDisConst = MD && MD->isConst();
7804     bool IsMember = MD || !IsLocalFriend;
7805 
7806     // FIXME: These notes are poorly worded for the local friend case.
7807     if (unsigned Idx = NearMatch->second) {
7808       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7809       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7810       if (Loc.isInvalid()) Loc = FD->getLocation();
7811       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7812                                  : diag::note_local_decl_close_param_match)
7813         << Idx << FDParam->getType()
7814         << NewFD->getParamDecl(Idx - 1)->getType();
7815     } else if (FDisConst != NewFDisConst) {
7816       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7817           << NewFDisConst << FD->getSourceRange().getEnd();
7818     } else
7819       SemaRef.Diag(FD->getLocation(),
7820                    IsMember ? diag::note_member_def_close_match
7821                             : diag::note_local_decl_close_match);
7822   }
7823   return nullptr;
7824 }
7825 
7826 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7827   switch (D.getDeclSpec().getStorageClassSpec()) {
7828   default: llvm_unreachable("Unknown storage class!");
7829   case DeclSpec::SCS_auto:
7830   case DeclSpec::SCS_register:
7831   case DeclSpec::SCS_mutable:
7832     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7833                  diag::err_typecheck_sclass_func);
7834     D.getMutableDeclSpec().ClearStorageClassSpecs();
7835     D.setInvalidType();
7836     break;
7837   case DeclSpec::SCS_unspecified: break;
7838   case DeclSpec::SCS_extern:
7839     if (D.getDeclSpec().isExternInLinkageSpec())
7840       return SC_None;
7841     return SC_Extern;
7842   case DeclSpec::SCS_static: {
7843     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7844       // C99 6.7.1p5:
7845       //   The declaration of an identifier for a function that has
7846       //   block scope shall have no explicit storage-class specifier
7847       //   other than extern
7848       // See also (C++ [dcl.stc]p4).
7849       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7850                    diag::err_static_block_func);
7851       break;
7852     } else
7853       return SC_Static;
7854   }
7855   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7856   }
7857 
7858   // No explicit storage class has already been returned
7859   return SC_None;
7860 }
7861 
7862 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7863                                            DeclContext *DC, QualType &R,
7864                                            TypeSourceInfo *TInfo,
7865                                            StorageClass SC,
7866                                            bool &IsVirtualOkay) {
7867   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7868   DeclarationName Name = NameInfo.getName();
7869 
7870   FunctionDecl *NewFD = nullptr;
7871   bool isInline = D.getDeclSpec().isInlineSpecified();
7872 
7873   if (!SemaRef.getLangOpts().CPlusPlus) {
7874     // Determine whether the function was written with a
7875     // prototype. This true when:
7876     //   - there is a prototype in the declarator, or
7877     //   - the type R of the function is some kind of typedef or other non-
7878     //     attributed reference to a type name (which eventually refers to a
7879     //     function type).
7880     bool HasPrototype =
7881       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7882       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7883 
7884     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7885                                  D.getLocStart(), NameInfo, R,
7886                                  TInfo, SC, isInline,
7887                                  HasPrototype, false);
7888     if (D.isInvalidType())
7889       NewFD->setInvalidDecl();
7890 
7891     return NewFD;
7892   }
7893 
7894   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7895   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7896 
7897   // Check that the return type is not an abstract class type.
7898   // For record types, this is done by the AbstractClassUsageDiagnoser once
7899   // the class has been completely parsed.
7900   if (!DC->isRecord() &&
7901       SemaRef.RequireNonAbstractType(
7902           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7903           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7904     D.setInvalidType();
7905 
7906   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7907     // This is a C++ constructor declaration.
7908     assert(DC->isRecord() &&
7909            "Constructors can only be declared in a member context");
7910 
7911     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7912     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7913                                       D.getLocStart(), NameInfo,
7914                                       R, TInfo, isExplicit, isInline,
7915                                       /*isImplicitlyDeclared=*/false,
7916                                       isConstexpr);
7917 
7918   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7919     // This is a C++ destructor declaration.
7920     if (DC->isRecord()) {
7921       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7922       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7923       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7924                                         SemaRef.Context, Record,
7925                                         D.getLocStart(),
7926                                         NameInfo, R, TInfo, isInline,
7927                                         /*isImplicitlyDeclared=*/false);
7928 
7929       // If the class is complete, then we now create the implicit exception
7930       // specification. If the class is incomplete or dependent, we can't do
7931       // it yet.
7932       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7933           Record->getDefinition() && !Record->isBeingDefined() &&
7934           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7935         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7936       }
7937 
7938       IsVirtualOkay = true;
7939       return NewDD;
7940 
7941     } else {
7942       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7943       D.setInvalidType();
7944 
7945       // Create a FunctionDecl to satisfy the function definition parsing
7946       // code path.
7947       return FunctionDecl::Create(SemaRef.Context, DC,
7948                                   D.getLocStart(),
7949                                   D.getIdentifierLoc(), Name, R, TInfo,
7950                                   SC, isInline,
7951                                   /*hasPrototype=*/true, isConstexpr);
7952     }
7953 
7954   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7955     if (!DC->isRecord()) {
7956       SemaRef.Diag(D.getIdentifierLoc(),
7957            diag::err_conv_function_not_member);
7958       return nullptr;
7959     }
7960 
7961     SemaRef.CheckConversionDeclarator(D, R, SC);
7962     IsVirtualOkay = true;
7963     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7964                                      D.getLocStart(), NameInfo,
7965                                      R, TInfo, isInline, isExplicit,
7966                                      isConstexpr, SourceLocation());
7967 
7968   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7969     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7970 
7971     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
7972                                          isExplicit, NameInfo, R, TInfo,
7973                                          D.getLocEnd());
7974   } else if (DC->isRecord()) {
7975     // If the name of the function is the same as the name of the record,
7976     // then this must be an invalid constructor that has a return type.
7977     // (The parser checks for a return type and makes the declarator a
7978     // constructor if it has no return type).
7979     if (Name.getAsIdentifierInfo() &&
7980         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7981       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7982         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7983         << SourceRange(D.getIdentifierLoc());
7984       return nullptr;
7985     }
7986 
7987     // This is a C++ method declaration.
7988     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7989                                                cast<CXXRecordDecl>(DC),
7990                                                D.getLocStart(), NameInfo, R,
7991                                                TInfo, SC, isInline,
7992                                                isConstexpr, SourceLocation());
7993     IsVirtualOkay = !Ret->isStatic();
7994     return Ret;
7995   } else {
7996     bool isFriend =
7997         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7998     if (!isFriend && SemaRef.CurContext->isRecord())
7999       return nullptr;
8000 
8001     // Determine whether the function was written with a
8002     // prototype. This true when:
8003     //   - we're in C++ (where every function has a prototype),
8004     return FunctionDecl::Create(SemaRef.Context, DC,
8005                                 D.getLocStart(),
8006                                 NameInfo, R, TInfo, SC, isInline,
8007                                 true/*HasPrototype*/, isConstexpr);
8008   }
8009 }
8010 
8011 enum OpenCLParamType {
8012   ValidKernelParam,
8013   PtrPtrKernelParam,
8014   PtrKernelParam,
8015   InvalidAddrSpacePtrKernelParam,
8016   InvalidKernelParam,
8017   RecordKernelParam
8018 };
8019 
8020 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8021   if (PT->isPointerType()) {
8022     QualType PointeeType = PT->getPointeeType();
8023     if (PointeeType->isPointerType())
8024       return PtrPtrKernelParam;
8025     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8026         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8027         PointeeType.getAddressSpace() == LangAS::Default)
8028       return InvalidAddrSpacePtrKernelParam;
8029     return PtrKernelParam;
8030   }
8031 
8032   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
8033   // be used as builtin types.
8034 
8035   if (PT->isImageType())
8036     return PtrKernelParam;
8037 
8038   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8039     return InvalidKernelParam;
8040 
8041   // OpenCL extension spec v1.2 s9.5:
8042   // This extension adds support for half scalar and vector types as built-in
8043   // types that can be used for arithmetic operations, conversions etc.
8044   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8045     return InvalidKernelParam;
8046 
8047   if (PT->isRecordType())
8048     return RecordKernelParam;
8049 
8050   return ValidKernelParam;
8051 }
8052 
8053 static void checkIsValidOpenCLKernelParameter(
8054   Sema &S,
8055   Declarator &D,
8056   ParmVarDecl *Param,
8057   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8058   QualType PT = Param->getType();
8059 
8060   // Cache the valid types we encounter to avoid rechecking structs that are
8061   // used again
8062   if (ValidTypes.count(PT.getTypePtr()))
8063     return;
8064 
8065   switch (getOpenCLKernelParameterType(S, PT)) {
8066   case PtrPtrKernelParam:
8067     // OpenCL v1.2 s6.9.a:
8068     // A kernel function argument cannot be declared as a
8069     // pointer to a pointer type.
8070     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8071     D.setInvalidType();
8072     return;
8073 
8074   case InvalidAddrSpacePtrKernelParam:
8075     // OpenCL v1.0 s6.5:
8076     // __kernel function arguments declared to be a pointer of a type can point
8077     // to one of the following address spaces only : __global, __local or
8078     // __constant.
8079     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8080     D.setInvalidType();
8081     return;
8082 
8083     // OpenCL v1.2 s6.9.k:
8084     // Arguments to kernel functions in a program cannot be declared with the
8085     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8086     // uintptr_t or a struct and/or union that contain fields declared to be
8087     // one of these built-in scalar types.
8088 
8089   case InvalidKernelParam:
8090     // OpenCL v1.2 s6.8 n:
8091     // A kernel function argument cannot be declared
8092     // of event_t type.
8093     // Do not diagnose half type since it is diagnosed as invalid argument
8094     // type for any function elsewhere.
8095     if (!PT->isHalfType())
8096       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8097     D.setInvalidType();
8098     return;
8099 
8100   case PtrKernelParam:
8101   case ValidKernelParam:
8102     ValidTypes.insert(PT.getTypePtr());
8103     return;
8104 
8105   case RecordKernelParam:
8106     break;
8107   }
8108 
8109   // Track nested structs we will inspect
8110   SmallVector<const Decl *, 4> VisitStack;
8111 
8112   // Track where we are in the nested structs. Items will migrate from
8113   // VisitStack to HistoryStack as we do the DFS for bad field.
8114   SmallVector<const FieldDecl *, 4> HistoryStack;
8115   HistoryStack.push_back(nullptr);
8116 
8117   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
8118   VisitStack.push_back(PD);
8119 
8120   assert(VisitStack.back() && "First decl null?");
8121 
8122   do {
8123     const Decl *Next = VisitStack.pop_back_val();
8124     if (!Next) {
8125       assert(!HistoryStack.empty());
8126       // Found a marker, we have gone up a level
8127       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8128         ValidTypes.insert(Hist->getType().getTypePtr());
8129 
8130       continue;
8131     }
8132 
8133     // Adds everything except the original parameter declaration (which is not a
8134     // field itself) to the history stack.
8135     const RecordDecl *RD;
8136     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8137       HistoryStack.push_back(Field);
8138       RD = Field->getType()->castAs<RecordType>()->getDecl();
8139     } else {
8140       RD = cast<RecordDecl>(Next);
8141     }
8142 
8143     // Add a null marker so we know when we've gone back up a level
8144     VisitStack.push_back(nullptr);
8145 
8146     for (const auto *FD : RD->fields()) {
8147       QualType QT = FD->getType();
8148 
8149       if (ValidTypes.count(QT.getTypePtr()))
8150         continue;
8151 
8152       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8153       if (ParamType == ValidKernelParam)
8154         continue;
8155 
8156       if (ParamType == RecordKernelParam) {
8157         VisitStack.push_back(FD);
8158         continue;
8159       }
8160 
8161       // OpenCL v1.2 s6.9.p:
8162       // Arguments to kernel functions that are declared to be a struct or union
8163       // do not allow OpenCL objects to be passed as elements of the struct or
8164       // union.
8165       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8166           ParamType == InvalidAddrSpacePtrKernelParam) {
8167         S.Diag(Param->getLocation(),
8168                diag::err_record_with_pointers_kernel_param)
8169           << PT->isUnionType()
8170           << PT;
8171       } else {
8172         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8173       }
8174 
8175       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
8176         << PD->getDeclName();
8177 
8178       // We have an error, now let's go back up through history and show where
8179       // the offending field came from
8180       for (ArrayRef<const FieldDecl *>::const_iterator
8181                I = HistoryStack.begin() + 1,
8182                E = HistoryStack.end();
8183            I != E; ++I) {
8184         const FieldDecl *OuterField = *I;
8185         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8186           << OuterField->getType();
8187       }
8188 
8189       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8190         << QT->isPointerType()
8191         << QT;
8192       D.setInvalidType();
8193       return;
8194     }
8195   } while (!VisitStack.empty());
8196 }
8197 
8198 /// Find the DeclContext in which a tag is implicitly declared if we see an
8199 /// elaborated type specifier in the specified context, and lookup finds
8200 /// nothing.
8201 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8202   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8203     DC = DC->getParent();
8204   return DC;
8205 }
8206 
8207 /// Find the Scope in which a tag is implicitly declared if we see an
8208 /// elaborated type specifier in the specified context, and lookup finds
8209 /// nothing.
8210 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8211   while (S->isClassScope() ||
8212          (LangOpts.CPlusPlus &&
8213           S->isFunctionPrototypeScope()) ||
8214          ((S->getFlags() & Scope::DeclScope) == 0) ||
8215          (S->getEntity() && S->getEntity()->isTransparentContext()))
8216     S = S->getParent();
8217   return S;
8218 }
8219 
8220 NamedDecl*
8221 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8222                               TypeSourceInfo *TInfo, LookupResult &Previous,
8223                               MultiTemplateParamsArg TemplateParamLists,
8224                               bool &AddToScope) {
8225   QualType R = TInfo->getType();
8226 
8227   assert(R.getTypePtr()->isFunctionType());
8228 
8229   // TODO: consider using NameInfo for diagnostic.
8230   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8231   DeclarationName Name = NameInfo.getName();
8232   StorageClass SC = getFunctionStorageClass(*this, D);
8233 
8234   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8235     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8236          diag::err_invalid_thread)
8237       << DeclSpec::getSpecifierName(TSCS);
8238 
8239   if (D.isFirstDeclarationOfMember())
8240     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8241                            D.getIdentifierLoc());
8242 
8243   bool isFriend = false;
8244   FunctionTemplateDecl *FunctionTemplate = nullptr;
8245   bool isMemberSpecialization = false;
8246   bool isFunctionTemplateSpecialization = false;
8247 
8248   bool isDependentClassScopeExplicitSpecialization = false;
8249   bool HasExplicitTemplateArgs = false;
8250   TemplateArgumentListInfo TemplateArgs;
8251 
8252   bool isVirtualOkay = false;
8253 
8254   DeclContext *OriginalDC = DC;
8255   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8256 
8257   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8258                                               isVirtualOkay);
8259   if (!NewFD) return nullptr;
8260 
8261   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8262     NewFD->setTopLevelDeclInObjCContainer();
8263 
8264   // Set the lexical context. If this is a function-scope declaration, or has a
8265   // C++ scope specifier, or is the object of a friend declaration, the lexical
8266   // context will be different from the semantic context.
8267   NewFD->setLexicalDeclContext(CurContext);
8268 
8269   if (IsLocalExternDecl)
8270     NewFD->setLocalExternDecl();
8271 
8272   if (getLangOpts().CPlusPlus) {
8273     bool isInline = D.getDeclSpec().isInlineSpecified();
8274     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8275     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8276     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8277     isFriend = D.getDeclSpec().isFriendSpecified();
8278     if (isFriend && !isInline && D.isFunctionDefinition()) {
8279       // C++ [class.friend]p5
8280       //   A function can be defined in a friend declaration of a
8281       //   class . . . . Such a function is implicitly inline.
8282       NewFD->setImplicitlyInline();
8283     }
8284 
8285     // If this is a method defined in an __interface, and is not a constructor
8286     // or an overloaded operator, then set the pure flag (isVirtual will already
8287     // return true).
8288     if (const CXXRecordDecl *Parent =
8289           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8290       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8291         NewFD->setPure(true);
8292 
8293       // C++ [class.union]p2
8294       //   A union can have member functions, but not virtual functions.
8295       if (isVirtual && Parent->isUnion())
8296         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8297     }
8298 
8299     SetNestedNameSpecifier(NewFD, D);
8300     isMemberSpecialization = false;
8301     isFunctionTemplateSpecialization = false;
8302     if (D.isInvalidType())
8303       NewFD->setInvalidDecl();
8304 
8305     // Match up the template parameter lists with the scope specifier, then
8306     // determine whether we have a template or a template specialization.
8307     bool Invalid = false;
8308     if (TemplateParameterList *TemplateParams =
8309             MatchTemplateParametersToScopeSpecifier(
8310                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
8311                 D.getCXXScopeSpec(),
8312                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8313                     ? D.getName().TemplateId
8314                     : nullptr,
8315                 TemplateParamLists, isFriend, isMemberSpecialization,
8316                 Invalid)) {
8317       if (TemplateParams->size() > 0) {
8318         // This is a function template
8319 
8320         // Check that we can declare a template here.
8321         if (CheckTemplateDeclScope(S, TemplateParams))
8322           NewFD->setInvalidDecl();
8323 
8324         // A destructor cannot be a template.
8325         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8326           Diag(NewFD->getLocation(), diag::err_destructor_template);
8327           NewFD->setInvalidDecl();
8328         }
8329 
8330         // If we're adding a template to a dependent context, we may need to
8331         // rebuilding some of the types used within the template parameter list,
8332         // now that we know what the current instantiation is.
8333         if (DC->isDependentContext()) {
8334           ContextRAII SavedContext(*this, DC);
8335           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8336             Invalid = true;
8337         }
8338 
8339         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8340                                                         NewFD->getLocation(),
8341                                                         Name, TemplateParams,
8342                                                         NewFD);
8343         FunctionTemplate->setLexicalDeclContext(CurContext);
8344         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8345 
8346         // For source fidelity, store the other template param lists.
8347         if (TemplateParamLists.size() > 1) {
8348           NewFD->setTemplateParameterListsInfo(Context,
8349                                                TemplateParamLists.drop_back(1));
8350         }
8351       } else {
8352         // This is a function template specialization.
8353         isFunctionTemplateSpecialization = true;
8354         // For source fidelity, store all the template param lists.
8355         if (TemplateParamLists.size() > 0)
8356           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8357 
8358         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8359         if (isFriend) {
8360           // We want to remove the "template<>", found here.
8361           SourceRange RemoveRange = TemplateParams->getSourceRange();
8362 
8363           // If we remove the template<> and the name is not a
8364           // template-id, we're actually silently creating a problem:
8365           // the friend declaration will refer to an untemplated decl,
8366           // and clearly the user wants a template specialization.  So
8367           // we need to insert '<>' after the name.
8368           SourceLocation InsertLoc;
8369           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8370             InsertLoc = D.getName().getSourceRange().getEnd();
8371             InsertLoc = getLocForEndOfToken(InsertLoc);
8372           }
8373 
8374           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8375             << Name << RemoveRange
8376             << FixItHint::CreateRemoval(RemoveRange)
8377             << FixItHint::CreateInsertion(InsertLoc, "<>");
8378         }
8379       }
8380     }
8381     else {
8382       // All template param lists were matched against the scope specifier:
8383       // this is NOT (an explicit specialization of) a template.
8384       if (TemplateParamLists.size() > 0)
8385         // For source fidelity, store all the template param lists.
8386         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8387     }
8388 
8389     if (Invalid) {
8390       NewFD->setInvalidDecl();
8391       if (FunctionTemplate)
8392         FunctionTemplate->setInvalidDecl();
8393     }
8394 
8395     // C++ [dcl.fct.spec]p5:
8396     //   The virtual specifier shall only be used in declarations of
8397     //   nonstatic class member functions that appear within a
8398     //   member-specification of a class declaration; see 10.3.
8399     //
8400     if (isVirtual && !NewFD->isInvalidDecl()) {
8401       if (!isVirtualOkay) {
8402         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8403              diag::err_virtual_non_function);
8404       } else if (!CurContext->isRecord()) {
8405         // 'virtual' was specified outside of the class.
8406         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8407              diag::err_virtual_out_of_class)
8408           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8409       } else if (NewFD->getDescribedFunctionTemplate()) {
8410         // C++ [temp.mem]p3:
8411         //  A member function template shall not be virtual.
8412         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8413              diag::err_virtual_member_function_template)
8414           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8415       } else {
8416         // Okay: Add virtual to the method.
8417         NewFD->setVirtualAsWritten(true);
8418       }
8419 
8420       if (getLangOpts().CPlusPlus14 &&
8421           NewFD->getReturnType()->isUndeducedType())
8422         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8423     }
8424 
8425     if (getLangOpts().CPlusPlus14 &&
8426         (NewFD->isDependentContext() ||
8427          (isFriend && CurContext->isDependentContext())) &&
8428         NewFD->getReturnType()->isUndeducedType()) {
8429       // If the function template is referenced directly (for instance, as a
8430       // member of the current instantiation), pretend it has a dependent type.
8431       // This is not really justified by the standard, but is the only sane
8432       // thing to do.
8433       // FIXME: For a friend function, we have not marked the function as being
8434       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8435       const FunctionProtoType *FPT =
8436           NewFD->getType()->castAs<FunctionProtoType>();
8437       QualType Result =
8438           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8439       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8440                                              FPT->getExtProtoInfo()));
8441     }
8442 
8443     // C++ [dcl.fct.spec]p3:
8444     //  The inline specifier shall not appear on a block scope function
8445     //  declaration.
8446     if (isInline && !NewFD->isInvalidDecl()) {
8447       if (CurContext->isFunctionOrMethod()) {
8448         // 'inline' is not allowed on block scope function declaration.
8449         Diag(D.getDeclSpec().getInlineSpecLoc(),
8450              diag::err_inline_declaration_block_scope) << Name
8451           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8452       }
8453     }
8454 
8455     // C++ [dcl.fct.spec]p6:
8456     //  The explicit specifier shall be used only in the declaration of a
8457     //  constructor or conversion function within its class definition;
8458     //  see 12.3.1 and 12.3.2.
8459     if (isExplicit && !NewFD->isInvalidDecl() &&
8460         !isa<CXXDeductionGuideDecl>(NewFD)) {
8461       if (!CurContext->isRecord()) {
8462         // 'explicit' was specified outside of the class.
8463         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8464              diag::err_explicit_out_of_class)
8465           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8466       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8467                  !isa<CXXConversionDecl>(NewFD)) {
8468         // 'explicit' was specified on a function that wasn't a constructor
8469         // or conversion function.
8470         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8471              diag::err_explicit_non_ctor_or_conv_function)
8472           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8473       }
8474     }
8475 
8476     if (isConstexpr) {
8477       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8478       // are implicitly inline.
8479       NewFD->setImplicitlyInline();
8480 
8481       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8482       // be either constructors or to return a literal type. Therefore,
8483       // destructors cannot be declared constexpr.
8484       if (isa<CXXDestructorDecl>(NewFD))
8485         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8486     }
8487 
8488     // If __module_private__ was specified, mark the function accordingly.
8489     if (D.getDeclSpec().isModulePrivateSpecified()) {
8490       if (isFunctionTemplateSpecialization) {
8491         SourceLocation ModulePrivateLoc
8492           = D.getDeclSpec().getModulePrivateSpecLoc();
8493         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8494           << 0
8495           << FixItHint::CreateRemoval(ModulePrivateLoc);
8496       } else {
8497         NewFD->setModulePrivate();
8498         if (FunctionTemplate)
8499           FunctionTemplate->setModulePrivate();
8500       }
8501     }
8502 
8503     if (isFriend) {
8504       if (FunctionTemplate) {
8505         FunctionTemplate->setObjectOfFriendDecl();
8506         FunctionTemplate->setAccess(AS_public);
8507       }
8508       NewFD->setObjectOfFriendDecl();
8509       NewFD->setAccess(AS_public);
8510     }
8511 
8512     // If a function is defined as defaulted or deleted, mark it as such now.
8513     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8514     // definition kind to FDK_Definition.
8515     switch (D.getFunctionDefinitionKind()) {
8516       case FDK_Declaration:
8517       case FDK_Definition:
8518         break;
8519 
8520       case FDK_Defaulted:
8521         NewFD->setDefaulted();
8522         break;
8523 
8524       case FDK_Deleted:
8525         NewFD->setDeletedAsWritten();
8526         break;
8527     }
8528 
8529     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8530         D.isFunctionDefinition()) {
8531       // C++ [class.mfct]p2:
8532       //   A member function may be defined (8.4) in its class definition, in
8533       //   which case it is an inline member function (7.1.2)
8534       NewFD->setImplicitlyInline();
8535     }
8536 
8537     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8538         !CurContext->isRecord()) {
8539       // C++ [class.static]p1:
8540       //   A data or function member of a class may be declared static
8541       //   in a class definition, in which case it is a static member of
8542       //   the class.
8543 
8544       // Complain about the 'static' specifier if it's on an out-of-line
8545       // member function definition.
8546       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8547            diag::err_static_out_of_line)
8548         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8549     }
8550 
8551     // C++11 [except.spec]p15:
8552     //   A deallocation function with no exception-specification is treated
8553     //   as if it were specified with noexcept(true).
8554     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8555     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8556          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8557         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8558       NewFD->setType(Context.getFunctionType(
8559           FPT->getReturnType(), FPT->getParamTypes(),
8560           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8561   }
8562 
8563   // Filter out previous declarations that don't match the scope.
8564   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8565                        D.getCXXScopeSpec().isNotEmpty() ||
8566                        isMemberSpecialization ||
8567                        isFunctionTemplateSpecialization);
8568 
8569   // Handle GNU asm-label extension (encoded as an attribute).
8570   if (Expr *E = (Expr*) D.getAsmLabel()) {
8571     // The parser guarantees this is a string.
8572     StringLiteral *SE = cast<StringLiteral>(E);
8573     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8574                                                 SE->getString(), 0));
8575   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8576     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8577       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8578     if (I != ExtnameUndeclaredIdentifiers.end()) {
8579       if (isDeclExternC(NewFD)) {
8580         NewFD->addAttr(I->second);
8581         ExtnameUndeclaredIdentifiers.erase(I);
8582       } else
8583         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8584             << /*Variable*/0 << NewFD;
8585     }
8586   }
8587 
8588   // Copy the parameter declarations from the declarator D to the function
8589   // declaration NewFD, if they are available.  First scavenge them into Params.
8590   SmallVector<ParmVarDecl*, 16> Params;
8591   unsigned FTIIdx;
8592   if (D.isFunctionDeclarator(FTIIdx)) {
8593     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8594 
8595     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8596     // function that takes no arguments, not a function that takes a
8597     // single void argument.
8598     // We let through "const void" here because Sema::GetTypeForDeclarator
8599     // already checks for that case.
8600     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8601       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8602         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8603         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8604         Param->setDeclContext(NewFD);
8605         Params.push_back(Param);
8606 
8607         if (Param->isInvalidDecl())
8608           NewFD->setInvalidDecl();
8609       }
8610     }
8611 
8612     if (!getLangOpts().CPlusPlus) {
8613       // In C, find all the tag declarations from the prototype and move them
8614       // into the function DeclContext. Remove them from the surrounding tag
8615       // injection context of the function, which is typically but not always
8616       // the TU.
8617       DeclContext *PrototypeTagContext =
8618           getTagInjectionContext(NewFD->getLexicalDeclContext());
8619       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8620         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8621 
8622         // We don't want to reparent enumerators. Look at their parent enum
8623         // instead.
8624         if (!TD) {
8625           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8626             TD = cast<EnumDecl>(ECD->getDeclContext());
8627         }
8628         if (!TD)
8629           continue;
8630         DeclContext *TagDC = TD->getLexicalDeclContext();
8631         if (!TagDC->containsDecl(TD))
8632           continue;
8633         TagDC->removeDecl(TD);
8634         TD->setDeclContext(NewFD);
8635         NewFD->addDecl(TD);
8636 
8637         // Preserve the lexical DeclContext if it is not the surrounding tag
8638         // injection context of the FD. In this example, the semantic context of
8639         // E will be f and the lexical context will be S, while both the
8640         // semantic and lexical contexts of S will be f:
8641         //   void f(struct S { enum E { a } f; } s);
8642         if (TagDC != PrototypeTagContext)
8643           TD->setLexicalDeclContext(TagDC);
8644       }
8645     }
8646   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8647     // When we're declaring a function with a typedef, typeof, etc as in the
8648     // following example, we'll need to synthesize (unnamed)
8649     // parameters for use in the declaration.
8650     //
8651     // @code
8652     // typedef void fn(int);
8653     // fn f;
8654     // @endcode
8655 
8656     // Synthesize a parameter for each argument type.
8657     for (const auto &AI : FT->param_types()) {
8658       ParmVarDecl *Param =
8659           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8660       Param->setScopeInfo(0, Params.size());
8661       Params.push_back(Param);
8662     }
8663   } else {
8664     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8665            "Should not need args for typedef of non-prototype fn");
8666   }
8667 
8668   // Finally, we know we have the right number of parameters, install them.
8669   NewFD->setParams(Params);
8670 
8671   if (D.getDeclSpec().isNoreturnSpecified())
8672     NewFD->addAttr(
8673         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8674                                        Context, 0));
8675 
8676   // Functions returning a variably modified type violate C99 6.7.5.2p2
8677   // because all functions have linkage.
8678   if (!NewFD->isInvalidDecl() &&
8679       NewFD->getReturnType()->isVariablyModifiedType()) {
8680     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8681     NewFD->setInvalidDecl();
8682   }
8683 
8684   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8685   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8686       !NewFD->hasAttr<SectionAttr>()) {
8687     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8688                                                  PragmaClangTextSection.SectionName,
8689                                                  PragmaClangTextSection.PragmaLocation));
8690   }
8691 
8692   // Apply an implicit SectionAttr if #pragma code_seg is active.
8693   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8694       !NewFD->hasAttr<SectionAttr>()) {
8695     NewFD->addAttr(
8696         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8697                                     CodeSegStack.CurrentValue->getString(),
8698                                     CodeSegStack.CurrentPragmaLocation));
8699     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8700                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8701                          ASTContext::PSF_Read,
8702                      NewFD))
8703       NewFD->dropAttr<SectionAttr>();
8704   }
8705 
8706   // Handle attributes.
8707   ProcessDeclAttributes(S, NewFD, D);
8708 
8709   if (getLangOpts().OpenCL) {
8710     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8711     // type declaration will generate a compilation error.
8712     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
8713     if (AddressSpace != LangAS::Default) {
8714       Diag(NewFD->getLocation(),
8715            diag::err_opencl_return_value_with_address_space);
8716       NewFD->setInvalidDecl();
8717     }
8718   }
8719 
8720   if (!getLangOpts().CPlusPlus) {
8721     // Perform semantic checking on the function declaration.
8722     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8723       CheckMain(NewFD, D.getDeclSpec());
8724 
8725     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8726       CheckMSVCRTEntryPoint(NewFD);
8727 
8728     if (!NewFD->isInvalidDecl())
8729       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8730                                                   isMemberSpecialization));
8731     else if (!Previous.empty())
8732       // Recover gracefully from an invalid redeclaration.
8733       D.setRedeclaration(true);
8734     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8735             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8736            "previous declaration set still overloaded");
8737 
8738     // Diagnose no-prototype function declarations with calling conventions that
8739     // don't support variadic calls. Only do this in C and do it after merging
8740     // possibly prototyped redeclarations.
8741     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8742     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8743       CallingConv CC = FT->getExtInfo().getCC();
8744       if (!supportsVariadicCall(CC)) {
8745         // Windows system headers sometimes accidentally use stdcall without
8746         // (void) parameters, so we relax this to a warning.
8747         int DiagID =
8748             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8749         Diag(NewFD->getLocation(), DiagID)
8750             << FunctionType::getNameForCallConv(CC);
8751       }
8752     }
8753   } else {
8754     // C++11 [replacement.functions]p3:
8755     //  The program's definitions shall not be specified as inline.
8756     //
8757     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8758     //
8759     // Suppress the diagnostic if the function is __attribute__((used)), since
8760     // that forces an external definition to be emitted.
8761     if (D.getDeclSpec().isInlineSpecified() &&
8762         NewFD->isReplaceableGlobalAllocationFunction() &&
8763         !NewFD->hasAttr<UsedAttr>())
8764       Diag(D.getDeclSpec().getInlineSpecLoc(),
8765            diag::ext_operator_new_delete_declared_inline)
8766         << NewFD->getDeclName();
8767 
8768     // If the declarator is a template-id, translate the parser's template
8769     // argument list into our AST format.
8770     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
8771       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8772       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8773       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8774       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8775                                          TemplateId->NumArgs);
8776       translateTemplateArguments(TemplateArgsPtr,
8777                                  TemplateArgs);
8778 
8779       HasExplicitTemplateArgs = true;
8780 
8781       if (NewFD->isInvalidDecl()) {
8782         HasExplicitTemplateArgs = false;
8783       } else if (FunctionTemplate) {
8784         // Function template with explicit template arguments.
8785         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8786           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8787 
8788         HasExplicitTemplateArgs = false;
8789       } else {
8790         assert((isFunctionTemplateSpecialization ||
8791                 D.getDeclSpec().isFriendSpecified()) &&
8792                "should have a 'template<>' for this decl");
8793         // "friend void foo<>(int);" is an implicit specialization decl.
8794         isFunctionTemplateSpecialization = true;
8795       }
8796     } else if (isFriend && isFunctionTemplateSpecialization) {
8797       // This combination is only possible in a recovery case;  the user
8798       // wrote something like:
8799       //   template <> friend void foo(int);
8800       // which we're recovering from as if the user had written:
8801       //   friend void foo<>(int);
8802       // Go ahead and fake up a template id.
8803       HasExplicitTemplateArgs = true;
8804       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8805       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8806     }
8807 
8808     // We do not add HD attributes to specializations here because
8809     // they may have different constexpr-ness compared to their
8810     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8811     // may end up with different effective targets. Instead, a
8812     // specialization inherits its target attributes from its template
8813     // in the CheckFunctionTemplateSpecialization() call below.
8814     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8815       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8816 
8817     // If it's a friend (and only if it's a friend), it's possible
8818     // that either the specialized function type or the specialized
8819     // template is dependent, and therefore matching will fail.  In
8820     // this case, don't check the specialization yet.
8821     bool InstantiationDependent = false;
8822     if (isFunctionTemplateSpecialization && isFriend &&
8823         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8824          TemplateSpecializationType::anyDependentTemplateArguments(
8825             TemplateArgs,
8826             InstantiationDependent))) {
8827       assert(HasExplicitTemplateArgs &&
8828              "friend function specialization without template args");
8829       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8830                                                        Previous))
8831         NewFD->setInvalidDecl();
8832     } else if (isFunctionTemplateSpecialization) {
8833       if (CurContext->isDependentContext() && CurContext->isRecord()
8834           && !isFriend) {
8835         isDependentClassScopeExplicitSpecialization = true;
8836       } else if (!NewFD->isInvalidDecl() &&
8837                  CheckFunctionTemplateSpecialization(
8838                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
8839                      Previous))
8840         NewFD->setInvalidDecl();
8841 
8842       // C++ [dcl.stc]p1:
8843       //   A storage-class-specifier shall not be specified in an explicit
8844       //   specialization (14.7.3)
8845       FunctionTemplateSpecializationInfo *Info =
8846           NewFD->getTemplateSpecializationInfo();
8847       if (Info && SC != SC_None) {
8848         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8849           Diag(NewFD->getLocation(),
8850                diag::err_explicit_specialization_inconsistent_storage_class)
8851             << SC
8852             << FixItHint::CreateRemoval(
8853                                       D.getDeclSpec().getStorageClassSpecLoc());
8854 
8855         else
8856           Diag(NewFD->getLocation(),
8857                diag::ext_explicit_specialization_storage_class)
8858             << FixItHint::CreateRemoval(
8859                                       D.getDeclSpec().getStorageClassSpecLoc());
8860       }
8861     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8862       if (CheckMemberSpecialization(NewFD, Previous))
8863           NewFD->setInvalidDecl();
8864     }
8865 
8866     // Perform semantic checking on the function declaration.
8867     if (!isDependentClassScopeExplicitSpecialization) {
8868       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8869         CheckMain(NewFD, D.getDeclSpec());
8870 
8871       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8872         CheckMSVCRTEntryPoint(NewFD);
8873 
8874       if (!NewFD->isInvalidDecl())
8875         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8876                                                     isMemberSpecialization));
8877       else if (!Previous.empty())
8878         // Recover gracefully from an invalid redeclaration.
8879         D.setRedeclaration(true);
8880     }
8881 
8882     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8883             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8884            "previous declaration set still overloaded");
8885 
8886     NamedDecl *PrincipalDecl = (FunctionTemplate
8887                                 ? cast<NamedDecl>(FunctionTemplate)
8888                                 : NewFD);
8889 
8890     if (isFriend && NewFD->getPreviousDecl()) {
8891       AccessSpecifier Access = AS_public;
8892       if (!NewFD->isInvalidDecl())
8893         Access = NewFD->getPreviousDecl()->getAccess();
8894 
8895       NewFD->setAccess(Access);
8896       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8897     }
8898 
8899     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8900         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8901       PrincipalDecl->setNonMemberOperator();
8902 
8903     // If we have a function template, check the template parameter
8904     // list. This will check and merge default template arguments.
8905     if (FunctionTemplate) {
8906       FunctionTemplateDecl *PrevTemplate =
8907                                      FunctionTemplate->getPreviousDecl();
8908       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8909                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8910                                     : nullptr,
8911                             D.getDeclSpec().isFriendSpecified()
8912                               ? (D.isFunctionDefinition()
8913                                    ? TPC_FriendFunctionTemplateDefinition
8914                                    : TPC_FriendFunctionTemplate)
8915                               : (D.getCXXScopeSpec().isSet() &&
8916                                  DC && DC->isRecord() &&
8917                                  DC->isDependentContext())
8918                                   ? TPC_ClassTemplateMember
8919                                   : TPC_FunctionTemplate);
8920     }
8921 
8922     if (NewFD->isInvalidDecl()) {
8923       // Ignore all the rest of this.
8924     } else if (!D.isRedeclaration()) {
8925       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8926                                        AddToScope };
8927       // Fake up an access specifier if it's supposed to be a class member.
8928       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8929         NewFD->setAccess(AS_public);
8930 
8931       // Qualified decls generally require a previous declaration.
8932       if (D.getCXXScopeSpec().isSet()) {
8933         // ...with the major exception of templated-scope or
8934         // dependent-scope friend declarations.
8935 
8936         // TODO: we currently also suppress this check in dependent
8937         // contexts because (1) the parameter depth will be off when
8938         // matching friend templates and (2) we might actually be
8939         // selecting a friend based on a dependent factor.  But there
8940         // are situations where these conditions don't apply and we
8941         // can actually do this check immediately.
8942         if (isFriend &&
8943             (TemplateParamLists.size() ||
8944              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8945              CurContext->isDependentContext())) {
8946           // ignore these
8947         } else {
8948           // The user tried to provide an out-of-line definition for a
8949           // function that is a member of a class or namespace, but there
8950           // was no such member function declared (C++ [class.mfct]p2,
8951           // C++ [namespace.memdef]p2). For example:
8952           //
8953           // class X {
8954           //   void f() const;
8955           // };
8956           //
8957           // void X::f() { } // ill-formed
8958           //
8959           // Complain about this problem, and attempt to suggest close
8960           // matches (e.g., those that differ only in cv-qualifiers and
8961           // whether the parameter types are references).
8962 
8963           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8964                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8965             AddToScope = ExtraArgs.AddToScope;
8966             return Result;
8967           }
8968         }
8969 
8970         // Unqualified local friend declarations are required to resolve
8971         // to something.
8972       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8973         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8974                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8975           AddToScope = ExtraArgs.AddToScope;
8976           return Result;
8977         }
8978       }
8979     } else if (!D.isFunctionDefinition() &&
8980                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8981                !isFriend && !isFunctionTemplateSpecialization &&
8982                !isMemberSpecialization) {
8983       // An out-of-line member function declaration must also be a
8984       // definition (C++ [class.mfct]p2).
8985       // Note that this is not the case for explicit specializations of
8986       // function templates or member functions of class templates, per
8987       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8988       // extension for compatibility with old SWIG code which likes to
8989       // generate them.
8990       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8991         << D.getCXXScopeSpec().getRange();
8992     }
8993   }
8994 
8995   ProcessPragmaWeak(S, NewFD);
8996   checkAttributesAfterMerging(*this, *NewFD);
8997 
8998   AddKnownFunctionAttributes(NewFD);
8999 
9000   if (NewFD->hasAttr<OverloadableAttr>() &&
9001       !NewFD->getType()->getAs<FunctionProtoType>()) {
9002     Diag(NewFD->getLocation(),
9003          diag::err_attribute_overloadable_no_prototype)
9004       << NewFD;
9005 
9006     // Turn this into a variadic function with no parameters.
9007     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9008     FunctionProtoType::ExtProtoInfo EPI(
9009         Context.getDefaultCallingConvention(true, false));
9010     EPI.Variadic = true;
9011     EPI.ExtInfo = FT->getExtInfo();
9012 
9013     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9014     NewFD->setType(R);
9015   }
9016 
9017   // If there's a #pragma GCC visibility in scope, and this isn't a class
9018   // member, set the visibility of this function.
9019   if (!DC->isRecord() && NewFD->isExternallyVisible())
9020     AddPushedVisibilityAttribute(NewFD);
9021 
9022   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9023   // marking the function.
9024   AddCFAuditedAttribute(NewFD);
9025 
9026   // If this is a function definition, check if we have to apply optnone due to
9027   // a pragma.
9028   if(D.isFunctionDefinition())
9029     AddRangeBasedOptnone(NewFD);
9030 
9031   // If this is the first declaration of an extern C variable, update
9032   // the map of such variables.
9033   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9034       isIncompleteDeclExternC(*this, NewFD))
9035     RegisterLocallyScopedExternCDecl(NewFD, S);
9036 
9037   // Set this FunctionDecl's range up to the right paren.
9038   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9039 
9040   if (D.isRedeclaration() && !Previous.empty()) {
9041     NamedDecl *Prev = Previous.getRepresentativeDecl();
9042     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9043                                    isMemberSpecialization ||
9044                                        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 actual 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, NewFD->getLocation(),
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 (NewFD->isCXXClassMember()) {
9646         NewFD->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 (NewFD->isCXXClassMember())
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       setFunctionHasBranchProtectedScope();
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 (if we're in one) for further checking even if the
11183         // looser rules of C++11 do not require such checks, so that we can
11184         // diagnose incompatibilities with C++98.
11185         if (!CXXRecord->isPOD())
11186           setFunctionHasBranchProtectedScope();
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       setFunctionHasBranchProtectedScope();
11323       break;
11324     }
11325   }
11326 
11327   if (var->hasLocalStorage() &&
11328       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
11329     setFunctionHasBranchProtectedScope();
11330 
11331   // Warn about externally-visible variables being defined without a
11332   // prior declaration.  We only want to do this for global
11333   // declarations, but we also specifically need to avoid doing it for
11334   // class members because the linkage of an anonymous class can
11335   // change if it's later given a typedef name.
11336   if (var->isThisDeclarationADefinition() &&
11337       var->getDeclContext()->getRedeclContext()->isFileContext() &&
11338       var->isExternallyVisible() && var->hasLinkage() &&
11339       !var->isInline() && !var->getDescribedVarTemplate() &&
11340       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
11341       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11342                                   var->getLocation())) {
11343     // Find a previous declaration that's not a definition.
11344     VarDecl *prev = var->getPreviousDecl();
11345     while (prev && prev->isThisDeclarationADefinition())
11346       prev = prev->getPreviousDecl();
11347 
11348     if (!prev)
11349       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11350   }
11351 
11352   // Cache the result of checking for constant initialization.
11353   Optional<bool> CacheHasConstInit;
11354   const Expr *CacheCulprit;
11355   auto checkConstInit = [&]() mutable {
11356     if (!CacheHasConstInit)
11357       CacheHasConstInit = var->getInit()->isConstantInitializer(
11358             Context, var->getType()->isReferenceType(), &CacheCulprit);
11359     return *CacheHasConstInit;
11360   };
11361 
11362   if (var->getTLSKind() == VarDecl::TLS_Static) {
11363     if (var->getType().isDestructedType()) {
11364       // GNU C++98 edits for __thread, [basic.start.term]p3:
11365       //   The type of an object with thread storage duration shall not
11366       //   have a non-trivial destructor.
11367       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11368       if (getLangOpts().CPlusPlus11)
11369         Diag(var->getLocation(), diag::note_use_thread_local);
11370     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11371       if (!checkConstInit()) {
11372         // GNU C++98 edits for __thread, [basic.start.init]p4:
11373         //   An object of thread storage duration shall not require dynamic
11374         //   initialization.
11375         // FIXME: Need strict checking here.
11376         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11377           << CacheCulprit->getSourceRange();
11378         if (getLangOpts().CPlusPlus11)
11379           Diag(var->getLocation(), diag::note_use_thread_local);
11380       }
11381     }
11382   }
11383 
11384   // Apply section attributes and pragmas to global variables.
11385   bool GlobalStorage = var->hasGlobalStorage();
11386   if (GlobalStorage && var->isThisDeclarationADefinition() &&
11387       !inTemplateInstantiation()) {
11388     PragmaStack<StringLiteral *> *Stack = nullptr;
11389     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11390     if (var->getType().isConstQualified())
11391       Stack = &ConstSegStack;
11392     else if (!var->getInit()) {
11393       Stack = &BSSSegStack;
11394       SectionFlags |= ASTContext::PSF_Write;
11395     } else {
11396       Stack = &DataSegStack;
11397       SectionFlags |= ASTContext::PSF_Write;
11398     }
11399     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11400       var->addAttr(SectionAttr::CreateImplicit(
11401           Context, SectionAttr::Declspec_allocate,
11402           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11403     }
11404     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11405       if (UnifySection(SA->getName(), SectionFlags, var))
11406         var->dropAttr<SectionAttr>();
11407 
11408     // Apply the init_seg attribute if this has an initializer.  If the
11409     // initializer turns out to not be dynamic, we'll end up ignoring this
11410     // attribute.
11411     if (CurInitSeg && var->getInit())
11412       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11413                                                CurInitSegLoc));
11414   }
11415 
11416   // All the following checks are C++ only.
11417   if (!getLangOpts().CPlusPlus) {
11418       // If this variable must be emitted, add it as an initializer for the
11419       // current module.
11420      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11421        Context.addModuleInitializer(ModuleScopes.back().Module, var);
11422      return;
11423   }
11424 
11425   if (auto *DD = dyn_cast<DecompositionDecl>(var))
11426     CheckCompleteDecompositionDeclaration(DD);
11427 
11428   QualType type = var->getType();
11429   if (type->isDependentType()) return;
11430 
11431   // __block variables might require us to capture a copy-initializer.
11432   if (var->hasAttr<BlocksAttr>()) {
11433     // It's currently invalid to ever have a __block variable with an
11434     // array type; should we diagnose that here?
11435 
11436     // Regardless, we don't want to ignore array nesting when
11437     // constructing this copy.
11438     if (type->isStructureOrClassType()) {
11439       EnterExpressionEvaluationContext scope(
11440           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
11441       SourceLocation poi = var->getLocation();
11442       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
11443       ExprResult result
11444         = PerformMoveOrCopyInitialization(
11445             InitializedEntity::InitializeBlock(poi, type, false),
11446             var, var->getType(), varRef, /*AllowNRVO=*/true);
11447       if (!result.isInvalid()) {
11448         result = MaybeCreateExprWithCleanups(result);
11449         Expr *init = result.getAs<Expr>();
11450         Context.setBlockVarCopyInits(var, init);
11451       }
11452     }
11453   }
11454 
11455   Expr *Init = var->getInit();
11456   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11457   QualType baseType = Context.getBaseElementType(type);
11458 
11459   if (Init && !Init->isValueDependent()) {
11460     if (var->isConstexpr()) {
11461       SmallVector<PartialDiagnosticAt, 8> Notes;
11462       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11463         SourceLocation DiagLoc = var->getLocation();
11464         // If the note doesn't add any useful information other than a source
11465         // location, fold it into the primary diagnostic.
11466         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11467               diag::note_invalid_subexpr_in_const_expr) {
11468           DiagLoc = Notes[0].first;
11469           Notes.clear();
11470         }
11471         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11472           << var << Init->getSourceRange();
11473         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11474           Diag(Notes[I].first, Notes[I].second);
11475       }
11476     } else if (var->isUsableInConstantExpressions(Context)) {
11477       // Check whether the initializer of a const variable of integral or
11478       // enumeration type is an ICE now, since we can't tell whether it was
11479       // initialized by a constant expression if we check later.
11480       var->checkInitIsICE();
11481     }
11482 
11483     // Don't emit further diagnostics about constexpr globals since they
11484     // were just diagnosed.
11485     if (!var->isConstexpr() && GlobalStorage &&
11486             var->hasAttr<RequireConstantInitAttr>()) {
11487       // FIXME: Need strict checking in C++03 here.
11488       bool DiagErr = getLangOpts().CPlusPlus11
11489           ? !var->checkInitIsICE() : !checkConstInit();
11490       if (DiagErr) {
11491         auto attr = var->getAttr<RequireConstantInitAttr>();
11492         Diag(var->getLocation(), diag::err_require_constant_init_failed)
11493           << Init->getSourceRange();
11494         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11495           << attr->getRange();
11496         if (getLangOpts().CPlusPlus11) {
11497           APValue Value;
11498           SmallVector<PartialDiagnosticAt, 8> Notes;
11499           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11500           for (auto &it : Notes)
11501             Diag(it.first, it.second);
11502         } else {
11503           Diag(CacheCulprit->getExprLoc(),
11504                diag::note_invalid_subexpr_in_const_expr)
11505               << CacheCulprit->getSourceRange();
11506         }
11507       }
11508     }
11509     else if (!var->isConstexpr() && IsGlobal &&
11510              !getDiagnostics().isIgnored(diag::warn_global_constructor,
11511                                     var->getLocation())) {
11512       // Warn about globals which don't have a constant initializer.  Don't
11513       // warn about globals with a non-trivial destructor because we already
11514       // warned about them.
11515       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11516       if (!(RD && !RD->hasTrivialDestructor())) {
11517         if (!checkConstInit())
11518           Diag(var->getLocation(), diag::warn_global_constructor)
11519             << Init->getSourceRange();
11520       }
11521     }
11522   }
11523 
11524   // Require the destructor.
11525   if (const RecordType *recordType = baseType->getAs<RecordType>())
11526     FinalizeVarWithDestructor(var, recordType);
11527 
11528   // If this variable must be emitted, add it as an initializer for the current
11529   // module.
11530   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11531     Context.addModuleInitializer(ModuleScopes.back().Module, var);
11532 }
11533 
11534 /// \brief Determines if a variable's alignment is dependent.
11535 static bool hasDependentAlignment(VarDecl *VD) {
11536   if (VD->getType()->isDependentType())
11537     return true;
11538   for (auto *I : VD->specific_attrs<AlignedAttr>())
11539     if (I->isAlignmentDependent())
11540       return true;
11541   return false;
11542 }
11543 
11544 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
11545 /// any semantic actions necessary after any initializer has been attached.
11546 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
11547   // Note that we are no longer parsing the initializer for this declaration.
11548   ParsingInitForAutoVars.erase(ThisDecl);
11549 
11550   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
11551   if (!VD)
11552     return;
11553 
11554   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
11555   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
11556       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
11557     if (PragmaClangBSSSection.Valid)
11558       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
11559                                                             PragmaClangBSSSection.SectionName,
11560                                                             PragmaClangBSSSection.PragmaLocation));
11561     if (PragmaClangDataSection.Valid)
11562       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
11563                                                              PragmaClangDataSection.SectionName,
11564                                                              PragmaClangDataSection.PragmaLocation));
11565     if (PragmaClangRodataSection.Valid)
11566       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
11567                                                                PragmaClangRodataSection.SectionName,
11568                                                                PragmaClangRodataSection.PragmaLocation));
11569   }
11570 
11571   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
11572     for (auto *BD : DD->bindings()) {
11573       FinalizeDeclaration(BD);
11574     }
11575   }
11576 
11577   checkAttributesAfterMerging(*this, *VD);
11578 
11579   // Perform TLS alignment check here after attributes attached to the variable
11580   // which may affect the alignment have been processed. Only perform the check
11581   // if the target has a maximum TLS alignment (zero means no constraints).
11582   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
11583     // Protect the check so that it's not performed on dependent types and
11584     // dependent alignments (we can't determine the alignment in that case).
11585     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
11586         !VD->isInvalidDecl()) {
11587       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
11588       if (Context.getDeclAlign(VD) > MaxAlignChars) {
11589         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
11590           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
11591           << (unsigned)MaxAlignChars.getQuantity();
11592       }
11593     }
11594   }
11595 
11596   if (VD->isStaticLocal()) {
11597     if (FunctionDecl *FD =
11598             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
11599       // Static locals inherit dll attributes from their function.
11600       if (Attr *A = getDLLAttr(FD)) {
11601         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11602         NewAttr->setInherited(true);
11603         VD->addAttr(NewAttr);
11604       }
11605       // CUDA E.2.9.4: Within the body of a __device__ or __global__
11606       // function, only __shared__ variables may be declared with
11607       // static storage class.
11608       if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
11609           CUDADiagIfDeviceCode(VD->getLocation(),
11610                                diag::err_device_static_local_var)
11611               << CurrentCUDATarget())
11612         VD->setInvalidDecl();
11613     }
11614   }
11615 
11616   // Perform check for initializers of device-side global variables.
11617   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
11618   // 7.5). We must also apply the same checks to all __shared__
11619   // variables whether they are local or not. CUDA also allows
11620   // constant initializers for __constant__ and __device__ variables.
11621   if (getLangOpts().CUDA) {
11622     const Expr *Init = VD->getInit();
11623     if (Init && VD->hasGlobalStorage()) {
11624       if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
11625           VD->hasAttr<CUDASharedAttr>()) {
11626         assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
11627         bool AllowedInit = false;
11628         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
11629           AllowedInit =
11630               isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
11631         // We'll allow constant initializers even if it's a non-empty
11632         // constructor according to CUDA rules. This deviates from NVCC,
11633         // but allows us to handle things like constexpr constructors.
11634         if (!AllowedInit &&
11635             (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
11636           AllowedInit = VD->getInit()->isConstantInitializer(
11637               Context, VD->getType()->isReferenceType());
11638 
11639         // Also make sure that destructor, if there is one, is empty.
11640         if (AllowedInit)
11641           if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
11642             AllowedInit =
11643                 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
11644 
11645         if (!AllowedInit) {
11646           Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
11647                                       ? diag::err_shared_var_init
11648                                       : diag::err_dynamic_var_init)
11649               << Init->getSourceRange();
11650           VD->setInvalidDecl();
11651         }
11652       } else {
11653         // This is a host-side global variable.  Check that the initializer is
11654         // callable from the host side.
11655         const FunctionDecl *InitFn = nullptr;
11656         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
11657           InitFn = CE->getConstructor();
11658         } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
11659           InitFn = CE->getDirectCallee();
11660         }
11661         if (InitFn) {
11662           CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
11663           if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
11664             Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
11665                 << InitFnTarget << InitFn;
11666             Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
11667             VD->setInvalidDecl();
11668           }
11669         }
11670       }
11671     }
11672   }
11673 
11674   // Grab the dllimport or dllexport attribute off of the VarDecl.
11675   const InheritableAttr *DLLAttr = getDLLAttr(VD);
11676 
11677   // Imported static data members cannot be defined out-of-line.
11678   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
11679     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
11680         VD->isThisDeclarationADefinition()) {
11681       // We allow definitions of dllimport class template static data members
11682       // with a warning.
11683       CXXRecordDecl *Context =
11684         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
11685       bool IsClassTemplateMember =
11686           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
11687           Context->getDescribedClassTemplate();
11688 
11689       Diag(VD->getLocation(),
11690            IsClassTemplateMember
11691                ? diag::warn_attribute_dllimport_static_field_definition
11692                : diag::err_attribute_dllimport_static_field_definition);
11693       Diag(IA->getLocation(), diag::note_attribute);
11694       if (!IsClassTemplateMember)
11695         VD->setInvalidDecl();
11696     }
11697   }
11698 
11699   // dllimport/dllexport variables cannot be thread local, their TLS index
11700   // isn't exported with the variable.
11701   if (DLLAttr && VD->getTLSKind()) {
11702     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11703     if (F && getDLLAttr(F)) {
11704       assert(VD->isStaticLocal());
11705       // But if this is a static local in a dlimport/dllexport function, the
11706       // function will never be inlined, which means the var would never be
11707       // imported, so having it marked import/export is safe.
11708     } else {
11709       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
11710                                                                     << DLLAttr;
11711       VD->setInvalidDecl();
11712     }
11713   }
11714 
11715   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
11716     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
11717       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11718       VD->dropAttr<UsedAttr>();
11719     }
11720   }
11721 
11722   const DeclContext *DC = VD->getDeclContext();
11723   // If there's a #pragma GCC visibility in scope, and this isn't a class
11724   // member, set the visibility of this variable.
11725   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11726     AddPushedVisibilityAttribute(VD);
11727 
11728   // FIXME: Warn on unused var template partial specializations.
11729   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
11730     MarkUnusedFileScopedDecl(VD);
11731 
11732   // Now we have parsed the initializer and can update the table of magic
11733   // tag values.
11734   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11735       !VD->getType()->isIntegralOrEnumerationType())
11736     return;
11737 
11738   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11739     const Expr *MagicValueExpr = VD->getInit();
11740     if (!MagicValueExpr) {
11741       continue;
11742     }
11743     llvm::APSInt MagicValueInt;
11744     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11745       Diag(I->getRange().getBegin(),
11746            diag::err_type_tag_for_datatype_not_ice)
11747         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11748       continue;
11749     }
11750     if (MagicValueInt.getActiveBits() > 64) {
11751       Diag(I->getRange().getBegin(),
11752            diag::err_type_tag_for_datatype_too_large)
11753         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11754       continue;
11755     }
11756     uint64_t MagicValue = MagicValueInt.getZExtValue();
11757     RegisterTypeTagForDatatype(I->getArgumentKind(),
11758                                MagicValue,
11759                                I->getMatchingCType(),
11760                                I->getLayoutCompatible(),
11761                                I->getMustBeNull());
11762   }
11763 }
11764 
11765 static bool hasDeducedAuto(DeclaratorDecl *DD) {
11766   auto *VD = dyn_cast<VarDecl>(DD);
11767   return VD && !VD->getType()->hasAutoForTrailingReturnType();
11768 }
11769 
11770 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
11771                                                    ArrayRef<Decl *> Group) {
11772   SmallVector<Decl*, 8> Decls;
11773 
11774   if (DS.isTypeSpecOwned())
11775     Decls.push_back(DS.getRepAsDecl());
11776 
11777   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11778   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11779   bool DiagnosedMultipleDecomps = false;
11780   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
11781   bool DiagnosedNonDeducedAuto = false;
11782 
11783   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11784     if (Decl *D = Group[i]) {
11785       // For declarators, there are some additional syntactic-ish checks we need
11786       // to perform.
11787       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11788         if (!FirstDeclaratorInGroup)
11789           FirstDeclaratorInGroup = DD;
11790         if (!FirstDecompDeclaratorInGroup)
11791           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
11792         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
11793             !hasDeducedAuto(DD))
11794           FirstNonDeducedAutoInGroup = DD;
11795 
11796         if (FirstDeclaratorInGroup != DD) {
11797           // A decomposition declaration cannot be combined with any other
11798           // declaration in the same group.
11799           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
11800             Diag(FirstDecompDeclaratorInGroup->getLocation(),
11801                  diag::err_decomp_decl_not_alone)
11802                 << FirstDeclaratorInGroup->getSourceRange()
11803                 << DD->getSourceRange();
11804             DiagnosedMultipleDecomps = true;
11805           }
11806 
11807           // A declarator that uses 'auto' in any way other than to declare a
11808           // variable with a deduced type cannot be combined with any other
11809           // declarator in the same group.
11810           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
11811             Diag(FirstNonDeducedAutoInGroup->getLocation(),
11812                  diag::err_auto_non_deduced_not_alone)
11813                 << FirstNonDeducedAutoInGroup->getType()
11814                        ->hasAutoForTrailingReturnType()
11815                 << FirstDeclaratorInGroup->getSourceRange()
11816                 << DD->getSourceRange();
11817             DiagnosedNonDeducedAuto = true;
11818           }
11819         }
11820       }
11821 
11822       Decls.push_back(D);
11823     }
11824   }
11825 
11826   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11827     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11828       handleTagNumbering(Tag, S);
11829       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11830           getLangOpts().CPlusPlus)
11831         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11832     }
11833   }
11834 
11835   return BuildDeclaratorGroup(Decls);
11836 }
11837 
11838 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11839 /// group, performing any necessary semantic checking.
11840 Sema::DeclGroupPtrTy
11841 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
11842   // C++14 [dcl.spec.auto]p7: (DR1347)
11843   //   If the type that replaces the placeholder type is not the same in each
11844   //   deduction, the program is ill-formed.
11845   if (Group.size() > 1) {
11846     QualType Deduced;
11847     VarDecl *DeducedDecl = nullptr;
11848     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11849       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
11850       if (!D || D->isInvalidDecl())
11851         break;
11852       DeducedType *DT = D->getType()->getContainedDeducedType();
11853       if (!DT || DT->getDeducedType().isNull())
11854         continue;
11855       if (Deduced.isNull()) {
11856         Deduced = DT->getDeducedType();
11857         DeducedDecl = D;
11858       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
11859         auto *AT = dyn_cast<AutoType>(DT);
11860         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11861              diag::err_auto_different_deductions)
11862           << (AT ? (unsigned)AT->getKeyword() : 3)
11863           << Deduced << DeducedDecl->getDeclName()
11864           << DT->getDeducedType() << D->getDeclName()
11865           << DeducedDecl->getInit()->getSourceRange()
11866           << D->getInit()->getSourceRange();
11867         D->setInvalidDecl();
11868         break;
11869       }
11870     }
11871   }
11872 
11873   ActOnDocumentableDecls(Group);
11874 
11875   return DeclGroupPtrTy::make(
11876       DeclGroupRef::Create(Context, Group.data(), Group.size()));
11877 }
11878 
11879 void Sema::ActOnDocumentableDecl(Decl *D) {
11880   ActOnDocumentableDecls(D);
11881 }
11882 
11883 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11884   // Don't parse the comment if Doxygen diagnostics are ignored.
11885   if (Group.empty() || !Group[0])
11886     return;
11887 
11888   if (Diags.isIgnored(diag::warn_doc_param_not_found,
11889                       Group[0]->getLocation()) &&
11890       Diags.isIgnored(diag::warn_unknown_comment_command_name,
11891                       Group[0]->getLocation()))
11892     return;
11893 
11894   if (Group.size() >= 2) {
11895     // This is a decl group.  Normally it will contain only declarations
11896     // produced from declarator list.  But in case we have any definitions or
11897     // additional declaration references:
11898     //   'typedef struct S {} S;'
11899     //   'typedef struct S *S;'
11900     //   'struct S *pS;'
11901     // FinalizeDeclaratorGroup adds these as separate declarations.
11902     Decl *MaybeTagDecl = Group[0];
11903     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11904       Group = Group.slice(1);
11905     }
11906   }
11907 
11908   // See if there are any new comments that are not attached to a decl.
11909   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11910   if (!Comments.empty() &&
11911       !Comments.back()->isAttached()) {
11912     // There is at least one comment that not attached to a decl.
11913     // Maybe it should be attached to one of these decls?
11914     //
11915     // Note that this way we pick up not only comments that precede the
11916     // declaration, but also comments that *follow* the declaration -- thanks to
11917     // the lookahead in the lexer: we've consumed the semicolon and looked
11918     // ahead through comments.
11919     for (unsigned i = 0, e = Group.size(); i != e; ++i)
11920       Context.getCommentForDecl(Group[i], &PP);
11921   }
11922 }
11923 
11924 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11925 /// to introduce parameters into function prototype scope.
11926 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11927   const DeclSpec &DS = D.getDeclSpec();
11928 
11929   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11930 
11931   // C++03 [dcl.stc]p2 also permits 'auto'.
11932   StorageClass SC = SC_None;
11933   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11934     SC = SC_Register;
11935     // In C++11, the 'register' storage class specifier is deprecated.
11936     // In C++17, it is not allowed, but we tolerate it as an extension.
11937     if (getLangOpts().CPlusPlus11) {
11938       Diag(DS.getStorageClassSpecLoc(),
11939            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
11940                                      : diag::warn_deprecated_register)
11941         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11942     }
11943   } else if (getLangOpts().CPlusPlus &&
11944              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11945     SC = SC_Auto;
11946   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11947     Diag(DS.getStorageClassSpecLoc(),
11948          diag::err_invalid_storage_class_in_func_decl);
11949     D.getMutableDeclSpec().ClearStorageClassSpecs();
11950   }
11951 
11952   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11953     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11954       << DeclSpec::getSpecifierName(TSCS);
11955   if (DS.isInlineSpecified())
11956     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11957         << getLangOpts().CPlusPlus17;
11958   if (DS.isConstexprSpecified())
11959     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11960       << 0;
11961 
11962   DiagnoseFunctionSpecifiers(DS);
11963 
11964   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11965   QualType parmDeclType = TInfo->getType();
11966 
11967   if (getLangOpts().CPlusPlus) {
11968     // Check that there are no default arguments inside the type of this
11969     // parameter.
11970     CheckExtraCXXDefaultArguments(D);
11971 
11972     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11973     if (D.getCXXScopeSpec().isSet()) {
11974       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11975         << D.getCXXScopeSpec().getRange();
11976       D.getCXXScopeSpec().clear();
11977     }
11978   }
11979 
11980   // Ensure we have a valid name
11981   IdentifierInfo *II = nullptr;
11982   if (D.hasName()) {
11983     II = D.getIdentifier();
11984     if (!II) {
11985       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11986         << GetNameForDeclarator(D).getName();
11987       D.setInvalidType(true);
11988     }
11989   }
11990 
11991   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11992   if (II) {
11993     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
11994                    ForVisibleRedeclaration);
11995     LookupName(R, S);
11996     if (R.isSingleResult()) {
11997       NamedDecl *PrevDecl = R.getFoundDecl();
11998       if (PrevDecl->isTemplateParameter()) {
11999         // Maybe we will complain about the shadowed template parameter.
12000         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12001         // Just pretend that we didn't see the previous declaration.
12002         PrevDecl = nullptr;
12003       } else if (S->isDeclScope(PrevDecl)) {
12004         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
12005         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12006 
12007         // Recover by removing the name
12008         II = nullptr;
12009         D.SetIdentifier(nullptr, D.getIdentifierLoc());
12010         D.setInvalidType(true);
12011       }
12012     }
12013   }
12014 
12015   // Temporarily put parameter variables in the translation unit, not
12016   // the enclosing context.  This prevents them from accidentally
12017   // looking like class members in C++.
12018   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
12019                                     D.getLocStart(),
12020                                     D.getIdentifierLoc(), II,
12021                                     parmDeclType, TInfo,
12022                                     SC);
12023 
12024   if (D.isInvalidType())
12025     New->setInvalidDecl();
12026 
12027   assert(S->isFunctionPrototypeScope());
12028   assert(S->getFunctionPrototypeDepth() >= 1);
12029   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
12030                     S->getNextFunctionPrototypeIndex());
12031 
12032   // Add the parameter declaration into this scope.
12033   S->AddDecl(New);
12034   if (II)
12035     IdResolver.AddDecl(New);
12036 
12037   ProcessDeclAttributes(S, New, D);
12038 
12039   if (D.getDeclSpec().isModulePrivateSpecified())
12040     Diag(New->getLocation(), diag::err_module_private_local)
12041       << 1 << New->getDeclName()
12042       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12043       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12044 
12045   if (New->hasAttr<BlocksAttr>()) {
12046     Diag(New->getLocation(), diag::err_block_on_nonlocal);
12047   }
12048   return New;
12049 }
12050 
12051 /// \brief Synthesizes a variable for a parameter arising from a
12052 /// typedef.
12053 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
12054                                               SourceLocation Loc,
12055                                               QualType T) {
12056   /* FIXME: setting StartLoc == Loc.
12057      Would it be worth to modify callers so as to provide proper source
12058      location for the unnamed parameters, embedding the parameter's type? */
12059   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
12060                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
12061                                            SC_None, nullptr);
12062   Param->setImplicit();
12063   return Param;
12064 }
12065 
12066 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
12067   // Don't diagnose unused-parameter errors in template instantiations; we
12068   // will already have done so in the template itself.
12069   if (inTemplateInstantiation())
12070     return;
12071 
12072   for (const ParmVarDecl *Parameter : Parameters) {
12073     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
12074         !Parameter->hasAttr<UnusedAttr>()) {
12075       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
12076         << Parameter->getDeclName();
12077     }
12078   }
12079 }
12080 
12081 void Sema::DiagnoseSizeOfParametersAndReturnValue(
12082     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
12083   if (LangOpts.NumLargeByValueCopy == 0) // No check.
12084     return;
12085 
12086   // Warn if the return value is pass-by-value and larger than the specified
12087   // threshold.
12088   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
12089     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
12090     if (Size > LangOpts.NumLargeByValueCopy)
12091       Diag(D->getLocation(), diag::warn_return_value_size)
12092           << D->getDeclName() << Size;
12093   }
12094 
12095   // Warn if any parameter is pass-by-value and larger than the specified
12096   // threshold.
12097   for (const ParmVarDecl *Parameter : Parameters) {
12098     QualType T = Parameter->getType();
12099     if (T->isDependentType() || !T.isPODType(Context))
12100       continue;
12101     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
12102     if (Size > LangOpts.NumLargeByValueCopy)
12103       Diag(Parameter->getLocation(), diag::warn_parameter_size)
12104           << Parameter->getDeclName() << Size;
12105   }
12106 }
12107 
12108 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
12109                                   SourceLocation NameLoc, IdentifierInfo *Name,
12110                                   QualType T, TypeSourceInfo *TSInfo,
12111                                   StorageClass SC) {
12112   // In ARC, infer a lifetime qualifier for appropriate parameter types.
12113   if (getLangOpts().ObjCAutoRefCount &&
12114       T.getObjCLifetime() == Qualifiers::OCL_None &&
12115       T->isObjCLifetimeType()) {
12116 
12117     Qualifiers::ObjCLifetime lifetime;
12118 
12119     // Special cases for arrays:
12120     //   - if it's const, use __unsafe_unretained
12121     //   - otherwise, it's an error
12122     if (T->isArrayType()) {
12123       if (!T.isConstQualified()) {
12124         DelayedDiagnostics.add(
12125             sema::DelayedDiagnostic::makeForbiddenType(
12126             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
12127       }
12128       lifetime = Qualifiers::OCL_ExplicitNone;
12129     } else {
12130       lifetime = T->getObjCARCImplicitLifetime();
12131     }
12132     T = Context.getLifetimeQualifiedType(T, lifetime);
12133   }
12134 
12135   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
12136                                          Context.getAdjustedParameterType(T),
12137                                          TSInfo, SC, nullptr);
12138 
12139   // Parameters can not be abstract class types.
12140   // For record types, this is done by the AbstractClassUsageDiagnoser once
12141   // the class has been completely parsed.
12142   if (!CurContext->isRecord() &&
12143       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
12144                              AbstractParamType))
12145     New->setInvalidDecl();
12146 
12147   // Parameter declarators cannot be interface types. All ObjC objects are
12148   // passed by reference.
12149   if (T->isObjCObjectType()) {
12150     SourceLocation TypeEndLoc =
12151         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
12152     Diag(NameLoc,
12153          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
12154       << FixItHint::CreateInsertion(TypeEndLoc, "*");
12155     T = Context.getObjCObjectPointerType(T);
12156     New->setType(T);
12157   }
12158 
12159   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
12160   // duration shall not be qualified by an address-space qualifier."
12161   // Since all parameters have automatic store duration, they can not have
12162   // an address space.
12163   if (T.getAddressSpace() != LangAS::Default &&
12164       // OpenCL allows function arguments declared to be an array of a type
12165       // to be qualified with an address space.
12166       !(getLangOpts().OpenCL &&
12167         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
12168     Diag(NameLoc, diag::err_arg_with_address_space);
12169     New->setInvalidDecl();
12170   }
12171 
12172   return New;
12173 }
12174 
12175 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
12176                                            SourceLocation LocAfterDecls) {
12177   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
12178 
12179   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
12180   // for a K&R function.
12181   if (!FTI.hasPrototype) {
12182     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
12183       --i;
12184       if (FTI.Params[i].Param == nullptr) {
12185         SmallString<256> Code;
12186         llvm::raw_svector_ostream(Code)
12187             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
12188         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
12189             << FTI.Params[i].Ident
12190             << FixItHint::CreateInsertion(LocAfterDecls, Code);
12191 
12192         // Implicitly declare the argument as type 'int' for lack of a better
12193         // type.
12194         AttributeFactory attrs;
12195         DeclSpec DS(attrs);
12196         const char* PrevSpec; // unused
12197         unsigned DiagID; // unused
12198         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
12199                            DiagID, Context.getPrintingPolicy());
12200         // Use the identifier location for the type source range.
12201         DS.SetRangeStart(FTI.Params[i].IdentLoc);
12202         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
12203         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
12204         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
12205         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
12206       }
12207     }
12208   }
12209 }
12210 
12211 Decl *
12212 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
12213                               MultiTemplateParamsArg TemplateParameterLists,
12214                               SkipBodyInfo *SkipBody) {
12215   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
12216   assert(D.isFunctionDeclarator() && "Not a function declarator!");
12217   Scope *ParentScope = FnBodyScope->getParent();
12218 
12219   D.setFunctionDefinitionKind(FDK_Definition);
12220   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
12221   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
12222 }
12223 
12224 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
12225   Consumer.HandleInlineFunctionDefinition(D);
12226 }
12227 
12228 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
12229                              const FunctionDecl*& PossibleZeroParamPrototype) {
12230   // Don't warn about invalid declarations.
12231   if (FD->isInvalidDecl())
12232     return false;
12233 
12234   // Or declarations that aren't global.
12235   if (!FD->isGlobal())
12236     return false;
12237 
12238   // Don't warn about C++ member functions.
12239   if (isa<CXXMethodDecl>(FD))
12240     return false;
12241 
12242   // Don't warn about 'main'.
12243   if (FD->isMain())
12244     return false;
12245 
12246   // Don't warn about inline functions.
12247   if (FD->isInlined())
12248     return false;
12249 
12250   // Don't warn about function templates.
12251   if (FD->getDescribedFunctionTemplate())
12252     return false;
12253 
12254   // Don't warn about function template specializations.
12255   if (FD->isFunctionTemplateSpecialization())
12256     return false;
12257 
12258   // Don't warn for OpenCL kernels.
12259   if (FD->hasAttr<OpenCLKernelAttr>())
12260     return false;
12261 
12262   // Don't warn on explicitly deleted functions.
12263   if (FD->isDeleted())
12264     return false;
12265 
12266   bool MissingPrototype = true;
12267   for (const FunctionDecl *Prev = FD->getPreviousDecl();
12268        Prev; Prev = Prev->getPreviousDecl()) {
12269     // Ignore any declarations that occur in function or method
12270     // scope, because they aren't visible from the header.
12271     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
12272       continue;
12273 
12274     MissingPrototype = !Prev->getType()->isFunctionProtoType();
12275     if (FD->getNumParams() == 0)
12276       PossibleZeroParamPrototype = Prev;
12277     break;
12278   }
12279 
12280   return MissingPrototype;
12281 }
12282 
12283 void
12284 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
12285                                    const FunctionDecl *EffectiveDefinition,
12286                                    SkipBodyInfo *SkipBody) {
12287   const FunctionDecl *Definition = EffectiveDefinition;
12288   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
12289     // If this is a friend function defined in a class template, it does not
12290     // have a body until it is used, nevertheless it is a definition, see
12291     // [temp.inst]p2:
12292     //
12293     // ... for the purpose of determining whether an instantiated redeclaration
12294     // is valid according to [basic.def.odr] and [class.mem], a declaration that
12295     // corresponds to a definition in the template is considered to be a
12296     // definition.
12297     //
12298     // The following code must produce redefinition error:
12299     //
12300     //     template<typename T> struct C20 { friend void func_20() {} };
12301     //     C20<int> c20i;
12302     //     void func_20() {}
12303     //
12304     for (auto I : FD->redecls()) {
12305       if (I != FD && !I->isInvalidDecl() &&
12306           I->getFriendObjectKind() != Decl::FOK_None) {
12307         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
12308           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
12309             // A merged copy of the same function, instantiated as a member of
12310             // the same class, is OK.
12311             if (declaresSameEntity(OrigFD, Original) &&
12312                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
12313                                    cast<Decl>(FD->getLexicalDeclContext())))
12314               continue;
12315           }
12316 
12317           if (Original->isThisDeclarationADefinition()) {
12318             Definition = I;
12319             break;
12320           }
12321         }
12322       }
12323     }
12324   }
12325   if (!Definition)
12326     return;
12327 
12328   if (canRedefineFunction(Definition, getLangOpts()))
12329     return;
12330 
12331   // Don't emit an error when this is redefinition of a typo-corrected
12332   // definition.
12333   if (TypoCorrectedFunctionDefinitions.count(Definition))
12334     return;
12335 
12336   // If we don't have a visible definition of the function, and it's inline or
12337   // a template, skip the new definition.
12338   if (SkipBody && !hasVisibleDefinition(Definition) &&
12339       (Definition->getFormalLinkage() == InternalLinkage ||
12340        Definition->isInlined() ||
12341        Definition->getDescribedFunctionTemplate() ||
12342        Definition->getNumTemplateParameterLists())) {
12343     SkipBody->ShouldSkip = true;
12344     if (auto *TD = Definition->getDescribedFunctionTemplate())
12345       makeMergedDefinitionVisible(TD);
12346     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
12347     return;
12348   }
12349 
12350   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
12351       Definition->getStorageClass() == SC_Extern)
12352     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
12353         << FD->getDeclName() << getLangOpts().CPlusPlus;
12354   else
12355     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12356 
12357   Diag(Definition->getLocation(), diag::note_previous_definition);
12358   FD->setInvalidDecl();
12359 }
12360 
12361 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12362                                    Sema &S) {
12363   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12364 
12365   LambdaScopeInfo *LSI = S.PushLambdaScope();
12366   LSI->CallOperator = CallOperator;
12367   LSI->Lambda = LambdaClass;
12368   LSI->ReturnType = CallOperator->getReturnType();
12369   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12370 
12371   if (LCD == LCD_None)
12372     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12373   else if (LCD == LCD_ByCopy)
12374     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12375   else if (LCD == LCD_ByRef)
12376     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12377   DeclarationNameInfo DNI = CallOperator->getNameInfo();
12378 
12379   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12380   LSI->Mutable = !CallOperator->isConst();
12381 
12382   // Add the captures to the LSI so they can be noted as already
12383   // captured within tryCaptureVar.
12384   auto I = LambdaClass->field_begin();
12385   for (const auto &C : LambdaClass->captures()) {
12386     if (C.capturesVariable()) {
12387       VarDecl *VD = C.getCapturedVar();
12388       if (VD->isInitCapture())
12389         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12390       QualType CaptureType = VD->getType();
12391       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12392       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12393           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12394           /*EllipsisLoc*/C.isPackExpansion()
12395                          ? C.getEllipsisLoc() : SourceLocation(),
12396           CaptureType, /*Expr*/ nullptr);
12397 
12398     } else if (C.capturesThis()) {
12399       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
12400                               /*Expr*/ nullptr,
12401                               C.getCaptureKind() == LCK_StarThis);
12402     } else {
12403       LSI->addVLATypeCapture(C.getLocation(), I->getType());
12404     }
12405     ++I;
12406   }
12407 }
12408 
12409 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12410                                     SkipBodyInfo *SkipBody) {
12411   if (!D) {
12412     // Parsing the function declaration failed in some way. Push on a fake scope
12413     // anyway so we can try to parse the function body.
12414     PushFunctionScope();
12415     return D;
12416   }
12417 
12418   FunctionDecl *FD = nullptr;
12419 
12420   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
12421     FD = FunTmpl->getTemplatedDecl();
12422   else
12423     FD = cast<FunctionDecl>(D);
12424 
12425   // Check for defining attributes before the check for redefinition.
12426   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
12427     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
12428     FD->dropAttr<AliasAttr>();
12429     FD->setInvalidDecl();
12430   }
12431   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12432     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12433     FD->dropAttr<IFuncAttr>();
12434     FD->setInvalidDecl();
12435   }
12436 
12437   // See if this is a redefinition. If 'will have body' is already set, then
12438   // these checks were already performed when it was set.
12439   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
12440     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
12441 
12442     // If we're skipping the body, we're done. Don't enter the scope.
12443     if (SkipBody && SkipBody->ShouldSkip)
12444       return D;
12445   }
12446 
12447   // Mark this function as "will have a body eventually".  This lets users to
12448   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12449   // this function.
12450   FD->setWillHaveBody();
12451 
12452   // If we are instantiating a generic lambda call operator, push
12453   // a LambdaScopeInfo onto the function stack.  But use the information
12454   // that's already been calculated (ActOnLambdaExpr) to prime the current
12455   // LambdaScopeInfo.
12456   // When the template operator is being specialized, the LambdaScopeInfo,
12457   // has to be properly restored so that tryCaptureVariable doesn't try
12458   // and capture any new variables. In addition when calculating potential
12459   // captures during transformation of nested lambdas, it is necessary to
12460   // have the LSI properly restored.
12461   if (isGenericLambdaCallOperatorSpecialization(FD)) {
12462     assert(inTemplateInstantiation() &&
12463            "There should be an active template instantiation on the stack "
12464            "when instantiating a generic lambda!");
12465     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12466   } else {
12467     // Enter a new function scope
12468     PushFunctionScope();
12469   }
12470 
12471   // Builtin functions cannot be defined.
12472   if (unsigned BuiltinID = FD->getBuiltinID()) {
12473     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12474         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12475       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12476       FD->setInvalidDecl();
12477     }
12478   }
12479 
12480   // The return type of a function definition must be complete
12481   // (C99 6.9.1p3, C++ [dcl.fct]p6).
12482   QualType ResultType = FD->getReturnType();
12483   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12484       !FD->isInvalidDecl() &&
12485       RequireCompleteType(FD->getLocation(), ResultType,
12486                           diag::err_func_def_incomplete_result))
12487     FD->setInvalidDecl();
12488 
12489   if (FnBodyScope)
12490     PushDeclContext(FnBodyScope, FD);
12491 
12492   // Check the validity of our function parameters
12493   CheckParmsForFunctionDef(FD->parameters(),
12494                            /*CheckParameterNames=*/true);
12495 
12496   // Add non-parameter declarations already in the function to the current
12497   // scope.
12498   if (FnBodyScope) {
12499     for (Decl *NPD : FD->decls()) {
12500       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
12501       if (!NonParmDecl)
12502         continue;
12503       assert(!isa<ParmVarDecl>(NonParmDecl) &&
12504              "parameters should not be in newly created FD yet");
12505 
12506       // If the decl has a name, make it accessible in the current scope.
12507       if (NonParmDecl->getDeclName())
12508         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
12509 
12510       // Similarly, dive into enums and fish their constants out, making them
12511       // accessible in this scope.
12512       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
12513         for (auto *EI : ED->enumerators())
12514           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
12515       }
12516     }
12517   }
12518 
12519   // Introduce our parameters into the function scope
12520   for (auto Param : FD->parameters()) {
12521     Param->setOwningFunction(FD);
12522 
12523     // If this has an identifier, add it to the scope stack.
12524     if (Param->getIdentifier() && FnBodyScope) {
12525       CheckShadow(FnBodyScope, Param);
12526 
12527       PushOnScopeChains(Param, FnBodyScope);
12528     }
12529   }
12530 
12531   // Ensure that the function's exception specification is instantiated.
12532   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
12533     ResolveExceptionSpec(D->getLocation(), FPT);
12534 
12535   // dllimport cannot be applied to non-inline function definitions.
12536   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
12537       !FD->isTemplateInstantiation()) {
12538     assert(!FD->hasAttr<DLLExportAttr>());
12539     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
12540     FD->setInvalidDecl();
12541     return D;
12542   }
12543   // We want to attach documentation to original Decl (which might be
12544   // a function template).
12545   ActOnDocumentableDecl(D);
12546   if (getCurLexicalContext()->isObjCContainer() &&
12547       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
12548       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
12549     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
12550 
12551   return D;
12552 }
12553 
12554 /// \brief Given the set of return statements within a function body,
12555 /// compute the variables that are subject to the named return value
12556 /// optimization.
12557 ///
12558 /// Each of the variables that is subject to the named return value
12559 /// optimization will be marked as NRVO variables in the AST, and any
12560 /// return statement that has a marked NRVO variable as its NRVO candidate can
12561 /// use the named return value optimization.
12562 ///
12563 /// This function applies a very simplistic algorithm for NRVO: if every return
12564 /// statement in the scope of a variable has the same NRVO candidate, that
12565 /// candidate is an NRVO variable.
12566 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
12567   ReturnStmt **Returns = Scope->Returns.data();
12568 
12569   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
12570     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
12571       if (!NRVOCandidate->isNRVOVariable())
12572         Returns[I]->setNRVOCandidate(nullptr);
12573     }
12574   }
12575 }
12576 
12577 bool Sema::canDelayFunctionBody(const Declarator &D) {
12578   // We can't delay parsing the body of a constexpr function template (yet).
12579   if (D.getDeclSpec().isConstexprSpecified())
12580     return false;
12581 
12582   // We can't delay parsing the body of a function template with a deduced
12583   // return type (yet).
12584   if (D.getDeclSpec().hasAutoTypeSpec()) {
12585     // If the placeholder introduces a non-deduced trailing return type,
12586     // we can still delay parsing it.
12587     if (D.getNumTypeObjects()) {
12588       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
12589       if (Outer.Kind == DeclaratorChunk::Function &&
12590           Outer.Fun.hasTrailingReturnType()) {
12591         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
12592         return Ty.isNull() || !Ty->isUndeducedType();
12593       }
12594     }
12595     return false;
12596   }
12597 
12598   return true;
12599 }
12600 
12601 bool Sema::canSkipFunctionBody(Decl *D) {
12602   // We cannot skip the body of a function (or function template) which is
12603   // constexpr, since we may need to evaluate its body in order to parse the
12604   // rest of the file.
12605   // We cannot skip the body of a function with an undeduced return type,
12606   // because any callers of that function need to know the type.
12607   if (const FunctionDecl *FD = D->getAsFunction())
12608     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
12609       return false;
12610   return Consumer.shouldSkipFunctionBody(D);
12611 }
12612 
12613 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
12614   if (!Decl)
12615     return nullptr;
12616   if (FunctionDecl *FD = Decl->getAsFunction())
12617     FD->setHasSkippedBody();
12618   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
12619     MD->setHasSkippedBody();
12620   return Decl;
12621 }
12622 
12623 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
12624   return ActOnFinishFunctionBody(D, BodyArg, false);
12625 }
12626 
12627 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
12628                                     bool IsInstantiation) {
12629   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
12630 
12631   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12632   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
12633 
12634   if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
12635     CheckCompletedCoroutineBody(FD, Body);
12636 
12637   if (FD) {
12638     FD->setBody(Body);
12639     FD->setWillHaveBody(false);
12640 
12641     if (getLangOpts().CPlusPlus14) {
12642       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
12643           FD->getReturnType()->isUndeducedType()) {
12644         // If the function has a deduced result type but contains no 'return'
12645         // statements, the result type as written must be exactly 'auto', and
12646         // the deduced result type is 'void'.
12647         if (!FD->getReturnType()->getAs<AutoType>()) {
12648           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
12649               << FD->getReturnType();
12650           FD->setInvalidDecl();
12651         } else {
12652           // Substitute 'void' for the 'auto' in the type.
12653           TypeLoc ResultType = getReturnTypeLoc(FD);
12654           Context.adjustDeducedFunctionResultType(
12655               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
12656         }
12657       }
12658     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
12659       // In C++11, we don't use 'auto' deduction rules for lambda call
12660       // operators because we don't support return type deduction.
12661       auto *LSI = getCurLambda();
12662       if (LSI->HasImplicitReturnType) {
12663         deduceClosureReturnType(*LSI);
12664 
12665         // C++11 [expr.prim.lambda]p4:
12666         //   [...] if there are no return statements in the compound-statement
12667         //   [the deduced type is] the type void
12668         QualType RetType =
12669             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
12670 
12671         // Update the return type to the deduced type.
12672         const FunctionProtoType *Proto =
12673             FD->getType()->getAs<FunctionProtoType>();
12674         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
12675                                             Proto->getExtProtoInfo()));
12676       }
12677     }
12678 
12679     // If the function implicitly returns zero (like 'main') or is naked,
12680     // don't complain about missing return statements.
12681     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
12682       WP.disableCheckFallThrough();
12683 
12684     // MSVC permits the use of pure specifier (=0) on function definition,
12685     // defined at class scope, warn about this non-standard construct.
12686     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
12687       Diag(FD->getLocation(), diag::ext_pure_function_definition);
12688 
12689     if (!FD->isInvalidDecl()) {
12690       // Don't diagnose unused parameters of defaulted or deleted functions.
12691       if (!FD->isDeleted() && !FD->isDefaulted())
12692         DiagnoseUnusedParameters(FD->parameters());
12693       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
12694                                              FD->getReturnType(), FD);
12695 
12696       // If this is a structor, we need a vtable.
12697       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
12698         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
12699       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
12700         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
12701 
12702       // Try to apply the named return value optimization. We have to check
12703       // if we can do this here because lambdas keep return statements around
12704       // to deduce an implicit return type.
12705       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
12706           !FD->isDependentContext())
12707         computeNRVO(Body, getCurFunction());
12708     }
12709 
12710     // GNU warning -Wmissing-prototypes:
12711     //   Warn if a global function is defined without a previous
12712     //   prototype declaration. This warning is issued even if the
12713     //   definition itself provides a prototype. The aim is to detect
12714     //   global functions that fail to be declared in header files.
12715     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
12716     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
12717       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
12718 
12719       if (PossibleZeroParamPrototype) {
12720         // We found a declaration that is not a prototype,
12721         // but that could be a zero-parameter prototype
12722         if (TypeSourceInfo *TI =
12723                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
12724           TypeLoc TL = TI->getTypeLoc();
12725           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
12726             Diag(PossibleZeroParamPrototype->getLocation(),
12727                  diag::note_declaration_not_a_prototype)
12728                 << PossibleZeroParamPrototype
12729                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
12730         }
12731       }
12732 
12733       // GNU warning -Wstrict-prototypes
12734       //   Warn if K&R function is defined without a previous declaration.
12735       //   This warning is issued only if the definition itself does not provide
12736       //   a prototype. Only K&R definitions do not provide a prototype.
12737       //   An empty list in a function declarator that is part of a definition
12738       //   of that function specifies that the function has no parameters
12739       //   (C99 6.7.5.3p14)
12740       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
12741           !LangOpts.CPlusPlus) {
12742         TypeSourceInfo *TI = FD->getTypeSourceInfo();
12743         TypeLoc TL = TI->getTypeLoc();
12744         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
12745         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
12746       }
12747     }
12748 
12749     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12750       const CXXMethodDecl *KeyFunction;
12751       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
12752           MD->isVirtual() &&
12753           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
12754           MD == KeyFunction->getCanonicalDecl()) {
12755         // Update the key-function state if necessary for this ABI.
12756         if (FD->isInlined() &&
12757             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12758           Context.setNonKeyFunction(MD);
12759 
12760           // If the newly-chosen key function is already defined, then we
12761           // need to mark the vtable as used retroactively.
12762           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
12763           const FunctionDecl *Definition;
12764           if (KeyFunction && KeyFunction->isDefined(Definition))
12765             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
12766         } else {
12767           // We just defined they key function; mark the vtable as used.
12768           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
12769         }
12770       }
12771     }
12772 
12773     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
12774            "Function parsing confused");
12775   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
12776     assert(MD == getCurMethodDecl() && "Method parsing confused");
12777     MD->setBody(Body);
12778     if (!MD->isInvalidDecl()) {
12779       DiagnoseUnusedParameters(MD->parameters());
12780       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
12781                                              MD->getReturnType(), MD);
12782 
12783       if (Body)
12784         computeNRVO(Body, getCurFunction());
12785     }
12786     if (getCurFunction()->ObjCShouldCallSuper) {
12787       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
12788         << MD->getSelector().getAsString();
12789       getCurFunction()->ObjCShouldCallSuper = false;
12790     }
12791     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12792       const ObjCMethodDecl *InitMethod = nullptr;
12793       bool isDesignated =
12794           MD->isDesignatedInitializerForTheInterface(&InitMethod);
12795       assert(isDesignated && InitMethod);
12796       (void)isDesignated;
12797 
12798       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12799         auto IFace = MD->getClassInterface();
12800         if (!IFace)
12801           return false;
12802         auto SuperD = IFace->getSuperClass();
12803         if (!SuperD)
12804           return false;
12805         return SuperD->getIdentifier() ==
12806             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12807       };
12808       // Don't issue this warning for unavailable inits or direct subclasses
12809       // of NSObject.
12810       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12811         Diag(MD->getLocation(),
12812              diag::warn_objc_designated_init_missing_super_call);
12813         Diag(InitMethod->getLocation(),
12814              diag::note_objc_designated_init_marked_here);
12815       }
12816       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12817     }
12818     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12819       // Don't issue this warning for unavaialable inits.
12820       if (!MD->isUnavailable())
12821         Diag(MD->getLocation(),
12822              diag::warn_objc_secondary_init_missing_init_call);
12823       getCurFunction()->ObjCWarnForNoInitDelegation = false;
12824     }
12825   } else {
12826     // Parsing the function declaration failed in some way. Pop the fake scope
12827     // we pushed on.
12828     PopFunctionScopeInfo(ActivePolicy, dcl);
12829     return nullptr;
12830   }
12831 
12832   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12833     DiagnoseUnguardedAvailabilityViolations(dcl);
12834 
12835   assert(!getCurFunction()->ObjCShouldCallSuper &&
12836          "This should only be set for ObjC methods, which should have been "
12837          "handled in the block above.");
12838 
12839   // Verify and clean out per-function state.
12840   if (Body && (!FD || !FD->isDefaulted())) {
12841     // C++ constructors that have function-try-blocks can't have return
12842     // statements in the handlers of that block. (C++ [except.handle]p14)
12843     // Verify this.
12844     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12845       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12846 
12847     // Verify that gotos and switch cases don't jump into scopes illegally.
12848     if (getCurFunction()->NeedsScopeChecking() &&
12849         !PP.isCodeCompletionEnabled())
12850       DiagnoseInvalidJumps(Body);
12851 
12852     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12853       if (!Destructor->getParent()->isDependentType())
12854         CheckDestructor(Destructor);
12855 
12856       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12857                                              Destructor->getParent());
12858     }
12859 
12860     // If any errors have occurred, clear out any temporaries that may have
12861     // been leftover. This ensures that these temporaries won't be picked up for
12862     // deletion in some later function.
12863     if (getDiagnostics().hasErrorOccurred() ||
12864         getDiagnostics().getSuppressAllDiagnostics()) {
12865       DiscardCleanupsInEvaluationContext();
12866     }
12867     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12868         !isa<FunctionTemplateDecl>(dcl)) {
12869       // Since the body is valid, issue any analysis-based warnings that are
12870       // enabled.
12871       ActivePolicy = &WP;
12872     }
12873 
12874     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12875         (!CheckConstexprFunctionDecl(FD) ||
12876          !CheckConstexprFunctionBody(FD, Body)))
12877       FD->setInvalidDecl();
12878 
12879     if (FD && FD->hasAttr<NakedAttr>()) {
12880       for (const Stmt *S : Body->children()) {
12881         // Allow local register variables without initializer as they don't
12882         // require prologue.
12883         bool RegisterVariables = false;
12884         if (auto *DS = dyn_cast<DeclStmt>(S)) {
12885           for (const auto *Decl : DS->decls()) {
12886             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12887               RegisterVariables =
12888                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12889               if (!RegisterVariables)
12890                 break;
12891             }
12892           }
12893         }
12894         if (RegisterVariables)
12895           continue;
12896         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12897           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12898           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12899           FD->setInvalidDecl();
12900           break;
12901         }
12902       }
12903     }
12904 
12905     assert(ExprCleanupObjects.size() ==
12906                ExprEvalContexts.back().NumCleanupObjects &&
12907            "Leftover temporaries in function");
12908     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12909     assert(MaybeODRUseExprs.empty() &&
12910            "Leftover expressions for odr-use checking");
12911   }
12912 
12913   if (!IsInstantiation)
12914     PopDeclContext();
12915 
12916   PopFunctionScopeInfo(ActivePolicy, dcl);
12917   // If any errors have occurred, clear out any temporaries that may have
12918   // been leftover. This ensures that these temporaries won't be picked up for
12919   // deletion in some later function.
12920   if (getDiagnostics().hasErrorOccurred()) {
12921     DiscardCleanupsInEvaluationContext();
12922   }
12923 
12924   return dcl;
12925 }
12926 
12927 /// When we finish delayed parsing of an attribute, we must attach it to the
12928 /// relevant Decl.
12929 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12930                                        ParsedAttributes &Attrs) {
12931   // Always attach attributes to the underlying decl.
12932   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12933     D = TD->getTemplatedDecl();
12934   ProcessDeclAttributeList(S, D, Attrs.getList());
12935 
12936   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12937     if (Method->isStatic())
12938       checkThisInStaticMemberFunctionAttributes(Method);
12939 }
12940 
12941 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12942 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12943 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12944                                           IdentifierInfo &II, Scope *S) {
12945   // Find the scope in which the identifier is injected and the corresponding
12946   // DeclContext.
12947   // FIXME: C89 does not say what happens if there is no enclosing block scope.
12948   // In that case, we inject the declaration into the translation unit scope
12949   // instead.
12950   Scope *BlockScope = S;
12951   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
12952     BlockScope = BlockScope->getParent();
12953 
12954   Scope *ContextScope = BlockScope;
12955   while (!ContextScope->getEntity())
12956     ContextScope = ContextScope->getParent();
12957   ContextRAII SavedContext(*this, ContextScope->getEntity());
12958 
12959   // Before we produce a declaration for an implicitly defined
12960   // function, see whether there was a locally-scoped declaration of
12961   // this name as a function or variable. If so, use that
12962   // (non-visible) declaration, and complain about it.
12963   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
12964   if (ExternCPrev) {
12965     // We still need to inject the function into the enclosing block scope so
12966     // that later (non-call) uses can see it.
12967     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
12968 
12969     // C89 footnote 38:
12970     //   If in fact it is not defined as having type "function returning int",
12971     //   the behavior is undefined.
12972     if (!isa<FunctionDecl>(ExternCPrev) ||
12973         !Context.typesAreCompatible(
12974             cast<FunctionDecl>(ExternCPrev)->getType(),
12975             Context.getFunctionNoProtoType(Context.IntTy))) {
12976       Diag(Loc, diag::ext_use_out_of_scope_declaration)
12977           << ExternCPrev << !getLangOpts().C99;
12978       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12979       return ExternCPrev;
12980     }
12981   }
12982 
12983   // Extension in C99.  Legal in C90, but warn about it.
12984   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
12985   unsigned diag_id;
12986   if (II.getName().startswith("__builtin_"))
12987     diag_id = diag::warn_builtin_unknown;
12988   else if (getLangOpts().C99 || getLangOpts().OpenCL)
12989     diag_id = diag::ext_implicit_function_decl;
12990   else
12991     diag_id = diag::warn_implicit_function_decl;
12992   Diag(Loc, diag_id) << &II << getLangOpts().OpenCL;
12993 
12994   // If we found a prior declaration of this function, don't bother building
12995   // another one. We've already pushed that one into scope, so there's nothing
12996   // more to do.
12997   if (ExternCPrev)
12998     return ExternCPrev;
12999 
13000   // Because typo correction is expensive, only do it if the implicit
13001   // function declaration is going to be treated as an error.
13002   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
13003     TypoCorrection Corrected;
13004     if (S &&
13005         (Corrected = CorrectTypo(
13006              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
13007              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
13008       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
13009                    /*ErrorRecovery*/false);
13010   }
13011 
13012   // Set a Declarator for the implicit definition: int foo();
13013   const char *Dummy;
13014   AttributeFactory attrFactory;
13015   DeclSpec DS(attrFactory);
13016   unsigned DiagID;
13017   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
13018                                   Context.getPrintingPolicy());
13019   (void)Error; // Silence warning.
13020   assert(!Error && "Error setting up implicit decl!");
13021   SourceLocation NoLoc;
13022   Declarator D(DS, DeclaratorContext::BlockContext);
13023   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
13024                                              /*IsAmbiguous=*/false,
13025                                              /*LParenLoc=*/NoLoc,
13026                                              /*Params=*/nullptr,
13027                                              /*NumParams=*/0,
13028                                              /*EllipsisLoc=*/NoLoc,
13029                                              /*RParenLoc=*/NoLoc,
13030                                              /*TypeQuals=*/0,
13031                                              /*RefQualifierIsLvalueRef=*/true,
13032                                              /*RefQualifierLoc=*/NoLoc,
13033                                              /*ConstQualifierLoc=*/NoLoc,
13034                                              /*VolatileQualifierLoc=*/NoLoc,
13035                                              /*RestrictQualifierLoc=*/NoLoc,
13036                                              /*MutableLoc=*/NoLoc,
13037                                              EST_None,
13038                                              /*ESpecRange=*/SourceRange(),
13039                                              /*Exceptions=*/nullptr,
13040                                              /*ExceptionRanges=*/nullptr,
13041                                              /*NumExceptions=*/0,
13042                                              /*NoexceptExpr=*/nullptr,
13043                                              /*ExceptionSpecTokens=*/nullptr,
13044                                              /*DeclsInPrototype=*/None,
13045                                              Loc, Loc, D),
13046                 DS.getAttributes(),
13047                 SourceLocation());
13048   D.SetIdentifier(&II, Loc);
13049 
13050   // Insert this function into the enclosing block scope.
13051   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
13052   FD->setImplicit();
13053 
13054   AddKnownFunctionAttributes(FD);
13055 
13056   return FD;
13057 }
13058 
13059 /// \brief Adds any function attributes that we know a priori based on
13060 /// the declaration of this function.
13061 ///
13062 /// These attributes can apply both to implicitly-declared builtins
13063 /// (like __builtin___printf_chk) or to library-declared functions
13064 /// like NSLog or printf.
13065 ///
13066 /// We need to check for duplicate attributes both here and where user-written
13067 /// attributes are applied to declarations.
13068 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
13069   if (FD->isInvalidDecl())
13070     return;
13071 
13072   // If this is a built-in function, map its builtin attributes to
13073   // actual attributes.
13074   if (unsigned BuiltinID = FD->getBuiltinID()) {
13075     // Handle printf-formatting attributes.
13076     unsigned FormatIdx;
13077     bool HasVAListArg;
13078     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
13079       if (!FD->hasAttr<FormatAttr>()) {
13080         const char *fmt = "printf";
13081         unsigned int NumParams = FD->getNumParams();
13082         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
13083             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
13084           fmt = "NSString";
13085         FD->addAttr(FormatAttr::CreateImplicit(Context,
13086                                                &Context.Idents.get(fmt),
13087                                                FormatIdx+1,
13088                                                HasVAListArg ? 0 : FormatIdx+2,
13089                                                FD->getLocation()));
13090       }
13091     }
13092     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
13093                                              HasVAListArg)) {
13094      if (!FD->hasAttr<FormatAttr>())
13095        FD->addAttr(FormatAttr::CreateImplicit(Context,
13096                                               &Context.Idents.get("scanf"),
13097                                               FormatIdx+1,
13098                                               HasVAListArg ? 0 : FormatIdx+2,
13099                                               FD->getLocation()));
13100     }
13101 
13102     // Mark const if we don't care about errno and that is the only thing
13103     // preventing the function from being const. This allows IRgen to use LLVM
13104     // intrinsics for such functions.
13105     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
13106         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
13107       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13108 
13109     // We make "fma" on GNU or Windows const because we know it does not set
13110     // errno in those environments even though it could set errno based on the
13111     // C standard.
13112     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
13113     if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
13114         !FD->hasAttr<ConstAttr>()) {
13115       switch (BuiltinID) {
13116       case Builtin::BI__builtin_fma:
13117       case Builtin::BI__builtin_fmaf:
13118       case Builtin::BI__builtin_fmal:
13119       case Builtin::BIfma:
13120       case Builtin::BIfmaf:
13121       case Builtin::BIfmal:
13122         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13123         break;
13124       default:
13125         break;
13126       }
13127     }
13128 
13129     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
13130         !FD->hasAttr<ReturnsTwiceAttr>())
13131       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
13132                                          FD->getLocation()));
13133     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
13134       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13135     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
13136       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
13137     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
13138       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13139     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
13140         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
13141       // Add the appropriate attribute, depending on the CUDA compilation mode
13142       // and which target the builtin belongs to. For example, during host
13143       // compilation, aux builtins are __device__, while the rest are __host__.
13144       if (getLangOpts().CUDAIsDevice !=
13145           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
13146         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
13147       else
13148         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
13149     }
13150   }
13151 
13152   // If C++ exceptions are enabled but we are told extern "C" functions cannot
13153   // throw, add an implicit nothrow attribute to any extern "C" function we come
13154   // across.
13155   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
13156       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
13157     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
13158     if (!FPT || FPT->getExceptionSpecType() == EST_None)
13159       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13160   }
13161 
13162   IdentifierInfo *Name = FD->getIdentifier();
13163   if (!Name)
13164     return;
13165   if ((!getLangOpts().CPlusPlus &&
13166        FD->getDeclContext()->isTranslationUnit()) ||
13167       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
13168        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
13169        LinkageSpecDecl::lang_c)) {
13170     // Okay: this could be a libc/libm/Objective-C function we know
13171     // about.
13172   } else
13173     return;
13174 
13175   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
13176     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
13177     // target-specific builtins, perhaps?
13178     if (!FD->hasAttr<FormatAttr>())
13179       FD->addAttr(FormatAttr::CreateImplicit(Context,
13180                                              &Context.Idents.get("printf"), 2,
13181                                              Name->isStr("vasprintf") ? 0 : 3,
13182                                              FD->getLocation()));
13183   }
13184 
13185   if (Name->isStr("__CFStringMakeConstantString")) {
13186     // We already have a __builtin___CFStringMakeConstantString,
13187     // but builds that use -fno-constant-cfstrings don't go through that.
13188     if (!FD->hasAttr<FormatArgAttr>())
13189       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
13190                                                 FD->getLocation()));
13191   }
13192 }
13193 
13194 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
13195                                     TypeSourceInfo *TInfo) {
13196   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
13197   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
13198 
13199   if (!TInfo) {
13200     assert(D.isInvalidType() && "no declarator info for valid type");
13201     TInfo = Context.getTrivialTypeSourceInfo(T);
13202   }
13203 
13204   // Scope manipulation handled by caller.
13205   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
13206                                            D.getLocStart(),
13207                                            D.getIdentifierLoc(),
13208                                            D.getIdentifier(),
13209                                            TInfo);
13210 
13211   // Bail out immediately if we have an invalid declaration.
13212   if (D.isInvalidType()) {
13213     NewTD->setInvalidDecl();
13214     return NewTD;
13215   }
13216 
13217   if (D.getDeclSpec().isModulePrivateSpecified()) {
13218     if (CurContext->isFunctionOrMethod())
13219       Diag(NewTD->getLocation(), diag::err_module_private_local)
13220         << 2 << NewTD->getDeclName()
13221         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13222         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13223     else
13224       NewTD->setModulePrivate();
13225   }
13226 
13227   // C++ [dcl.typedef]p8:
13228   //   If the typedef declaration defines an unnamed class (or
13229   //   enum), the first typedef-name declared by the declaration
13230   //   to be that class type (or enum type) is used to denote the
13231   //   class type (or enum type) for linkage purposes only.
13232   // We need to check whether the type was declared in the declaration.
13233   switch (D.getDeclSpec().getTypeSpecType()) {
13234   case TST_enum:
13235   case TST_struct:
13236   case TST_interface:
13237   case TST_union:
13238   case TST_class: {
13239     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
13240     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
13241     break;
13242   }
13243 
13244   default:
13245     break;
13246   }
13247 
13248   return NewTD;
13249 }
13250 
13251 /// \brief Check that this is a valid underlying type for an enum declaration.
13252 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
13253   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
13254   QualType T = TI->getType();
13255 
13256   if (T->isDependentType())
13257     return false;
13258 
13259   if (const BuiltinType *BT = T->getAs<BuiltinType>())
13260     if (BT->isInteger())
13261       return false;
13262 
13263   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
13264   return true;
13265 }
13266 
13267 /// Check whether this is a valid redeclaration of a previous enumeration.
13268 /// \return true if the redeclaration was invalid.
13269 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
13270                                   QualType EnumUnderlyingTy, bool IsFixed,
13271                                   const EnumDecl *Prev) {
13272   if (IsScoped != Prev->isScoped()) {
13273     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
13274       << Prev->isScoped();
13275     Diag(Prev->getLocation(), diag::note_previous_declaration);
13276     return true;
13277   }
13278 
13279   if (IsFixed && Prev->isFixed()) {
13280     if (!EnumUnderlyingTy->isDependentType() &&
13281         !Prev->getIntegerType()->isDependentType() &&
13282         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
13283                                         Prev->getIntegerType())) {
13284       // TODO: Highlight the underlying type of the redeclaration.
13285       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
13286         << EnumUnderlyingTy << Prev->getIntegerType();
13287       Diag(Prev->getLocation(), diag::note_previous_declaration)
13288           << Prev->getIntegerTypeRange();
13289       return true;
13290     }
13291   } else if (IsFixed != Prev->isFixed()) {
13292     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
13293       << Prev->isFixed();
13294     Diag(Prev->getLocation(), diag::note_previous_declaration);
13295     return true;
13296   }
13297 
13298   return false;
13299 }
13300 
13301 /// \brief Get diagnostic %select index for tag kind for
13302 /// redeclaration diagnostic message.
13303 /// WARNING: Indexes apply to particular diagnostics only!
13304 ///
13305 /// \returns diagnostic %select index.
13306 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
13307   switch (Tag) {
13308   case TTK_Struct: return 0;
13309   case TTK_Interface: return 1;
13310   case TTK_Class:  return 2;
13311   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
13312   }
13313 }
13314 
13315 /// \brief Determine if tag kind is a class-key compatible with
13316 /// class for redeclaration (class, struct, or __interface).
13317 ///
13318 /// \returns true iff the tag kind is compatible.
13319 static bool isClassCompatTagKind(TagTypeKind Tag)
13320 {
13321   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
13322 }
13323 
13324 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
13325                                              TagTypeKind TTK) {
13326   if (isa<TypedefDecl>(PrevDecl))
13327     return NTK_Typedef;
13328   else if (isa<TypeAliasDecl>(PrevDecl))
13329     return NTK_TypeAlias;
13330   else if (isa<ClassTemplateDecl>(PrevDecl))
13331     return NTK_Template;
13332   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
13333     return NTK_TypeAliasTemplate;
13334   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
13335     return NTK_TemplateTemplateArgument;
13336   switch (TTK) {
13337   case TTK_Struct:
13338   case TTK_Interface:
13339   case TTK_Class:
13340     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
13341   case TTK_Union:
13342     return NTK_NonUnion;
13343   case TTK_Enum:
13344     return NTK_NonEnum;
13345   }
13346   llvm_unreachable("invalid TTK");
13347 }
13348 
13349 /// \brief Determine whether a tag with a given kind is acceptable
13350 /// as a redeclaration of the given tag declaration.
13351 ///
13352 /// \returns true if the new tag kind is acceptable, false otherwise.
13353 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
13354                                         TagTypeKind NewTag, bool isDefinition,
13355                                         SourceLocation NewTagLoc,
13356                                         const IdentifierInfo *Name) {
13357   // C++ [dcl.type.elab]p3:
13358   //   The class-key or enum keyword present in the
13359   //   elaborated-type-specifier shall agree in kind with the
13360   //   declaration to which the name in the elaborated-type-specifier
13361   //   refers. This rule also applies to the form of
13362   //   elaborated-type-specifier that declares a class-name or
13363   //   friend class since it can be construed as referring to the
13364   //   definition of the class. Thus, in any
13365   //   elaborated-type-specifier, the enum keyword shall be used to
13366   //   refer to an enumeration (7.2), the union class-key shall be
13367   //   used to refer to a union (clause 9), and either the class or
13368   //   struct class-key shall be used to refer to a class (clause 9)
13369   //   declared using the class or struct class-key.
13370   TagTypeKind OldTag = Previous->getTagKind();
13371   if (!isDefinition || !isClassCompatTagKind(NewTag))
13372     if (OldTag == NewTag)
13373       return true;
13374 
13375   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
13376     // Warn about the struct/class tag mismatch.
13377     bool isTemplate = false;
13378     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
13379       isTemplate = Record->getDescribedClassTemplate();
13380 
13381     if (inTemplateInstantiation()) {
13382       // In a template instantiation, do not offer fix-its for tag mismatches
13383       // since they usually mess up the template instead of fixing the problem.
13384       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13385         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13386         << getRedeclDiagFromTagKind(OldTag);
13387       return true;
13388     }
13389 
13390     if (isDefinition) {
13391       // On definitions, check previous tags and issue a fix-it for each
13392       // one that doesn't match the current tag.
13393       if (Previous->getDefinition()) {
13394         // Don't suggest fix-its for redefinitions.
13395         return true;
13396       }
13397 
13398       bool previousMismatch = false;
13399       for (auto I : Previous->redecls()) {
13400         if (I->getTagKind() != NewTag) {
13401           if (!previousMismatch) {
13402             previousMismatch = true;
13403             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
13404               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13405               << getRedeclDiagFromTagKind(I->getTagKind());
13406           }
13407           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
13408             << getRedeclDiagFromTagKind(NewTag)
13409             << FixItHint::CreateReplacement(I->getInnerLocStart(),
13410                  TypeWithKeyword::getTagTypeKindName(NewTag));
13411         }
13412       }
13413       return true;
13414     }
13415 
13416     // Check for a previous definition.  If current tag and definition
13417     // are same type, do nothing.  If no definition, but disagree with
13418     // with previous tag type, give a warning, but no fix-it.
13419     const TagDecl *Redecl = Previous->getDefinition() ?
13420                             Previous->getDefinition() : Previous;
13421     if (Redecl->getTagKind() == NewTag) {
13422       return true;
13423     }
13424 
13425     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13426       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13427       << getRedeclDiagFromTagKind(OldTag);
13428     Diag(Redecl->getLocation(), diag::note_previous_use);
13429 
13430     // If there is a previous definition, suggest a fix-it.
13431     if (Previous->getDefinition()) {
13432         Diag(NewTagLoc, diag::note_struct_class_suggestion)
13433           << getRedeclDiagFromTagKind(Redecl->getTagKind())
13434           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
13435                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
13436     }
13437 
13438     return true;
13439   }
13440   return false;
13441 }
13442 
13443 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
13444 /// from an outer enclosing namespace or file scope inside a friend declaration.
13445 /// This should provide the commented out code in the following snippet:
13446 ///   namespace N {
13447 ///     struct X;
13448 ///     namespace M {
13449 ///       struct Y { friend struct /*N::*/ X; };
13450 ///     }
13451 ///   }
13452 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
13453                                          SourceLocation NameLoc) {
13454   // While the decl is in a namespace, do repeated lookup of that name and see
13455   // if we get the same namespace back.  If we do not, continue until
13456   // translation unit scope, at which point we have a fully qualified NNS.
13457   SmallVector<IdentifierInfo *, 4> Namespaces;
13458   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13459   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
13460     // This tag should be declared in a namespace, which can only be enclosed by
13461     // other namespaces.  Bail if there's an anonymous namespace in the chain.
13462     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
13463     if (!Namespace || Namespace->isAnonymousNamespace())
13464       return FixItHint();
13465     IdentifierInfo *II = Namespace->getIdentifier();
13466     Namespaces.push_back(II);
13467     NamedDecl *Lookup = SemaRef.LookupSingleName(
13468         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
13469     if (Lookup == Namespace)
13470       break;
13471   }
13472 
13473   // Once we have all the namespaces, reverse them to go outermost first, and
13474   // build an NNS.
13475   SmallString<64> Insertion;
13476   llvm::raw_svector_ostream OS(Insertion);
13477   if (DC->isTranslationUnit())
13478     OS << "::";
13479   std::reverse(Namespaces.begin(), Namespaces.end());
13480   for (auto *II : Namespaces)
13481     OS << II->getName() << "::";
13482   return FixItHint::CreateInsertion(NameLoc, Insertion);
13483 }
13484 
13485 /// \brief Determine whether a tag originally declared in context \p OldDC can
13486 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
13487 /// found a declaration in \p OldDC as a previous decl, perhaps through a
13488 /// using-declaration).
13489 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
13490                                          DeclContext *NewDC) {
13491   OldDC = OldDC->getRedeclContext();
13492   NewDC = NewDC->getRedeclContext();
13493 
13494   if (OldDC->Equals(NewDC))
13495     return true;
13496 
13497   // In MSVC mode, we allow a redeclaration if the contexts are related (either
13498   // encloses the other).
13499   if (S.getLangOpts().MSVCCompat &&
13500       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
13501     return true;
13502 
13503   return false;
13504 }
13505 
13506 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
13507 /// former case, Name will be non-null.  In the later case, Name will be null.
13508 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
13509 /// reference/declaration/definition of a tag.
13510 ///
13511 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
13512 /// trailing-type-specifier) other than one in an alias-declaration.
13513 ///
13514 /// \param SkipBody If non-null, will be set to indicate if the caller should
13515 /// skip the definition of this tag and treat it as if it were a declaration.
13516 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
13517                      SourceLocation KWLoc, CXXScopeSpec &SS,
13518                      IdentifierInfo *Name, SourceLocation NameLoc,
13519                      AttributeList *Attr, AccessSpecifier AS,
13520                      SourceLocation ModulePrivateLoc,
13521                      MultiTemplateParamsArg TemplateParameterLists,
13522                      bool &OwnedDecl, bool &IsDependent,
13523                      SourceLocation ScopedEnumKWLoc,
13524                      bool ScopedEnumUsesClassTag,
13525                      TypeResult UnderlyingType,
13526                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
13527                      SkipBodyInfo *SkipBody) {
13528   // If this is not a definition, it must have a name.
13529   IdentifierInfo *OrigName = Name;
13530   assert((Name != nullptr || TUK == TUK_Definition) &&
13531          "Nameless record must be a definition!");
13532   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
13533 
13534   OwnedDecl = false;
13535   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13536   bool ScopedEnum = ScopedEnumKWLoc.isValid();
13537 
13538   // FIXME: Check member specializations more carefully.
13539   bool isMemberSpecialization = false;
13540   bool Invalid = false;
13541 
13542   // We only need to do this matching if we have template parameters
13543   // or a scope specifier, which also conveniently avoids this work
13544   // for non-C++ cases.
13545   if (TemplateParameterLists.size() > 0 ||
13546       (SS.isNotEmpty() && TUK != TUK_Reference)) {
13547     if (TemplateParameterList *TemplateParams =
13548             MatchTemplateParametersToScopeSpecifier(
13549                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
13550                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
13551       if (Kind == TTK_Enum) {
13552         Diag(KWLoc, diag::err_enum_template);
13553         return nullptr;
13554       }
13555 
13556       if (TemplateParams->size() > 0) {
13557         // This is a declaration or definition of a class template (which may
13558         // be a member of another template).
13559 
13560         if (Invalid)
13561           return nullptr;
13562 
13563         OwnedDecl = false;
13564         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
13565                                                SS, Name, NameLoc, Attr,
13566                                                TemplateParams, AS,
13567                                                ModulePrivateLoc,
13568                                                /*FriendLoc*/SourceLocation(),
13569                                                TemplateParameterLists.size()-1,
13570                                                TemplateParameterLists.data(),
13571                                                SkipBody);
13572         return Result.get();
13573       } else {
13574         // The "template<>" header is extraneous.
13575         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13576           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13577         isMemberSpecialization = true;
13578       }
13579     }
13580   }
13581 
13582   // Figure out the underlying type if this a enum declaration. We need to do
13583   // this early, because it's needed to detect if this is an incompatible
13584   // redeclaration.
13585   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
13586   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
13587 
13588   if (Kind == TTK_Enum) {
13589     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
13590       // No underlying type explicitly specified, or we failed to parse the
13591       // type, default to int.
13592       EnumUnderlying = Context.IntTy.getTypePtr();
13593     } else if (UnderlyingType.get()) {
13594       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
13595       // integral type; any cv-qualification is ignored.
13596       TypeSourceInfo *TI = nullptr;
13597       GetTypeFromParser(UnderlyingType.get(), &TI);
13598       EnumUnderlying = TI;
13599 
13600       if (CheckEnumUnderlyingType(TI))
13601         // Recover by falling back to int.
13602         EnumUnderlying = Context.IntTy.getTypePtr();
13603 
13604       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
13605                                           UPPC_FixedUnderlyingType))
13606         EnumUnderlying = Context.IntTy.getTypePtr();
13607 
13608     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13609       // For MSVC ABI compatibility, unfixed enums must use an underlying type
13610       // of 'int'. However, if this is an unfixed forward declaration, don't set
13611       // the underlying type unless the user enables -fms-compatibility. This
13612       // makes unfixed forward declared enums incomplete and is more conforming.
13613       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
13614         EnumUnderlying = Context.IntTy.getTypePtr();
13615     }
13616   }
13617 
13618   DeclContext *SearchDC = CurContext;
13619   DeclContext *DC = CurContext;
13620   bool isStdBadAlloc = false;
13621   bool isStdAlignValT = false;
13622 
13623   RedeclarationKind Redecl = forRedeclarationInCurContext();
13624   if (TUK == TUK_Friend || TUK == TUK_Reference)
13625     Redecl = NotForRedeclaration;
13626 
13627   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
13628   /// implemented asks for structural equivalence checking, the returned decl
13629   /// here is passed back to the parser, allowing the tag body to be parsed.
13630   auto createTagFromNewDecl = [&]() -> TagDecl * {
13631     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
13632     // If there is an identifier, use the location of the identifier as the
13633     // location of the decl, otherwise use the location of the struct/union
13634     // keyword.
13635     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13636     TagDecl *New = nullptr;
13637 
13638     if (Kind == TTK_Enum) {
13639       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
13640                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
13641       // If this is an undefined enum, bail.
13642       if (TUK != TUK_Definition && !Invalid)
13643         return nullptr;
13644       if (EnumUnderlying) {
13645         EnumDecl *ED = cast<EnumDecl>(New);
13646         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
13647           ED->setIntegerTypeSourceInfo(TI);
13648         else
13649           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
13650         ED->setPromotionType(ED->getIntegerType());
13651       }
13652     } else { // struct/union
13653       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13654                                nullptr);
13655     }
13656 
13657     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13658       // Add alignment attributes if necessary; these attributes are checked
13659       // when the ASTContext lays out the structure.
13660       //
13661       // It is important for implementing the correct semantics that this
13662       // happen here (in ActOnTag). The #pragma pack stack is
13663       // maintained as a result of parser callbacks which can occur at
13664       // many points during the parsing of a struct declaration (because
13665       // the #pragma tokens are effectively skipped over during the
13666       // parsing of the struct).
13667       if (TUK == TUK_Definition) {
13668         AddAlignmentAttributesForRecord(RD);
13669         AddMsStructLayoutForRecord(RD);
13670       }
13671     }
13672     New->setLexicalDeclContext(CurContext);
13673     return New;
13674   };
13675 
13676   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
13677   if (Name && SS.isNotEmpty()) {
13678     // We have a nested-name tag ('struct foo::bar').
13679 
13680     // Check for invalid 'foo::'.
13681     if (SS.isInvalid()) {
13682       Name = nullptr;
13683       goto CreateNewDecl;
13684     }
13685 
13686     // If this is a friend or a reference to a class in a dependent
13687     // context, don't try to make a decl for it.
13688     if (TUK == TUK_Friend || TUK == TUK_Reference) {
13689       DC = computeDeclContext(SS, false);
13690       if (!DC) {
13691         IsDependent = true;
13692         return nullptr;
13693       }
13694     } else {
13695       DC = computeDeclContext(SS, true);
13696       if (!DC) {
13697         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
13698           << SS.getRange();
13699         return nullptr;
13700       }
13701     }
13702 
13703     if (RequireCompleteDeclContext(SS, DC))
13704       return nullptr;
13705 
13706     SearchDC = DC;
13707     // Look-up name inside 'foo::'.
13708     LookupQualifiedName(Previous, DC);
13709 
13710     if (Previous.isAmbiguous())
13711       return nullptr;
13712 
13713     if (Previous.empty()) {
13714       // Name lookup did not find anything. However, if the
13715       // nested-name-specifier refers to the current instantiation,
13716       // and that current instantiation has any dependent base
13717       // classes, we might find something at instantiation time: treat
13718       // this as a dependent elaborated-type-specifier.
13719       // But this only makes any sense for reference-like lookups.
13720       if (Previous.wasNotFoundInCurrentInstantiation() &&
13721           (TUK == TUK_Reference || TUK == TUK_Friend)) {
13722         IsDependent = true;
13723         return nullptr;
13724       }
13725 
13726       // A tag 'foo::bar' must already exist.
13727       Diag(NameLoc, diag::err_not_tag_in_scope)
13728         << Kind << Name << DC << SS.getRange();
13729       Name = nullptr;
13730       Invalid = true;
13731       goto CreateNewDecl;
13732     }
13733   } else if (Name) {
13734     // C++14 [class.mem]p14:
13735     //   If T is the name of a class, then each of the following shall have a
13736     //   name different from T:
13737     //    -- every member of class T that is itself a type
13738     if (TUK != TUK_Reference && TUK != TUK_Friend &&
13739         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
13740       return nullptr;
13741 
13742     // If this is a named struct, check to see if there was a previous forward
13743     // declaration or definition.
13744     // FIXME: We're looking into outer scopes here, even when we
13745     // shouldn't be. Doing so can result in ambiguities that we
13746     // shouldn't be diagnosing.
13747     LookupName(Previous, S);
13748 
13749     // When declaring or defining a tag, ignore ambiguities introduced
13750     // by types using'ed into this scope.
13751     if (Previous.isAmbiguous() &&
13752         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
13753       LookupResult::Filter F = Previous.makeFilter();
13754       while (F.hasNext()) {
13755         NamedDecl *ND = F.next();
13756         if (!ND->getDeclContext()->getRedeclContext()->Equals(
13757                 SearchDC->getRedeclContext()))
13758           F.erase();
13759       }
13760       F.done();
13761     }
13762 
13763     // C++11 [namespace.memdef]p3:
13764     //   If the name in a friend declaration is neither qualified nor
13765     //   a template-id and the declaration is a function or an
13766     //   elaborated-type-specifier, the lookup to determine whether
13767     //   the entity has been previously declared shall not consider
13768     //   any scopes outside the innermost enclosing namespace.
13769     //
13770     // MSVC doesn't implement the above rule for types, so a friend tag
13771     // declaration may be a redeclaration of a type declared in an enclosing
13772     // scope.  They do implement this rule for friend functions.
13773     //
13774     // Does it matter that this should be by scope instead of by
13775     // semantic context?
13776     if (!Previous.empty() && TUK == TUK_Friend) {
13777       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
13778       LookupResult::Filter F = Previous.makeFilter();
13779       bool FriendSawTagOutsideEnclosingNamespace = false;
13780       while (F.hasNext()) {
13781         NamedDecl *ND = F.next();
13782         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13783         if (DC->isFileContext() &&
13784             !EnclosingNS->Encloses(ND->getDeclContext())) {
13785           if (getLangOpts().MSVCCompat)
13786             FriendSawTagOutsideEnclosingNamespace = true;
13787           else
13788             F.erase();
13789         }
13790       }
13791       F.done();
13792 
13793       // Diagnose this MSVC extension in the easy case where lookup would have
13794       // unambiguously found something outside the enclosing namespace.
13795       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
13796         NamedDecl *ND = Previous.getFoundDecl();
13797         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
13798             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
13799       }
13800     }
13801 
13802     // Note:  there used to be some attempt at recovery here.
13803     if (Previous.isAmbiguous())
13804       return nullptr;
13805 
13806     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
13807       // FIXME: This makes sure that we ignore the contexts associated
13808       // with C structs, unions, and enums when looking for a matching
13809       // tag declaration or definition. See the similar lookup tweak
13810       // in Sema::LookupName; is there a better way to deal with this?
13811       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
13812         SearchDC = SearchDC->getParent();
13813     }
13814   }
13815 
13816   if (Previous.isSingleResult() &&
13817       Previous.getFoundDecl()->isTemplateParameter()) {
13818     // Maybe we will complain about the shadowed template parameter.
13819     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
13820     // Just pretend that we didn't see the previous declaration.
13821     Previous.clear();
13822   }
13823 
13824   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
13825       DC->Equals(getStdNamespace())) {
13826     if (Name->isStr("bad_alloc")) {
13827       // This is a declaration of or a reference to "std::bad_alloc".
13828       isStdBadAlloc = true;
13829 
13830       // If std::bad_alloc has been implicitly declared (but made invisible to
13831       // name lookup), fill in this implicit declaration as the previous
13832       // declaration, so that the declarations get chained appropriately.
13833       if (Previous.empty() && StdBadAlloc)
13834         Previous.addDecl(getStdBadAlloc());
13835     } else if (Name->isStr("align_val_t")) {
13836       isStdAlignValT = true;
13837       if (Previous.empty() && StdAlignValT)
13838         Previous.addDecl(getStdAlignValT());
13839     }
13840   }
13841 
13842   // If we didn't find a previous declaration, and this is a reference
13843   // (or friend reference), move to the correct scope.  In C++, we
13844   // also need to do a redeclaration lookup there, just in case
13845   // there's a shadow friend decl.
13846   if (Name && Previous.empty() &&
13847       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
13848     if (Invalid) goto CreateNewDecl;
13849     assert(SS.isEmpty());
13850 
13851     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
13852       // C++ [basic.scope.pdecl]p5:
13853       //   -- for an elaborated-type-specifier of the form
13854       //
13855       //          class-key identifier
13856       //
13857       //      if the elaborated-type-specifier is used in the
13858       //      decl-specifier-seq or parameter-declaration-clause of a
13859       //      function defined in namespace scope, the identifier is
13860       //      declared as a class-name in the namespace that contains
13861       //      the declaration; otherwise, except as a friend
13862       //      declaration, the identifier is declared in the smallest
13863       //      non-class, non-function-prototype scope that contains the
13864       //      declaration.
13865       //
13866       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
13867       // C structs and unions.
13868       //
13869       // It is an error in C++ to declare (rather than define) an enum
13870       // type, including via an elaborated type specifier.  We'll
13871       // diagnose that later; for now, declare the enum in the same
13872       // scope as we would have picked for any other tag type.
13873       //
13874       // GNU C also supports this behavior as part of its incomplete
13875       // enum types extension, while GNU C++ does not.
13876       //
13877       // Find the context where we'll be declaring the tag.
13878       // FIXME: We would like to maintain the current DeclContext as the
13879       // lexical context,
13880       SearchDC = getTagInjectionContext(SearchDC);
13881 
13882       // Find the scope where we'll be declaring the tag.
13883       S = getTagInjectionScope(S, getLangOpts());
13884     } else {
13885       assert(TUK == TUK_Friend);
13886       // C++ [namespace.memdef]p3:
13887       //   If a friend declaration in a non-local class first declares a
13888       //   class or function, the friend class or function is a member of
13889       //   the innermost enclosing namespace.
13890       SearchDC = SearchDC->getEnclosingNamespaceContext();
13891     }
13892 
13893     // In C++, we need to do a redeclaration lookup to properly
13894     // diagnose some problems.
13895     // FIXME: redeclaration lookup is also used (with and without C++) to find a
13896     // hidden declaration so that we don't get ambiguity errors when using a
13897     // type declared by an elaborated-type-specifier.  In C that is not correct
13898     // and we should instead merge compatible types found by lookup.
13899     if (getLangOpts().CPlusPlus) {
13900       Previous.setRedeclarationKind(forRedeclarationInCurContext());
13901       LookupQualifiedName(Previous, SearchDC);
13902     } else {
13903       Previous.setRedeclarationKind(forRedeclarationInCurContext());
13904       LookupName(Previous, S);
13905     }
13906   }
13907 
13908   // If we have a known previous declaration to use, then use it.
13909   if (Previous.empty() && SkipBody && SkipBody->Previous)
13910     Previous.addDecl(SkipBody->Previous);
13911 
13912   if (!Previous.empty()) {
13913     NamedDecl *PrevDecl = Previous.getFoundDecl();
13914     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13915 
13916     // It's okay to have a tag decl in the same scope as a typedef
13917     // which hides a tag decl in the same scope.  Finding this
13918     // insanity with a redeclaration lookup can only actually happen
13919     // in C++.
13920     //
13921     // This is also okay for elaborated-type-specifiers, which is
13922     // technically forbidden by the current standard but which is
13923     // okay according to the likely resolution of an open issue;
13924     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13925     if (getLangOpts().CPlusPlus) {
13926       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13927         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13928           TagDecl *Tag = TT->getDecl();
13929           if (Tag->getDeclName() == Name &&
13930               Tag->getDeclContext()->getRedeclContext()
13931                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
13932             PrevDecl = Tag;
13933             Previous.clear();
13934             Previous.addDecl(Tag);
13935             Previous.resolveKind();
13936           }
13937         }
13938       }
13939     }
13940 
13941     // If this is a redeclaration of a using shadow declaration, it must
13942     // declare a tag in the same context. In MSVC mode, we allow a
13943     // redefinition if either context is within the other.
13944     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13945       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13946       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13947           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
13948           !(OldTag && isAcceptableTagRedeclContext(
13949                           *this, OldTag->getDeclContext(), SearchDC))) {
13950         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13951         Diag(Shadow->getTargetDecl()->getLocation(),
13952              diag::note_using_decl_target);
13953         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13954             << 0;
13955         // Recover by ignoring the old declaration.
13956         Previous.clear();
13957         goto CreateNewDecl;
13958       }
13959     }
13960 
13961     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13962       // If this is a use of a previous tag, or if the tag is already declared
13963       // in the same scope (so that the definition/declaration completes or
13964       // rementions the tag), reuse the decl.
13965       if (TUK == TUK_Reference || TUK == TUK_Friend ||
13966           isDeclInScope(DirectPrevDecl, SearchDC, S,
13967                         SS.isNotEmpty() || isMemberSpecialization)) {
13968         // Make sure that this wasn't declared as an enum and now used as a
13969         // struct or something similar.
13970         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13971                                           TUK == TUK_Definition, KWLoc,
13972                                           Name)) {
13973           bool SafeToContinue
13974             = (PrevTagDecl->getTagKind() != TTK_Enum &&
13975                Kind != TTK_Enum);
13976           if (SafeToContinue)
13977             Diag(KWLoc, diag::err_use_with_wrong_tag)
13978               << Name
13979               << FixItHint::CreateReplacement(SourceRange(KWLoc),
13980                                               PrevTagDecl->getKindName());
13981           else
13982             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13983           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13984 
13985           if (SafeToContinue)
13986             Kind = PrevTagDecl->getTagKind();
13987           else {
13988             // Recover by making this an anonymous redefinition.
13989             Name = nullptr;
13990             Previous.clear();
13991             Invalid = true;
13992           }
13993         }
13994 
13995         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
13996           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
13997 
13998           // If this is an elaborated-type-specifier for a scoped enumeration,
13999           // the 'class' keyword is not necessary and not permitted.
14000           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14001             if (ScopedEnum)
14002               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
14003                 << PrevEnum->isScoped()
14004                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
14005             return PrevTagDecl;
14006           }
14007 
14008           QualType EnumUnderlyingTy;
14009           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14010             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
14011           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
14012             EnumUnderlyingTy = QualType(T, 0);
14013 
14014           // All conflicts with previous declarations are recovered by
14015           // returning the previous declaration, unless this is a definition,
14016           // in which case we want the caller to bail out.
14017           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
14018                                      ScopedEnum, EnumUnderlyingTy,
14019                                      IsFixed, PrevEnum))
14020             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
14021         }
14022 
14023         // C++11 [class.mem]p1:
14024         //   A member shall not be declared twice in the member-specification,
14025         //   except that a nested class or member class template can be declared
14026         //   and then later defined.
14027         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
14028             S->isDeclScope(PrevDecl)) {
14029           Diag(NameLoc, diag::ext_member_redeclared);
14030           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
14031         }
14032 
14033         if (!Invalid) {
14034           // If this is a use, just return the declaration we found, unless
14035           // we have attributes.
14036           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14037             if (Attr) {
14038               // FIXME: Diagnose these attributes. For now, we create a new
14039               // declaration to hold them.
14040             } else if (TUK == TUK_Reference &&
14041                        (PrevTagDecl->getFriendObjectKind() ==
14042                             Decl::FOK_Undeclared ||
14043                         PrevDecl->getOwningModule() != getCurrentModule()) &&
14044                        SS.isEmpty()) {
14045               // This declaration is a reference to an existing entity, but
14046               // has different visibility from that entity: it either makes
14047               // a friend visible or it makes a type visible in a new module.
14048               // In either case, create a new declaration. We only do this if
14049               // the declaration would have meant the same thing if no prior
14050               // declaration were found, that is, if it was found in the same
14051               // scope where we would have injected a declaration.
14052               if (!getTagInjectionContext(CurContext)->getRedeclContext()
14053                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
14054                 return PrevTagDecl;
14055               // This is in the injected scope, create a new declaration in
14056               // that scope.
14057               S = getTagInjectionScope(S, getLangOpts());
14058             } else {
14059               return PrevTagDecl;
14060             }
14061           }
14062 
14063           // Diagnose attempts to redefine a tag.
14064           if (TUK == TUK_Definition) {
14065             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
14066               // If we're defining a specialization and the previous definition
14067               // is from an implicit instantiation, don't emit an error
14068               // here; we'll catch this in the general case below.
14069               bool IsExplicitSpecializationAfterInstantiation = false;
14070               if (isMemberSpecialization) {
14071                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
14072                   IsExplicitSpecializationAfterInstantiation =
14073                     RD->getTemplateSpecializationKind() !=
14074                     TSK_ExplicitSpecialization;
14075                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
14076                   IsExplicitSpecializationAfterInstantiation =
14077                     ED->getTemplateSpecializationKind() !=
14078                     TSK_ExplicitSpecialization;
14079               }
14080 
14081               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
14082               // not keep more that one definition around (merge them). However,
14083               // ensure the decl passes the structural compatibility check in
14084               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
14085               NamedDecl *Hidden = nullptr;
14086               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
14087                 // There is a definition of this tag, but it is not visible. We
14088                 // explicitly make use of C++'s one definition rule here, and
14089                 // assume that this definition is identical to the hidden one
14090                 // we already have. Make the existing definition visible and
14091                 // use it in place of this one.
14092                 if (!getLangOpts().CPlusPlus) {
14093                   // Postpone making the old definition visible until after we
14094                   // complete parsing the new one and do the structural
14095                   // comparison.
14096                   SkipBody->CheckSameAsPrevious = true;
14097                   SkipBody->New = createTagFromNewDecl();
14098                   SkipBody->Previous = Hidden;
14099                 } else {
14100                   SkipBody->ShouldSkip = true;
14101                   makeMergedDefinitionVisible(Hidden);
14102                 }
14103                 return Def;
14104               } else if (!IsExplicitSpecializationAfterInstantiation) {
14105                 // A redeclaration in function prototype scope in C isn't
14106                 // visible elsewhere, so merely issue a warning.
14107                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
14108                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
14109                 else
14110                   Diag(NameLoc, diag::err_redefinition) << Name;
14111                 notePreviousDefinition(Def,
14112                                        NameLoc.isValid() ? NameLoc : KWLoc);
14113                 // If this is a redefinition, recover by making this
14114                 // struct be anonymous, which will make any later
14115                 // references get the previous definition.
14116                 Name = nullptr;
14117                 Previous.clear();
14118                 Invalid = true;
14119               }
14120             } else {
14121               // If the type is currently being defined, complain
14122               // about a nested redefinition.
14123               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
14124               if (TD->isBeingDefined()) {
14125                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
14126                 Diag(PrevTagDecl->getLocation(),
14127                      diag::note_previous_definition);
14128                 Name = nullptr;
14129                 Previous.clear();
14130                 Invalid = true;
14131               }
14132             }
14133 
14134             // Okay, this is definition of a previously declared or referenced
14135             // tag. We're going to create a new Decl for it.
14136           }
14137 
14138           // Okay, we're going to make a redeclaration.  If this is some kind
14139           // of reference, make sure we build the redeclaration in the same DC
14140           // as the original, and ignore the current access specifier.
14141           if (TUK == TUK_Friend || TUK == TUK_Reference) {
14142             SearchDC = PrevTagDecl->getDeclContext();
14143             AS = AS_none;
14144           }
14145         }
14146         // If we get here we have (another) forward declaration or we
14147         // have a definition.  Just create a new decl.
14148 
14149       } else {
14150         // If we get here, this is a definition of a new tag type in a nested
14151         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
14152         // new decl/type.  We set PrevDecl to NULL so that the entities
14153         // have distinct types.
14154         Previous.clear();
14155       }
14156       // If we get here, we're going to create a new Decl. If PrevDecl
14157       // is non-NULL, it's a definition of the tag declared by
14158       // PrevDecl. If it's NULL, we have a new definition.
14159 
14160     // Otherwise, PrevDecl is not a tag, but was found with tag
14161     // lookup.  This is only actually possible in C++, where a few
14162     // things like templates still live in the tag namespace.
14163     } else {
14164       // Use a better diagnostic if an elaborated-type-specifier
14165       // found the wrong kind of type on the first
14166       // (non-redeclaration) lookup.
14167       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
14168           !Previous.isForRedeclaration()) {
14169         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14170         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
14171                                                        << Kind;
14172         Diag(PrevDecl->getLocation(), diag::note_declared_at);
14173         Invalid = true;
14174 
14175       // Otherwise, only diagnose if the declaration is in scope.
14176       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
14177                                 SS.isNotEmpty() || isMemberSpecialization)) {
14178         // do nothing
14179 
14180       // Diagnose implicit declarations introduced by elaborated types.
14181       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
14182         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14183         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
14184         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14185         Invalid = true;
14186 
14187       // Otherwise it's a declaration.  Call out a particularly common
14188       // case here.
14189       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14190         unsigned Kind = 0;
14191         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
14192         Diag(NameLoc, diag::err_tag_definition_of_typedef)
14193           << Name << Kind << TND->getUnderlyingType();
14194         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14195         Invalid = true;
14196 
14197       // Otherwise, diagnose.
14198       } else {
14199         // The tag name clashes with something else in the target scope,
14200         // issue an error and recover by making this tag be anonymous.
14201         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
14202         notePreviousDefinition(PrevDecl, NameLoc);
14203         Name = nullptr;
14204         Invalid = true;
14205       }
14206 
14207       // The existing declaration isn't relevant to us; we're in a
14208       // new scope, so clear out the previous declaration.
14209       Previous.clear();
14210     }
14211   }
14212 
14213 CreateNewDecl:
14214 
14215   TagDecl *PrevDecl = nullptr;
14216   if (Previous.isSingleResult())
14217     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
14218 
14219   // If there is an identifier, use the location of the identifier as the
14220   // location of the decl, otherwise use the location of the struct/union
14221   // keyword.
14222   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14223 
14224   // Otherwise, create a new declaration. If there is a previous
14225   // declaration of the same entity, the two will be linked via
14226   // PrevDecl.
14227   TagDecl *New;
14228 
14229   bool IsForwardReference = false;
14230   if (Kind == TTK_Enum) {
14231     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14232     // enum X { A, B, C } D;    D should chain to X.
14233     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
14234                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
14235                            ScopedEnumUsesClassTag, IsFixed);
14236 
14237     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
14238       StdAlignValT = cast<EnumDecl>(New);
14239 
14240     // If this is an undefined enum, warn.
14241     if (TUK != TUK_Definition && !Invalid) {
14242       TagDecl *Def;
14243       if (IsFixed && (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
14244           cast<EnumDecl>(New)->isFixed()) {
14245         // C++0x: 7.2p2: opaque-enum-declaration.
14246         // Conflicts are diagnosed above. Do nothing.
14247       }
14248       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
14249         Diag(Loc, diag::ext_forward_ref_enum_def)
14250           << New;
14251         Diag(Def->getLocation(), diag::note_previous_definition);
14252       } else {
14253         unsigned DiagID = diag::ext_forward_ref_enum;
14254         if (getLangOpts().MSVCCompat)
14255           DiagID = diag::ext_ms_forward_ref_enum;
14256         else if (getLangOpts().CPlusPlus)
14257           DiagID = diag::err_forward_ref_enum;
14258         Diag(Loc, DiagID);
14259 
14260         // If this is a forward-declared reference to an enumeration, make a
14261         // note of it; we won't actually be introducing the declaration into
14262         // the declaration context.
14263         if (TUK == TUK_Reference)
14264           IsForwardReference = true;
14265       }
14266     }
14267 
14268     if (EnumUnderlying) {
14269       EnumDecl *ED = cast<EnumDecl>(New);
14270       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14271         ED->setIntegerTypeSourceInfo(TI);
14272       else
14273         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
14274       ED->setPromotionType(ED->getIntegerType());
14275       assert(ED->isComplete() && "enum with type should be complete");
14276     }
14277   } else {
14278     // struct/union/class
14279 
14280     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14281     // struct X { int A; } D;    D should chain to X.
14282     if (getLangOpts().CPlusPlus) {
14283       // FIXME: Look for a way to use RecordDecl for simple structs.
14284       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14285                                   cast_or_null<CXXRecordDecl>(PrevDecl));
14286 
14287       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
14288         StdBadAlloc = cast<CXXRecordDecl>(New);
14289     } else
14290       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14291                                cast_or_null<RecordDecl>(PrevDecl));
14292   }
14293 
14294   // C++11 [dcl.type]p3:
14295   //   A type-specifier-seq shall not define a class or enumeration [...].
14296   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
14297       TUK == TUK_Definition) {
14298     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
14299       << Context.getTagDeclType(New);
14300     Invalid = true;
14301   }
14302 
14303   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
14304       DC->getDeclKind() == Decl::Enum) {
14305     Diag(New->getLocation(), diag::err_type_defined_in_enum)
14306       << Context.getTagDeclType(New);
14307     Invalid = true;
14308   }
14309 
14310   // Maybe add qualifier info.
14311   if (SS.isNotEmpty()) {
14312     if (SS.isSet()) {
14313       // If this is either a declaration or a definition, check the
14314       // nested-name-specifier against the current context.
14315       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
14316           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
14317                                        isMemberSpecialization))
14318         Invalid = true;
14319 
14320       New->setQualifierInfo(SS.getWithLocInContext(Context));
14321       if (TemplateParameterLists.size() > 0) {
14322         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
14323       }
14324     }
14325     else
14326       Invalid = true;
14327   }
14328 
14329   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14330     // Add alignment attributes if necessary; these attributes are checked when
14331     // the ASTContext lays out the structure.
14332     //
14333     // It is important for implementing the correct semantics that this
14334     // happen here (in ActOnTag). The #pragma pack stack is
14335     // maintained as a result of parser callbacks which can occur at
14336     // many points during the parsing of a struct declaration (because
14337     // the #pragma tokens are effectively skipped over during the
14338     // parsing of the struct).
14339     if (TUK == TUK_Definition) {
14340       AddAlignmentAttributesForRecord(RD);
14341       AddMsStructLayoutForRecord(RD);
14342     }
14343   }
14344 
14345   if (ModulePrivateLoc.isValid()) {
14346     if (isMemberSpecialization)
14347       Diag(New->getLocation(), diag::err_module_private_specialization)
14348         << 2
14349         << FixItHint::CreateRemoval(ModulePrivateLoc);
14350     // __module_private__ does not apply to local classes. However, we only
14351     // diagnose this as an error when the declaration specifiers are
14352     // freestanding. Here, we just ignore the __module_private__.
14353     else if (!SearchDC->isFunctionOrMethod())
14354       New->setModulePrivate();
14355   }
14356 
14357   // If this is a specialization of a member class (of a class template),
14358   // check the specialization.
14359   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
14360     Invalid = true;
14361 
14362   // If we're declaring or defining a tag in function prototype scope in C,
14363   // note that this type can only be used within the function and add it to
14364   // the list of decls to inject into the function definition scope.
14365   if ((Name || Kind == TTK_Enum) &&
14366       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
14367     if (getLangOpts().CPlusPlus) {
14368       // C++ [dcl.fct]p6:
14369       //   Types shall not be defined in return or parameter types.
14370       if (TUK == TUK_Definition && !IsTypeSpecifier) {
14371         Diag(Loc, diag::err_type_defined_in_param_type)
14372             << Name;
14373         Invalid = true;
14374       }
14375     } else if (!PrevDecl) {
14376       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
14377     }
14378   }
14379 
14380   if (Invalid)
14381     New->setInvalidDecl();
14382 
14383   // Set the lexical context. If the tag has a C++ scope specifier, the
14384   // lexical context will be different from the semantic context.
14385   New->setLexicalDeclContext(CurContext);
14386 
14387   // Mark this as a friend decl if applicable.
14388   // In Microsoft mode, a friend declaration also acts as a forward
14389   // declaration so we always pass true to setObjectOfFriendDecl to make
14390   // the tag name visible.
14391   if (TUK == TUK_Friend)
14392     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
14393 
14394   // Set the access specifier.
14395   if (!Invalid && SearchDC->isRecord())
14396     SetMemberAccessSpecifier(New, PrevDecl, AS);
14397 
14398   if (PrevDecl)
14399     CheckRedeclarationModuleOwnership(New, PrevDecl);
14400 
14401   if (TUK == TUK_Definition)
14402     New->startDefinition();
14403 
14404   if (Attr)
14405     ProcessDeclAttributeList(S, New, Attr);
14406   AddPragmaAttributes(S, New);
14407 
14408   // If this has an identifier, add it to the scope stack.
14409   if (TUK == TUK_Friend) {
14410     // We might be replacing an existing declaration in the lookup tables;
14411     // if so, borrow its access specifier.
14412     if (PrevDecl)
14413       New->setAccess(PrevDecl->getAccess());
14414 
14415     DeclContext *DC = New->getDeclContext()->getRedeclContext();
14416     DC->makeDeclVisibleInContext(New);
14417     if (Name) // can be null along some error paths
14418       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14419         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
14420   } else if (Name) {
14421     S = getNonFieldDeclScope(S);
14422     PushOnScopeChains(New, S, !IsForwardReference);
14423     if (IsForwardReference)
14424       SearchDC->makeDeclVisibleInContext(New);
14425   } else {
14426     CurContext->addDecl(New);
14427   }
14428 
14429   // If this is the C FILE type, notify the AST context.
14430   if (IdentifierInfo *II = New->getIdentifier())
14431     if (!New->isInvalidDecl() &&
14432         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
14433         II->isStr("FILE"))
14434       Context.setFILEDecl(New);
14435 
14436   if (PrevDecl)
14437     mergeDeclAttributes(New, PrevDecl);
14438 
14439   // If there's a #pragma GCC visibility in scope, set the visibility of this
14440   // record.
14441   AddPushedVisibilityAttribute(New);
14442 
14443   if (isMemberSpecialization && !New->isInvalidDecl())
14444     CompleteMemberSpecialization(New, Previous);
14445 
14446   OwnedDecl = true;
14447   // In C++, don't return an invalid declaration. We can't recover well from
14448   // the cases where we make the type anonymous.
14449   if (Invalid && getLangOpts().CPlusPlus) {
14450     if (New->isBeingDefined())
14451       if (auto RD = dyn_cast<RecordDecl>(New))
14452         RD->completeDefinition();
14453     return nullptr;
14454   } else {
14455     return New;
14456   }
14457 }
14458 
14459 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
14460   AdjustDeclIfTemplate(TagD);
14461   TagDecl *Tag = cast<TagDecl>(TagD);
14462 
14463   // Enter the tag context.
14464   PushDeclContext(S, Tag);
14465 
14466   ActOnDocumentableDecl(TagD);
14467 
14468   // If there's a #pragma GCC visibility in scope, set the visibility of this
14469   // record.
14470   AddPushedVisibilityAttribute(Tag);
14471 }
14472 
14473 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
14474                                     SkipBodyInfo &SkipBody) {
14475   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
14476     return false;
14477 
14478   // Make the previous decl visible.
14479   makeMergedDefinitionVisible(SkipBody.Previous);
14480   return true;
14481 }
14482 
14483 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
14484   assert(isa<ObjCContainerDecl>(IDecl) &&
14485          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
14486   DeclContext *OCD = cast<DeclContext>(IDecl);
14487   assert(getContainingDC(OCD) == CurContext &&
14488       "The next DeclContext should be lexically contained in the current one.");
14489   CurContext = OCD;
14490   return IDecl;
14491 }
14492 
14493 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
14494                                            SourceLocation FinalLoc,
14495                                            bool IsFinalSpelledSealed,
14496                                            SourceLocation LBraceLoc) {
14497   AdjustDeclIfTemplate(TagD);
14498   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
14499 
14500   FieldCollector->StartClass();
14501 
14502   if (!Record->getIdentifier())
14503     return;
14504 
14505   if (FinalLoc.isValid())
14506     Record->addAttr(new (Context)
14507                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
14508 
14509   // C++ [class]p2:
14510   //   [...] The class-name is also inserted into the scope of the
14511   //   class itself; this is known as the injected-class-name. For
14512   //   purposes of access checking, the injected-class-name is treated
14513   //   as if it were a public member name.
14514   CXXRecordDecl *InjectedClassName
14515     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
14516                             Record->getLocStart(), Record->getLocation(),
14517                             Record->getIdentifier(),
14518                             /*PrevDecl=*/nullptr,
14519                             /*DelayTypeCreation=*/true);
14520   Context.getTypeDeclType(InjectedClassName, Record);
14521   InjectedClassName->setImplicit();
14522   InjectedClassName->setAccess(AS_public);
14523   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
14524       InjectedClassName->setDescribedClassTemplate(Template);
14525   PushOnScopeChains(InjectedClassName, S);
14526   assert(InjectedClassName->isInjectedClassName() &&
14527          "Broken injected-class-name");
14528 }
14529 
14530 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
14531                                     SourceRange BraceRange) {
14532   AdjustDeclIfTemplate(TagD);
14533   TagDecl *Tag = cast<TagDecl>(TagD);
14534   Tag->setBraceRange(BraceRange);
14535 
14536   // Make sure we "complete" the definition even it is invalid.
14537   if (Tag->isBeingDefined()) {
14538     assert(Tag->isInvalidDecl() && "We should already have completed it");
14539     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14540       RD->completeDefinition();
14541   }
14542 
14543   if (isa<CXXRecordDecl>(Tag)) {
14544     FieldCollector->FinishClass();
14545   }
14546 
14547   // Exit this scope of this tag's definition.
14548   PopDeclContext();
14549 
14550   if (getCurLexicalContext()->isObjCContainer() &&
14551       Tag->getDeclContext()->isFileContext())
14552     Tag->setTopLevelDeclInObjCContainer();
14553 
14554   // Notify the consumer that we've defined a tag.
14555   if (!Tag->isInvalidDecl())
14556     Consumer.HandleTagDeclDefinition(Tag);
14557 }
14558 
14559 void Sema::ActOnObjCContainerFinishDefinition() {
14560   // Exit this scope of this interface definition.
14561   PopDeclContext();
14562 }
14563 
14564 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
14565   assert(DC == CurContext && "Mismatch of container contexts");
14566   OriginalLexicalContext = DC;
14567   ActOnObjCContainerFinishDefinition();
14568 }
14569 
14570 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
14571   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
14572   OriginalLexicalContext = nullptr;
14573 }
14574 
14575 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
14576   AdjustDeclIfTemplate(TagD);
14577   TagDecl *Tag = cast<TagDecl>(TagD);
14578   Tag->setInvalidDecl();
14579 
14580   // Make sure we "complete" the definition even it is invalid.
14581   if (Tag->isBeingDefined()) {
14582     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14583       RD->completeDefinition();
14584   }
14585 
14586   // We're undoing ActOnTagStartDefinition here, not
14587   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
14588   // the FieldCollector.
14589 
14590   PopDeclContext();
14591 }
14592 
14593 // Note that FieldName may be null for anonymous bitfields.
14594 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
14595                                 IdentifierInfo *FieldName,
14596                                 QualType FieldTy, bool IsMsStruct,
14597                                 Expr *BitWidth, bool *ZeroWidth) {
14598   // Default to true; that shouldn't confuse checks for emptiness
14599   if (ZeroWidth)
14600     *ZeroWidth = true;
14601 
14602   // C99 6.7.2.1p4 - verify the field type.
14603   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
14604   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
14605     // Handle incomplete types with specific error.
14606     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
14607       return ExprError();
14608     if (FieldName)
14609       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
14610         << FieldName << FieldTy << BitWidth->getSourceRange();
14611     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
14612       << FieldTy << BitWidth->getSourceRange();
14613   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
14614                                              UPPC_BitFieldWidth))
14615     return ExprError();
14616 
14617   // If the bit-width is type- or value-dependent, don't try to check
14618   // it now.
14619   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
14620     return BitWidth;
14621 
14622   llvm::APSInt Value;
14623   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
14624   if (ICE.isInvalid())
14625     return ICE;
14626   BitWidth = ICE.get();
14627 
14628   if (Value != 0 && ZeroWidth)
14629     *ZeroWidth = false;
14630 
14631   // Zero-width bitfield is ok for anonymous field.
14632   if (Value == 0 && FieldName)
14633     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
14634 
14635   if (Value.isSigned() && Value.isNegative()) {
14636     if (FieldName)
14637       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
14638                << FieldName << Value.toString(10);
14639     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
14640       << Value.toString(10);
14641   }
14642 
14643   if (!FieldTy->isDependentType()) {
14644     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
14645     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
14646     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
14647 
14648     // Over-wide bitfields are an error in C or when using the MSVC bitfield
14649     // ABI.
14650     bool CStdConstraintViolation =
14651         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
14652     bool MSBitfieldViolation =
14653         Value.ugt(TypeStorageSize) &&
14654         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
14655     if (CStdConstraintViolation || MSBitfieldViolation) {
14656       unsigned DiagWidth =
14657           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
14658       if (FieldName)
14659         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
14660                << FieldName << (unsigned)Value.getZExtValue()
14661                << !CStdConstraintViolation << DiagWidth;
14662 
14663       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
14664              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
14665              << DiagWidth;
14666     }
14667 
14668     // Warn on types where the user might conceivably expect to get all
14669     // specified bits as value bits: that's all integral types other than
14670     // 'bool'.
14671     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
14672       if (FieldName)
14673         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
14674             << FieldName << (unsigned)Value.getZExtValue()
14675             << (unsigned)TypeWidth;
14676       else
14677         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
14678             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
14679     }
14680   }
14681 
14682   return BitWidth;
14683 }
14684 
14685 /// ActOnField - Each field of a C struct/union is passed into this in order
14686 /// to create a FieldDecl object for it.
14687 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
14688                        Declarator &D, Expr *BitfieldWidth) {
14689   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
14690                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
14691                                /*InitStyle=*/ICIS_NoInit, AS_public);
14692   return Res;
14693 }
14694 
14695 /// HandleField - Analyze a field of a C struct or a C++ data member.
14696 ///
14697 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
14698                              SourceLocation DeclStart,
14699                              Declarator &D, Expr *BitWidth,
14700                              InClassInitStyle InitStyle,
14701                              AccessSpecifier AS) {
14702   if (D.isDecompositionDeclarator()) {
14703     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
14704     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
14705       << Decomp.getSourceRange();
14706     return nullptr;
14707   }
14708 
14709   IdentifierInfo *II = D.getIdentifier();
14710   SourceLocation Loc = DeclStart;
14711   if (II) Loc = D.getIdentifierLoc();
14712 
14713   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14714   QualType T = TInfo->getType();
14715   if (getLangOpts().CPlusPlus) {
14716     CheckExtraCXXDefaultArguments(D);
14717 
14718     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14719                                         UPPC_DataMemberType)) {
14720       D.setInvalidType();
14721       T = Context.IntTy;
14722       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14723     }
14724   }
14725 
14726   // TR 18037 does not allow fields to be declared with address spaces.
14727   if (T.getQualifiers().hasAddressSpace() ||
14728       T->isDependentAddressSpaceType() ||
14729       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
14730     Diag(Loc, diag::err_field_with_address_space);
14731     D.setInvalidType();
14732   }
14733 
14734   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
14735   // used as structure or union field: image, sampler, event or block types.
14736   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
14737                           T->isSamplerT() || T->isBlockPointerType())) {
14738     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
14739     D.setInvalidType();
14740   }
14741 
14742   DiagnoseFunctionSpecifiers(D.getDeclSpec());
14743 
14744   if (D.getDeclSpec().isInlineSpecified())
14745     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14746         << getLangOpts().CPlusPlus17;
14747   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14748     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14749          diag::err_invalid_thread)
14750       << DeclSpec::getSpecifierName(TSCS);
14751 
14752   // Check to see if this name was declared as a member previously
14753   NamedDecl *PrevDecl = nullptr;
14754   LookupResult Previous(*this, II, Loc, LookupMemberName,
14755                         ForVisibleRedeclaration);
14756   LookupName(Previous, S);
14757   switch (Previous.getResultKind()) {
14758     case LookupResult::Found:
14759     case LookupResult::FoundUnresolvedValue:
14760       PrevDecl = Previous.getAsSingle<NamedDecl>();
14761       break;
14762 
14763     case LookupResult::FoundOverloaded:
14764       PrevDecl = Previous.getRepresentativeDecl();
14765       break;
14766 
14767     case LookupResult::NotFound:
14768     case LookupResult::NotFoundInCurrentInstantiation:
14769     case LookupResult::Ambiguous:
14770       break;
14771   }
14772   Previous.suppressDiagnostics();
14773 
14774   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14775     // Maybe we will complain about the shadowed template parameter.
14776     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14777     // Just pretend that we didn't see the previous declaration.
14778     PrevDecl = nullptr;
14779   }
14780 
14781   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14782     PrevDecl = nullptr;
14783 
14784   bool Mutable
14785     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
14786   SourceLocation TSSL = D.getLocStart();
14787   FieldDecl *NewFD
14788     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
14789                      TSSL, AS, PrevDecl, &D);
14790 
14791   if (NewFD->isInvalidDecl())
14792     Record->setInvalidDecl();
14793 
14794   if (D.getDeclSpec().isModulePrivateSpecified())
14795     NewFD->setModulePrivate();
14796 
14797   if (NewFD->isInvalidDecl() && PrevDecl) {
14798     // Don't introduce NewFD into scope; there's already something
14799     // with the same name in the same scope.
14800   } else if (II) {
14801     PushOnScopeChains(NewFD, S);
14802   } else
14803     Record->addDecl(NewFD);
14804 
14805   return NewFD;
14806 }
14807 
14808 /// \brief Build a new FieldDecl and check its well-formedness.
14809 ///
14810 /// This routine builds a new FieldDecl given the fields name, type,
14811 /// record, etc. \p PrevDecl should refer to any previous declaration
14812 /// with the same name and in the same scope as the field to be
14813 /// created.
14814 ///
14815 /// \returns a new FieldDecl.
14816 ///
14817 /// \todo The Declarator argument is a hack. It will be removed once
14818 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
14819                                 TypeSourceInfo *TInfo,
14820                                 RecordDecl *Record, SourceLocation Loc,
14821                                 bool Mutable, Expr *BitWidth,
14822                                 InClassInitStyle InitStyle,
14823                                 SourceLocation TSSL,
14824                                 AccessSpecifier AS, NamedDecl *PrevDecl,
14825                                 Declarator *D) {
14826   IdentifierInfo *II = Name.getAsIdentifierInfo();
14827   bool InvalidDecl = false;
14828   if (D) InvalidDecl = D->isInvalidType();
14829 
14830   // If we receive a broken type, recover by assuming 'int' and
14831   // marking this declaration as invalid.
14832   if (T.isNull()) {
14833     InvalidDecl = true;
14834     T = Context.IntTy;
14835   }
14836 
14837   QualType EltTy = Context.getBaseElementType(T);
14838   if (!EltTy->isDependentType()) {
14839     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
14840       // Fields of incomplete type force their record to be invalid.
14841       Record->setInvalidDecl();
14842       InvalidDecl = true;
14843     } else {
14844       NamedDecl *Def;
14845       EltTy->isIncompleteType(&Def);
14846       if (Def && Def->isInvalidDecl()) {
14847         Record->setInvalidDecl();
14848         InvalidDecl = true;
14849       }
14850     }
14851   }
14852 
14853   // OpenCL v1.2 s6.9.c: bitfields are not supported.
14854   if (BitWidth && getLangOpts().OpenCL) {
14855     Diag(Loc, diag::err_opencl_bitfields);
14856     InvalidDecl = true;
14857   }
14858 
14859   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
14860   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
14861       T.hasQualifiers()) {
14862     InvalidDecl = true;
14863     Diag(Loc, diag::err_anon_bitfield_qualifiers);
14864   }
14865 
14866   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14867   // than a variably modified type.
14868   if (!InvalidDecl && T->isVariablyModifiedType()) {
14869     bool SizeIsNegative;
14870     llvm::APSInt Oversized;
14871 
14872     TypeSourceInfo *FixedTInfo =
14873       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
14874                                                     SizeIsNegative,
14875                                                     Oversized);
14876     if (FixedTInfo) {
14877       Diag(Loc, diag::warn_illegal_constant_array_size);
14878       TInfo = FixedTInfo;
14879       T = FixedTInfo->getType();
14880     } else {
14881       if (SizeIsNegative)
14882         Diag(Loc, diag::err_typecheck_negative_array_size);
14883       else if (Oversized.getBoolValue())
14884         Diag(Loc, diag::err_array_too_large)
14885           << Oversized.toString(10);
14886       else
14887         Diag(Loc, diag::err_typecheck_field_variable_size);
14888       InvalidDecl = true;
14889     }
14890   }
14891 
14892   // Fields can not have abstract class types
14893   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
14894                                              diag::err_abstract_type_in_decl,
14895                                              AbstractFieldType))
14896     InvalidDecl = true;
14897 
14898   bool ZeroWidth = false;
14899   if (InvalidDecl)
14900     BitWidth = nullptr;
14901   // If this is declared as a bit-field, check the bit-field.
14902   if (BitWidth) {
14903     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
14904                               &ZeroWidth).get();
14905     if (!BitWidth) {
14906       InvalidDecl = true;
14907       BitWidth = nullptr;
14908       ZeroWidth = false;
14909     }
14910   }
14911 
14912   // Check that 'mutable' is consistent with the type of the declaration.
14913   if (!InvalidDecl && Mutable) {
14914     unsigned DiagID = 0;
14915     if (T->isReferenceType())
14916       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
14917                                         : diag::err_mutable_reference;
14918     else if (T.isConstQualified())
14919       DiagID = diag::err_mutable_const;
14920 
14921     if (DiagID) {
14922       SourceLocation ErrLoc = Loc;
14923       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
14924         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
14925       Diag(ErrLoc, DiagID);
14926       if (DiagID != diag::ext_mutable_reference) {
14927         Mutable = false;
14928         InvalidDecl = true;
14929       }
14930     }
14931   }
14932 
14933   // C++11 [class.union]p8 (DR1460):
14934   //   At most one variant member of a union may have a
14935   //   brace-or-equal-initializer.
14936   if (InitStyle != ICIS_NoInit)
14937     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14938 
14939   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14940                                        BitWidth, Mutable, InitStyle);
14941   if (InvalidDecl)
14942     NewFD->setInvalidDecl();
14943 
14944   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14945     Diag(Loc, diag::err_duplicate_member) << II;
14946     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14947     NewFD->setInvalidDecl();
14948   }
14949 
14950   if (!InvalidDecl && getLangOpts().CPlusPlus) {
14951     if (Record->isUnion()) {
14952       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14953         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14954         if (RDecl->getDefinition()) {
14955           // C++ [class.union]p1: An object of a class with a non-trivial
14956           // constructor, a non-trivial copy constructor, a non-trivial
14957           // destructor, or a non-trivial copy assignment operator
14958           // cannot be a member of a union, nor can an array of such
14959           // objects.
14960           if (CheckNontrivialField(NewFD))
14961             NewFD->setInvalidDecl();
14962         }
14963       }
14964 
14965       // C++ [class.union]p1: If a union contains a member of reference type,
14966       // the program is ill-formed, except when compiling with MSVC extensions
14967       // enabled.
14968       if (EltTy->isReferenceType()) {
14969         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14970                                     diag::ext_union_member_of_reference_type :
14971                                     diag::err_union_member_of_reference_type)
14972           << NewFD->getDeclName() << EltTy;
14973         if (!getLangOpts().MicrosoftExt)
14974           NewFD->setInvalidDecl();
14975       }
14976     }
14977   }
14978 
14979   // FIXME: We need to pass in the attributes given an AST
14980   // representation, not a parser representation.
14981   if (D) {
14982     // FIXME: The current scope is almost... but not entirely... correct here.
14983     ProcessDeclAttributes(getCurScope(), NewFD, *D);
14984 
14985     if (NewFD->hasAttrs())
14986       CheckAlignasUnderalignment(NewFD);
14987   }
14988 
14989   // In auto-retain/release, infer strong retension for fields of
14990   // retainable type.
14991   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
14992     NewFD->setInvalidDecl();
14993 
14994   if (T.isObjCGCWeak())
14995     Diag(Loc, diag::warn_attribute_weak_on_field);
14996 
14997   NewFD->setAccess(AS);
14998   return NewFD;
14999 }
15000 
15001 bool Sema::CheckNontrivialField(FieldDecl *FD) {
15002   assert(FD);
15003   assert(getLangOpts().CPlusPlus && "valid check only for C++");
15004 
15005   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
15006     return false;
15007 
15008   QualType EltTy = Context.getBaseElementType(FD->getType());
15009   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15010     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
15011     if (RDecl->getDefinition()) {
15012       // We check for copy constructors before constructors
15013       // because otherwise we'll never get complaints about
15014       // copy constructors.
15015 
15016       CXXSpecialMember member = CXXInvalid;
15017       // We're required to check for any non-trivial constructors. Since the
15018       // implicit default constructor is suppressed if there are any
15019       // user-declared constructors, we just need to check that there is a
15020       // trivial default constructor and a trivial copy constructor. (We don't
15021       // worry about move constructors here, since this is a C++98 check.)
15022       if (RDecl->hasNonTrivialCopyConstructor())
15023         member = CXXCopyConstructor;
15024       else if (!RDecl->hasTrivialDefaultConstructor())
15025         member = CXXDefaultConstructor;
15026       else if (RDecl->hasNonTrivialCopyAssignment())
15027         member = CXXCopyAssignment;
15028       else if (RDecl->hasNonTrivialDestructor())
15029         member = CXXDestructor;
15030 
15031       if (member != CXXInvalid) {
15032         if (!getLangOpts().CPlusPlus11 &&
15033             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
15034           // Objective-C++ ARC: it is an error to have a non-trivial field of
15035           // a union. However, system headers in Objective-C programs
15036           // occasionally have Objective-C lifetime objects within unions,
15037           // and rather than cause the program to fail, we make those
15038           // members unavailable.
15039           SourceLocation Loc = FD->getLocation();
15040           if (getSourceManager().isInSystemHeader(Loc)) {
15041             if (!FD->hasAttr<UnavailableAttr>())
15042               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15043                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
15044             return false;
15045           }
15046         }
15047 
15048         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
15049                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
15050                diag::err_illegal_union_or_anon_struct_member)
15051           << FD->getParent()->isUnion() << FD->getDeclName() << member;
15052         DiagnoseNontrivial(RDecl, member);
15053         return !getLangOpts().CPlusPlus11;
15054       }
15055     }
15056   }
15057 
15058   return false;
15059 }
15060 
15061 /// TranslateIvarVisibility - Translate visibility from a token ID to an
15062 ///  AST enum value.
15063 static ObjCIvarDecl::AccessControl
15064 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
15065   switch (ivarVisibility) {
15066   default: llvm_unreachable("Unknown visitibility kind");
15067   case tok::objc_private: return ObjCIvarDecl::Private;
15068   case tok::objc_public: return ObjCIvarDecl::Public;
15069   case tok::objc_protected: return ObjCIvarDecl::Protected;
15070   case tok::objc_package: return ObjCIvarDecl::Package;
15071   }
15072 }
15073 
15074 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
15075 /// in order to create an IvarDecl object for it.
15076 Decl *Sema::ActOnIvar(Scope *S,
15077                                 SourceLocation DeclStart,
15078                                 Declarator &D, Expr *BitfieldWidth,
15079                                 tok::ObjCKeywordKind Visibility) {
15080 
15081   IdentifierInfo *II = D.getIdentifier();
15082   Expr *BitWidth = (Expr*)BitfieldWidth;
15083   SourceLocation Loc = DeclStart;
15084   if (II) Loc = D.getIdentifierLoc();
15085 
15086   // FIXME: Unnamed fields can be handled in various different ways, for
15087   // example, unnamed unions inject all members into the struct namespace!
15088 
15089   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15090   QualType T = TInfo->getType();
15091 
15092   if (BitWidth) {
15093     // 6.7.2.1p3, 6.7.2.1p4
15094     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
15095     if (!BitWidth)
15096       D.setInvalidType();
15097   } else {
15098     // Not a bitfield.
15099 
15100     // validate II.
15101 
15102   }
15103   if (T->isReferenceType()) {
15104     Diag(Loc, diag::err_ivar_reference_type);
15105     D.setInvalidType();
15106   }
15107   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15108   // than a variably modified type.
15109   else if (T->isVariablyModifiedType()) {
15110     Diag(Loc, diag::err_typecheck_ivar_variable_size);
15111     D.setInvalidType();
15112   }
15113 
15114   // Get the visibility (access control) for this ivar.
15115   ObjCIvarDecl::AccessControl ac =
15116     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
15117                                         : ObjCIvarDecl::None;
15118   // Must set ivar's DeclContext to its enclosing interface.
15119   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
15120   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
15121     return nullptr;
15122   ObjCContainerDecl *EnclosingContext;
15123   if (ObjCImplementationDecl *IMPDecl =
15124       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15125     if (LangOpts.ObjCRuntime.isFragile()) {
15126     // Case of ivar declared in an implementation. Context is that of its class.
15127       EnclosingContext = IMPDecl->getClassInterface();
15128       assert(EnclosingContext && "Implementation has no class interface!");
15129     }
15130     else
15131       EnclosingContext = EnclosingDecl;
15132   } else {
15133     if (ObjCCategoryDecl *CDecl =
15134         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15135       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
15136         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
15137         return nullptr;
15138       }
15139     }
15140     EnclosingContext = EnclosingDecl;
15141   }
15142 
15143   // Construct the decl.
15144   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
15145                                              DeclStart, Loc, II, T,
15146                                              TInfo, ac, (Expr *)BitfieldWidth);
15147 
15148   if (II) {
15149     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
15150                                            ForVisibleRedeclaration);
15151     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
15152         && !isa<TagDecl>(PrevDecl)) {
15153       Diag(Loc, diag::err_duplicate_member) << II;
15154       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15155       NewID->setInvalidDecl();
15156     }
15157   }
15158 
15159   // Process attributes attached to the ivar.
15160   ProcessDeclAttributes(S, NewID, D);
15161 
15162   if (D.isInvalidType())
15163     NewID->setInvalidDecl();
15164 
15165   // In ARC, infer 'retaining' for ivars of retainable type.
15166   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
15167     NewID->setInvalidDecl();
15168 
15169   if (D.getDeclSpec().isModulePrivateSpecified())
15170     NewID->setModulePrivate();
15171 
15172   if (II) {
15173     // FIXME: When interfaces are DeclContexts, we'll need to add
15174     // these to the interface.
15175     S->AddDecl(NewID);
15176     IdResolver.AddDecl(NewID);
15177   }
15178 
15179   if (LangOpts.ObjCRuntime.isNonFragile() &&
15180       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
15181     Diag(Loc, diag::warn_ivars_in_interface);
15182 
15183   return NewID;
15184 }
15185 
15186 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
15187 /// class and class extensions. For every class \@interface and class
15188 /// extension \@interface, if the last ivar is a bitfield of any type,
15189 /// then add an implicit `char :0` ivar to the end of that interface.
15190 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
15191                              SmallVectorImpl<Decl *> &AllIvarDecls) {
15192   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
15193     return;
15194 
15195   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
15196   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
15197 
15198   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
15199     return;
15200   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
15201   if (!ID) {
15202     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
15203       if (!CD->IsClassExtension())
15204         return;
15205     }
15206     // No need to add this to end of @implementation.
15207     else
15208       return;
15209   }
15210   // All conditions are met. Add a new bitfield to the tail end of ivars.
15211   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
15212   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
15213 
15214   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
15215                               DeclLoc, DeclLoc, nullptr,
15216                               Context.CharTy,
15217                               Context.getTrivialTypeSourceInfo(Context.CharTy,
15218                                                                DeclLoc),
15219                               ObjCIvarDecl::Private, BW,
15220                               true);
15221   AllIvarDecls.push_back(Ivar);
15222 }
15223 
15224 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
15225                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
15226                        SourceLocation RBrac, AttributeList *Attr) {
15227   assert(EnclosingDecl && "missing record or interface decl");
15228 
15229   // If this is an Objective-C @implementation or category and we have
15230   // new fields here we should reset the layout of the interface since
15231   // it will now change.
15232   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
15233     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
15234     switch (DC->getKind()) {
15235     default: break;
15236     case Decl::ObjCCategory:
15237       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
15238       break;
15239     case Decl::ObjCImplementation:
15240       Context.
15241         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
15242       break;
15243     }
15244   }
15245 
15246   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
15247 
15248   // Start counting up the number of named members; make sure to include
15249   // members of anonymous structs and unions in the total.
15250   unsigned NumNamedMembers = 0;
15251   if (Record) {
15252     for (const auto *I : Record->decls()) {
15253       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
15254         if (IFD->getDeclName())
15255           ++NumNamedMembers;
15256     }
15257   }
15258 
15259   // Verify that all the fields are okay.
15260   SmallVector<FieldDecl*, 32> RecFields;
15261 
15262   bool ObjCFieldLifetimeErrReported = false;
15263   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
15264        i != end; ++i) {
15265     FieldDecl *FD = cast<FieldDecl>(*i);
15266 
15267     // Get the type for the field.
15268     const Type *FDTy = FD->getType().getTypePtr();
15269 
15270     if (!FD->isAnonymousStructOrUnion()) {
15271       // Remember all fields written by the user.
15272       RecFields.push_back(FD);
15273     }
15274 
15275     // If the field is already invalid for some reason, don't emit more
15276     // diagnostics about it.
15277     if (FD->isInvalidDecl()) {
15278       EnclosingDecl->setInvalidDecl();
15279       continue;
15280     }
15281 
15282     // C99 6.7.2.1p2:
15283     //   A structure or union shall not contain a member with
15284     //   incomplete or function type (hence, a structure shall not
15285     //   contain an instance of itself, but may contain a pointer to
15286     //   an instance of itself), except that the last member of a
15287     //   structure with more than one named member may have incomplete
15288     //   array type; such a structure (and any union containing,
15289     //   possibly recursively, a member that is such a structure)
15290     //   shall not be a member of a structure or an element of an
15291     //   array.
15292     bool IsLastField = (i + 1 == Fields.end());
15293     if (FDTy->isFunctionType()) {
15294       // Field declared as a function.
15295       Diag(FD->getLocation(), diag::err_field_declared_as_function)
15296         << FD->getDeclName();
15297       FD->setInvalidDecl();
15298       EnclosingDecl->setInvalidDecl();
15299       continue;
15300     } else if (FDTy->isIncompleteArrayType() &&
15301                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
15302       if (Record) {
15303         // Flexible array member.
15304         // Microsoft and g++ is more permissive regarding flexible array.
15305         // It will accept flexible array in union and also
15306         // as the sole element of a struct/class.
15307         unsigned DiagID = 0;
15308         if (!Record->isUnion() && !IsLastField) {
15309           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
15310             << FD->getDeclName() << FD->getType() << Record->getTagKind();
15311           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
15312           FD->setInvalidDecl();
15313           EnclosingDecl->setInvalidDecl();
15314           continue;
15315         } else if (Record->isUnion())
15316           DiagID = getLangOpts().MicrosoftExt
15317                        ? diag::ext_flexible_array_union_ms
15318                        : getLangOpts().CPlusPlus
15319                              ? diag::ext_flexible_array_union_gnu
15320                              : diag::err_flexible_array_union;
15321         else if (NumNamedMembers < 1)
15322           DiagID = getLangOpts().MicrosoftExt
15323                        ? diag::ext_flexible_array_empty_aggregate_ms
15324                        : getLangOpts().CPlusPlus
15325                              ? diag::ext_flexible_array_empty_aggregate_gnu
15326                              : diag::err_flexible_array_empty_aggregate;
15327 
15328         if (DiagID)
15329           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
15330                                           << Record->getTagKind();
15331         // While the layout of types that contain virtual bases is not specified
15332         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
15333         // virtual bases after the derived members.  This would make a flexible
15334         // array member declared at the end of an object not adjacent to the end
15335         // of the type.
15336         if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
15337           if (RD->getNumVBases() != 0)
15338             Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
15339               << FD->getDeclName() << Record->getTagKind();
15340         if (!getLangOpts().C99)
15341           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
15342             << FD->getDeclName() << Record->getTagKind();
15343 
15344         // If the element type has a non-trivial destructor, we would not
15345         // implicitly destroy the elements, so disallow it for now.
15346         //
15347         // FIXME: GCC allows this. We should probably either implicitly delete
15348         // the destructor of the containing class, or just allow this.
15349         QualType BaseElem = Context.getBaseElementType(FD->getType());
15350         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
15351           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
15352             << FD->getDeclName() << FD->getType();
15353           FD->setInvalidDecl();
15354           EnclosingDecl->setInvalidDecl();
15355           continue;
15356         }
15357         // Okay, we have a legal flexible array member at the end of the struct.
15358         Record->setHasFlexibleArrayMember(true);
15359       } else {
15360         // In ObjCContainerDecl ivars with incomplete array type are accepted,
15361         // unless they are followed by another ivar. That check is done
15362         // elsewhere, after synthesized ivars are known.
15363       }
15364     } else if (!FDTy->isDependentType() &&
15365                RequireCompleteType(FD->getLocation(), FD->getType(),
15366                                    diag::err_field_incomplete)) {
15367       // Incomplete type
15368       FD->setInvalidDecl();
15369       EnclosingDecl->setInvalidDecl();
15370       continue;
15371     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
15372       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
15373         // A type which contains a flexible array member is considered to be a
15374         // flexible array member.
15375         Record->setHasFlexibleArrayMember(true);
15376         if (!Record->isUnion()) {
15377           // If this is a struct/class and this is not the last element, reject
15378           // it.  Note that GCC supports variable sized arrays in the middle of
15379           // structures.
15380           if (!IsLastField)
15381             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
15382               << FD->getDeclName() << FD->getType();
15383           else {
15384             // We support flexible arrays at the end of structs in
15385             // other structs as an extension.
15386             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
15387               << FD->getDeclName();
15388           }
15389         }
15390       }
15391       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
15392           RequireNonAbstractType(FD->getLocation(), FD->getType(),
15393                                  diag::err_abstract_type_in_decl,
15394                                  AbstractIvarType)) {
15395         // Ivars can not have abstract class types
15396         FD->setInvalidDecl();
15397       }
15398       if (Record && FDTTy->getDecl()->hasObjectMember())
15399         Record->setHasObjectMember(true);
15400       if (Record && FDTTy->getDecl()->hasVolatileMember())
15401         Record->setHasVolatileMember(true);
15402     } else if (FDTy->isObjCObjectType()) {
15403       /// A field cannot be an Objective-c object
15404       Diag(FD->getLocation(), diag::err_statically_allocated_object)
15405         << FixItHint::CreateInsertion(FD->getLocation(), "*");
15406       QualType T = Context.getObjCObjectPointerType(FD->getType());
15407       FD->setType(T);
15408     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
15409                Record && !ObjCFieldLifetimeErrReported && Record->isUnion()) {
15410       // It's an error in ARC or Weak if a field has lifetime.
15411       // We don't want to report this in a system header, though,
15412       // so we just make the field unavailable.
15413       // FIXME: that's really not sufficient; we need to make the type
15414       // itself invalid to, say, initialize or copy.
15415       QualType T = FD->getType();
15416       if (T.hasNonTrivialObjCLifetime()) {
15417         SourceLocation loc = FD->getLocation();
15418         if (getSourceManager().isInSystemHeader(loc)) {
15419           if (!FD->hasAttr<UnavailableAttr>()) {
15420             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15421                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
15422           }
15423         } else {
15424           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
15425             << T->isBlockPointerType() << Record->getTagKind();
15426         }
15427         ObjCFieldLifetimeErrReported = true;
15428       }
15429     } else if (getLangOpts().ObjC1 &&
15430                getLangOpts().getGC() != LangOptions::NonGC &&
15431                Record && !Record->hasObjectMember()) {
15432       if (FD->getType()->isObjCObjectPointerType() ||
15433           FD->getType().isObjCGCStrong())
15434         Record->setHasObjectMember(true);
15435       else if (Context.getAsArrayType(FD->getType())) {
15436         QualType BaseType = Context.getBaseElementType(FD->getType());
15437         if (BaseType->isRecordType() &&
15438             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
15439           Record->setHasObjectMember(true);
15440         else if (BaseType->isObjCObjectPointerType() ||
15441                  BaseType.isObjCGCStrong())
15442                Record->setHasObjectMember(true);
15443       }
15444     }
15445 
15446     if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
15447       QualType FT = FD->getType();
15448       if (FT.isNonTrivialToPrimitiveDefaultInitialize())
15449         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
15450       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
15451       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial)
15452         Record->setNonTrivialToPrimitiveCopy(true);
15453       if (FT.isDestructedType())
15454         Record->setNonTrivialToPrimitiveDestroy(true);
15455       if (!FT.canPassInRegisters())
15456         Record->setCanPassInRegisters(false);
15457     }
15458 
15459     if (Record && FD->getType().isVolatileQualified())
15460       Record->setHasVolatileMember(true);
15461     // Keep track of the number of named members.
15462     if (FD->getIdentifier())
15463       ++NumNamedMembers;
15464   }
15465 
15466   // Okay, we successfully defined 'Record'.
15467   if (Record) {
15468     bool Completed = false;
15469     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15470       if (!CXXRecord->isInvalidDecl()) {
15471         // Set access bits correctly on the directly-declared conversions.
15472         for (CXXRecordDecl::conversion_iterator
15473                I = CXXRecord->conversion_begin(),
15474                E = CXXRecord->conversion_end(); I != E; ++I)
15475           I.setAccess((*I)->getAccess());
15476       }
15477 
15478       if (!CXXRecord->isDependentType()) {
15479         if (CXXRecord->hasUserDeclaredDestructor()) {
15480           // Adjust user-defined destructor exception spec.
15481           if (getLangOpts().CPlusPlus11)
15482             AdjustDestructorExceptionSpec(CXXRecord,
15483                                           CXXRecord->getDestructor());
15484         }
15485 
15486         // Add any implicitly-declared members to this class.
15487         AddImplicitlyDeclaredMembersToClass(CXXRecord);
15488 
15489         if (!CXXRecord->isInvalidDecl()) {
15490           // If we have virtual base classes, we may end up finding multiple
15491           // final overriders for a given virtual function. Check for this
15492           // problem now.
15493           if (CXXRecord->getNumVBases()) {
15494             CXXFinalOverriderMap FinalOverriders;
15495             CXXRecord->getFinalOverriders(FinalOverriders);
15496 
15497             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
15498                                              MEnd = FinalOverriders.end();
15499                  M != MEnd; ++M) {
15500               for (OverridingMethods::iterator SO = M->second.begin(),
15501                                             SOEnd = M->second.end();
15502                    SO != SOEnd; ++SO) {
15503                 assert(SO->second.size() > 0 &&
15504                        "Virtual function without overridding functions?");
15505                 if (SO->second.size() == 1)
15506                   continue;
15507 
15508                 // C++ [class.virtual]p2:
15509                 //   In a derived class, if a virtual member function of a base
15510                 //   class subobject has more than one final overrider the
15511                 //   program is ill-formed.
15512                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
15513                   << (const NamedDecl *)M->first << Record;
15514                 Diag(M->first->getLocation(),
15515                      diag::note_overridden_virtual_function);
15516                 for (OverridingMethods::overriding_iterator
15517                           OM = SO->second.begin(),
15518                        OMEnd = SO->second.end();
15519                      OM != OMEnd; ++OM)
15520                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
15521                     << (const NamedDecl *)M->first << OM->Method->getParent();
15522 
15523                 Record->setInvalidDecl();
15524               }
15525             }
15526             CXXRecord->completeDefinition(&FinalOverriders);
15527             Completed = true;
15528           }
15529         }
15530       }
15531     }
15532 
15533     if (!Completed)
15534       Record->completeDefinition();
15535 
15536     // We may have deferred checking for a deleted destructor. Check now.
15537     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15538       auto *Dtor = CXXRecord->getDestructor();
15539       if (Dtor && Dtor->isImplicit() &&
15540           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
15541         CXXRecord->setImplicitDestructorIsDeleted();
15542         SetDeclDeleted(Dtor, CXXRecord->getLocation());
15543       }
15544     }
15545 
15546     if (Record->hasAttrs()) {
15547       CheckAlignasUnderalignment(Record);
15548 
15549       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
15550         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
15551                                            IA->getRange(), IA->getBestCase(),
15552                                            IA->getSemanticSpelling());
15553     }
15554 
15555     // Check if the structure/union declaration is a type that can have zero
15556     // size in C. For C this is a language extension, for C++ it may cause
15557     // compatibility problems.
15558     bool CheckForZeroSize;
15559     if (!getLangOpts().CPlusPlus) {
15560       CheckForZeroSize = true;
15561     } else {
15562       // For C++ filter out types that cannot be referenced in C code.
15563       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
15564       CheckForZeroSize =
15565           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
15566           !CXXRecord->isDependentType() &&
15567           CXXRecord->isCLike();
15568     }
15569     if (CheckForZeroSize) {
15570       bool ZeroSize = true;
15571       bool IsEmpty = true;
15572       unsigned NonBitFields = 0;
15573       for (RecordDecl::field_iterator I = Record->field_begin(),
15574                                       E = Record->field_end();
15575            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
15576         IsEmpty = false;
15577         if (I->isUnnamedBitfield()) {
15578           if (I->getBitWidthValue(Context) > 0)
15579             ZeroSize = false;
15580         } else {
15581           ++NonBitFields;
15582           QualType FieldType = I->getType();
15583           if (FieldType->isIncompleteType() ||
15584               !Context.getTypeSizeInChars(FieldType).isZero())
15585             ZeroSize = false;
15586         }
15587       }
15588 
15589       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
15590       // allowed in C++, but warn if its declaration is inside
15591       // extern "C" block.
15592       if (ZeroSize) {
15593         Diag(RecLoc, getLangOpts().CPlusPlus ?
15594                          diag::warn_zero_size_struct_union_in_extern_c :
15595                          diag::warn_zero_size_struct_union_compat)
15596           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
15597       }
15598 
15599       // Structs without named members are extension in C (C99 6.7.2.1p7),
15600       // but are accepted by GCC.
15601       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
15602         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
15603                                diag::ext_no_named_members_in_struct_union)
15604           << Record->isUnion();
15605       }
15606     }
15607   } else {
15608     ObjCIvarDecl **ClsFields =
15609       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
15610     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
15611       ID->setEndOfDefinitionLoc(RBrac);
15612       // Add ivar's to class's DeclContext.
15613       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15614         ClsFields[i]->setLexicalDeclContext(ID);
15615         ID->addDecl(ClsFields[i]);
15616       }
15617       // Must enforce the rule that ivars in the base classes may not be
15618       // duplicates.
15619       if (ID->getSuperClass())
15620         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
15621     } else if (ObjCImplementationDecl *IMPDecl =
15622                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15623       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
15624       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
15625         // Ivar declared in @implementation never belongs to the implementation.
15626         // Only it is in implementation's lexical context.
15627         ClsFields[I]->setLexicalDeclContext(IMPDecl);
15628       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
15629       IMPDecl->setIvarLBraceLoc(LBrac);
15630       IMPDecl->setIvarRBraceLoc(RBrac);
15631     } else if (ObjCCategoryDecl *CDecl =
15632                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15633       // case of ivars in class extension; all other cases have been
15634       // reported as errors elsewhere.
15635       // FIXME. Class extension does not have a LocEnd field.
15636       // CDecl->setLocEnd(RBrac);
15637       // Add ivar's to class extension's DeclContext.
15638       // Diagnose redeclaration of private ivars.
15639       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
15640       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15641         if (IDecl) {
15642           if (const ObjCIvarDecl *ClsIvar =
15643               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
15644             Diag(ClsFields[i]->getLocation(),
15645                  diag::err_duplicate_ivar_declaration);
15646             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
15647             continue;
15648           }
15649           for (const auto *Ext : IDecl->known_extensions()) {
15650             if (const ObjCIvarDecl *ClsExtIvar
15651                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
15652               Diag(ClsFields[i]->getLocation(),
15653                    diag::err_duplicate_ivar_declaration);
15654               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
15655               continue;
15656             }
15657           }
15658         }
15659         ClsFields[i]->setLexicalDeclContext(CDecl);
15660         CDecl->addDecl(ClsFields[i]);
15661       }
15662       CDecl->setIvarLBraceLoc(LBrac);
15663       CDecl->setIvarRBraceLoc(RBrac);
15664     }
15665   }
15666 
15667   if (Attr)
15668     ProcessDeclAttributeList(S, Record, Attr);
15669 }
15670 
15671 /// \brief Determine whether the given integral value is representable within
15672 /// the given type T.
15673 static bool isRepresentableIntegerValue(ASTContext &Context,
15674                                         llvm::APSInt &Value,
15675                                         QualType T) {
15676   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
15677          "Integral type required!");
15678   unsigned BitWidth = Context.getIntWidth(T);
15679 
15680   if (Value.isUnsigned() || Value.isNonNegative()) {
15681     if (T->isSignedIntegerOrEnumerationType())
15682       --BitWidth;
15683     return Value.getActiveBits() <= BitWidth;
15684   }
15685   return Value.getMinSignedBits() <= BitWidth;
15686 }
15687 
15688 // \brief Given an integral type, return the next larger integral type
15689 // (or a NULL type of no such type exists).
15690 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
15691   // FIXME: Int128/UInt128 support, which also needs to be introduced into
15692   // enum checking below.
15693   assert((T->isIntegralType(Context) ||
15694          T->isEnumeralType()) && "Integral type required!");
15695   const unsigned NumTypes = 4;
15696   QualType SignedIntegralTypes[NumTypes] = {
15697     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
15698   };
15699   QualType UnsignedIntegralTypes[NumTypes] = {
15700     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
15701     Context.UnsignedLongLongTy
15702   };
15703 
15704   unsigned BitWidth = Context.getTypeSize(T);
15705   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
15706                                                         : UnsignedIntegralTypes;
15707   for (unsigned I = 0; I != NumTypes; ++I)
15708     if (Context.getTypeSize(Types[I]) > BitWidth)
15709       return Types[I];
15710 
15711   return QualType();
15712 }
15713 
15714 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
15715                                           EnumConstantDecl *LastEnumConst,
15716                                           SourceLocation IdLoc,
15717                                           IdentifierInfo *Id,
15718                                           Expr *Val) {
15719   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15720   llvm::APSInt EnumVal(IntWidth);
15721   QualType EltTy;
15722 
15723   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
15724     Val = nullptr;
15725 
15726   if (Val)
15727     Val = DefaultLvalueConversion(Val).get();
15728 
15729   if (Val) {
15730     if (Enum->isDependentType() || Val->isTypeDependent())
15731       EltTy = Context.DependentTy;
15732     else {
15733       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
15734           !getLangOpts().MSVCCompat) {
15735         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
15736         // constant-expression in the enumerator-definition shall be a converted
15737         // constant expression of the underlying type.
15738         EltTy = Enum->getIntegerType();
15739         ExprResult Converted =
15740           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
15741                                            CCEK_Enumerator);
15742         if (Converted.isInvalid())
15743           Val = nullptr;
15744         else
15745           Val = Converted.get();
15746       } else if (!Val->isValueDependent() &&
15747                  !(Val = VerifyIntegerConstantExpression(Val,
15748                                                          &EnumVal).get())) {
15749         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
15750       } else {
15751         if (Enum->isComplete()) {
15752           EltTy = Enum->getIntegerType();
15753 
15754           // In Obj-C and Microsoft mode, require the enumeration value to be
15755           // representable in the underlying type of the enumeration. In C++11,
15756           // we perform a non-narrowing conversion as part of converted constant
15757           // expression checking.
15758           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15759             if (getLangOpts().MSVCCompat) {
15760               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
15761               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
15762             } else
15763               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
15764           } else
15765             Val = ImpCastExprToType(Val, EltTy,
15766                                     EltTy->isBooleanType() ?
15767                                     CK_IntegralToBoolean : CK_IntegralCast)
15768                     .get();
15769         } else if (getLangOpts().CPlusPlus) {
15770           // C++11 [dcl.enum]p5:
15771           //   If the underlying type is not fixed, the type of each enumerator
15772           //   is the type of its initializing value:
15773           //     - If an initializer is specified for an enumerator, the
15774           //       initializing value has the same type as the expression.
15775           EltTy = Val->getType();
15776         } else {
15777           // C99 6.7.2.2p2:
15778           //   The expression that defines the value of an enumeration constant
15779           //   shall be an integer constant expression that has a value
15780           //   representable as an int.
15781 
15782           // Complain if the value is not representable in an int.
15783           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
15784             Diag(IdLoc, diag::ext_enum_value_not_int)
15785               << EnumVal.toString(10) << Val->getSourceRange()
15786               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
15787           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
15788             // Force the type of the expression to 'int'.
15789             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
15790           }
15791           EltTy = Val->getType();
15792         }
15793       }
15794     }
15795   }
15796 
15797   if (!Val) {
15798     if (Enum->isDependentType())
15799       EltTy = Context.DependentTy;
15800     else if (!LastEnumConst) {
15801       // C++0x [dcl.enum]p5:
15802       //   If the underlying type is not fixed, the type of each enumerator
15803       //   is the type of its initializing value:
15804       //     - If no initializer is specified for the first enumerator, the
15805       //       initializing value has an unspecified integral type.
15806       //
15807       // GCC uses 'int' for its unspecified integral type, as does
15808       // C99 6.7.2.2p3.
15809       if (Enum->isFixed()) {
15810         EltTy = Enum->getIntegerType();
15811       }
15812       else {
15813         EltTy = Context.IntTy;
15814       }
15815     } else {
15816       // Assign the last value + 1.
15817       EnumVal = LastEnumConst->getInitVal();
15818       ++EnumVal;
15819       EltTy = LastEnumConst->getType();
15820 
15821       // Check for overflow on increment.
15822       if (EnumVal < LastEnumConst->getInitVal()) {
15823         // C++0x [dcl.enum]p5:
15824         //   If the underlying type is not fixed, the type of each enumerator
15825         //   is the type of its initializing value:
15826         //
15827         //     - Otherwise the type of the initializing value is the same as
15828         //       the type of the initializing value of the preceding enumerator
15829         //       unless the incremented value is not representable in that type,
15830         //       in which case the type is an unspecified integral type
15831         //       sufficient to contain the incremented value. If no such type
15832         //       exists, the program is ill-formed.
15833         QualType T = getNextLargerIntegralType(Context, EltTy);
15834         if (T.isNull() || Enum->isFixed()) {
15835           // There is no integral type larger enough to represent this
15836           // value. Complain, then allow the value to wrap around.
15837           EnumVal = LastEnumConst->getInitVal();
15838           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
15839           ++EnumVal;
15840           if (Enum->isFixed())
15841             // When the underlying type is fixed, this is ill-formed.
15842             Diag(IdLoc, diag::err_enumerator_wrapped)
15843               << EnumVal.toString(10)
15844               << EltTy;
15845           else
15846             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
15847               << EnumVal.toString(10);
15848         } else {
15849           EltTy = T;
15850         }
15851 
15852         // Retrieve the last enumerator's value, extent that type to the
15853         // type that is supposed to be large enough to represent the incremented
15854         // value, then increment.
15855         EnumVal = LastEnumConst->getInitVal();
15856         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15857         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
15858         ++EnumVal;
15859 
15860         // If we're not in C++, diagnose the overflow of enumerator values,
15861         // which in C99 means that the enumerator value is not representable in
15862         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
15863         // permits enumerator values that are representable in some larger
15864         // integral type.
15865         if (!getLangOpts().CPlusPlus && !T.isNull())
15866           Diag(IdLoc, diag::warn_enum_value_overflow);
15867       } else if (!getLangOpts().CPlusPlus &&
15868                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15869         // Enforce C99 6.7.2.2p2 even when we compute the next value.
15870         Diag(IdLoc, diag::ext_enum_value_not_int)
15871           << EnumVal.toString(10) << 1;
15872       }
15873     }
15874   }
15875 
15876   if (!EltTy->isDependentType()) {
15877     // Make the enumerator value match the signedness and size of the
15878     // enumerator's type.
15879     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
15880     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15881   }
15882 
15883   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
15884                                   Val, EnumVal);
15885 }
15886 
15887 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
15888                                                 SourceLocation IILoc) {
15889   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
15890       !getLangOpts().CPlusPlus)
15891     return SkipBodyInfo();
15892 
15893   // We have an anonymous enum definition. Look up the first enumerator to
15894   // determine if we should merge the definition with an existing one and
15895   // skip the body.
15896   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
15897                                          forRedeclarationInCurContext());
15898   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
15899   if (!PrevECD)
15900     return SkipBodyInfo();
15901 
15902   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
15903   NamedDecl *Hidden;
15904   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
15905     SkipBodyInfo Skip;
15906     Skip.Previous = Hidden;
15907     return Skip;
15908   }
15909 
15910   return SkipBodyInfo();
15911 }
15912 
15913 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
15914                               SourceLocation IdLoc, IdentifierInfo *Id,
15915                               AttributeList *Attr,
15916                               SourceLocation EqualLoc, Expr *Val) {
15917   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
15918   EnumConstantDecl *LastEnumConst =
15919     cast_or_null<EnumConstantDecl>(lastEnumConst);
15920 
15921   // The scope passed in may not be a decl scope.  Zip up the scope tree until
15922   // we find one that is.
15923   S = getNonFieldDeclScope(S);
15924 
15925   // Verify that there isn't already something declared with this name in this
15926   // scope.
15927   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
15928                                          ForVisibleRedeclaration);
15929   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15930     // Maybe we will complain about the shadowed template parameter.
15931     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
15932     // Just pretend that we didn't see the previous declaration.
15933     PrevDecl = nullptr;
15934   }
15935 
15936   // C++ [class.mem]p15:
15937   // If T is the name of a class, then each of the following shall have a name
15938   // different from T:
15939   // - every enumerator of every member of class T that is an unscoped
15940   // enumerated type
15941   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
15942     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
15943                             DeclarationNameInfo(Id, IdLoc));
15944 
15945   EnumConstantDecl *New =
15946     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
15947   if (!New)
15948     return nullptr;
15949 
15950   if (PrevDecl) {
15951     // When in C++, we may get a TagDecl with the same name; in this case the
15952     // enum constant will 'hide' the tag.
15953     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
15954            "Received TagDecl when not in C++!");
15955     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
15956       if (isa<EnumConstantDecl>(PrevDecl))
15957         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15958       else
15959         Diag(IdLoc, diag::err_redefinition) << Id;
15960       notePreviousDefinition(PrevDecl, IdLoc);
15961       return nullptr;
15962     }
15963   }
15964 
15965   // Process attributes.
15966   if (Attr) ProcessDeclAttributeList(S, New, Attr);
15967   AddPragmaAttributes(S, New);
15968 
15969   // Register this decl in the current scope stack.
15970   New->setAccess(TheEnumDecl->getAccess());
15971   PushOnScopeChains(New, S);
15972 
15973   ActOnDocumentableDecl(New);
15974 
15975   return New;
15976 }
15977 
15978 // Returns true when the enum initial expression does not trigger the
15979 // duplicate enum warning.  A few common cases are exempted as follows:
15980 // Element2 = Element1
15981 // Element2 = Element1 + 1
15982 // Element2 = Element1 - 1
15983 // Where Element2 and Element1 are from the same enum.
15984 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
15985   Expr *InitExpr = ECD->getInitExpr();
15986   if (!InitExpr)
15987     return true;
15988   InitExpr = InitExpr->IgnoreImpCasts();
15989 
15990   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
15991     if (!BO->isAdditiveOp())
15992       return true;
15993     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
15994     if (!IL)
15995       return true;
15996     if (IL->getValue() != 1)
15997       return true;
15998 
15999     InitExpr = BO->getLHS();
16000   }
16001 
16002   // This checks if the elements are from the same enum.
16003   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
16004   if (!DRE)
16005     return true;
16006 
16007   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
16008   if (!EnumConstant)
16009     return true;
16010 
16011   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
16012       Enum)
16013     return true;
16014 
16015   return false;
16016 }
16017 
16018 namespace {
16019 struct DupKey {
16020   int64_t val;
16021   bool isTombstoneOrEmptyKey;
16022   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
16023     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
16024 };
16025 
16026 static DupKey GetDupKey(const llvm::APSInt& Val) {
16027   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
16028                 false);
16029 }
16030 
16031 struct DenseMapInfoDupKey {
16032   static DupKey getEmptyKey() { return DupKey(0, true); }
16033   static DupKey getTombstoneKey() { return DupKey(1, true); }
16034   static unsigned getHashValue(const DupKey Key) {
16035     return (unsigned)(Key.val * 37);
16036   }
16037   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
16038     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
16039            LHS.val == RHS.val;
16040   }
16041 };
16042 } // end anonymous namespace
16043 
16044 // Emits a warning when an element is implicitly set a value that
16045 // a previous element has already been set to.
16046 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
16047                                         EnumDecl *Enum,
16048                                         QualType EnumType) {
16049   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
16050     return;
16051   // Avoid anonymous enums
16052   if (!Enum->getIdentifier())
16053     return;
16054 
16055   // Only check for small enums.
16056   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
16057     return;
16058 
16059   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
16060   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
16061 
16062   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
16063   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
16064           ValueToVectorMap;
16065 
16066   DuplicatesVector DupVector;
16067   ValueToVectorMap EnumMap;
16068 
16069   // Populate the EnumMap with all values represented by enum constants without
16070   // an initialier.
16071   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16072     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
16073 
16074     // Null EnumConstantDecl means a previous diagnostic has been emitted for
16075     // this constant.  Skip this enum since it may be ill-formed.
16076     if (!ECD) {
16077       return;
16078     }
16079 
16080     if (ECD->getInitExpr())
16081       continue;
16082 
16083     DupKey Key = GetDupKey(ECD->getInitVal());
16084     DeclOrVector &Entry = EnumMap[Key];
16085 
16086     // First time encountering this value.
16087     if (Entry.isNull())
16088       Entry = ECD;
16089   }
16090 
16091   // Create vectors for any values that has duplicates.
16092   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16093     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
16094     if (!ValidDuplicateEnum(ECD, Enum))
16095       continue;
16096 
16097     DupKey Key = GetDupKey(ECD->getInitVal());
16098 
16099     DeclOrVector& Entry = EnumMap[Key];
16100     if (Entry.isNull())
16101       continue;
16102 
16103     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
16104       // Ensure constants are different.
16105       if (D == ECD)
16106         continue;
16107 
16108       // Create new vector and push values onto it.
16109       ECDVector *Vec = new ECDVector();
16110       Vec->push_back(D);
16111       Vec->push_back(ECD);
16112 
16113       // Update entry to point to the duplicates vector.
16114       Entry = Vec;
16115 
16116       // Store the vector somewhere we can consult later for quick emission of
16117       // diagnostics.
16118       DupVector.push_back(Vec);
16119       continue;
16120     }
16121 
16122     ECDVector *Vec = Entry.get<ECDVector*>();
16123     // Make sure constants are not added more than once.
16124     if (*Vec->begin() == ECD)
16125       continue;
16126 
16127     Vec->push_back(ECD);
16128   }
16129 
16130   // Emit diagnostics.
16131   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
16132                                   DupVectorEnd = DupVector.end();
16133        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
16134     ECDVector *Vec = *DupVectorIter;
16135     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
16136 
16137     // Emit warning for one enum constant.
16138     ECDVector::iterator I = Vec->begin();
16139     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
16140       << (*I)->getName() << (*I)->getInitVal().toString(10)
16141       << (*I)->getSourceRange();
16142     ++I;
16143 
16144     // Emit one note for each of the remaining enum constants with
16145     // the same value.
16146     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
16147       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
16148         << (*I)->getName() << (*I)->getInitVal().toString(10)
16149         << (*I)->getSourceRange();
16150     delete Vec;
16151   }
16152 }
16153 
16154 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
16155                              bool AllowMask) const {
16156   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
16157   assert(ED->isCompleteDefinition() && "expected enum definition");
16158 
16159   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
16160   llvm::APInt &FlagBits = R.first->second;
16161 
16162   if (R.second) {
16163     for (auto *E : ED->enumerators()) {
16164       const auto &EVal = E->getInitVal();
16165       // Only single-bit enumerators introduce new flag values.
16166       if (EVal.isPowerOf2())
16167         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
16168     }
16169   }
16170 
16171   // A value is in a flag enum if either its bits are a subset of the enum's
16172   // flag bits (the first condition) or we are allowing masks and the same is
16173   // true of its complement (the second condition). When masks are allowed, we
16174   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
16175   //
16176   // While it's true that any value could be used as a mask, the assumption is
16177   // that a mask will have all of the insignificant bits set. Anything else is
16178   // likely a logic error.
16179   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
16180   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
16181 }
16182 
16183 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
16184                          Decl *EnumDeclX,
16185                          ArrayRef<Decl *> Elements,
16186                          Scope *S, AttributeList *Attr) {
16187   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
16188   QualType EnumType = Context.getTypeDeclType(Enum);
16189 
16190   if (Attr)
16191     ProcessDeclAttributeList(S, Enum, Attr);
16192 
16193   if (Enum->isDependentType()) {
16194     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16195       EnumConstantDecl *ECD =
16196         cast_or_null<EnumConstantDecl>(Elements[i]);
16197       if (!ECD) continue;
16198 
16199       ECD->setType(EnumType);
16200     }
16201 
16202     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
16203     return;
16204   }
16205 
16206   // TODO: If the result value doesn't fit in an int, it must be a long or long
16207   // long value.  ISO C does not support this, but GCC does as an extension,
16208   // emit a warning.
16209   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16210   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
16211   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
16212 
16213   // Verify that all the values are okay, compute the size of the values, and
16214   // reverse the list.
16215   unsigned NumNegativeBits = 0;
16216   unsigned NumPositiveBits = 0;
16217 
16218   // Keep track of whether all elements have type int.
16219   bool AllElementsInt = true;
16220 
16221   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16222     EnumConstantDecl *ECD =
16223       cast_or_null<EnumConstantDecl>(Elements[i]);
16224     if (!ECD) continue;  // Already issued a diagnostic.
16225 
16226     const llvm::APSInt &InitVal = ECD->getInitVal();
16227 
16228     // Keep track of the size of positive and negative values.
16229     if (InitVal.isUnsigned() || InitVal.isNonNegative())
16230       NumPositiveBits = std::max(NumPositiveBits,
16231                                  (unsigned)InitVal.getActiveBits());
16232     else
16233       NumNegativeBits = std::max(NumNegativeBits,
16234                                  (unsigned)InitVal.getMinSignedBits());
16235 
16236     // Keep track of whether every enum element has type int (very commmon).
16237     if (AllElementsInt)
16238       AllElementsInt = ECD->getType() == Context.IntTy;
16239   }
16240 
16241   // Figure out the type that should be used for this enum.
16242   QualType BestType;
16243   unsigned BestWidth;
16244 
16245   // C++0x N3000 [conv.prom]p3:
16246   //   An rvalue of an unscoped enumeration type whose underlying
16247   //   type is not fixed can be converted to an rvalue of the first
16248   //   of the following types that can represent all the values of
16249   //   the enumeration: int, unsigned int, long int, unsigned long
16250   //   int, long long int, or unsigned long long int.
16251   // C99 6.4.4.3p2:
16252   //   An identifier declared as an enumeration constant has type int.
16253   // The C99 rule is modified by a gcc extension
16254   QualType BestPromotionType;
16255 
16256   bool Packed = Enum->hasAttr<PackedAttr>();
16257   // -fshort-enums is the equivalent to specifying the packed attribute on all
16258   // enum definitions.
16259   if (LangOpts.ShortEnums)
16260     Packed = true;
16261 
16262   // If the enum already has a type because it is fixed or dictated by the
16263   // target, promote that type instead of analyzing the enumerators.
16264   if (Enum->isComplete()) {
16265     BestType = Enum->getIntegerType();
16266     if (BestType->isPromotableIntegerType())
16267       BestPromotionType = Context.getPromotedIntegerType(BestType);
16268     else
16269       BestPromotionType = BestType;
16270 
16271     BestWidth = Context.getIntWidth(BestType);
16272   }
16273   else if (NumNegativeBits) {
16274     // If there is a negative value, figure out the smallest integer type (of
16275     // int/long/longlong) that fits.
16276     // If it's packed, check also if it fits a char or a short.
16277     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
16278       BestType = Context.SignedCharTy;
16279       BestWidth = CharWidth;
16280     } else if (Packed && NumNegativeBits <= ShortWidth &&
16281                NumPositiveBits < ShortWidth) {
16282       BestType = Context.ShortTy;
16283       BestWidth = ShortWidth;
16284     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
16285       BestType = Context.IntTy;
16286       BestWidth = IntWidth;
16287     } else {
16288       BestWidth = Context.getTargetInfo().getLongWidth();
16289 
16290       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
16291         BestType = Context.LongTy;
16292       } else {
16293         BestWidth = Context.getTargetInfo().getLongLongWidth();
16294 
16295         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
16296           Diag(Enum->getLocation(), diag::ext_enum_too_large);
16297         BestType = Context.LongLongTy;
16298       }
16299     }
16300     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
16301   } else {
16302     // If there is no negative value, figure out the smallest type that fits
16303     // all of the enumerator values.
16304     // If it's packed, check also if it fits a char or a short.
16305     if (Packed && NumPositiveBits <= CharWidth) {
16306       BestType = Context.UnsignedCharTy;
16307       BestPromotionType = Context.IntTy;
16308       BestWidth = CharWidth;
16309     } else if (Packed && NumPositiveBits <= ShortWidth) {
16310       BestType = Context.UnsignedShortTy;
16311       BestPromotionType = Context.IntTy;
16312       BestWidth = ShortWidth;
16313     } else if (NumPositiveBits <= IntWidth) {
16314       BestType = Context.UnsignedIntTy;
16315       BestWidth = IntWidth;
16316       BestPromotionType
16317         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16318                            ? Context.UnsignedIntTy : Context.IntTy;
16319     } else if (NumPositiveBits <=
16320                (BestWidth = Context.getTargetInfo().getLongWidth())) {
16321       BestType = Context.UnsignedLongTy;
16322       BestPromotionType
16323         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16324                            ? Context.UnsignedLongTy : Context.LongTy;
16325     } else {
16326       BestWidth = Context.getTargetInfo().getLongLongWidth();
16327       assert(NumPositiveBits <= BestWidth &&
16328              "How could an initializer get larger than ULL?");
16329       BestType = Context.UnsignedLongLongTy;
16330       BestPromotionType
16331         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16332                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
16333     }
16334   }
16335 
16336   // Loop over all of the enumerator constants, changing their types to match
16337   // the type of the enum if needed.
16338   for (auto *D : Elements) {
16339     auto *ECD = cast_or_null<EnumConstantDecl>(D);
16340     if (!ECD) continue;  // Already issued a diagnostic.
16341 
16342     // Standard C says the enumerators have int type, but we allow, as an
16343     // extension, the enumerators to be larger than int size.  If each
16344     // enumerator value fits in an int, type it as an int, otherwise type it the
16345     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
16346     // that X has type 'int', not 'unsigned'.
16347 
16348     // Determine whether the value fits into an int.
16349     llvm::APSInt InitVal = ECD->getInitVal();
16350 
16351     // If it fits into an integer type, force it.  Otherwise force it to match
16352     // the enum decl type.
16353     QualType NewTy;
16354     unsigned NewWidth;
16355     bool NewSign;
16356     if (!getLangOpts().CPlusPlus &&
16357         !Enum->isFixed() &&
16358         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
16359       NewTy = Context.IntTy;
16360       NewWidth = IntWidth;
16361       NewSign = true;
16362     } else if (ECD->getType() == BestType) {
16363       // Already the right type!
16364       if (getLangOpts().CPlusPlus)
16365         // C++ [dcl.enum]p4: Following the closing brace of an
16366         // enum-specifier, each enumerator has the type of its
16367         // enumeration.
16368         ECD->setType(EnumType);
16369       continue;
16370     } else {
16371       NewTy = BestType;
16372       NewWidth = BestWidth;
16373       NewSign = BestType->isSignedIntegerOrEnumerationType();
16374     }
16375 
16376     // Adjust the APSInt value.
16377     InitVal = InitVal.extOrTrunc(NewWidth);
16378     InitVal.setIsSigned(NewSign);
16379     ECD->setInitVal(InitVal);
16380 
16381     // Adjust the Expr initializer and type.
16382     if (ECD->getInitExpr() &&
16383         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
16384       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
16385                                                 CK_IntegralCast,
16386                                                 ECD->getInitExpr(),
16387                                                 /*base paths*/ nullptr,
16388                                                 VK_RValue));
16389     if (getLangOpts().CPlusPlus)
16390       // C++ [dcl.enum]p4: Following the closing brace of an
16391       // enum-specifier, each enumerator has the type of its
16392       // enumeration.
16393       ECD->setType(EnumType);
16394     else
16395       ECD->setType(NewTy);
16396   }
16397 
16398   Enum->completeDefinition(BestType, BestPromotionType,
16399                            NumPositiveBits, NumNegativeBits);
16400 
16401   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
16402 
16403   if (Enum->isClosedFlag()) {
16404     for (Decl *D : Elements) {
16405       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
16406       if (!ECD) continue;  // Already issued a diagnostic.
16407 
16408       llvm::APSInt InitVal = ECD->getInitVal();
16409       if (InitVal != 0 && !InitVal.isPowerOf2() &&
16410           !IsValueInFlagEnum(Enum, InitVal, true))
16411         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
16412           << ECD << Enum;
16413     }
16414   }
16415 
16416   // Now that the enum type is defined, ensure it's not been underaligned.
16417   if (Enum->hasAttrs())
16418     CheckAlignasUnderalignment(Enum);
16419 }
16420 
16421 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
16422                                   SourceLocation StartLoc,
16423                                   SourceLocation EndLoc) {
16424   StringLiteral *AsmString = cast<StringLiteral>(expr);
16425 
16426   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
16427                                                    AsmString, StartLoc,
16428                                                    EndLoc);
16429   CurContext->addDecl(New);
16430   return New;
16431 }
16432 
16433 static void checkModuleImportContext(Sema &S, Module *M,
16434                                      SourceLocation ImportLoc, DeclContext *DC,
16435                                      bool FromInclude = false) {
16436   SourceLocation ExternCLoc;
16437 
16438   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
16439     switch (LSD->getLanguage()) {
16440     case LinkageSpecDecl::lang_c:
16441       if (ExternCLoc.isInvalid())
16442         ExternCLoc = LSD->getLocStart();
16443       break;
16444     case LinkageSpecDecl::lang_cxx:
16445       break;
16446     }
16447     DC = LSD->getParent();
16448   }
16449 
16450   while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
16451     DC = DC->getParent();
16452 
16453   if (!isa<TranslationUnitDecl>(DC)) {
16454     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
16455                           ? diag::ext_module_import_not_at_top_level_noop
16456                           : diag::err_module_import_not_at_top_level_fatal)
16457         << M->getFullModuleName() << DC;
16458     S.Diag(cast<Decl>(DC)->getLocStart(),
16459            diag::note_module_import_not_at_top_level) << DC;
16460   } else if (!M->IsExternC && ExternCLoc.isValid()) {
16461     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
16462       << M->getFullModuleName();
16463     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
16464   }
16465 }
16466 
16467 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
16468                                            SourceLocation ModuleLoc,
16469                                            ModuleDeclKind MDK,
16470                                            ModuleIdPath Path) {
16471   assert(getLangOpts().ModulesTS &&
16472          "should only have module decl in modules TS");
16473 
16474   // A module implementation unit requires that we are not compiling a module
16475   // of any kind. A module interface unit requires that we are not compiling a
16476   // module map.
16477   switch (getLangOpts().getCompilingModule()) {
16478   case LangOptions::CMK_None:
16479     // It's OK to compile a module interface as a normal translation unit.
16480     break;
16481 
16482   case LangOptions::CMK_ModuleInterface:
16483     if (MDK != ModuleDeclKind::Implementation)
16484       break;
16485 
16486     // We were asked to compile a module interface unit but this is a module
16487     // implementation unit. That indicates the 'export' is missing.
16488     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
16489       << FixItHint::CreateInsertion(ModuleLoc, "export ");
16490     MDK = ModuleDeclKind::Interface;
16491     break;
16492 
16493   case LangOptions::CMK_ModuleMap:
16494     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
16495     return nullptr;
16496   }
16497 
16498   assert(ModuleScopes.size() == 1 && "expected to be at global module scope");
16499 
16500   // FIXME: Most of this work should be done by the preprocessor rather than
16501   // here, in order to support macro import.
16502 
16503   // Only one module-declaration is permitted per source file.
16504   if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) {
16505     Diag(ModuleLoc, diag::err_module_redeclaration);
16506     Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
16507          diag::note_prev_module_declaration);
16508     return nullptr;
16509   }
16510 
16511   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
16512   // modules, the dots here are just another character that can appear in a
16513   // module name.
16514   std::string ModuleName;
16515   for (auto &Piece : Path) {
16516     if (!ModuleName.empty())
16517       ModuleName += ".";
16518     ModuleName += Piece.first->getName();
16519   }
16520 
16521   // If a module name was explicitly specified on the command line, it must be
16522   // correct.
16523   if (!getLangOpts().CurrentModule.empty() &&
16524       getLangOpts().CurrentModule != ModuleName) {
16525     Diag(Path.front().second, diag::err_current_module_name_mismatch)
16526         << SourceRange(Path.front().second, Path.back().second)
16527         << getLangOpts().CurrentModule;
16528     return nullptr;
16529   }
16530   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
16531 
16532   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
16533   Module *Mod;
16534 
16535   switch (MDK) {
16536   case ModuleDeclKind::Interface: {
16537     // We can't have parsed or imported a definition of this module or parsed a
16538     // module map defining it already.
16539     if (auto *M = Map.findModule(ModuleName)) {
16540       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
16541       if (M->DefinitionLoc.isValid())
16542         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
16543       else if (const auto *FE = M->getASTFile())
16544         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
16545             << FE->getName();
16546       Mod = M;
16547       break;
16548     }
16549 
16550     // Create a Module for the module that we're defining.
16551     Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16552                                            ModuleScopes.front().Module);
16553     assert(Mod && "module creation should not fail");
16554     break;
16555   }
16556 
16557   case ModuleDeclKind::Partition:
16558     // FIXME: Check we are in a submodule of the named module.
16559     return nullptr;
16560 
16561   case ModuleDeclKind::Implementation:
16562     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
16563         PP.getIdentifierInfo(ModuleName), Path[0].second);
16564     Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible,
16565                                        /*IsIncludeDirective=*/false);
16566     if (!Mod) {
16567       Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
16568       // Create an empty module interface unit for error recovery.
16569       Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16570                                              ModuleScopes.front().Module);
16571     }
16572     break;
16573   }
16574 
16575   // Switch from the global module to the named module.
16576   ModuleScopes.back().Module = Mod;
16577   ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
16578   VisibleModules.setVisible(Mod, ModuleLoc);
16579 
16580   // From now on, we have an owning module for all declarations we see.
16581   // However, those declarations are module-private unless explicitly
16582   // exported.
16583   auto *TU = Context.getTranslationUnitDecl();
16584   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
16585   TU->setLocalOwningModule(Mod);
16586 
16587   // FIXME: Create a ModuleDecl.
16588   return nullptr;
16589 }
16590 
16591 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
16592                                    SourceLocation ImportLoc,
16593                                    ModuleIdPath Path) {
16594   Module *Mod =
16595       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
16596                                    /*IsIncludeDirective=*/false);
16597   if (!Mod)
16598     return true;
16599 
16600   VisibleModules.setVisible(Mod, ImportLoc);
16601 
16602   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
16603 
16604   // FIXME: we should support importing a submodule within a different submodule
16605   // of the same top-level module. Until we do, make it an error rather than
16606   // silently ignoring the import.
16607   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
16608   // warn on a redundant import of the current module?
16609   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
16610       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
16611     Diag(ImportLoc, getLangOpts().isCompilingModule()
16612                         ? diag::err_module_self_import
16613                         : diag::err_module_import_in_implementation)
16614         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
16615 
16616   SmallVector<SourceLocation, 2> IdentifierLocs;
16617   Module *ModCheck = Mod;
16618   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
16619     // If we've run out of module parents, just drop the remaining identifiers.
16620     // We need the length to be consistent.
16621     if (!ModCheck)
16622       break;
16623     ModCheck = ModCheck->Parent;
16624 
16625     IdentifierLocs.push_back(Path[I].second);
16626   }
16627 
16628   ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
16629                                           Mod, IdentifierLocs);
16630   if (!ModuleScopes.empty())
16631     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
16632   CurContext->addDecl(Import);
16633 
16634   // Re-export the module if needed.
16635   if (Import->isExported() &&
16636       !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface)
16637     getCurrentModule()->Exports.emplace_back(Mod, false);
16638 
16639   return Import;
16640 }
16641 
16642 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16643   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16644   BuildModuleInclude(DirectiveLoc, Mod);
16645 }
16646 
16647 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16648   // Determine whether we're in the #include buffer for a module. The #includes
16649   // in that buffer do not qualify as module imports; they're just an
16650   // implementation detail of us building the module.
16651   //
16652   // FIXME: Should we even get ActOnModuleInclude calls for those?
16653   bool IsInModuleIncludes =
16654       TUKind == TU_Module &&
16655       getSourceManager().isWrittenInMainFile(DirectiveLoc);
16656 
16657   bool ShouldAddImport = !IsInModuleIncludes;
16658 
16659   // If this module import was due to an inclusion directive, create an
16660   // implicit import declaration to capture it in the AST.
16661   if (ShouldAddImport) {
16662     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16663     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16664                                                      DirectiveLoc, Mod,
16665                                                      DirectiveLoc);
16666     if (!ModuleScopes.empty())
16667       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
16668     TU->addDecl(ImportD);
16669     Consumer.HandleImplicitImportDecl(ImportD);
16670   }
16671 
16672   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
16673   VisibleModules.setVisible(Mod, DirectiveLoc);
16674 }
16675 
16676 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
16677   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16678 
16679   ModuleScopes.push_back({});
16680   ModuleScopes.back().Module = Mod;
16681   if (getLangOpts().ModulesLocalVisibility)
16682     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
16683 
16684   VisibleModules.setVisible(Mod, DirectiveLoc);
16685 
16686   // The enclosing context is now part of this module.
16687   // FIXME: Consider creating a child DeclContext to hold the entities
16688   // lexically within the module.
16689   if (getLangOpts().trackLocalOwningModule()) {
16690     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16691       cast<Decl>(DC)->setModuleOwnershipKind(
16692           getLangOpts().ModulesLocalVisibility
16693               ? Decl::ModuleOwnershipKind::VisibleWhenImported
16694               : Decl::ModuleOwnershipKind::Visible);
16695       cast<Decl>(DC)->setLocalOwningModule(Mod);
16696     }
16697   }
16698 }
16699 
16700 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
16701   if (getLangOpts().ModulesLocalVisibility) {
16702     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
16703     // Leaving a module hides namespace names, so our visible namespace cache
16704     // is now out of date.
16705     VisibleNamespaceCache.clear();
16706   }
16707 
16708   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
16709          "left the wrong module scope");
16710   ModuleScopes.pop_back();
16711 
16712   // We got to the end of processing a local module. Create an
16713   // ImportDecl as we would for an imported module.
16714   FileID File = getSourceManager().getFileID(EomLoc);
16715   SourceLocation DirectiveLoc;
16716   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
16717     // We reached the end of a #included module header. Use the #include loc.
16718     assert(File != getSourceManager().getMainFileID() &&
16719            "end of submodule in main source file");
16720     DirectiveLoc = getSourceManager().getIncludeLoc(File);
16721   } else {
16722     // We reached an EOM pragma. Use the pragma location.
16723     DirectiveLoc = EomLoc;
16724   }
16725   BuildModuleInclude(DirectiveLoc, Mod);
16726 
16727   // Any further declarations are in whatever module we returned to.
16728   if (getLangOpts().trackLocalOwningModule()) {
16729     // The parser guarantees that this is the same context that we entered
16730     // the module within.
16731     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16732       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
16733       if (!getCurrentModule())
16734         cast<Decl>(DC)->setModuleOwnershipKind(
16735             Decl::ModuleOwnershipKind::Unowned);
16736     }
16737   }
16738 }
16739 
16740 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
16741                                                       Module *Mod) {
16742   // Bail if we're not allowed to implicitly import a module here.
16743   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
16744       VisibleModules.isVisible(Mod))
16745     return;
16746 
16747   // Create the implicit import declaration.
16748   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16749   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16750                                                    Loc, Mod, Loc);
16751   TU->addDecl(ImportD);
16752   Consumer.HandleImplicitImportDecl(ImportD);
16753 
16754   // Make the module visible.
16755   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
16756   VisibleModules.setVisible(Mod, Loc);
16757 }
16758 
16759 /// We have parsed the start of an export declaration, including the '{'
16760 /// (if present).
16761 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
16762                                  SourceLocation LBraceLoc) {
16763   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
16764 
16765   // C++ Modules TS draft:
16766   //   An export-declaration shall appear in the purview of a module other than
16767   //   the global module.
16768   if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface)
16769     Diag(ExportLoc, diag::err_export_not_in_module_interface);
16770 
16771   //   An export-declaration [...] shall not contain more than one
16772   //   export keyword.
16773   //
16774   // The intent here is that an export-declaration cannot appear within another
16775   // export-declaration.
16776   if (D->isExported())
16777     Diag(ExportLoc, diag::err_export_within_export);
16778 
16779   CurContext->addDecl(D);
16780   PushDeclContext(S, D);
16781   D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
16782   return D;
16783 }
16784 
16785 /// Complete the definition of an export declaration.
16786 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
16787   auto *ED = cast<ExportDecl>(D);
16788   if (RBraceLoc.isValid())
16789     ED->setRBraceLoc(RBraceLoc);
16790 
16791   // FIXME: Diagnose export of internal-linkage declaration (including
16792   // anonymous namespace).
16793 
16794   PopDeclContext();
16795   return D;
16796 }
16797 
16798 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
16799                                       IdentifierInfo* AliasName,
16800                                       SourceLocation PragmaLoc,
16801                                       SourceLocation NameLoc,
16802                                       SourceLocation AliasNameLoc) {
16803   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
16804                                          LookupOrdinaryName);
16805   AsmLabelAttr *Attr =
16806       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
16807 
16808   // If a declaration that:
16809   // 1) declares a function or a variable
16810   // 2) has external linkage
16811   // already exists, add a label attribute to it.
16812   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16813     if (isDeclExternC(PrevDecl))
16814       PrevDecl->addAttr(Attr);
16815     else
16816       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
16817           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
16818   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
16819   } else
16820     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
16821 }
16822 
16823 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
16824                              SourceLocation PragmaLoc,
16825                              SourceLocation NameLoc) {
16826   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
16827 
16828   if (PrevDecl) {
16829     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
16830   } else {
16831     (void)WeakUndeclaredIdentifiers.insert(
16832       std::pair<IdentifierInfo*,WeakInfo>
16833         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
16834   }
16835 }
16836 
16837 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
16838                                 IdentifierInfo* AliasName,
16839                                 SourceLocation PragmaLoc,
16840                                 SourceLocation NameLoc,
16841                                 SourceLocation AliasNameLoc) {
16842   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
16843                                     LookupOrdinaryName);
16844   WeakInfo W = WeakInfo(Name, NameLoc);
16845 
16846   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16847     if (!PrevDecl->hasAttr<AliasAttr>())
16848       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
16849         DeclApplyPragmaWeak(TUScope, ND, W);
16850   } else {
16851     (void)WeakUndeclaredIdentifiers.insert(
16852       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
16853   }
16854 }
16855 
16856 Decl *Sema::getObjCDeclContext() const {
16857   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
16858 }
16859