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       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70         AllowTemplates(AllowTemplates) {
71     WantExpressionKeywords = false;
72     WantCXXNamedCasts = false;
73     WantRemainingKeywords = false;
74   }
75 
76   bool ValidateCandidate(const TypoCorrection &candidate) override {
77     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
78       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
79       bool AllowedTemplate = AllowTemplates && getAsTypeTemplateDecl(ND);
80       return (IsType || AllowedTemplate) &&
81              (AllowInvalidDecl || !ND->isInvalidDecl());
82     }
83     return !WantClassName && candidate.isKeyword();
84   }
85 
86  private:
87   bool AllowInvalidDecl;
88   bool WantClassName;
89   bool AllowTemplates;
90 };
91 
92 } // end anonymous namespace
93 
94 /// \brief Determine whether the token kind starts a simple-type-specifier.
95 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
96   switch (Kind) {
97   // FIXME: Take into account the current language when deciding whether a
98   // token kind is a valid type specifier
99   case tok::kw_short:
100   case tok::kw_long:
101   case tok::kw___int64:
102   case tok::kw___int128:
103   case tok::kw_signed:
104   case tok::kw_unsigned:
105   case tok::kw_void:
106   case tok::kw_char:
107   case tok::kw_int:
108   case tok::kw_half:
109   case tok::kw_float:
110   case tok::kw_double:
111   case tok::kw___float128:
112   case tok::kw_wchar_t:
113   case tok::kw_bool:
114   case tok::kw___underlying_type:
115   case tok::kw___auto_type:
116     return true;
117 
118   case tok::annot_typename:
119   case tok::kw_char16_t:
120   case tok::kw_char32_t:
121   case tok::kw_typeof:
122   case tok::annot_decltype:
123   case tok::kw_decltype:
124     return getLangOpts().CPlusPlus;
125 
126   default:
127     break;
128   }
129 
130   return false;
131 }
132 
133 namespace {
134 enum class UnqualifiedTypeNameLookupResult {
135   NotFound,
136   FoundNonType,
137   FoundType
138 };
139 } // end anonymous namespace
140 
141 /// \brief Tries to perform unqualified lookup of the type decls in bases for
142 /// dependent class.
143 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
144 /// type decl, \a FoundType if only type decls are found.
145 static UnqualifiedTypeNameLookupResult
146 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
147                                 SourceLocation NameLoc,
148                                 const CXXRecordDecl *RD) {
149   if (!RD->hasDefinition())
150     return UnqualifiedTypeNameLookupResult::NotFound;
151   // Look for type decls in base classes.
152   UnqualifiedTypeNameLookupResult FoundTypeDecl =
153       UnqualifiedTypeNameLookupResult::NotFound;
154   for (const auto &Base : RD->bases()) {
155     const CXXRecordDecl *BaseRD = nullptr;
156     if (auto *BaseTT = Base.getType()->getAs<TagType>())
157       BaseRD = BaseTT->getAsCXXRecordDecl();
158     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
159       // Look for type decls in dependent base classes that have known primary
160       // templates.
161       if (!TST || !TST->isDependentType())
162         continue;
163       auto *TD = TST->getTemplateName().getAsTemplateDecl();
164       if (!TD)
165         continue;
166       if (auto *BasePrimaryTemplate =
167           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
168         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
169           BaseRD = BasePrimaryTemplate;
170         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
171           if (const ClassTemplatePartialSpecializationDecl *PS =
172                   CTD->findPartialSpecialization(Base.getType()))
173             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
174               BaseRD = PS;
175         }
176       }
177     }
178     if (BaseRD) {
179       for (NamedDecl *ND : BaseRD->lookup(&II)) {
180         if (!isa<TypeDecl>(ND))
181           return UnqualifiedTypeNameLookupResult::FoundNonType;
182         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
183       }
184       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
185         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
186         case UnqualifiedTypeNameLookupResult::FoundNonType:
187           return UnqualifiedTypeNameLookupResult::FoundNonType;
188         case UnqualifiedTypeNameLookupResult::FoundType:
189           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
190           break;
191         case UnqualifiedTypeNameLookupResult::NotFound:
192           break;
193         }
194       }
195     }
196   }
197 
198   return FoundTypeDecl;
199 }
200 
201 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
202                                                       const IdentifierInfo &II,
203                                                       SourceLocation NameLoc) {
204   // Lookup in the parent class template context, if any.
205   const CXXRecordDecl *RD = nullptr;
206   UnqualifiedTypeNameLookupResult FoundTypeDecl =
207       UnqualifiedTypeNameLookupResult::NotFound;
208   for (DeclContext *DC = S.CurContext;
209        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
210        DC = DC->getParent()) {
211     // Look for type decls in dependent base classes that have known primary
212     // templates.
213     RD = dyn_cast<CXXRecordDecl>(DC);
214     if (RD && RD->getDescribedClassTemplate())
215       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
216   }
217   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
218     return nullptr;
219 
220   // We found some types in dependent base classes.  Recover as if the user
221   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
222   // lookup during template instantiation.
223   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
224 
225   ASTContext &Context = S.Context;
226   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
227                                           cast<Type>(Context.getRecordType(RD)));
228   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
229 
230   CXXScopeSpec SS;
231   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
232 
233   TypeLocBuilder Builder;
234   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
235   DepTL.setNameLoc(NameLoc);
236   DepTL.setElaboratedKeywordLoc(SourceLocation());
237   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
238   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
239 }
240 
241 /// \brief If the identifier refers to a type name within this scope,
242 /// return the declaration of that type.
243 ///
244 /// This routine performs ordinary name lookup of the identifier II
245 /// within the given scope, with optional C++ scope specifier SS, to
246 /// determine whether the name refers to a type. If so, returns an
247 /// opaque pointer (actually a QualType) corresponding to that
248 /// type. Otherwise, returns NULL.
249 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
250                              Scope *S, CXXScopeSpec *SS,
251                              bool isClassName, bool HasTrailingDot,
252                              ParsedType ObjectTypePtr,
253                              bool IsCtorOrDtorName,
254                              bool WantNontrivialTypeSourceInfo,
255                              bool IsClassTemplateDeductionContext,
256                              IdentifierInfo **CorrectedII) {
257   // FIXME: Consider allowing this outside C++1z mode as an extension.
258   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
259                               getLangOpts().CPlusPlus1z && !IsCtorOrDtorName &&
260                               !isClassName && !HasTrailingDot;
261 
262   // Determine where we will perform name lookup.
263   DeclContext *LookupCtx = nullptr;
264   if (ObjectTypePtr) {
265     QualType ObjectType = ObjectTypePtr.get();
266     if (ObjectType->isRecordType())
267       LookupCtx = computeDeclContext(ObjectType);
268   } else if (SS && SS->isNotEmpty()) {
269     LookupCtx = computeDeclContext(*SS, false);
270 
271     if (!LookupCtx) {
272       if (isDependentScopeSpecifier(*SS)) {
273         // C++ [temp.res]p3:
274         //   A qualified-id that refers to a type and in which the
275         //   nested-name-specifier depends on a template-parameter (14.6.2)
276         //   shall be prefixed by the keyword typename to indicate that the
277         //   qualified-id denotes a type, forming an
278         //   elaborated-type-specifier (7.1.5.3).
279         //
280         // We therefore do not perform any name lookup if the result would
281         // refer to a member of an unknown specialization.
282         if (!isClassName && !IsCtorOrDtorName)
283           return nullptr;
284 
285         // We know from the grammar that this name refers to a type,
286         // so build a dependent node to describe the type.
287         if (WantNontrivialTypeSourceInfo)
288           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
289 
290         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
291         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
292                                        II, NameLoc);
293         return ParsedType::make(T);
294       }
295 
296       return nullptr;
297     }
298 
299     if (!LookupCtx->isDependentContext() &&
300         RequireCompleteDeclContext(*SS, LookupCtx))
301       return nullptr;
302   }
303 
304   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
305   // lookup for class-names.
306   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
307                                       LookupOrdinaryName;
308   LookupResult Result(*this, &II, NameLoc, Kind);
309   if (LookupCtx) {
310     // Perform "qualified" name lookup into the declaration context we
311     // computed, which is either the type of the base of a member access
312     // expression or the declaration context associated with a prior
313     // nested-name-specifier.
314     LookupQualifiedName(Result, LookupCtx);
315 
316     if (ObjectTypePtr && Result.empty()) {
317       // C++ [basic.lookup.classref]p3:
318       //   If the unqualified-id is ~type-name, the type-name is looked up
319       //   in the context of the entire postfix-expression. If the type T of
320       //   the object expression is of a class type C, the type-name is also
321       //   looked up in the scope of class C. At least one of the lookups shall
322       //   find a name that refers to (possibly cv-qualified) T.
323       LookupName(Result, S);
324     }
325   } else {
326     // Perform unqualified name lookup.
327     LookupName(Result, S);
328 
329     // For unqualified lookup in a class template in MSVC mode, look into
330     // dependent base classes where the primary class template is known.
331     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
332       if (ParsedType TypeInBase =
333               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
334         return TypeInBase;
335     }
336   }
337 
338   NamedDecl *IIDecl = nullptr;
339   switch (Result.getResultKind()) {
340   case LookupResult::NotFound:
341   case LookupResult::NotFoundInCurrentInstantiation:
342     if (CorrectedII) {
343       TypoCorrection Correction =
344           CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
345                       llvm::make_unique<TypeNameValidatorCCC>(
346                           true, isClassName, AllowDeducedTemplate),
347                       CTK_ErrorRecovery);
348       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
349       TemplateTy Template;
350       bool MemberOfUnknownSpecialization;
351       UnqualifiedId TemplateName;
352       TemplateName.setIdentifier(NewII, NameLoc);
353       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
354       CXXScopeSpec NewSS, *NewSSPtr = SS;
355       if (SS && NNS) {
356         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
357         NewSSPtr = &NewSS;
358       }
359       if (Correction && (NNS || NewII != &II) &&
360           // Ignore a correction to a template type as the to-be-corrected
361           // identifier is not a template (typo correction for template names
362           // is handled elsewhere).
363           !(getLangOpts().CPlusPlus && NewSSPtr &&
364             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
365                            Template, MemberOfUnknownSpecialization))) {
366         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
367                                     isClassName, HasTrailingDot, ObjectTypePtr,
368                                     IsCtorOrDtorName,
369                                     WantNontrivialTypeSourceInfo,
370                                     IsClassTemplateDeductionContext);
371         if (Ty) {
372           diagnoseTypo(Correction,
373                        PDiag(diag::err_unknown_type_or_class_name_suggest)
374                          << Result.getLookupName() << isClassName);
375           if (SS && NNS)
376             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
377           *CorrectedII = NewII;
378           return Ty;
379         }
380       }
381     }
382     // If typo correction failed or was not performed, fall through
383   case LookupResult::FoundOverloaded:
384   case LookupResult::FoundUnresolvedValue:
385     Result.suppressDiagnostics();
386     return nullptr;
387 
388   case LookupResult::Ambiguous:
389     // Recover from type-hiding ambiguities by hiding the type.  We'll
390     // do the lookup again when looking for an object, and we can
391     // diagnose the error then.  If we don't do this, then the error
392     // about hiding the type will be immediately followed by an error
393     // that only makes sense if the identifier was treated like a type.
394     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
395       Result.suppressDiagnostics();
396       return nullptr;
397     }
398 
399     // Look to see if we have a type anywhere in the list of results.
400     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
401          Res != ResEnd; ++Res) {
402       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
403           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
404         if (!IIDecl ||
405             (*Res)->getLocation().getRawEncoding() <
406               IIDecl->getLocation().getRawEncoding())
407           IIDecl = *Res;
408       }
409     }
410 
411     if (!IIDecl) {
412       // None of the entities we found is a type, so there is no way
413       // to even assume that the result is a type. In this case, don't
414       // complain about the ambiguity. The parser will either try to
415       // perform this lookup again (e.g., as an object name), which
416       // will produce the ambiguity, or will complain that it expected
417       // a type name.
418       Result.suppressDiagnostics();
419       return nullptr;
420     }
421 
422     // We found a type within the ambiguous lookup; diagnose the
423     // ambiguity and then return that type. This might be the right
424     // answer, or it might not be, but it suppresses any attempt to
425     // perform the name lookup again.
426     break;
427 
428   case LookupResult::Found:
429     IIDecl = Result.getFoundDecl();
430     break;
431   }
432 
433   assert(IIDecl && "Didn't find decl");
434 
435   QualType T;
436   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
437     // C++ [class.qual]p2: A lookup that would find the injected-class-name
438     // instead names the constructors of the class, except when naming a class.
439     // This is ill-formed when we're not actually forming a ctor or dtor name.
440     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
441     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
442     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
443         FoundRD->isInjectedClassName() &&
444         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
445       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
446           << &II << /*Type*/1;
447 
448     DiagnoseUseOfDecl(IIDecl, NameLoc);
449 
450     T = Context.getTypeDeclType(TD);
451     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
452   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
453     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
454     if (!HasTrailingDot)
455       T = Context.getObjCInterfaceType(IDecl);
456   } else if (AllowDeducedTemplate) {
457     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
458       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
459                                                        QualType(), false);
460   }
461 
462   if (T.isNull()) {
463     // If it's not plausibly a type, suppress diagnostics.
464     Result.suppressDiagnostics();
465     return nullptr;
466   }
467 
468   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
469   // constructor or destructor name (in such a case, the scope specifier
470   // will be attached to the enclosing Expr or Decl node).
471   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
472       !isa<ObjCInterfaceDecl>(IIDecl)) {
473     if (WantNontrivialTypeSourceInfo) {
474       // Construct a type with type-source information.
475       TypeLocBuilder Builder;
476       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
477 
478       T = getElaboratedType(ETK_None, *SS, T);
479       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
480       ElabTL.setElaboratedKeywordLoc(SourceLocation());
481       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
482       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
483     } else {
484       T = getElaboratedType(ETK_None, *SS, T);
485     }
486   }
487 
488   return ParsedType::make(T);
489 }
490 
491 // Builds a fake NNS for the given decl context.
492 static NestedNameSpecifier *
493 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
494   for (;; DC = DC->getLookupParent()) {
495     DC = DC->getPrimaryContext();
496     auto *ND = dyn_cast<NamespaceDecl>(DC);
497     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
498       return NestedNameSpecifier::Create(Context, nullptr, ND);
499     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
500       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
501                                          RD->getTypeForDecl());
502     else if (isa<TranslationUnitDecl>(DC))
503       return NestedNameSpecifier::GlobalSpecifier(Context);
504   }
505   llvm_unreachable("something isn't in TU scope?");
506 }
507 
508 /// Find the parent class with dependent bases of the innermost enclosing method
509 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
510 /// up allowing unqualified dependent type names at class-level, which MSVC
511 /// correctly rejects.
512 static const CXXRecordDecl *
513 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
514   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
515     DC = DC->getPrimaryContext();
516     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
517       if (MD->getParent()->hasAnyDependentBases())
518         return MD->getParent();
519   }
520   return nullptr;
521 }
522 
523 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
524                                           SourceLocation NameLoc,
525                                           bool IsTemplateTypeArg) {
526   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
527 
528   NestedNameSpecifier *NNS = nullptr;
529   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
530     // If we weren't able to parse a default template argument, delay lookup
531     // until instantiation time by making a non-dependent DependentTypeName. We
532     // pretend we saw a NestedNameSpecifier referring to the current scope, and
533     // lookup is retried.
534     // FIXME: This hurts our diagnostic quality, since we get errors like "no
535     // type named 'Foo' in 'current_namespace'" when the user didn't write any
536     // name specifiers.
537     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
538     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
539   } else if (const CXXRecordDecl *RD =
540                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
541     // Build a DependentNameType that will perform lookup into RD at
542     // instantiation time.
543     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
544                                       RD->getTypeForDecl());
545 
546     // Diagnose that this identifier was undeclared, and retry the lookup during
547     // template instantiation.
548     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
549                                                                       << RD;
550   } else {
551     // This is not a situation that we should recover from.
552     return ParsedType();
553   }
554 
555   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
556 
557   // Build type location information.  We synthesized the qualifier, so we have
558   // to build a fake NestedNameSpecifierLoc.
559   NestedNameSpecifierLocBuilder NNSLocBuilder;
560   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
561   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
562 
563   TypeLocBuilder Builder;
564   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
565   DepTL.setNameLoc(NameLoc);
566   DepTL.setElaboratedKeywordLoc(SourceLocation());
567   DepTL.setQualifierLoc(QualifierLoc);
568   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
569 }
570 
571 /// isTagName() - This method is called *for error recovery purposes only*
572 /// to determine if the specified name is a valid tag name ("struct foo").  If
573 /// so, this returns the TST for the tag corresponding to it (TST_enum,
574 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
575 /// cases in C where the user forgot to specify the tag.
576 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
577   // Do a tag name lookup in this scope.
578   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
579   LookupName(R, S, false);
580   R.suppressDiagnostics();
581   if (R.getResultKind() == LookupResult::Found)
582     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
583       switch (TD->getTagKind()) {
584       case TTK_Struct: return DeclSpec::TST_struct;
585       case TTK_Interface: return DeclSpec::TST_interface;
586       case TTK_Union:  return DeclSpec::TST_union;
587       case TTK_Class:  return DeclSpec::TST_class;
588       case TTK_Enum:   return DeclSpec::TST_enum;
589       }
590     }
591 
592   return DeclSpec::TST_unspecified;
593 }
594 
595 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
596 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
597 /// then downgrade the missing typename error to a warning.
598 /// This is needed for MSVC compatibility; Example:
599 /// @code
600 /// template<class T> class A {
601 /// public:
602 ///   typedef int TYPE;
603 /// };
604 /// template<class T> class B : public A<T> {
605 /// public:
606 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
607 /// };
608 /// @endcode
609 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
610   if (CurContext->isRecord()) {
611     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
612       return true;
613 
614     const Type *Ty = SS->getScopeRep()->getAsType();
615 
616     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
617     for (const auto &Base : RD->bases())
618       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
619         return true;
620     return S->isFunctionPrototypeScope();
621   }
622   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
623 }
624 
625 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
626                                    SourceLocation IILoc,
627                                    Scope *S,
628                                    CXXScopeSpec *SS,
629                                    ParsedType &SuggestedType,
630                                    bool AllowClassTemplates) {
631   // Don't report typename errors for editor placeholders.
632   if (II->isEditorPlaceholder())
633     return;
634   // We don't have anything to suggest (yet).
635   SuggestedType = nullptr;
636 
637   // There may have been a typo in the name of the type. Look up typo
638   // results, in case we have something that we can suggest.
639   if (TypoCorrection Corrected =
640           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
641                       llvm::make_unique<TypeNameValidatorCCC>(
642                           false, false, AllowClassTemplates),
643                       CTK_ErrorRecovery)) {
644     if (Corrected.isKeyword()) {
645       // We corrected to a keyword.
646       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
647       II = Corrected.getCorrectionAsIdentifierInfo();
648     } else {
649       // We found a similarly-named type or interface; suggest that.
650       if (!SS || !SS->isSet()) {
651         diagnoseTypo(Corrected,
652                      PDiag(diag::err_unknown_typename_suggest) << II);
653       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
654         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
655         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
656                                 II->getName().equals(CorrectedStr);
657         diagnoseTypo(Corrected,
658                      PDiag(diag::err_unknown_nested_typename_suggest)
659                        << II << DC << DroppedSpecifier << SS->getRange());
660       } else {
661         llvm_unreachable("could not have corrected a typo here");
662       }
663 
664       CXXScopeSpec tmpSS;
665       if (Corrected.getCorrectionSpecifier())
666         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
667                           SourceRange(IILoc));
668       // FIXME: Support class template argument deduction here.
669       SuggestedType =
670           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
671                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
672                       /*IsCtorOrDtorName=*/false,
673                       /*NonTrivialTypeSourceInfo=*/true);
674     }
675     return;
676   }
677 
678   if (getLangOpts().CPlusPlus) {
679     // See if II is a class template that the user forgot to pass arguments to.
680     UnqualifiedId Name;
681     Name.setIdentifier(II, IILoc);
682     CXXScopeSpec EmptySS;
683     TemplateTy TemplateResult;
684     bool MemberOfUnknownSpecialization;
685     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
686                        Name, nullptr, true, TemplateResult,
687                        MemberOfUnknownSpecialization) == TNK_Type_template) {
688       TemplateName TplName = TemplateResult.get();
689       Diag(IILoc, diag::err_template_missing_args)
690         << (int)getTemplateNameKindForDiagnostics(TplName) << TplName;
691       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
692         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
693           << TplDecl->getTemplateParameters()->getSourceRange();
694       }
695       return;
696     }
697   }
698 
699   // FIXME: Should we move the logic that tries to recover from a missing tag
700   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
701 
702   if (!SS || (!SS->isSet() && !SS->isInvalid()))
703     Diag(IILoc, diag::err_unknown_typename) << II;
704   else if (DeclContext *DC = computeDeclContext(*SS, false))
705     Diag(IILoc, diag::err_typename_nested_not_found)
706       << II << DC << SS->getRange();
707   else if (isDependentScopeSpecifier(*SS)) {
708     unsigned DiagID = diag::err_typename_missing;
709     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
710       DiagID = diag::ext_typename_missing;
711 
712     Diag(SS->getRange().getBegin(), DiagID)
713       << SS->getScopeRep() << II->getName()
714       << SourceRange(SS->getRange().getBegin(), IILoc)
715       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
716     SuggestedType = ActOnTypenameType(S, SourceLocation(),
717                                       *SS, *II, IILoc).get();
718   } else {
719     assert(SS && SS->isInvalid() &&
720            "Invalid scope specifier has already been diagnosed");
721   }
722 }
723 
724 /// \brief Determine whether the given result set contains either a type name
725 /// or
726 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
727   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
728                        NextToken.is(tok::less);
729 
730   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
731     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
732       return true;
733 
734     if (CheckTemplate && isa<TemplateDecl>(*I))
735       return true;
736   }
737 
738   return false;
739 }
740 
741 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
742                                     Scope *S, CXXScopeSpec &SS,
743                                     IdentifierInfo *&Name,
744                                     SourceLocation NameLoc) {
745   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
746   SemaRef.LookupParsedName(R, S, &SS);
747   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
748     StringRef FixItTagName;
749     switch (Tag->getTagKind()) {
750       case TTK_Class:
751         FixItTagName = "class ";
752         break;
753 
754       case TTK_Enum:
755         FixItTagName = "enum ";
756         break;
757 
758       case TTK_Struct:
759         FixItTagName = "struct ";
760         break;
761 
762       case TTK_Interface:
763         FixItTagName = "__interface ";
764         break;
765 
766       case TTK_Union:
767         FixItTagName = "union ";
768         break;
769     }
770 
771     StringRef TagName = FixItTagName.drop_back();
772     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
773       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
774       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
775 
776     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
777          I != IEnd; ++I)
778       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
779         << Name << TagName;
780 
781     // Replace lookup results with just the tag decl.
782     Result.clear(Sema::LookupTagName);
783     SemaRef.LookupParsedName(Result, S, &SS);
784     return true;
785   }
786 
787   return false;
788 }
789 
790 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
791 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
792                                   QualType T, SourceLocation NameLoc) {
793   ASTContext &Context = S.Context;
794 
795   TypeLocBuilder Builder;
796   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
797 
798   T = S.getElaboratedType(ETK_None, SS, T);
799   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
800   ElabTL.setElaboratedKeywordLoc(SourceLocation());
801   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
802   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
803 }
804 
805 Sema::NameClassification
806 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
807                    SourceLocation NameLoc, const Token &NextToken,
808                    bool IsAddressOfOperand,
809                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
810   DeclarationNameInfo NameInfo(Name, NameLoc);
811   ObjCMethodDecl *CurMethod = getCurMethodDecl();
812 
813   if (NextToken.is(tok::coloncolon)) {
814     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
815     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
816   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
817              isCurrentClassName(*Name, S, &SS)) {
818     // Per [class.qual]p2, this names the constructors of SS, not the
819     // injected-class-name. We don't have a classification for that.
820     // There's not much point caching this result, since the parser
821     // will reject it later.
822     return NameClassification::Unknown();
823   }
824 
825   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
826   LookupParsedName(Result, S, &SS, !CurMethod);
827 
828   // For unqualified lookup in a class template in MSVC mode, look into
829   // dependent base classes where the primary class template is known.
830   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
831     if (ParsedType TypeInBase =
832             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
833       return TypeInBase;
834   }
835 
836   // Perform lookup for Objective-C instance variables (including automatically
837   // synthesized instance variables), if we're in an Objective-C method.
838   // FIXME: This lookup really, really needs to be folded in to the normal
839   // unqualified lookup mechanism.
840   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
841     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
842     if (E.get() || E.isInvalid())
843       return E;
844   }
845 
846   bool SecondTry = false;
847   bool IsFilteredTemplateName = false;
848 
849 Corrected:
850   switch (Result.getResultKind()) {
851   case LookupResult::NotFound:
852     // If an unqualified-id is followed by a '(', then we have a function
853     // call.
854     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
855       // In C++, this is an ADL-only call.
856       // FIXME: Reference?
857       if (getLangOpts().CPlusPlus)
858         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
859 
860       // C90 6.3.2.2:
861       //   If the expression that precedes the parenthesized argument list in a
862       //   function call consists solely of an identifier, and if no
863       //   declaration is visible for this identifier, the identifier is
864       //   implicitly declared exactly as if, in the innermost block containing
865       //   the function call, the declaration
866       //
867       //     extern int identifier ();
868       //
869       //   appeared.
870       //
871       // We also allow this in C99 as an extension.
872       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
873         Result.addDecl(D);
874         Result.resolveKind();
875         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
876       }
877     }
878 
879     // In C, we first see whether there is a tag type by the same name, in
880     // which case it's likely that the user just forgot to write "enum",
881     // "struct", or "union".
882     if (!getLangOpts().CPlusPlus && !SecondTry &&
883         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
884       break;
885     }
886 
887     // Perform typo correction to determine if there is another name that is
888     // close to this name.
889     if (!SecondTry && CCC) {
890       SecondTry = true;
891       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
892                                                  Result.getLookupKind(), S,
893                                                  &SS, std::move(CCC),
894                                                  CTK_ErrorRecovery)) {
895         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
896         unsigned QualifiedDiag = diag::err_no_member_suggest;
897 
898         NamedDecl *FirstDecl = Corrected.getFoundDecl();
899         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
900         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
901             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
902           UnqualifiedDiag = diag::err_no_template_suggest;
903           QualifiedDiag = diag::err_no_member_template_suggest;
904         } else if (UnderlyingFirstDecl &&
905                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
906                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
907                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
908           UnqualifiedDiag = diag::err_unknown_typename_suggest;
909           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
910         }
911 
912         if (SS.isEmpty()) {
913           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
914         } else {// FIXME: is this even reachable? Test it.
915           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
916           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
917                                   Name->getName().equals(CorrectedStr);
918           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
919                                     << Name << computeDeclContext(SS, false)
920                                     << DroppedSpecifier << SS.getRange());
921         }
922 
923         // Update the name, so that the caller has the new name.
924         Name = Corrected.getCorrectionAsIdentifierInfo();
925 
926         // Typo correction corrected to a keyword.
927         if (Corrected.isKeyword())
928           return Name;
929 
930         // Also update the LookupResult...
931         // FIXME: This should probably go away at some point
932         Result.clear();
933         Result.setLookupName(Corrected.getCorrection());
934         if (FirstDecl)
935           Result.addDecl(FirstDecl);
936 
937         // If we found an Objective-C instance variable, let
938         // LookupInObjCMethod build the appropriate expression to
939         // reference the ivar.
940         // FIXME: This is a gross hack.
941         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
942           Result.clear();
943           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
944           return E;
945         }
946 
947         goto Corrected;
948       }
949     }
950 
951     // We failed to correct; just fall through and let the parser deal with it.
952     Result.suppressDiagnostics();
953     return NameClassification::Unknown();
954 
955   case LookupResult::NotFoundInCurrentInstantiation: {
956     // We performed name lookup into the current instantiation, and there were
957     // dependent bases, so we treat this result the same way as any other
958     // dependent nested-name-specifier.
959 
960     // C++ [temp.res]p2:
961     //   A name used in a template declaration or definition and that is
962     //   dependent on a template-parameter is assumed not to name a type
963     //   unless the applicable name lookup finds a type name or the name is
964     //   qualified by the keyword typename.
965     //
966     // FIXME: If the next token is '<', we might want to ask the parser to
967     // perform some heroics to see if we actually have a
968     // template-argument-list, which would indicate a missing 'template'
969     // keyword here.
970     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
971                                       NameInfo, IsAddressOfOperand,
972                                       /*TemplateArgs=*/nullptr);
973   }
974 
975   case LookupResult::Found:
976   case LookupResult::FoundOverloaded:
977   case LookupResult::FoundUnresolvedValue:
978     break;
979 
980   case LookupResult::Ambiguous:
981     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
982         hasAnyAcceptableTemplateNames(Result)) {
983       // C++ [temp.local]p3:
984       //   A lookup that finds an injected-class-name (10.2) can result in an
985       //   ambiguity in certain cases (for example, if it is found in more than
986       //   one base class). If all of the injected-class-names that are found
987       //   refer to specializations of the same class template, and if the name
988       //   is followed by a template-argument-list, the reference refers to the
989       //   class template itself and not a specialization thereof, and is not
990       //   ambiguous.
991       //
992       // This filtering can make an ambiguous result into an unambiguous one,
993       // so try again after filtering out template names.
994       FilterAcceptableTemplateNames(Result);
995       if (!Result.isAmbiguous()) {
996         IsFilteredTemplateName = true;
997         break;
998       }
999     }
1000 
1001     // Diagnose the ambiguity and return an error.
1002     return NameClassification::Error();
1003   }
1004 
1005   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1006       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
1007     // C++ [temp.names]p3:
1008     //   After name lookup (3.4) finds that a name is a template-name or that
1009     //   an operator-function-id or a literal- operator-id refers to a set of
1010     //   overloaded functions any member of which is a function template if
1011     //   this is followed by a <, the < is always taken as the delimiter of a
1012     //   template-argument-list and never as the less-than operator.
1013     if (!IsFilteredTemplateName)
1014       FilterAcceptableTemplateNames(Result);
1015 
1016     if (!Result.empty()) {
1017       bool IsFunctionTemplate;
1018       bool IsVarTemplate;
1019       TemplateName Template;
1020       if (Result.end() - Result.begin() > 1) {
1021         IsFunctionTemplate = true;
1022         Template = Context.getOverloadedTemplateName(Result.begin(),
1023                                                      Result.end());
1024       } else {
1025         TemplateDecl *TD
1026           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1027         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1028         IsVarTemplate = isa<VarTemplateDecl>(TD);
1029 
1030         if (SS.isSet() && !SS.isInvalid())
1031           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1032                                                     /*TemplateKeyword=*/false,
1033                                                       TD);
1034         else
1035           Template = TemplateName(TD);
1036       }
1037 
1038       if (IsFunctionTemplate) {
1039         // Function templates always go through overload resolution, at which
1040         // point we'll perform the various checks (e.g., accessibility) we need
1041         // to based on which function we selected.
1042         Result.suppressDiagnostics();
1043 
1044         return NameClassification::FunctionTemplate(Template);
1045       }
1046 
1047       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1048                            : NameClassification::TypeTemplate(Template);
1049     }
1050   }
1051 
1052   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1053   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1054     DiagnoseUseOfDecl(Type, NameLoc);
1055     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1056     QualType T = Context.getTypeDeclType(Type);
1057     if (SS.isNotEmpty())
1058       return buildNestedType(*this, SS, T, NameLoc);
1059     return ParsedType::make(T);
1060   }
1061 
1062   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1063   if (!Class) {
1064     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1065     if (ObjCCompatibleAliasDecl *Alias =
1066             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1067       Class = Alias->getClassInterface();
1068   }
1069 
1070   if (Class) {
1071     DiagnoseUseOfDecl(Class, NameLoc);
1072 
1073     if (NextToken.is(tok::period)) {
1074       // Interface. <something> is parsed as a property reference expression.
1075       // Just return "unknown" as a fall-through for now.
1076       Result.suppressDiagnostics();
1077       return NameClassification::Unknown();
1078     }
1079 
1080     QualType T = Context.getObjCInterfaceType(Class);
1081     return ParsedType::make(T);
1082   }
1083 
1084   // We can have a type template here if we're classifying a template argument.
1085   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1086       !isa<VarTemplateDecl>(FirstDecl))
1087     return NameClassification::TypeTemplate(
1088         TemplateName(cast<TemplateDecl>(FirstDecl)));
1089 
1090   // Check for a tag type hidden by a non-type decl in a few cases where it
1091   // seems likely a type is wanted instead of the non-type that was found.
1092   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1093   if ((NextToken.is(tok::identifier) ||
1094        (NextIsOp &&
1095         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1096       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1097     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1098     DiagnoseUseOfDecl(Type, NameLoc);
1099     QualType T = Context.getTypeDeclType(Type);
1100     if (SS.isNotEmpty())
1101       return buildNestedType(*this, SS, T, NameLoc);
1102     return ParsedType::make(T);
1103   }
1104 
1105   if (FirstDecl->isCXXClassMember())
1106     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1107                                            nullptr, S);
1108 
1109   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1110   return BuildDeclarationNameExpr(SS, Result, ADL);
1111 }
1112 
1113 Sema::TemplateNameKindForDiagnostics
1114 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1115   auto *TD = Name.getAsTemplateDecl();
1116   if (!TD)
1117     return TemplateNameKindForDiagnostics::DependentTemplate;
1118   if (isa<ClassTemplateDecl>(TD))
1119     return TemplateNameKindForDiagnostics::ClassTemplate;
1120   if (isa<FunctionTemplateDecl>(TD))
1121     return TemplateNameKindForDiagnostics::FunctionTemplate;
1122   if (isa<VarTemplateDecl>(TD))
1123     return TemplateNameKindForDiagnostics::VarTemplate;
1124   if (isa<TypeAliasTemplateDecl>(TD))
1125     return TemplateNameKindForDiagnostics::AliasTemplate;
1126   if (isa<TemplateTemplateParmDecl>(TD))
1127     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1128   return TemplateNameKindForDiagnostics::DependentTemplate;
1129 }
1130 
1131 // Determines the context to return to after temporarily entering a
1132 // context.  This depends in an unnecessarily complicated way on the
1133 // exact ordering of callbacks from the parser.
1134 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1135 
1136   // Functions defined inline within classes aren't parsed until we've
1137   // finished parsing the top-level class, so the top-level class is
1138   // the context we'll need to return to.
1139   // A Lambda call operator whose parent is a class must not be treated
1140   // as an inline member function.  A Lambda can be used legally
1141   // either as an in-class member initializer or a default argument.  These
1142   // are parsed once the class has been marked complete and so the containing
1143   // context would be the nested class (when the lambda is defined in one);
1144   // If the class is not complete, then the lambda is being used in an
1145   // ill-formed fashion (such as to specify the width of a bit-field, or
1146   // in an array-bound) - in which case we still want to return the
1147   // lexically containing DC (which could be a nested class).
1148   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1149     DC = DC->getLexicalParent();
1150 
1151     // A function not defined within a class will always return to its
1152     // lexical context.
1153     if (!isa<CXXRecordDecl>(DC))
1154       return DC;
1155 
1156     // A C++ inline method/friend is parsed *after* the topmost class
1157     // it was declared in is fully parsed ("complete");  the topmost
1158     // class is the context we need to return to.
1159     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1160       DC = RD;
1161 
1162     // Return the declaration context of the topmost class the inline method is
1163     // declared in.
1164     return DC;
1165   }
1166 
1167   return DC->getLexicalParent();
1168 }
1169 
1170 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1171   assert(getContainingDC(DC) == CurContext &&
1172       "The next DeclContext should be lexically contained in the current one.");
1173   CurContext = DC;
1174   S->setEntity(DC);
1175 }
1176 
1177 void Sema::PopDeclContext() {
1178   assert(CurContext && "DeclContext imbalance!");
1179 
1180   CurContext = getContainingDC(CurContext);
1181   assert(CurContext && "Popped translation unit!");
1182 }
1183 
1184 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1185                                                                     Decl *D) {
1186   // Unlike PushDeclContext, the context to which we return is not necessarily
1187   // the containing DC of TD, because the new context will be some pre-existing
1188   // TagDecl definition instead of a fresh one.
1189   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1190   CurContext = cast<TagDecl>(D)->getDefinition();
1191   assert(CurContext && "skipping definition of undefined tag");
1192   // Start lookups from the parent of the current context; we don't want to look
1193   // into the pre-existing complete definition.
1194   S->setEntity(CurContext->getLookupParent());
1195   return Result;
1196 }
1197 
1198 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1199   CurContext = static_cast<decltype(CurContext)>(Context);
1200 }
1201 
1202 /// EnterDeclaratorContext - Used when we must lookup names in the context
1203 /// of a declarator's nested name specifier.
1204 ///
1205 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1206   // C++0x [basic.lookup.unqual]p13:
1207   //   A name used in the definition of a static data member of class
1208   //   X (after the qualified-id of the static member) is looked up as
1209   //   if the name was used in a member function of X.
1210   // C++0x [basic.lookup.unqual]p14:
1211   //   If a variable member of a namespace is defined outside of the
1212   //   scope of its namespace then any name used in the definition of
1213   //   the variable member (after the declarator-id) is looked up as
1214   //   if the definition of the variable member occurred in its
1215   //   namespace.
1216   // Both of these imply that we should push a scope whose context
1217   // is the semantic context of the declaration.  We can't use
1218   // PushDeclContext here because that context is not necessarily
1219   // lexically contained in the current context.  Fortunately,
1220   // the containing scope should have the appropriate information.
1221 
1222   assert(!S->getEntity() && "scope already has entity");
1223 
1224 #ifndef NDEBUG
1225   Scope *Ancestor = S->getParent();
1226   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1227   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1228 #endif
1229 
1230   CurContext = DC;
1231   S->setEntity(DC);
1232 }
1233 
1234 void Sema::ExitDeclaratorContext(Scope *S) {
1235   assert(S->getEntity() == CurContext && "Context imbalance!");
1236 
1237   // Switch back to the lexical context.  The safety of this is
1238   // enforced by an assert in EnterDeclaratorContext.
1239   Scope *Ancestor = S->getParent();
1240   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1241   CurContext = Ancestor->getEntity();
1242 
1243   // We don't need to do anything with the scope, which is going to
1244   // disappear.
1245 }
1246 
1247 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1248   // We assume that the caller has already called
1249   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1250   FunctionDecl *FD = D->getAsFunction();
1251   if (!FD)
1252     return;
1253 
1254   // Same implementation as PushDeclContext, but enters the context
1255   // from the lexical parent, rather than the top-level class.
1256   assert(CurContext == FD->getLexicalParent() &&
1257     "The next DeclContext should be lexically contained in the current one.");
1258   CurContext = FD;
1259   S->setEntity(CurContext);
1260 
1261   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1262     ParmVarDecl *Param = FD->getParamDecl(P);
1263     // If the parameter has an identifier, then add it to the scope
1264     if (Param->getIdentifier()) {
1265       S->AddDecl(Param);
1266       IdResolver.AddDecl(Param);
1267     }
1268   }
1269 }
1270 
1271 void Sema::ActOnExitFunctionContext() {
1272   // Same implementation as PopDeclContext, but returns to the lexical parent,
1273   // rather than the top-level class.
1274   assert(CurContext && "DeclContext imbalance!");
1275   CurContext = CurContext->getLexicalParent();
1276   assert(CurContext && "Popped translation unit!");
1277 }
1278 
1279 /// \brief Determine whether we allow overloading of the function
1280 /// PrevDecl with another declaration.
1281 ///
1282 /// This routine determines whether overloading is possible, not
1283 /// whether some new function is actually an overload. It will return
1284 /// true in C++ (where we can always provide overloads) or, as an
1285 /// extension, in C when the previous function is already an
1286 /// overloaded function declaration or has the "overloadable"
1287 /// attribute.
1288 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1289                                        ASTContext &Context) {
1290   if (Context.getLangOpts().CPlusPlus)
1291     return true;
1292 
1293   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1294     return true;
1295 
1296   return (Previous.getResultKind() == LookupResult::Found
1297           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1298 }
1299 
1300 /// Add this decl to the scope shadowed decl chains.
1301 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1302   // Move up the scope chain until we find the nearest enclosing
1303   // non-transparent context. The declaration will be introduced into this
1304   // scope.
1305   while (S->getEntity() && S->getEntity()->isTransparentContext())
1306     S = S->getParent();
1307 
1308   // Add scoped declarations into their context, so that they can be
1309   // found later. Declarations without a context won't be inserted
1310   // into any context.
1311   if (AddToContext)
1312     CurContext->addDecl(D);
1313 
1314   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1315   // are function-local declarations.
1316   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1317       !D->getDeclContext()->getRedeclContext()->Equals(
1318         D->getLexicalDeclContext()->getRedeclContext()) &&
1319       !D->getLexicalDeclContext()->isFunctionOrMethod())
1320     return;
1321 
1322   // Template instantiations should also not be pushed into scope.
1323   if (isa<FunctionDecl>(D) &&
1324       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1325     return;
1326 
1327   // If this replaces anything in the current scope,
1328   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1329                                IEnd = IdResolver.end();
1330   for (; I != IEnd; ++I) {
1331     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1332       S->RemoveDecl(*I);
1333       IdResolver.RemoveDecl(*I);
1334 
1335       // Should only need to replace one decl.
1336       break;
1337     }
1338   }
1339 
1340   S->AddDecl(D);
1341 
1342   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1343     // Implicitly-generated labels may end up getting generated in an order that
1344     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1345     // the label at the appropriate place in the identifier chain.
1346     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1347       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1348       if (IDC == CurContext) {
1349         if (!S->isDeclScope(*I))
1350           continue;
1351       } else if (IDC->Encloses(CurContext))
1352         break;
1353     }
1354 
1355     IdResolver.InsertDeclAfter(I, D);
1356   } else {
1357     IdResolver.AddDecl(D);
1358   }
1359 }
1360 
1361 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1362   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1363     TUScope->AddDecl(D);
1364 }
1365 
1366 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1367                          bool AllowInlineNamespace) {
1368   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1369 }
1370 
1371 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1372   DeclContext *TargetDC = DC->getPrimaryContext();
1373   do {
1374     if (DeclContext *ScopeDC = S->getEntity())
1375       if (ScopeDC->getPrimaryContext() == TargetDC)
1376         return S;
1377   } while ((S = S->getParent()));
1378 
1379   return nullptr;
1380 }
1381 
1382 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1383                                             DeclContext*,
1384                                             ASTContext&);
1385 
1386 /// Filters out lookup results that don't fall within the given scope
1387 /// as determined by isDeclInScope.
1388 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1389                                 bool ConsiderLinkage,
1390                                 bool AllowInlineNamespace) {
1391   LookupResult::Filter F = R.makeFilter();
1392   while (F.hasNext()) {
1393     NamedDecl *D = F.next();
1394 
1395     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1396       continue;
1397 
1398     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1399       continue;
1400 
1401     F.erase();
1402   }
1403 
1404   F.done();
1405 }
1406 
1407 static bool isUsingDecl(NamedDecl *D) {
1408   return isa<UsingShadowDecl>(D) ||
1409          isa<UnresolvedUsingTypenameDecl>(D) ||
1410          isa<UnresolvedUsingValueDecl>(D);
1411 }
1412 
1413 /// Removes using shadow declarations from the lookup results.
1414 static void RemoveUsingDecls(LookupResult &R) {
1415   LookupResult::Filter F = R.makeFilter();
1416   while (F.hasNext())
1417     if (isUsingDecl(F.next()))
1418       F.erase();
1419 
1420   F.done();
1421 }
1422 
1423 /// \brief Check for this common pattern:
1424 /// @code
1425 /// class S {
1426 ///   S(const S&); // DO NOT IMPLEMENT
1427 ///   void operator=(const S&); // DO NOT IMPLEMENT
1428 /// };
1429 /// @endcode
1430 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1431   // FIXME: Should check for private access too but access is set after we get
1432   // the decl here.
1433   if (D->doesThisDeclarationHaveABody())
1434     return false;
1435 
1436   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1437     return CD->isCopyConstructor();
1438   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1439     return Method->isCopyAssignmentOperator();
1440   return false;
1441 }
1442 
1443 // We need this to handle
1444 //
1445 // typedef struct {
1446 //   void *foo() { return 0; }
1447 // } A;
1448 //
1449 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1450 // for example. If 'A', foo will have external linkage. If we have '*A',
1451 // foo will have no linkage. Since we can't know until we get to the end
1452 // of the typedef, this function finds out if D might have non-external linkage.
1453 // Callers should verify at the end of the TU if it D has external linkage or
1454 // not.
1455 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1456   const DeclContext *DC = D->getDeclContext();
1457   while (!DC->isTranslationUnit()) {
1458     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1459       if (!RD->hasNameForLinkage())
1460         return true;
1461     }
1462     DC = DC->getParent();
1463   }
1464 
1465   return !D->isExternallyVisible();
1466 }
1467 
1468 // FIXME: This needs to be refactored; some other isInMainFile users want
1469 // these semantics.
1470 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1471   if (S.TUKind != TU_Complete)
1472     return false;
1473   return S.SourceMgr.isInMainFile(Loc);
1474 }
1475 
1476 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1477   assert(D);
1478 
1479   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1480     return false;
1481 
1482   // Ignore all entities declared within templates, and out-of-line definitions
1483   // of members of class templates.
1484   if (D->getDeclContext()->isDependentContext() ||
1485       D->getLexicalDeclContext()->isDependentContext())
1486     return false;
1487 
1488   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1489     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1490       return false;
1491 
1492     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1493       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1494         return false;
1495     } else {
1496       // 'static inline' functions are defined in headers; don't warn.
1497       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1498         return false;
1499     }
1500 
1501     if (FD->doesThisDeclarationHaveABody() &&
1502         Context.DeclMustBeEmitted(FD))
1503       return false;
1504   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1505     // Constants and utility variables are defined in headers with internal
1506     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1507     // like "inline".)
1508     if (!isMainFileLoc(*this, VD->getLocation()))
1509       return false;
1510 
1511     if (Context.DeclMustBeEmitted(VD))
1512       return false;
1513 
1514     if (VD->isStaticDataMember() &&
1515         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1516       return false;
1517 
1518     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1519       return false;
1520   } else {
1521     return false;
1522   }
1523 
1524   // Only warn for unused decls internal to the translation unit.
1525   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1526   // for inline functions defined in the main source file, for instance.
1527   return mightHaveNonExternalLinkage(D);
1528 }
1529 
1530 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1531   if (!D)
1532     return;
1533 
1534   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1535     const FunctionDecl *First = FD->getFirstDecl();
1536     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1537       return; // First should already be in the vector.
1538   }
1539 
1540   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1541     const VarDecl *First = VD->getFirstDecl();
1542     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1543       return; // First should already be in the vector.
1544   }
1545 
1546   if (ShouldWarnIfUnusedFileScopedDecl(D))
1547     UnusedFileScopedDecls.push_back(D);
1548 }
1549 
1550 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1551   if (D->isInvalidDecl())
1552     return false;
1553 
1554   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1555       D->hasAttr<ObjCPreciseLifetimeAttr>())
1556     return false;
1557 
1558   if (isa<LabelDecl>(D))
1559     return true;
1560 
1561   // Except for labels, we only care about unused decls that are local to
1562   // functions.
1563   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1564   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1565     // For dependent types, the diagnostic is deferred.
1566     WithinFunction =
1567         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1568   if (!WithinFunction)
1569     return false;
1570 
1571   if (isa<TypedefNameDecl>(D))
1572     return true;
1573 
1574   // White-list anything that isn't a local variable.
1575   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1576     return false;
1577 
1578   // Types of valid local variables should be complete, so this should succeed.
1579   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1580 
1581     // White-list anything with an __attribute__((unused)) type.
1582     const auto *Ty = VD->getType().getTypePtr();
1583 
1584     // Only look at the outermost level of typedef.
1585     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1586       if (TT->getDecl()->hasAttr<UnusedAttr>())
1587         return false;
1588     }
1589 
1590     // If we failed to complete the type for some reason, or if the type is
1591     // dependent, don't diagnose the variable.
1592     if (Ty->isIncompleteType() || Ty->isDependentType())
1593       return false;
1594 
1595     // Look at the element type to ensure that the warning behaviour is
1596     // consistent for both scalars and arrays.
1597     Ty = Ty->getBaseElementTypeUnsafe();
1598 
1599     if (const TagType *TT = Ty->getAs<TagType>()) {
1600       const TagDecl *Tag = TT->getDecl();
1601       if (Tag->hasAttr<UnusedAttr>())
1602         return false;
1603 
1604       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1605         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1606           return false;
1607 
1608         if (const Expr *Init = VD->getInit()) {
1609           if (const ExprWithCleanups *Cleanups =
1610                   dyn_cast<ExprWithCleanups>(Init))
1611             Init = Cleanups->getSubExpr();
1612           const CXXConstructExpr *Construct =
1613             dyn_cast<CXXConstructExpr>(Init);
1614           if (Construct && !Construct->isElidable()) {
1615             CXXConstructorDecl *CD = Construct->getConstructor();
1616             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1617               return false;
1618           }
1619         }
1620       }
1621     }
1622 
1623     // TODO: __attribute__((unused)) templates?
1624   }
1625 
1626   return true;
1627 }
1628 
1629 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1630                                      FixItHint &Hint) {
1631   if (isa<LabelDecl>(D)) {
1632     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1633                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1634     if (AfterColon.isInvalid())
1635       return;
1636     Hint = FixItHint::CreateRemoval(CharSourceRange::
1637                                     getCharRange(D->getLocStart(), AfterColon));
1638   }
1639 }
1640 
1641 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1642   if (D->getTypeForDecl()->isDependentType())
1643     return;
1644 
1645   for (auto *TmpD : D->decls()) {
1646     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1647       DiagnoseUnusedDecl(T);
1648     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1649       DiagnoseUnusedNestedTypedefs(R);
1650   }
1651 }
1652 
1653 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1654 /// unless they are marked attr(unused).
1655 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1656   if (!ShouldDiagnoseUnusedDecl(D))
1657     return;
1658 
1659   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1660     // typedefs can be referenced later on, so the diagnostics are emitted
1661     // at end-of-translation-unit.
1662     UnusedLocalTypedefNameCandidates.insert(TD);
1663     return;
1664   }
1665 
1666   FixItHint Hint;
1667   GenerateFixForUnusedDecl(D, Context, Hint);
1668 
1669   unsigned DiagID;
1670   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1671     DiagID = diag::warn_unused_exception_param;
1672   else if (isa<LabelDecl>(D))
1673     DiagID = diag::warn_unused_label;
1674   else
1675     DiagID = diag::warn_unused_variable;
1676 
1677   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1678 }
1679 
1680 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1681   // Verify that we have no forward references left.  If so, there was a goto
1682   // or address of a label taken, but no definition of it.  Label fwd
1683   // definitions are indicated with a null substmt which is also not a resolved
1684   // MS inline assembly label name.
1685   bool Diagnose = false;
1686   if (L->isMSAsmLabel())
1687     Diagnose = !L->isResolvedMSAsmLabel();
1688   else
1689     Diagnose = L->getStmt() == nullptr;
1690   if (Diagnose)
1691     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1692 }
1693 
1694 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1695   S->mergeNRVOIntoParent();
1696 
1697   if (S->decl_empty()) return;
1698   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1699          "Scope shouldn't contain decls!");
1700 
1701   for (auto *TmpD : S->decls()) {
1702     assert(TmpD && "This decl didn't get pushed??");
1703 
1704     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1705     NamedDecl *D = cast<NamedDecl>(TmpD);
1706 
1707     if (!D->getDeclName()) continue;
1708 
1709     // Diagnose unused variables in this scope.
1710     if (!S->hasUnrecoverableErrorOccurred()) {
1711       DiagnoseUnusedDecl(D);
1712       if (const auto *RD = dyn_cast<RecordDecl>(D))
1713         DiagnoseUnusedNestedTypedefs(RD);
1714     }
1715 
1716     // If this was a forward reference to a label, verify it was defined.
1717     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1718       CheckPoppedLabel(LD, *this);
1719 
1720     // Remove this name from our lexical scope, and warn on it if we haven't
1721     // already.
1722     IdResolver.RemoveDecl(D);
1723     auto ShadowI = ShadowingDecls.find(D);
1724     if (ShadowI != ShadowingDecls.end()) {
1725       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1726         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1727             << D << FD << FD->getParent();
1728         Diag(FD->getLocation(), diag::note_previous_declaration);
1729       }
1730       ShadowingDecls.erase(ShadowI);
1731     }
1732   }
1733 }
1734 
1735 /// \brief Look for an Objective-C class in the translation unit.
1736 ///
1737 /// \param Id The name of the Objective-C class we're looking for. If
1738 /// typo-correction fixes this name, the Id will be updated
1739 /// to the fixed name.
1740 ///
1741 /// \param IdLoc The location of the name in the translation unit.
1742 ///
1743 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1744 /// if there is no class with the given name.
1745 ///
1746 /// \returns The declaration of the named Objective-C class, or NULL if the
1747 /// class could not be found.
1748 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1749                                               SourceLocation IdLoc,
1750                                               bool DoTypoCorrection) {
1751   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1752   // creation from this context.
1753   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1754 
1755   if (!IDecl && DoTypoCorrection) {
1756     // Perform typo correction at the given location, but only if we
1757     // find an Objective-C class name.
1758     if (TypoCorrection C = CorrectTypo(
1759             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1760             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1761             CTK_ErrorRecovery)) {
1762       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1763       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1764       Id = IDecl->getIdentifier();
1765     }
1766   }
1767   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1768   // This routine must always return a class definition, if any.
1769   if (Def && Def->getDefinition())
1770       Def = Def->getDefinition();
1771   return Def;
1772 }
1773 
1774 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1775 /// from S, where a non-field would be declared. This routine copes
1776 /// with the difference between C and C++ scoping rules in structs and
1777 /// unions. For example, the following code is well-formed in C but
1778 /// ill-formed in C++:
1779 /// @code
1780 /// struct S6 {
1781 ///   enum { BAR } e;
1782 /// };
1783 ///
1784 /// void test_S6() {
1785 ///   struct S6 a;
1786 ///   a.e = BAR;
1787 /// }
1788 /// @endcode
1789 /// For the declaration of BAR, this routine will return a different
1790 /// scope. The scope S will be the scope of the unnamed enumeration
1791 /// within S6. In C++, this routine will return the scope associated
1792 /// with S6, because the enumeration's scope is a transparent
1793 /// context but structures can contain non-field names. In C, this
1794 /// routine will return the translation unit scope, since the
1795 /// enumeration's scope is a transparent context and structures cannot
1796 /// contain non-field names.
1797 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1798   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1799          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1800          (S->isClassScope() && !getLangOpts().CPlusPlus))
1801     S = S->getParent();
1802   return S;
1803 }
1804 
1805 /// \brief Looks up the declaration of "struct objc_super" and
1806 /// saves it for later use in building builtin declaration of
1807 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1808 /// pre-existing declaration exists no action takes place.
1809 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1810                                         IdentifierInfo *II) {
1811   if (!II->isStr("objc_msgSendSuper"))
1812     return;
1813   ASTContext &Context = ThisSema.Context;
1814 
1815   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1816                       SourceLocation(), Sema::LookupTagName);
1817   ThisSema.LookupName(Result, S);
1818   if (Result.getResultKind() == LookupResult::Found)
1819     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1820       Context.setObjCSuperType(Context.getTagDeclType(TD));
1821 }
1822 
1823 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1824   switch (Error) {
1825   case ASTContext::GE_None:
1826     return "";
1827   case ASTContext::GE_Missing_stdio:
1828     return "stdio.h";
1829   case ASTContext::GE_Missing_setjmp:
1830     return "setjmp.h";
1831   case ASTContext::GE_Missing_ucontext:
1832     return "ucontext.h";
1833   }
1834   llvm_unreachable("unhandled error kind");
1835 }
1836 
1837 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1838 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1839 /// if we're creating this built-in in anticipation of redeclaring the
1840 /// built-in.
1841 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1842                                      Scope *S, bool ForRedeclaration,
1843                                      SourceLocation Loc) {
1844   LookupPredefedObjCSuperType(*this, S, II);
1845 
1846   ASTContext::GetBuiltinTypeError Error;
1847   QualType R = Context.GetBuiltinType(ID, Error);
1848   if (Error) {
1849     if (ForRedeclaration)
1850       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1851           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1852     return nullptr;
1853   }
1854 
1855   if (!ForRedeclaration &&
1856       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1857        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1858     Diag(Loc, diag::ext_implicit_lib_function_decl)
1859         << Context.BuiltinInfo.getName(ID) << R;
1860     if (Context.BuiltinInfo.getHeaderName(ID) &&
1861         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1862       Diag(Loc, diag::note_include_header_or_declare)
1863           << Context.BuiltinInfo.getHeaderName(ID)
1864           << Context.BuiltinInfo.getName(ID);
1865   }
1866 
1867   if (R.isNull())
1868     return nullptr;
1869 
1870   DeclContext *Parent = Context.getTranslationUnitDecl();
1871   if (getLangOpts().CPlusPlus) {
1872     LinkageSpecDecl *CLinkageDecl =
1873         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1874                                 LinkageSpecDecl::lang_c, false);
1875     CLinkageDecl->setImplicit();
1876     Parent->addDecl(CLinkageDecl);
1877     Parent = CLinkageDecl;
1878   }
1879 
1880   FunctionDecl *New = FunctionDecl::Create(Context,
1881                                            Parent,
1882                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1883                                            SC_Extern,
1884                                            false,
1885                                            R->isFunctionProtoType());
1886   New->setImplicit();
1887 
1888   // Create Decl objects for each parameter, adding them to the
1889   // FunctionDecl.
1890   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1891     SmallVector<ParmVarDecl*, 16> Params;
1892     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1893       ParmVarDecl *parm =
1894           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1895                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1896                               SC_None, nullptr);
1897       parm->setScopeInfo(0, i);
1898       Params.push_back(parm);
1899     }
1900     New->setParams(Params);
1901   }
1902 
1903   AddKnownFunctionAttributes(New);
1904   RegisterLocallyScopedExternCDecl(New, S);
1905 
1906   // TUScope is the translation-unit scope to insert this function into.
1907   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1908   // relate Scopes to DeclContexts, and probably eliminate CurContext
1909   // entirely, but we're not there yet.
1910   DeclContext *SavedContext = CurContext;
1911   CurContext = Parent;
1912   PushOnScopeChains(New, TUScope);
1913   CurContext = SavedContext;
1914   return New;
1915 }
1916 
1917 /// Typedef declarations don't have linkage, but they still denote the same
1918 /// entity if their types are the same.
1919 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1920 /// isSameEntity.
1921 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1922                                                      TypedefNameDecl *Decl,
1923                                                      LookupResult &Previous) {
1924   // This is only interesting when modules are enabled.
1925   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1926     return;
1927 
1928   // Empty sets are uninteresting.
1929   if (Previous.empty())
1930     return;
1931 
1932   LookupResult::Filter Filter = Previous.makeFilter();
1933   while (Filter.hasNext()) {
1934     NamedDecl *Old = Filter.next();
1935 
1936     // Non-hidden declarations are never ignored.
1937     if (S.isVisible(Old))
1938       continue;
1939 
1940     // Declarations of the same entity are not ignored, even if they have
1941     // different linkages.
1942     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1943       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1944                                 Decl->getUnderlyingType()))
1945         continue;
1946 
1947       // If both declarations give a tag declaration a typedef name for linkage
1948       // purposes, then they declare the same entity.
1949       if (S.getLangOpts().CPlusPlus &&
1950           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1951           Decl->getAnonDeclWithTypedefName())
1952         continue;
1953     }
1954 
1955     Filter.erase();
1956   }
1957 
1958   Filter.done();
1959 }
1960 
1961 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1962   QualType OldType;
1963   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1964     OldType = OldTypedef->getUnderlyingType();
1965   else
1966     OldType = Context.getTypeDeclType(Old);
1967   QualType NewType = New->getUnderlyingType();
1968 
1969   if (NewType->isVariablyModifiedType()) {
1970     // Must not redefine a typedef with a variably-modified type.
1971     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1972     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1973       << Kind << NewType;
1974     if (Old->getLocation().isValid())
1975       Diag(Old->getLocation(), diag::note_previous_definition);
1976     New->setInvalidDecl();
1977     return true;
1978   }
1979 
1980   if (OldType != NewType &&
1981       !OldType->isDependentType() &&
1982       !NewType->isDependentType() &&
1983       !Context.hasSameType(OldType, NewType)) {
1984     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1985     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1986       << Kind << NewType << OldType;
1987     if (Old->getLocation().isValid())
1988       Diag(Old->getLocation(), diag::note_previous_definition);
1989     New->setInvalidDecl();
1990     return true;
1991   }
1992   return false;
1993 }
1994 
1995 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1996 /// same name and scope as a previous declaration 'Old'.  Figure out
1997 /// how to resolve this situation, merging decls or emitting
1998 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1999 ///
2000 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2001                                 LookupResult &OldDecls) {
2002   // If the new decl is known invalid already, don't bother doing any
2003   // merging checks.
2004   if (New->isInvalidDecl()) return;
2005 
2006   // Allow multiple definitions for ObjC built-in typedefs.
2007   // FIXME: Verify the underlying types are equivalent!
2008   if (getLangOpts().ObjC1) {
2009     const IdentifierInfo *TypeID = New->getIdentifier();
2010     switch (TypeID->getLength()) {
2011     default: break;
2012     case 2:
2013       {
2014         if (!TypeID->isStr("id"))
2015           break;
2016         QualType T = New->getUnderlyingType();
2017         if (!T->isPointerType())
2018           break;
2019         if (!T->isVoidPointerType()) {
2020           QualType PT = T->getAs<PointerType>()->getPointeeType();
2021           if (!PT->isStructureType())
2022             break;
2023         }
2024         Context.setObjCIdRedefinitionType(T);
2025         // Install the built-in type for 'id', ignoring the current definition.
2026         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2027         return;
2028       }
2029     case 5:
2030       if (!TypeID->isStr("Class"))
2031         break;
2032       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2033       // Install the built-in type for 'Class', ignoring the current definition.
2034       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2035       return;
2036     case 3:
2037       if (!TypeID->isStr("SEL"))
2038         break;
2039       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2040       // Install the built-in type for 'SEL', ignoring the current definition.
2041       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2042       return;
2043     }
2044     // Fall through - the typedef name was not a builtin type.
2045   }
2046 
2047   // Verify the old decl was also a type.
2048   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2049   if (!Old) {
2050     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2051       << New->getDeclName();
2052 
2053     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2054     if (OldD->getLocation().isValid())
2055       Diag(OldD->getLocation(), diag::note_previous_definition);
2056 
2057     return New->setInvalidDecl();
2058   }
2059 
2060   // If the old declaration is invalid, just give up here.
2061   if (Old->isInvalidDecl())
2062     return New->setInvalidDecl();
2063 
2064   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2065     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2066     auto *NewTag = New->getAnonDeclWithTypedefName();
2067     NamedDecl *Hidden = nullptr;
2068     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
2069         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2070         !hasVisibleDefinition(OldTag, &Hidden)) {
2071       // There is a definition of this tag, but it is not visible. Use it
2072       // instead of our tag.
2073       New->setTypeForDecl(OldTD->getTypeForDecl());
2074       if (OldTD->isModed())
2075         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2076                                     OldTD->getUnderlyingType());
2077       else
2078         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2079 
2080       // Make the old tag definition visible.
2081       makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
2082 
2083       // If this was an unscoped enumeration, yank all of its enumerators
2084       // out of the scope.
2085       if (isa<EnumDecl>(NewTag)) {
2086         Scope *EnumScope = getNonFieldDeclScope(S);
2087         for (auto *D : NewTag->decls()) {
2088           auto *ED = cast<EnumConstantDecl>(D);
2089           assert(EnumScope->isDeclScope(ED));
2090           EnumScope->RemoveDecl(ED);
2091           IdResolver.RemoveDecl(ED);
2092           ED->getLexicalDeclContext()->removeDecl(ED);
2093         }
2094       }
2095     }
2096   }
2097 
2098   // If the typedef types are not identical, reject them in all languages and
2099   // with any extensions enabled.
2100   if (isIncompatibleTypedef(Old, New))
2101     return;
2102 
2103   // The types match.  Link up the redeclaration chain and merge attributes if
2104   // the old declaration was a typedef.
2105   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2106     New->setPreviousDecl(Typedef);
2107     mergeDeclAttributes(New, Old);
2108   }
2109 
2110   if (getLangOpts().MicrosoftExt)
2111     return;
2112 
2113   if (getLangOpts().CPlusPlus) {
2114     // C++ [dcl.typedef]p2:
2115     //   In a given non-class scope, a typedef specifier can be used to
2116     //   redefine the name of any type declared in that scope to refer
2117     //   to the type to which it already refers.
2118     if (!isa<CXXRecordDecl>(CurContext))
2119       return;
2120 
2121     // C++0x [dcl.typedef]p4:
2122     //   In a given class scope, a typedef specifier can be used to redefine
2123     //   any class-name declared in that scope that is not also a typedef-name
2124     //   to refer to the type to which it already refers.
2125     //
2126     // This wording came in via DR424, which was a correction to the
2127     // wording in DR56, which accidentally banned code like:
2128     //
2129     //   struct S {
2130     //     typedef struct A { } A;
2131     //   };
2132     //
2133     // in the C++03 standard. We implement the C++0x semantics, which
2134     // allow the above but disallow
2135     //
2136     //   struct S {
2137     //     typedef int I;
2138     //     typedef int I;
2139     //   };
2140     //
2141     // since that was the intent of DR56.
2142     if (!isa<TypedefNameDecl>(Old))
2143       return;
2144 
2145     Diag(New->getLocation(), diag::err_redefinition)
2146       << New->getDeclName();
2147     Diag(Old->getLocation(), diag::note_previous_definition);
2148     return New->setInvalidDecl();
2149   }
2150 
2151   // Modules always permit redefinition of typedefs, as does C11.
2152   if (getLangOpts().Modules || getLangOpts().C11)
2153     return;
2154 
2155   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2156   // is normally mapped to an error, but can be controlled with
2157   // -Wtypedef-redefinition.  If either the original or the redefinition is
2158   // in a system header, don't emit this for compatibility with GCC.
2159   if (getDiagnostics().getSuppressSystemWarnings() &&
2160       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2161       (Old->isImplicit() ||
2162        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2163        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2164     return;
2165 
2166   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2167     << New->getDeclName();
2168   Diag(Old->getLocation(), diag::note_previous_definition);
2169 }
2170 
2171 /// DeclhasAttr - returns true if decl Declaration already has the target
2172 /// attribute.
2173 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2174   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2175   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2176   for (const auto *i : D->attrs())
2177     if (i->getKind() == A->getKind()) {
2178       if (Ann) {
2179         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2180           return true;
2181         continue;
2182       }
2183       // FIXME: Don't hardcode this check
2184       if (OA && isa<OwnershipAttr>(i))
2185         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2186       return true;
2187     }
2188 
2189   return false;
2190 }
2191 
2192 static bool isAttributeTargetADefinition(Decl *D) {
2193   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2194     return VD->isThisDeclarationADefinition();
2195   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2196     return TD->isCompleteDefinition() || TD->isBeingDefined();
2197   return true;
2198 }
2199 
2200 /// Merge alignment attributes from \p Old to \p New, taking into account the
2201 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2202 ///
2203 /// \return \c true if any attributes were added to \p New.
2204 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2205   // Look for alignas attributes on Old, and pick out whichever attribute
2206   // specifies the strictest alignment requirement.
2207   AlignedAttr *OldAlignasAttr = nullptr;
2208   AlignedAttr *OldStrictestAlignAttr = nullptr;
2209   unsigned OldAlign = 0;
2210   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2211     // FIXME: We have no way of representing inherited dependent alignments
2212     // in a case like:
2213     //   template<int A, int B> struct alignas(A) X;
2214     //   template<int A, int B> struct alignas(B) X {};
2215     // For now, we just ignore any alignas attributes which are not on the
2216     // definition in such a case.
2217     if (I->isAlignmentDependent())
2218       return false;
2219 
2220     if (I->isAlignas())
2221       OldAlignasAttr = I;
2222 
2223     unsigned Align = I->getAlignment(S.Context);
2224     if (Align > OldAlign) {
2225       OldAlign = Align;
2226       OldStrictestAlignAttr = I;
2227     }
2228   }
2229 
2230   // Look for alignas attributes on New.
2231   AlignedAttr *NewAlignasAttr = nullptr;
2232   unsigned NewAlign = 0;
2233   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2234     if (I->isAlignmentDependent())
2235       return false;
2236 
2237     if (I->isAlignas())
2238       NewAlignasAttr = I;
2239 
2240     unsigned Align = I->getAlignment(S.Context);
2241     if (Align > NewAlign)
2242       NewAlign = Align;
2243   }
2244 
2245   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2246     // Both declarations have 'alignas' attributes. We require them to match.
2247     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2248     // fall short. (If two declarations both have alignas, they must both match
2249     // every definition, and so must match each other if there is a definition.)
2250 
2251     // If either declaration only contains 'alignas(0)' specifiers, then it
2252     // specifies the natural alignment for the type.
2253     if (OldAlign == 0 || NewAlign == 0) {
2254       QualType Ty;
2255       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2256         Ty = VD->getType();
2257       else
2258         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2259 
2260       if (OldAlign == 0)
2261         OldAlign = S.Context.getTypeAlign(Ty);
2262       if (NewAlign == 0)
2263         NewAlign = S.Context.getTypeAlign(Ty);
2264     }
2265 
2266     if (OldAlign != NewAlign) {
2267       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2268         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2269         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2270       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2271     }
2272   }
2273 
2274   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2275     // C++11 [dcl.align]p6:
2276     //   if any declaration of an entity has an alignment-specifier,
2277     //   every defining declaration of that entity shall specify an
2278     //   equivalent alignment.
2279     // C11 6.7.5/7:
2280     //   If the definition of an object does not have an alignment
2281     //   specifier, any other declaration of that object shall also
2282     //   have no alignment specifier.
2283     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2284       << OldAlignasAttr;
2285     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2286       << OldAlignasAttr;
2287   }
2288 
2289   bool AnyAdded = false;
2290 
2291   // Ensure we have an attribute representing the strictest alignment.
2292   if (OldAlign > NewAlign) {
2293     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2294     Clone->setInherited(true);
2295     New->addAttr(Clone);
2296     AnyAdded = true;
2297   }
2298 
2299   // Ensure we have an alignas attribute if the old declaration had one.
2300   if (OldAlignasAttr && !NewAlignasAttr &&
2301       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2302     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2303     Clone->setInherited(true);
2304     New->addAttr(Clone);
2305     AnyAdded = true;
2306   }
2307 
2308   return AnyAdded;
2309 }
2310 
2311 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2312                                const InheritableAttr *Attr,
2313                                Sema::AvailabilityMergeKind AMK) {
2314   // This function copies an attribute Attr from a previous declaration to the
2315   // new declaration D if the new declaration doesn't itself have that attribute
2316   // yet or if that attribute allows duplicates.
2317   // If you're adding a new attribute that requires logic different from
2318   // "use explicit attribute on decl if present, else use attribute from
2319   // previous decl", for example if the attribute needs to be consistent
2320   // between redeclarations, you need to call a custom merge function here.
2321   InheritableAttr *NewAttr = nullptr;
2322   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2323   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2324     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2325                                       AA->isImplicit(), AA->getIntroduced(),
2326                                       AA->getDeprecated(),
2327                                       AA->getObsoleted(), AA->getUnavailable(),
2328                                       AA->getMessage(), AA->getStrict(),
2329                                       AA->getReplacement(), AMK,
2330                                       AttrSpellingListIndex);
2331   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2332     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2333                                     AttrSpellingListIndex);
2334   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2335     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2336                                         AttrSpellingListIndex);
2337   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2338     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2339                                    AttrSpellingListIndex);
2340   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2341     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2342                                    AttrSpellingListIndex);
2343   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2344     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2345                                 FA->getFormatIdx(), FA->getFirstArg(),
2346                                 AttrSpellingListIndex);
2347   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2348     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2349                                  AttrSpellingListIndex);
2350   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2351     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2352                                        AttrSpellingListIndex,
2353                                        IA->getSemanticSpelling());
2354   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2355     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2356                                       &S.Context.Idents.get(AA->getSpelling()),
2357                                       AttrSpellingListIndex);
2358   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2359            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2360             isa<CUDAGlobalAttr>(Attr))) {
2361     // CUDA target attributes are part of function signature for
2362     // overloading purposes and must not be merged.
2363     return false;
2364   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2365     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2366   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2367     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2368   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2369     NewAttr = S.mergeInternalLinkageAttr(
2370         D, InternalLinkageA->getRange(),
2371         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2372         AttrSpellingListIndex);
2373   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2374     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2375                                 &S.Context.Idents.get(CommonA->getSpelling()),
2376                                 AttrSpellingListIndex);
2377   else if (isa<AlignedAttr>(Attr))
2378     // AlignedAttrs are handled separately, because we need to handle all
2379     // such attributes on a declaration at the same time.
2380     NewAttr = nullptr;
2381   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2382            (AMK == Sema::AMK_Override ||
2383             AMK == Sema::AMK_ProtocolImplementation))
2384     NewAttr = nullptr;
2385   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2386     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2387                               UA->getGuid());
2388   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2389     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2390 
2391   if (NewAttr) {
2392     NewAttr->setInherited(true);
2393     D->addAttr(NewAttr);
2394     if (isa<MSInheritanceAttr>(NewAttr))
2395       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2396     return true;
2397   }
2398 
2399   return false;
2400 }
2401 
2402 static const Decl *getDefinition(const Decl *D) {
2403   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2404     return TD->getDefinition();
2405   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2406     const VarDecl *Def = VD->getDefinition();
2407     if (Def)
2408       return Def;
2409     return VD->getActingDefinition();
2410   }
2411   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2412     return FD->getDefinition();
2413   return nullptr;
2414 }
2415 
2416 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2417   for (const auto *Attribute : D->attrs())
2418     if (Attribute->getKind() == Kind)
2419       return true;
2420   return false;
2421 }
2422 
2423 /// checkNewAttributesAfterDef - If we already have a definition, check that
2424 /// there are no new attributes in this declaration.
2425 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2426   if (!New->hasAttrs())
2427     return;
2428 
2429   const Decl *Def = getDefinition(Old);
2430   if (!Def || Def == New)
2431     return;
2432 
2433   AttrVec &NewAttributes = New->getAttrs();
2434   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2435     const Attr *NewAttribute = NewAttributes[I];
2436 
2437     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2438       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2439         Sema::SkipBodyInfo SkipBody;
2440         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2441 
2442         // If we're skipping this definition, drop the "alias" attribute.
2443         if (SkipBody.ShouldSkip) {
2444           NewAttributes.erase(NewAttributes.begin() + I);
2445           --E;
2446           continue;
2447         }
2448       } else {
2449         VarDecl *VD = cast<VarDecl>(New);
2450         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2451                                 VarDecl::TentativeDefinition
2452                             ? diag::err_alias_after_tentative
2453                             : diag::err_redefinition;
2454         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2455         S.Diag(Def->getLocation(), diag::note_previous_definition);
2456         VD->setInvalidDecl();
2457       }
2458       ++I;
2459       continue;
2460     }
2461 
2462     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2463       // Tentative definitions are only interesting for the alias check above.
2464       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2465         ++I;
2466         continue;
2467       }
2468     }
2469 
2470     if (hasAttribute(Def, NewAttribute->getKind())) {
2471       ++I;
2472       continue; // regular attr merging will take care of validating this.
2473     }
2474 
2475     if (isa<C11NoReturnAttr>(NewAttribute)) {
2476       // C's _Noreturn is allowed to be added to a function after it is defined.
2477       ++I;
2478       continue;
2479     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2480       if (AA->isAlignas()) {
2481         // C++11 [dcl.align]p6:
2482         //   if any declaration of an entity has an alignment-specifier,
2483         //   every defining declaration of that entity shall specify an
2484         //   equivalent alignment.
2485         // C11 6.7.5/7:
2486         //   If the definition of an object does not have an alignment
2487         //   specifier, any other declaration of that object shall also
2488         //   have no alignment specifier.
2489         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2490           << AA;
2491         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2492           << AA;
2493         NewAttributes.erase(NewAttributes.begin() + I);
2494         --E;
2495         continue;
2496       }
2497     }
2498 
2499     S.Diag(NewAttribute->getLocation(),
2500            diag::warn_attribute_precede_definition);
2501     S.Diag(Def->getLocation(), diag::note_previous_definition);
2502     NewAttributes.erase(NewAttributes.begin() + I);
2503     --E;
2504   }
2505 }
2506 
2507 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2508 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2509                                AvailabilityMergeKind AMK) {
2510   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2511     UsedAttr *NewAttr = OldAttr->clone(Context);
2512     NewAttr->setInherited(true);
2513     New->addAttr(NewAttr);
2514   }
2515 
2516   if (!Old->hasAttrs() && !New->hasAttrs())
2517     return;
2518 
2519   // Attributes declared post-definition are currently ignored.
2520   checkNewAttributesAfterDef(*this, New, Old);
2521 
2522   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2523     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2524       if (OldA->getLabel() != NewA->getLabel()) {
2525         // This redeclaration changes __asm__ label.
2526         Diag(New->getLocation(), diag::err_different_asm_label);
2527         Diag(OldA->getLocation(), diag::note_previous_declaration);
2528       }
2529     } else if (Old->isUsed()) {
2530       // This redeclaration adds an __asm__ label to a declaration that has
2531       // already been ODR-used.
2532       Diag(New->getLocation(), diag::err_late_asm_label_name)
2533         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2534     }
2535   }
2536 
2537   // Re-declaration cannot add abi_tag's.
2538   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2539     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2540       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2541         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2542                       NewTag) == OldAbiTagAttr->tags_end()) {
2543           Diag(NewAbiTagAttr->getLocation(),
2544                diag::err_new_abi_tag_on_redeclaration)
2545               << NewTag;
2546           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2547         }
2548       }
2549     } else {
2550       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2551       Diag(Old->getLocation(), diag::note_previous_declaration);
2552     }
2553   }
2554 
2555   if (!Old->hasAttrs())
2556     return;
2557 
2558   bool foundAny = New->hasAttrs();
2559 
2560   // Ensure that any moving of objects within the allocated map is done before
2561   // we process them.
2562   if (!foundAny) New->setAttrs(AttrVec());
2563 
2564   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2565     // Ignore deprecated/unavailable/availability attributes if requested.
2566     AvailabilityMergeKind LocalAMK = AMK_None;
2567     if (isa<DeprecatedAttr>(I) ||
2568         isa<UnavailableAttr>(I) ||
2569         isa<AvailabilityAttr>(I)) {
2570       switch (AMK) {
2571       case AMK_None:
2572         continue;
2573 
2574       case AMK_Redeclaration:
2575       case AMK_Override:
2576       case AMK_ProtocolImplementation:
2577         LocalAMK = AMK;
2578         break;
2579       }
2580     }
2581 
2582     // Already handled.
2583     if (isa<UsedAttr>(I))
2584       continue;
2585 
2586     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2587       foundAny = true;
2588   }
2589 
2590   if (mergeAlignedAttrs(*this, New, Old))
2591     foundAny = true;
2592 
2593   if (!foundAny) New->dropAttrs();
2594 }
2595 
2596 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2597 /// to the new one.
2598 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2599                                      const ParmVarDecl *oldDecl,
2600                                      Sema &S) {
2601   // C++11 [dcl.attr.depend]p2:
2602   //   The first declaration of a function shall specify the
2603   //   carries_dependency attribute for its declarator-id if any declaration
2604   //   of the function specifies the carries_dependency attribute.
2605   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2606   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2607     S.Diag(CDA->getLocation(),
2608            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2609     // Find the first declaration of the parameter.
2610     // FIXME: Should we build redeclaration chains for function parameters?
2611     const FunctionDecl *FirstFD =
2612       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2613     const ParmVarDecl *FirstVD =
2614       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2615     S.Diag(FirstVD->getLocation(),
2616            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2617   }
2618 
2619   if (!oldDecl->hasAttrs())
2620     return;
2621 
2622   bool foundAny = newDecl->hasAttrs();
2623 
2624   // Ensure that any moving of objects within the allocated map is
2625   // done before we process them.
2626   if (!foundAny) newDecl->setAttrs(AttrVec());
2627 
2628   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2629     if (!DeclHasAttr(newDecl, I)) {
2630       InheritableAttr *newAttr =
2631         cast<InheritableParamAttr>(I->clone(S.Context));
2632       newAttr->setInherited(true);
2633       newDecl->addAttr(newAttr);
2634       foundAny = true;
2635     }
2636   }
2637 
2638   if (!foundAny) newDecl->dropAttrs();
2639 }
2640 
2641 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2642                                 const ParmVarDecl *OldParam,
2643                                 Sema &S) {
2644   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2645     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2646       if (*Oldnullability != *Newnullability) {
2647         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2648           << DiagNullabilityKind(
2649                *Newnullability,
2650                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2651                 != 0))
2652           << DiagNullabilityKind(
2653                *Oldnullability,
2654                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2655                 != 0));
2656         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2657       }
2658     } else {
2659       QualType NewT = NewParam->getType();
2660       NewT = S.Context.getAttributedType(
2661                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2662                          NewT, NewT);
2663       NewParam->setType(NewT);
2664     }
2665   }
2666 }
2667 
2668 namespace {
2669 
2670 /// Used in MergeFunctionDecl to keep track of function parameters in
2671 /// C.
2672 struct GNUCompatibleParamWarning {
2673   ParmVarDecl *OldParm;
2674   ParmVarDecl *NewParm;
2675   QualType PromotedType;
2676 };
2677 
2678 } // end anonymous namespace
2679 
2680 /// getSpecialMember - get the special member enum for a method.
2681 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2682   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2683     if (Ctor->isDefaultConstructor())
2684       return Sema::CXXDefaultConstructor;
2685 
2686     if (Ctor->isCopyConstructor())
2687       return Sema::CXXCopyConstructor;
2688 
2689     if (Ctor->isMoveConstructor())
2690       return Sema::CXXMoveConstructor;
2691   } else if (isa<CXXDestructorDecl>(MD)) {
2692     return Sema::CXXDestructor;
2693   } else if (MD->isCopyAssignmentOperator()) {
2694     return Sema::CXXCopyAssignment;
2695   } else if (MD->isMoveAssignmentOperator()) {
2696     return Sema::CXXMoveAssignment;
2697   }
2698 
2699   return Sema::CXXInvalid;
2700 }
2701 
2702 // Determine whether the previous declaration was a definition, implicit
2703 // declaration, or a declaration.
2704 template <typename T>
2705 static std::pair<diag::kind, SourceLocation>
2706 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2707   diag::kind PrevDiag;
2708   SourceLocation OldLocation = Old->getLocation();
2709   if (Old->isThisDeclarationADefinition())
2710     PrevDiag = diag::note_previous_definition;
2711   else if (Old->isImplicit()) {
2712     PrevDiag = diag::note_previous_implicit_declaration;
2713     if (OldLocation.isInvalid())
2714       OldLocation = New->getLocation();
2715   } else
2716     PrevDiag = diag::note_previous_declaration;
2717   return std::make_pair(PrevDiag, OldLocation);
2718 }
2719 
2720 /// canRedefineFunction - checks if a function can be redefined. Currently,
2721 /// only extern inline functions can be redefined, and even then only in
2722 /// GNU89 mode.
2723 static bool canRedefineFunction(const FunctionDecl *FD,
2724                                 const LangOptions& LangOpts) {
2725   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2726           !LangOpts.CPlusPlus &&
2727           FD->isInlineSpecified() &&
2728           FD->getStorageClass() == SC_Extern);
2729 }
2730 
2731 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2732   const AttributedType *AT = T->getAs<AttributedType>();
2733   while (AT && !AT->isCallingConv())
2734     AT = AT->getModifiedType()->getAs<AttributedType>();
2735   return AT;
2736 }
2737 
2738 template <typename T>
2739 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2740   const DeclContext *DC = Old->getDeclContext();
2741   if (DC->isRecord())
2742     return false;
2743 
2744   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2745   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2746     return true;
2747   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2748     return true;
2749   return false;
2750 }
2751 
2752 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2753 static bool isExternC(VarTemplateDecl *) { return false; }
2754 
2755 /// \brief Check whether a redeclaration of an entity introduced by a
2756 /// using-declaration is valid, given that we know it's not an overload
2757 /// (nor a hidden tag declaration).
2758 template<typename ExpectedDecl>
2759 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2760                                    ExpectedDecl *New) {
2761   // C++11 [basic.scope.declarative]p4:
2762   //   Given a set of declarations in a single declarative region, each of
2763   //   which specifies the same unqualified name,
2764   //   -- they shall all refer to the same entity, or all refer to functions
2765   //      and function templates; or
2766   //   -- exactly one declaration shall declare a class name or enumeration
2767   //      name that is not a typedef name and the other declarations shall all
2768   //      refer to the same variable or enumerator, or all refer to functions
2769   //      and function templates; in this case the class name or enumeration
2770   //      name is hidden (3.3.10).
2771 
2772   // C++11 [namespace.udecl]p14:
2773   //   If a function declaration in namespace scope or block scope has the
2774   //   same name and the same parameter-type-list as a function introduced
2775   //   by a using-declaration, and the declarations do not declare the same
2776   //   function, the program is ill-formed.
2777 
2778   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2779   if (Old &&
2780       !Old->getDeclContext()->getRedeclContext()->Equals(
2781           New->getDeclContext()->getRedeclContext()) &&
2782       !(isExternC(Old) && isExternC(New)))
2783     Old = nullptr;
2784 
2785   if (!Old) {
2786     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2787     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2788     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2789     return true;
2790   }
2791   return false;
2792 }
2793 
2794 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2795                                             const FunctionDecl *B) {
2796   assert(A->getNumParams() == B->getNumParams());
2797 
2798   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2799     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2800     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2801     if (AttrA == AttrB)
2802       return true;
2803     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2804   };
2805 
2806   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2807 }
2808 
2809 /// MergeFunctionDecl - We just parsed a function 'New' from
2810 /// declarator D which has the same name and scope as a previous
2811 /// declaration 'Old'.  Figure out how to resolve this situation,
2812 /// merging decls or emitting diagnostics as appropriate.
2813 ///
2814 /// In C++, New and Old must be declarations that are not
2815 /// overloaded. Use IsOverload to determine whether New and Old are
2816 /// overloaded, and to select the Old declaration that New should be
2817 /// merged with.
2818 ///
2819 /// Returns true if there was an error, false otherwise.
2820 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2821                              Scope *S, bool MergeTypeWithOld) {
2822   // Verify the old decl was also a function.
2823   FunctionDecl *Old = OldD->getAsFunction();
2824   if (!Old) {
2825     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2826       if (New->getFriendObjectKind()) {
2827         Diag(New->getLocation(), diag::err_using_decl_friend);
2828         Diag(Shadow->getTargetDecl()->getLocation(),
2829              diag::note_using_decl_target);
2830         Diag(Shadow->getUsingDecl()->getLocation(),
2831              diag::note_using_decl) << 0;
2832         return true;
2833       }
2834 
2835       // Check whether the two declarations might declare the same function.
2836       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2837         return true;
2838       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2839     } else {
2840       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2841         << New->getDeclName();
2842       Diag(OldD->getLocation(), diag::note_previous_definition);
2843       return true;
2844     }
2845   }
2846 
2847   // If the old declaration is invalid, just give up here.
2848   if (Old->isInvalidDecl())
2849     return true;
2850 
2851   diag::kind PrevDiag;
2852   SourceLocation OldLocation;
2853   std::tie(PrevDiag, OldLocation) =
2854       getNoteDiagForInvalidRedeclaration(Old, New);
2855 
2856   // Don't complain about this if we're in GNU89 mode and the old function
2857   // is an extern inline function.
2858   // Don't complain about specializations. They are not supposed to have
2859   // storage classes.
2860   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2861       New->getStorageClass() == SC_Static &&
2862       Old->hasExternalFormalLinkage() &&
2863       !New->getTemplateSpecializationInfo() &&
2864       !canRedefineFunction(Old, getLangOpts())) {
2865     if (getLangOpts().MicrosoftExt) {
2866       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2867       Diag(OldLocation, PrevDiag);
2868     } else {
2869       Diag(New->getLocation(), diag::err_static_non_static) << New;
2870       Diag(OldLocation, PrevDiag);
2871       return true;
2872     }
2873   }
2874 
2875   if (New->hasAttr<InternalLinkageAttr>() &&
2876       !Old->hasAttr<InternalLinkageAttr>()) {
2877     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2878         << New->getDeclName();
2879     Diag(Old->getLocation(), diag::note_previous_definition);
2880     New->dropAttr<InternalLinkageAttr>();
2881   }
2882 
2883   // If a function is first declared with a calling convention, but is later
2884   // declared or defined without one, all following decls assume the calling
2885   // convention of the first.
2886   //
2887   // It's OK if a function is first declared without a calling convention,
2888   // but is later declared or defined with the default calling convention.
2889   //
2890   // To test if either decl has an explicit calling convention, we look for
2891   // AttributedType sugar nodes on the type as written.  If they are missing or
2892   // were canonicalized away, we assume the calling convention was implicit.
2893   //
2894   // Note also that we DO NOT return at this point, because we still have
2895   // other tests to run.
2896   QualType OldQType = Context.getCanonicalType(Old->getType());
2897   QualType NewQType = Context.getCanonicalType(New->getType());
2898   const FunctionType *OldType = cast<FunctionType>(OldQType);
2899   const FunctionType *NewType = cast<FunctionType>(NewQType);
2900   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2901   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2902   bool RequiresAdjustment = false;
2903 
2904   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2905     FunctionDecl *First = Old->getFirstDecl();
2906     const FunctionType *FT =
2907         First->getType().getCanonicalType()->castAs<FunctionType>();
2908     FunctionType::ExtInfo FI = FT->getExtInfo();
2909     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2910     if (!NewCCExplicit) {
2911       // Inherit the CC from the previous declaration if it was specified
2912       // there but not here.
2913       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2914       RequiresAdjustment = true;
2915     } else {
2916       // Calling conventions aren't compatible, so complain.
2917       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2918       Diag(New->getLocation(), diag::err_cconv_change)
2919         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2920         << !FirstCCExplicit
2921         << (!FirstCCExplicit ? "" :
2922             FunctionType::getNameForCallConv(FI.getCC()));
2923 
2924       // Put the note on the first decl, since it is the one that matters.
2925       Diag(First->getLocation(), diag::note_previous_declaration);
2926       return true;
2927     }
2928   }
2929 
2930   // FIXME: diagnose the other way around?
2931   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2932     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2933     RequiresAdjustment = true;
2934   }
2935 
2936   // Merge regparm attribute.
2937   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2938       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2939     if (NewTypeInfo.getHasRegParm()) {
2940       Diag(New->getLocation(), diag::err_regparm_mismatch)
2941         << NewType->getRegParmType()
2942         << OldType->getRegParmType();
2943       Diag(OldLocation, diag::note_previous_declaration);
2944       return true;
2945     }
2946 
2947     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2948     RequiresAdjustment = true;
2949   }
2950 
2951   // Merge ns_returns_retained attribute.
2952   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2953     if (NewTypeInfo.getProducesResult()) {
2954       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2955       Diag(OldLocation, diag::note_previous_declaration);
2956       return true;
2957     }
2958 
2959     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2960     RequiresAdjustment = true;
2961   }
2962 
2963   if (OldTypeInfo.getNoCallerSavedRegs() !=
2964       NewTypeInfo.getNoCallerSavedRegs()) {
2965     if (NewTypeInfo.getNoCallerSavedRegs()) {
2966       AnyX86NoCallerSavedRegistersAttr *Attr =
2967         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
2968       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
2969       Diag(OldLocation, diag::note_previous_declaration);
2970       return true;
2971     }
2972 
2973     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
2974     RequiresAdjustment = true;
2975   }
2976 
2977   if (RequiresAdjustment) {
2978     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2979     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2980     New->setType(QualType(AdjustedType, 0));
2981     NewQType = Context.getCanonicalType(New->getType());
2982     NewType = cast<FunctionType>(NewQType);
2983   }
2984 
2985   // If this redeclaration makes the function inline, we may need to add it to
2986   // UndefinedButUsed.
2987   if (!Old->isInlined() && New->isInlined() &&
2988       !New->hasAttr<GNUInlineAttr>() &&
2989       !getLangOpts().GNUInline &&
2990       Old->isUsed(false) &&
2991       !Old->isDefined() && !New->isThisDeclarationADefinition())
2992     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2993                                            SourceLocation()));
2994 
2995   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2996   // about it.
2997   if (New->hasAttr<GNUInlineAttr>() &&
2998       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2999     UndefinedButUsed.erase(Old->getCanonicalDecl());
3000   }
3001 
3002   // If pass_object_size params don't match up perfectly, this isn't a valid
3003   // redeclaration.
3004   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3005       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3006     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3007         << New->getDeclName();
3008     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3009     return true;
3010   }
3011 
3012   if (getLangOpts().CPlusPlus) {
3013     // C++1z [over.load]p2
3014     //   Certain function declarations cannot be overloaded:
3015     //     -- Function declarations that differ only in the return type,
3016     //        the exception specification, or both cannot be overloaded.
3017 
3018     // Check the exception specifications match. This may recompute the type of
3019     // both Old and New if it resolved exception specifications, so grab the
3020     // types again after this. Because this updates the type, we do this before
3021     // any of the other checks below, which may update the "de facto" NewQType
3022     // but do not necessarily update the type of New.
3023     if (CheckEquivalentExceptionSpec(Old, New))
3024       return true;
3025     OldQType = Context.getCanonicalType(Old->getType());
3026     NewQType = Context.getCanonicalType(New->getType());
3027 
3028     // Go back to the type source info to compare the declared return types,
3029     // per C++1y [dcl.type.auto]p13:
3030     //   Redeclarations or specializations of a function or function template
3031     //   with a declared return type that uses a placeholder type shall also
3032     //   use that placeholder, not a deduced type.
3033     QualType OldDeclaredReturnType =
3034         (Old->getTypeSourceInfo()
3035              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3036              : OldType)->getReturnType();
3037     QualType NewDeclaredReturnType =
3038         (New->getTypeSourceInfo()
3039              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3040              : NewType)->getReturnType();
3041     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3042         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3043           New->isLocalExternDecl())) {
3044       QualType ResQT;
3045       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3046           OldDeclaredReturnType->isObjCObjectPointerType())
3047         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3048       if (ResQT.isNull()) {
3049         if (New->isCXXClassMember() && New->isOutOfLine())
3050           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3051               << New << New->getReturnTypeSourceRange();
3052         else
3053           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3054               << New->getReturnTypeSourceRange();
3055         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3056                                     << Old->getReturnTypeSourceRange();
3057         return true;
3058       }
3059       else
3060         NewQType = ResQT;
3061     }
3062 
3063     QualType OldReturnType = OldType->getReturnType();
3064     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3065     if (OldReturnType != NewReturnType) {
3066       // If this function has a deduced return type and has already been
3067       // defined, copy the deduced value from the old declaration.
3068       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3069       if (OldAT && OldAT->isDeduced()) {
3070         New->setType(
3071             SubstAutoType(New->getType(),
3072                           OldAT->isDependentType() ? Context.DependentTy
3073                                                    : OldAT->getDeducedType()));
3074         NewQType = Context.getCanonicalType(
3075             SubstAutoType(NewQType,
3076                           OldAT->isDependentType() ? Context.DependentTy
3077                                                    : OldAT->getDeducedType()));
3078       }
3079     }
3080 
3081     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3082     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3083     if (OldMethod && NewMethod) {
3084       // Preserve triviality.
3085       NewMethod->setTrivial(OldMethod->isTrivial());
3086 
3087       // MSVC allows explicit template specialization at class scope:
3088       // 2 CXXMethodDecls referring to the same function will be injected.
3089       // We don't want a redeclaration error.
3090       bool IsClassScopeExplicitSpecialization =
3091                               OldMethod->isFunctionTemplateSpecialization() &&
3092                               NewMethod->isFunctionTemplateSpecialization();
3093       bool isFriend = NewMethod->getFriendObjectKind();
3094 
3095       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3096           !IsClassScopeExplicitSpecialization) {
3097         //    -- Member function declarations with the same name and the
3098         //       same parameter types cannot be overloaded if any of them
3099         //       is a static member function declaration.
3100         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3101           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3102           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3103           return true;
3104         }
3105 
3106         // C++ [class.mem]p1:
3107         //   [...] A member shall not be declared twice in the
3108         //   member-specification, except that a nested class or member
3109         //   class template can be declared and then later defined.
3110         if (!inTemplateInstantiation()) {
3111           unsigned NewDiag;
3112           if (isa<CXXConstructorDecl>(OldMethod))
3113             NewDiag = diag::err_constructor_redeclared;
3114           else if (isa<CXXDestructorDecl>(NewMethod))
3115             NewDiag = diag::err_destructor_redeclared;
3116           else if (isa<CXXConversionDecl>(NewMethod))
3117             NewDiag = diag::err_conv_function_redeclared;
3118           else
3119             NewDiag = diag::err_member_redeclared;
3120 
3121           Diag(New->getLocation(), NewDiag);
3122         } else {
3123           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3124             << New << New->getType();
3125         }
3126         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3127         return true;
3128 
3129       // Complain if this is an explicit declaration of a special
3130       // member that was initially declared implicitly.
3131       //
3132       // As an exception, it's okay to befriend such methods in order
3133       // to permit the implicit constructor/destructor/operator calls.
3134       } else if (OldMethod->isImplicit()) {
3135         if (isFriend) {
3136           NewMethod->setImplicit();
3137         } else {
3138           Diag(NewMethod->getLocation(),
3139                diag::err_definition_of_implicitly_declared_member)
3140             << New << getSpecialMember(OldMethod);
3141           return true;
3142         }
3143       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3144         Diag(NewMethod->getLocation(),
3145              diag::err_definition_of_explicitly_defaulted_member)
3146           << getSpecialMember(OldMethod);
3147         return true;
3148       }
3149     }
3150 
3151     // C++11 [dcl.attr.noreturn]p1:
3152     //   The first declaration of a function shall specify the noreturn
3153     //   attribute if any declaration of that function specifies the noreturn
3154     //   attribute.
3155     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3156     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3157       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3158       Diag(Old->getFirstDecl()->getLocation(),
3159            diag::note_noreturn_missing_first_decl);
3160     }
3161 
3162     // C++11 [dcl.attr.depend]p2:
3163     //   The first declaration of a function shall specify the
3164     //   carries_dependency attribute for its declarator-id if any declaration
3165     //   of the function specifies the carries_dependency attribute.
3166     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3167     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3168       Diag(CDA->getLocation(),
3169            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3170       Diag(Old->getFirstDecl()->getLocation(),
3171            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3172     }
3173 
3174     // (C++98 8.3.5p3):
3175     //   All declarations for a function shall agree exactly in both the
3176     //   return type and the parameter-type-list.
3177     // We also want to respect all the extended bits except noreturn.
3178 
3179     // noreturn should now match unless the old type info didn't have it.
3180     QualType OldQTypeForComparison = OldQType;
3181     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3182       auto *OldType = OldQType->castAs<FunctionProtoType>();
3183       const FunctionType *OldTypeForComparison
3184         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3185       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3186       assert(OldQTypeForComparison.isCanonical());
3187     }
3188 
3189     if (haveIncompatibleLanguageLinkages(Old, New)) {
3190       // As a special case, retain the language linkage from previous
3191       // declarations of a friend function as an extension.
3192       //
3193       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3194       // and is useful because there's otherwise no way to specify language
3195       // linkage within class scope.
3196       //
3197       // Check cautiously as the friend object kind isn't yet complete.
3198       if (New->getFriendObjectKind() != Decl::FOK_None) {
3199         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3200         Diag(OldLocation, PrevDiag);
3201       } else {
3202         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3203         Diag(OldLocation, PrevDiag);
3204         return true;
3205       }
3206     }
3207 
3208     if (OldQTypeForComparison == NewQType)
3209       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3210 
3211     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3212         New->isLocalExternDecl()) {
3213       // It's OK if we couldn't merge types for a local function declaraton
3214       // if either the old or new type is dependent. We'll merge the types
3215       // when we instantiate the function.
3216       return false;
3217     }
3218 
3219     // Fall through for conflicting redeclarations and redefinitions.
3220   }
3221 
3222   // C: Function types need to be compatible, not identical. This handles
3223   // duplicate function decls like "void f(int); void f(enum X);" properly.
3224   if (!getLangOpts().CPlusPlus &&
3225       Context.typesAreCompatible(OldQType, NewQType)) {
3226     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3227     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3228     const FunctionProtoType *OldProto = nullptr;
3229     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3230         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3231       // The old declaration provided a function prototype, but the
3232       // new declaration does not. Merge in the prototype.
3233       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3234       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3235       NewQType =
3236           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3237                                   OldProto->getExtProtoInfo());
3238       New->setType(NewQType);
3239       New->setHasInheritedPrototype();
3240 
3241       // Synthesize parameters with the same types.
3242       SmallVector<ParmVarDecl*, 16> Params;
3243       for (const auto &ParamType : OldProto->param_types()) {
3244         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3245                                                  SourceLocation(), nullptr,
3246                                                  ParamType, /*TInfo=*/nullptr,
3247                                                  SC_None, nullptr);
3248         Param->setScopeInfo(0, Params.size());
3249         Param->setImplicit();
3250         Params.push_back(Param);
3251       }
3252 
3253       New->setParams(Params);
3254     }
3255 
3256     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3257   }
3258 
3259   // GNU C permits a K&R definition to follow a prototype declaration
3260   // if the declared types of the parameters in the K&R definition
3261   // match the types in the prototype declaration, even when the
3262   // promoted types of the parameters from the K&R definition differ
3263   // from the types in the prototype. GCC then keeps the types from
3264   // the prototype.
3265   //
3266   // If a variadic prototype is followed by a non-variadic K&R definition,
3267   // the K&R definition becomes variadic.  This is sort of an edge case, but
3268   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3269   // C99 6.9.1p8.
3270   if (!getLangOpts().CPlusPlus &&
3271       Old->hasPrototype() && !New->hasPrototype() &&
3272       New->getType()->getAs<FunctionProtoType>() &&
3273       Old->getNumParams() == New->getNumParams()) {
3274     SmallVector<QualType, 16> ArgTypes;
3275     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3276     const FunctionProtoType *OldProto
3277       = Old->getType()->getAs<FunctionProtoType>();
3278     const FunctionProtoType *NewProto
3279       = New->getType()->getAs<FunctionProtoType>();
3280 
3281     // Determine whether this is the GNU C extension.
3282     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3283                                                NewProto->getReturnType());
3284     bool LooseCompatible = !MergedReturn.isNull();
3285     for (unsigned Idx = 0, End = Old->getNumParams();
3286          LooseCompatible && Idx != End; ++Idx) {
3287       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3288       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3289       if (Context.typesAreCompatible(OldParm->getType(),
3290                                      NewProto->getParamType(Idx))) {
3291         ArgTypes.push_back(NewParm->getType());
3292       } else if (Context.typesAreCompatible(OldParm->getType(),
3293                                             NewParm->getType(),
3294                                             /*CompareUnqualified=*/true)) {
3295         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3296                                            NewProto->getParamType(Idx) };
3297         Warnings.push_back(Warn);
3298         ArgTypes.push_back(NewParm->getType());
3299       } else
3300         LooseCompatible = false;
3301     }
3302 
3303     if (LooseCompatible) {
3304       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3305         Diag(Warnings[Warn].NewParm->getLocation(),
3306              diag::ext_param_promoted_not_compatible_with_prototype)
3307           << Warnings[Warn].PromotedType
3308           << Warnings[Warn].OldParm->getType();
3309         if (Warnings[Warn].OldParm->getLocation().isValid())
3310           Diag(Warnings[Warn].OldParm->getLocation(),
3311                diag::note_previous_declaration);
3312       }
3313 
3314       if (MergeTypeWithOld)
3315         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3316                                              OldProto->getExtProtoInfo()));
3317       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3318     }
3319 
3320     // Fall through to diagnose conflicting types.
3321   }
3322 
3323   // A function that has already been declared has been redeclared or
3324   // defined with a different type; show an appropriate diagnostic.
3325 
3326   // If the previous declaration was an implicitly-generated builtin
3327   // declaration, then at the very least we should use a specialized note.
3328   unsigned BuiltinID;
3329   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3330     // If it's actually a library-defined builtin function like 'malloc'
3331     // or 'printf', just warn about the incompatible redeclaration.
3332     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3333       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3334       Diag(OldLocation, diag::note_previous_builtin_declaration)
3335         << Old << Old->getType();
3336 
3337       // If this is a global redeclaration, just forget hereafter
3338       // about the "builtin-ness" of the function.
3339       //
3340       // Doing this for local extern declarations is problematic.  If
3341       // the builtin declaration remains visible, a second invalid
3342       // local declaration will produce a hard error; if it doesn't
3343       // remain visible, a single bogus local redeclaration (which is
3344       // actually only a warning) could break all the downstream code.
3345       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3346         New->getIdentifier()->revertBuiltin();
3347 
3348       return false;
3349     }
3350 
3351     PrevDiag = diag::note_previous_builtin_declaration;
3352   }
3353 
3354   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3355   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3356   return true;
3357 }
3358 
3359 /// \brief Completes the merge of two function declarations that are
3360 /// known to be compatible.
3361 ///
3362 /// This routine handles the merging of attributes and other
3363 /// properties of function declarations from the old declaration to
3364 /// the new declaration, once we know that New is in fact a
3365 /// redeclaration of Old.
3366 ///
3367 /// \returns false
3368 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3369                                         Scope *S, bool MergeTypeWithOld) {
3370   // Merge the attributes
3371   mergeDeclAttributes(New, Old);
3372 
3373   // Merge "pure" flag.
3374   if (Old->isPure())
3375     New->setPure();
3376 
3377   // Merge "used" flag.
3378   if (Old->getMostRecentDecl()->isUsed(false))
3379     New->setIsUsed();
3380 
3381   // Merge attributes from the parameters.  These can mismatch with K&R
3382   // declarations.
3383   if (New->getNumParams() == Old->getNumParams())
3384       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3385         ParmVarDecl *NewParam = New->getParamDecl(i);
3386         ParmVarDecl *OldParam = Old->getParamDecl(i);
3387         mergeParamDeclAttributes(NewParam, OldParam, *this);
3388         mergeParamDeclTypes(NewParam, OldParam, *this);
3389       }
3390 
3391   if (getLangOpts().CPlusPlus)
3392     return MergeCXXFunctionDecl(New, Old, S);
3393 
3394   // Merge the function types so the we get the composite types for the return
3395   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3396   // was visible.
3397   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3398   if (!Merged.isNull() && MergeTypeWithOld)
3399     New->setType(Merged);
3400 
3401   return false;
3402 }
3403 
3404 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3405                                 ObjCMethodDecl *oldMethod) {
3406   // Merge the attributes, including deprecated/unavailable
3407   AvailabilityMergeKind MergeKind =
3408     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3409       ? AMK_ProtocolImplementation
3410       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3411                                                        : AMK_Override;
3412 
3413   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3414 
3415   // Merge attributes from the parameters.
3416   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3417                                        oe = oldMethod->param_end();
3418   for (ObjCMethodDecl::param_iterator
3419          ni = newMethod->param_begin(), ne = newMethod->param_end();
3420        ni != ne && oi != oe; ++ni, ++oi)
3421     mergeParamDeclAttributes(*ni, *oi, *this);
3422 
3423   CheckObjCMethodOverride(newMethod, oldMethod);
3424 }
3425 
3426 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3427   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3428 
3429   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3430          ? diag::err_redefinition_different_type
3431          : diag::err_redeclaration_different_type)
3432     << New->getDeclName() << New->getType() << Old->getType();
3433 
3434   diag::kind PrevDiag;
3435   SourceLocation OldLocation;
3436   std::tie(PrevDiag, OldLocation)
3437     = getNoteDiagForInvalidRedeclaration(Old, New);
3438   S.Diag(OldLocation, PrevDiag);
3439   New->setInvalidDecl();
3440 }
3441 
3442 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3443 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3444 /// emitting diagnostics as appropriate.
3445 ///
3446 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3447 /// to here in AddInitializerToDecl. We can't check them before the initializer
3448 /// is attached.
3449 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3450                              bool MergeTypeWithOld) {
3451   if (New->isInvalidDecl() || Old->isInvalidDecl())
3452     return;
3453 
3454   QualType MergedT;
3455   if (getLangOpts().CPlusPlus) {
3456     if (New->getType()->isUndeducedType()) {
3457       // We don't know what the new type is until the initializer is attached.
3458       return;
3459     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3460       // These could still be something that needs exception specs checked.
3461       return MergeVarDeclExceptionSpecs(New, Old);
3462     }
3463     // C++ [basic.link]p10:
3464     //   [...] the types specified by all declarations referring to a given
3465     //   object or function shall be identical, except that declarations for an
3466     //   array object can specify array types that differ by the presence or
3467     //   absence of a major array bound (8.3.4).
3468     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3469       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3470       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3471 
3472       // We are merging a variable declaration New into Old. If it has an array
3473       // bound, and that bound differs from Old's bound, we should diagnose the
3474       // mismatch.
3475       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3476         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3477              PrevVD = PrevVD->getPreviousDecl()) {
3478           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3479           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3480             continue;
3481 
3482           if (!Context.hasSameType(NewArray, PrevVDTy))
3483             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3484         }
3485       }
3486 
3487       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3488         if (Context.hasSameType(OldArray->getElementType(),
3489                                 NewArray->getElementType()))
3490           MergedT = New->getType();
3491       }
3492       // FIXME: Check visibility. New is hidden but has a complete type. If New
3493       // has no array bound, it should not inherit one from Old, if Old is not
3494       // visible.
3495       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3496         if (Context.hasSameType(OldArray->getElementType(),
3497                                 NewArray->getElementType()))
3498           MergedT = Old->getType();
3499       }
3500     }
3501     else if (New->getType()->isObjCObjectPointerType() &&
3502                Old->getType()->isObjCObjectPointerType()) {
3503       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3504                                               Old->getType());
3505     }
3506   } else {
3507     // C 6.2.7p2:
3508     //   All declarations that refer to the same object or function shall have
3509     //   compatible type.
3510     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3511   }
3512   if (MergedT.isNull()) {
3513     // It's OK if we couldn't merge types if either type is dependent, for a
3514     // block-scope variable. In other cases (static data members of class
3515     // templates, variable templates, ...), we require the types to be
3516     // equivalent.
3517     // FIXME: The C++ standard doesn't say anything about this.
3518     if ((New->getType()->isDependentType() ||
3519          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3520       // If the old type was dependent, we can't merge with it, so the new type
3521       // becomes dependent for now. We'll reproduce the original type when we
3522       // instantiate the TypeSourceInfo for the variable.
3523       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3524         New->setType(Context.DependentTy);
3525       return;
3526     }
3527     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3528   }
3529 
3530   // Don't actually update the type on the new declaration if the old
3531   // declaration was an extern declaration in a different scope.
3532   if (MergeTypeWithOld)
3533     New->setType(MergedT);
3534 }
3535 
3536 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3537                                   LookupResult &Previous) {
3538   // C11 6.2.7p4:
3539   //   For an identifier with internal or external linkage declared
3540   //   in a scope in which a prior declaration of that identifier is
3541   //   visible, if the prior declaration specifies internal or
3542   //   external linkage, the type of the identifier at the later
3543   //   declaration becomes the composite type.
3544   //
3545   // If the variable isn't visible, we do not merge with its type.
3546   if (Previous.isShadowed())
3547     return false;
3548 
3549   if (S.getLangOpts().CPlusPlus) {
3550     // C++11 [dcl.array]p3:
3551     //   If there is a preceding declaration of the entity in the same
3552     //   scope in which the bound was specified, an omitted array bound
3553     //   is taken to be the same as in that earlier declaration.
3554     return NewVD->isPreviousDeclInSameBlockScope() ||
3555            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3556             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3557   } else {
3558     // If the old declaration was function-local, don't merge with its
3559     // type unless we're in the same function.
3560     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3561            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3562   }
3563 }
3564 
3565 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3566 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3567 /// situation, merging decls or emitting diagnostics as appropriate.
3568 ///
3569 /// Tentative definition rules (C99 6.9.2p2) are checked by
3570 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3571 /// definitions here, since the initializer hasn't been attached.
3572 ///
3573 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3574   // If the new decl is already invalid, don't do any other checking.
3575   if (New->isInvalidDecl())
3576     return;
3577 
3578   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3579     return;
3580 
3581   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3582 
3583   // Verify the old decl was also a variable or variable template.
3584   VarDecl *Old = nullptr;
3585   VarTemplateDecl *OldTemplate = nullptr;
3586   if (Previous.isSingleResult()) {
3587     if (NewTemplate) {
3588       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3589       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3590 
3591       if (auto *Shadow =
3592               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3593         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3594           return New->setInvalidDecl();
3595     } else {
3596       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3597 
3598       if (auto *Shadow =
3599               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3600         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3601           return New->setInvalidDecl();
3602     }
3603   }
3604   if (!Old) {
3605     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3606       << New->getDeclName();
3607     Diag(Previous.getRepresentativeDecl()->getLocation(),
3608          diag::note_previous_definition);
3609     return New->setInvalidDecl();
3610   }
3611 
3612   // Ensure the template parameters are compatible.
3613   if (NewTemplate &&
3614       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3615                                       OldTemplate->getTemplateParameters(),
3616                                       /*Complain=*/true, TPL_TemplateMatch))
3617     return New->setInvalidDecl();
3618 
3619   // C++ [class.mem]p1:
3620   //   A member shall not be declared twice in the member-specification [...]
3621   //
3622   // Here, we need only consider static data members.
3623   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3624     Diag(New->getLocation(), diag::err_duplicate_member)
3625       << New->getIdentifier();
3626     Diag(Old->getLocation(), diag::note_previous_declaration);
3627     New->setInvalidDecl();
3628   }
3629 
3630   mergeDeclAttributes(New, Old);
3631   // Warn if an already-declared variable is made a weak_import in a subsequent
3632   // declaration
3633   if (New->hasAttr<WeakImportAttr>() &&
3634       Old->getStorageClass() == SC_None &&
3635       !Old->hasAttr<WeakImportAttr>()) {
3636     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3637     Diag(Old->getLocation(), diag::note_previous_definition);
3638     // Remove weak_import attribute on new declaration.
3639     New->dropAttr<WeakImportAttr>();
3640   }
3641 
3642   if (New->hasAttr<InternalLinkageAttr>() &&
3643       !Old->hasAttr<InternalLinkageAttr>()) {
3644     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3645         << New->getDeclName();
3646     Diag(Old->getLocation(), diag::note_previous_definition);
3647     New->dropAttr<InternalLinkageAttr>();
3648   }
3649 
3650   // Merge the types.
3651   VarDecl *MostRecent = Old->getMostRecentDecl();
3652   if (MostRecent != Old) {
3653     MergeVarDeclTypes(New, MostRecent,
3654                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3655     if (New->isInvalidDecl())
3656       return;
3657   }
3658 
3659   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3660   if (New->isInvalidDecl())
3661     return;
3662 
3663   diag::kind PrevDiag;
3664   SourceLocation OldLocation;
3665   std::tie(PrevDiag, OldLocation) =
3666       getNoteDiagForInvalidRedeclaration(Old, New);
3667 
3668   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3669   if (New->getStorageClass() == SC_Static &&
3670       !New->isStaticDataMember() &&
3671       Old->hasExternalFormalLinkage()) {
3672     if (getLangOpts().MicrosoftExt) {
3673       Diag(New->getLocation(), diag::ext_static_non_static)
3674           << New->getDeclName();
3675       Diag(OldLocation, PrevDiag);
3676     } else {
3677       Diag(New->getLocation(), diag::err_static_non_static)
3678           << New->getDeclName();
3679       Diag(OldLocation, PrevDiag);
3680       return New->setInvalidDecl();
3681     }
3682   }
3683   // C99 6.2.2p4:
3684   //   For an identifier declared with the storage-class specifier
3685   //   extern in a scope in which a prior declaration of that
3686   //   identifier is visible,23) if the prior declaration specifies
3687   //   internal or external linkage, the linkage of the identifier at
3688   //   the later declaration is the same as the linkage specified at
3689   //   the prior declaration. If no prior declaration is visible, or
3690   //   if the prior declaration specifies no linkage, then the
3691   //   identifier has external linkage.
3692   if (New->hasExternalStorage() && Old->hasLinkage())
3693     /* Okay */;
3694   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3695            !New->isStaticDataMember() &&
3696            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3697     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3698     Diag(OldLocation, PrevDiag);
3699     return New->setInvalidDecl();
3700   }
3701 
3702   // Check if extern is followed by non-extern and vice-versa.
3703   if (New->hasExternalStorage() &&
3704       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3705     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3706     Diag(OldLocation, PrevDiag);
3707     return New->setInvalidDecl();
3708   }
3709   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3710       !New->hasExternalStorage()) {
3711     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3712     Diag(OldLocation, PrevDiag);
3713     return New->setInvalidDecl();
3714   }
3715 
3716   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3717 
3718   // FIXME: The test for external storage here seems wrong? We still
3719   // need to check for mismatches.
3720   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3721       // Don't complain about out-of-line definitions of static members.
3722       !(Old->getLexicalDeclContext()->isRecord() &&
3723         !New->getLexicalDeclContext()->isRecord())) {
3724     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3725     Diag(OldLocation, PrevDiag);
3726     return New->setInvalidDecl();
3727   }
3728 
3729   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3730     if (VarDecl *Def = Old->getDefinition()) {
3731       // C++1z [dcl.fcn.spec]p4:
3732       //   If the definition of a variable appears in a translation unit before
3733       //   its first declaration as inline, the program is ill-formed.
3734       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3735       Diag(Def->getLocation(), diag::note_previous_definition);
3736     }
3737   }
3738 
3739   // If this redeclaration makes the function inline, we may need to add it to
3740   // UndefinedButUsed.
3741   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3742       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3743     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3744                                            SourceLocation()));
3745 
3746   if (New->getTLSKind() != Old->getTLSKind()) {
3747     if (!Old->getTLSKind()) {
3748       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3749       Diag(OldLocation, PrevDiag);
3750     } else if (!New->getTLSKind()) {
3751       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3752       Diag(OldLocation, PrevDiag);
3753     } else {
3754       // Do not allow redeclaration to change the variable between requiring
3755       // static and dynamic initialization.
3756       // FIXME: GCC allows this, but uses the TLS keyword on the first
3757       // declaration to determine the kind. Do we need to be compatible here?
3758       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3759         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3760       Diag(OldLocation, PrevDiag);
3761     }
3762   }
3763 
3764   // C++ doesn't have tentative definitions, so go right ahead and check here.
3765   if (getLangOpts().CPlusPlus &&
3766       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3767     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3768         Old->getCanonicalDecl()->isConstexpr()) {
3769       // This definition won't be a definition any more once it's been merged.
3770       Diag(New->getLocation(),
3771            diag::warn_deprecated_redundant_constexpr_static_def);
3772     } else if (VarDecl *Def = Old->getDefinition()) {
3773       if (checkVarDeclRedefinition(Def, New))
3774         return;
3775     }
3776   }
3777 
3778   if (haveIncompatibleLanguageLinkages(Old, New)) {
3779     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3780     Diag(OldLocation, PrevDiag);
3781     New->setInvalidDecl();
3782     return;
3783   }
3784 
3785   // Merge "used" flag.
3786   if (Old->getMostRecentDecl()->isUsed(false))
3787     New->setIsUsed();
3788 
3789   // Keep a chain of previous declarations.
3790   New->setPreviousDecl(Old);
3791   if (NewTemplate)
3792     NewTemplate->setPreviousDecl(OldTemplate);
3793 
3794   // Inherit access appropriately.
3795   New->setAccess(Old->getAccess());
3796   if (NewTemplate)
3797     NewTemplate->setAccess(New->getAccess());
3798 
3799   if (Old->isInline())
3800     New->setImplicitlyInline();
3801 }
3802 
3803 /// We've just determined that \p Old and \p New both appear to be definitions
3804 /// of the same variable. Either diagnose or fix the problem.
3805 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
3806   if (!hasVisibleDefinition(Old) &&
3807       (New->getFormalLinkage() == InternalLinkage ||
3808        New->isInline() ||
3809        New->getDescribedVarTemplate() ||
3810        New->getNumTemplateParameterLists() ||
3811        New->getDeclContext()->isDependentContext())) {
3812     // The previous definition is hidden, and multiple definitions are
3813     // permitted (in separate TUs). Demote this to a declaration.
3814     New->demoteThisDefinitionToDeclaration();
3815 
3816     // Make the canonical definition visible.
3817     if (auto *OldTD = Old->getDescribedVarTemplate())
3818       makeMergedDefinitionVisible(OldTD, New->getLocation());
3819     makeMergedDefinitionVisible(Old, New->getLocation());
3820     return false;
3821   } else {
3822     Diag(New->getLocation(), diag::err_redefinition) << New;
3823     Diag(Old->getLocation(), diag::note_previous_definition);
3824     New->setInvalidDecl();
3825     return true;
3826   }
3827 }
3828 
3829 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3830 /// no declarator (e.g. "struct foo;") is parsed.
3831 Decl *
3832 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3833                                  RecordDecl *&AnonRecord) {
3834   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3835                                     AnonRecord);
3836 }
3837 
3838 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3839 // disambiguate entities defined in different scopes.
3840 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3841 // compatibility.
3842 // We will pick our mangling number depending on which version of MSVC is being
3843 // targeted.
3844 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3845   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3846              ? S->getMSCurManglingNumber()
3847              : S->getMSLastManglingNumber();
3848 }
3849 
3850 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3851   if (!Context.getLangOpts().CPlusPlus)
3852     return;
3853 
3854   if (isa<CXXRecordDecl>(Tag->getParent())) {
3855     // If this tag is the direct child of a class, number it if
3856     // it is anonymous.
3857     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3858       return;
3859     MangleNumberingContext &MCtx =
3860         Context.getManglingNumberContext(Tag->getParent());
3861     Context.setManglingNumber(
3862         Tag, MCtx.getManglingNumber(
3863                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3864     return;
3865   }
3866 
3867   // If this tag isn't a direct child of a class, number it if it is local.
3868   Decl *ManglingContextDecl;
3869   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3870           Tag->getDeclContext(), ManglingContextDecl)) {
3871     Context.setManglingNumber(
3872         Tag, MCtx->getManglingNumber(
3873                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3874   }
3875 }
3876 
3877 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3878                                         TypedefNameDecl *NewTD) {
3879   if (TagFromDeclSpec->isInvalidDecl())
3880     return;
3881 
3882   // Do nothing if the tag already has a name for linkage purposes.
3883   if (TagFromDeclSpec->hasNameForLinkage())
3884     return;
3885 
3886   // A well-formed anonymous tag must always be a TUK_Definition.
3887   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3888 
3889   // The type must match the tag exactly;  no qualifiers allowed.
3890   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3891                            Context.getTagDeclType(TagFromDeclSpec))) {
3892     if (getLangOpts().CPlusPlus)
3893       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3894     return;
3895   }
3896 
3897   // If we've already computed linkage for the anonymous tag, then
3898   // adding a typedef name for the anonymous decl can change that
3899   // linkage, which might be a serious problem.  Diagnose this as
3900   // unsupported and ignore the typedef name.  TODO: we should
3901   // pursue this as a language defect and establish a formal rule
3902   // for how to handle it.
3903   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3904     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3905 
3906     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3907     tagLoc = getLocForEndOfToken(tagLoc);
3908 
3909     llvm::SmallString<40> textToInsert;
3910     textToInsert += ' ';
3911     textToInsert += NewTD->getIdentifier()->getName();
3912     Diag(tagLoc, diag::note_typedef_changes_linkage)
3913         << FixItHint::CreateInsertion(tagLoc, textToInsert);
3914     return;
3915   }
3916 
3917   // Otherwise, set this is the anon-decl typedef for the tag.
3918   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3919 }
3920 
3921 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3922   switch (T) {
3923   case DeclSpec::TST_class:
3924     return 0;
3925   case DeclSpec::TST_struct:
3926     return 1;
3927   case DeclSpec::TST_interface:
3928     return 2;
3929   case DeclSpec::TST_union:
3930     return 3;
3931   case DeclSpec::TST_enum:
3932     return 4;
3933   default:
3934     llvm_unreachable("unexpected type specifier");
3935   }
3936 }
3937 
3938 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3939 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3940 /// parameters to cope with template friend declarations.
3941 Decl *
3942 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3943                                  MultiTemplateParamsArg TemplateParams,
3944                                  bool IsExplicitInstantiation,
3945                                  RecordDecl *&AnonRecord) {
3946   Decl *TagD = nullptr;
3947   TagDecl *Tag = nullptr;
3948   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3949       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3950       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3951       DS.getTypeSpecType() == DeclSpec::TST_union ||
3952       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3953     TagD = DS.getRepAsDecl();
3954 
3955     if (!TagD) // We probably had an error
3956       return nullptr;
3957 
3958     // Note that the above type specs guarantee that the
3959     // type rep is a Decl, whereas in many of the others
3960     // it's a Type.
3961     if (isa<TagDecl>(TagD))
3962       Tag = cast<TagDecl>(TagD);
3963     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3964       Tag = CTD->getTemplatedDecl();
3965   }
3966 
3967   if (Tag) {
3968     handleTagNumbering(Tag, S);
3969     Tag->setFreeStanding();
3970     if (Tag->isInvalidDecl())
3971       return Tag;
3972   }
3973 
3974   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3975     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3976     // or incomplete types shall not be restrict-qualified."
3977     if (TypeQuals & DeclSpec::TQ_restrict)
3978       Diag(DS.getRestrictSpecLoc(),
3979            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3980            << DS.getSourceRange();
3981   }
3982 
3983   if (DS.isInlineSpecified())
3984     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
3985         << getLangOpts().CPlusPlus1z;
3986 
3987   if (DS.isConstexprSpecified()) {
3988     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3989     // and definitions of functions and variables.
3990     if (Tag)
3991       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3992           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3993     else
3994       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3995     // Don't emit warnings after this error.
3996     return TagD;
3997   }
3998 
3999   if (DS.isConceptSpecified()) {
4000     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
4001     // either a function concept and its definition or a variable concept and
4002     // its initializer.
4003     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
4004     return TagD;
4005   }
4006 
4007   DiagnoseFunctionSpecifiers(DS);
4008 
4009   if (DS.isFriendSpecified()) {
4010     // If we're dealing with a decl but not a TagDecl, assume that
4011     // whatever routines created it handled the friendship aspect.
4012     if (TagD && !Tag)
4013       return nullptr;
4014     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4015   }
4016 
4017   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4018   bool IsExplicitSpecialization =
4019     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4020   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4021       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4022       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4023     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4024     // nested-name-specifier unless it is an explicit instantiation
4025     // or an explicit specialization.
4026     //
4027     // FIXME: We allow class template partial specializations here too, per the
4028     // obvious intent of DR1819.
4029     //
4030     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4031     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4032         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4033     return nullptr;
4034   }
4035 
4036   // Track whether this decl-specifier declares anything.
4037   bool DeclaresAnything = true;
4038 
4039   // Handle anonymous struct definitions.
4040   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4041     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4042         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4043       if (getLangOpts().CPlusPlus ||
4044           Record->getDeclContext()->isRecord()) {
4045         // If CurContext is a DeclContext that can contain statements,
4046         // RecursiveASTVisitor won't visit the decls that
4047         // BuildAnonymousStructOrUnion() will put into CurContext.
4048         // Also store them here so that they can be part of the
4049         // DeclStmt that gets created in this case.
4050         // FIXME: Also return the IndirectFieldDecls created by
4051         // BuildAnonymousStructOr union, for the same reason?
4052         if (CurContext->isFunctionOrMethod())
4053           AnonRecord = Record;
4054         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4055                                            Context.getPrintingPolicy());
4056       }
4057 
4058       DeclaresAnything = false;
4059     }
4060   }
4061 
4062   // C11 6.7.2.1p2:
4063   //   A struct-declaration that does not declare an anonymous structure or
4064   //   anonymous union shall contain a struct-declarator-list.
4065   //
4066   // This rule also existed in C89 and C99; the grammar for struct-declaration
4067   // did not permit a struct-declaration without a struct-declarator-list.
4068   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4069       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4070     // Check for Microsoft C extension: anonymous struct/union member.
4071     // Handle 2 kinds of anonymous struct/union:
4072     //   struct STRUCT;
4073     //   union UNION;
4074     // and
4075     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4076     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4077     if ((Tag && Tag->getDeclName()) ||
4078         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4079       RecordDecl *Record = nullptr;
4080       if (Tag)
4081         Record = dyn_cast<RecordDecl>(Tag);
4082       else if (const RecordType *RT =
4083                    DS.getRepAsType().get()->getAsStructureType())
4084         Record = RT->getDecl();
4085       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4086         Record = UT->getDecl();
4087 
4088       if (Record && getLangOpts().MicrosoftExt) {
4089         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4090           << Record->isUnion() << DS.getSourceRange();
4091         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4092       }
4093 
4094       DeclaresAnything = false;
4095     }
4096   }
4097 
4098   // Skip all the checks below if we have a type error.
4099   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4100       (TagD && TagD->isInvalidDecl()))
4101     return TagD;
4102 
4103   if (getLangOpts().CPlusPlus &&
4104       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4105     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4106       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4107           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4108         DeclaresAnything = false;
4109 
4110   if (!DS.isMissingDeclaratorOk()) {
4111     // Customize diagnostic for a typedef missing a name.
4112     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4113       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4114         << DS.getSourceRange();
4115     else
4116       DeclaresAnything = false;
4117   }
4118 
4119   if (DS.isModulePrivateSpecified() &&
4120       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4121     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4122       << Tag->getTagKind()
4123       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4124 
4125   ActOnDocumentableDecl(TagD);
4126 
4127   // C 6.7/2:
4128   //   A declaration [...] shall declare at least a declarator [...], a tag,
4129   //   or the members of an enumeration.
4130   // C++ [dcl.dcl]p3:
4131   //   [If there are no declarators], and except for the declaration of an
4132   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4133   //   names into the program, or shall redeclare a name introduced by a
4134   //   previous declaration.
4135   if (!DeclaresAnything) {
4136     // In C, we allow this as a (popular) extension / bug. Don't bother
4137     // producing further diagnostics for redundant qualifiers after this.
4138     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4139     return TagD;
4140   }
4141 
4142   // C++ [dcl.stc]p1:
4143   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4144   //   init-declarator-list of the declaration shall not be empty.
4145   // C++ [dcl.fct.spec]p1:
4146   //   If a cv-qualifier appears in a decl-specifier-seq, the
4147   //   init-declarator-list of the declaration shall not be empty.
4148   //
4149   // Spurious qualifiers here appear to be valid in C.
4150   unsigned DiagID = diag::warn_standalone_specifier;
4151   if (getLangOpts().CPlusPlus)
4152     DiagID = diag::ext_standalone_specifier;
4153 
4154   // Note that a linkage-specification sets a storage class, but
4155   // 'extern "C" struct foo;' is actually valid and not theoretically
4156   // useless.
4157   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4158     if (SCS == DeclSpec::SCS_mutable)
4159       // Since mutable is not a viable storage class specifier in C, there is
4160       // no reason to treat it as an extension. Instead, diagnose as an error.
4161       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4162     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4163       Diag(DS.getStorageClassSpecLoc(), DiagID)
4164         << DeclSpec::getSpecifierName(SCS);
4165   }
4166 
4167   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4168     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4169       << DeclSpec::getSpecifierName(TSCS);
4170   if (DS.getTypeQualifiers()) {
4171     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4172       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4173     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4174       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4175     // Restrict is covered above.
4176     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4177       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4178     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4179       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4180   }
4181 
4182   // Warn about ignored type attributes, for example:
4183   // __attribute__((aligned)) struct A;
4184   // Attributes should be placed after tag to apply to type declaration.
4185   if (!DS.getAttributes().empty()) {
4186     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4187     if (TypeSpecType == DeclSpec::TST_class ||
4188         TypeSpecType == DeclSpec::TST_struct ||
4189         TypeSpecType == DeclSpec::TST_interface ||
4190         TypeSpecType == DeclSpec::TST_union ||
4191         TypeSpecType == DeclSpec::TST_enum) {
4192       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4193            attrs = attrs->getNext())
4194         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4195             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4196     }
4197   }
4198 
4199   return TagD;
4200 }
4201 
4202 /// We are trying to inject an anonymous member into the given scope;
4203 /// check if there's an existing declaration that can't be overloaded.
4204 ///
4205 /// \return true if this is a forbidden redeclaration
4206 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4207                                          Scope *S,
4208                                          DeclContext *Owner,
4209                                          DeclarationName Name,
4210                                          SourceLocation NameLoc,
4211                                          bool IsUnion) {
4212   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4213                  Sema::ForRedeclaration);
4214   if (!SemaRef.LookupName(R, S)) return false;
4215 
4216   // Pick a representative declaration.
4217   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4218   assert(PrevDecl && "Expected a non-null Decl");
4219 
4220   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4221     return false;
4222 
4223   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4224     << IsUnion << Name;
4225   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4226 
4227   return true;
4228 }
4229 
4230 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4231 /// anonymous struct or union AnonRecord into the owning context Owner
4232 /// and scope S. This routine will be invoked just after we realize
4233 /// that an unnamed union or struct is actually an anonymous union or
4234 /// struct, e.g.,
4235 ///
4236 /// @code
4237 /// union {
4238 ///   int i;
4239 ///   float f;
4240 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4241 ///    // f into the surrounding scope.x
4242 /// @endcode
4243 ///
4244 /// This routine is recursive, injecting the names of nested anonymous
4245 /// structs/unions into the owning context and scope as well.
4246 static bool
4247 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4248                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4249                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4250   bool Invalid = false;
4251 
4252   // Look every FieldDecl and IndirectFieldDecl with a name.
4253   for (auto *D : AnonRecord->decls()) {
4254     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4255         cast<NamedDecl>(D)->getDeclName()) {
4256       ValueDecl *VD = cast<ValueDecl>(D);
4257       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4258                                        VD->getLocation(),
4259                                        AnonRecord->isUnion())) {
4260         // C++ [class.union]p2:
4261         //   The names of the members of an anonymous union shall be
4262         //   distinct from the names of any other entity in the
4263         //   scope in which the anonymous union is declared.
4264         Invalid = true;
4265       } else {
4266         // C++ [class.union]p2:
4267         //   For the purpose of name lookup, after the anonymous union
4268         //   definition, the members of the anonymous union are
4269         //   considered to have been defined in the scope in which the
4270         //   anonymous union is declared.
4271         unsigned OldChainingSize = Chaining.size();
4272         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4273           Chaining.append(IF->chain_begin(), IF->chain_end());
4274         else
4275           Chaining.push_back(VD);
4276 
4277         assert(Chaining.size() >= 2);
4278         NamedDecl **NamedChain =
4279           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4280         for (unsigned i = 0; i < Chaining.size(); i++)
4281           NamedChain[i] = Chaining[i];
4282 
4283         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4284             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4285             VD->getType(), {NamedChain, Chaining.size()});
4286 
4287         for (const auto *Attr : VD->attrs())
4288           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4289 
4290         IndirectField->setAccess(AS);
4291         IndirectField->setImplicit();
4292         SemaRef.PushOnScopeChains(IndirectField, S);
4293 
4294         // That includes picking up the appropriate access specifier.
4295         if (AS != AS_none) IndirectField->setAccess(AS);
4296 
4297         Chaining.resize(OldChainingSize);
4298       }
4299     }
4300   }
4301 
4302   return Invalid;
4303 }
4304 
4305 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4306 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4307 /// illegal input values are mapped to SC_None.
4308 static StorageClass
4309 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4310   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4311   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4312          "Parser allowed 'typedef' as storage class VarDecl.");
4313   switch (StorageClassSpec) {
4314   case DeclSpec::SCS_unspecified:    return SC_None;
4315   case DeclSpec::SCS_extern:
4316     if (DS.isExternInLinkageSpec())
4317       return SC_None;
4318     return SC_Extern;
4319   case DeclSpec::SCS_static:         return SC_Static;
4320   case DeclSpec::SCS_auto:           return SC_Auto;
4321   case DeclSpec::SCS_register:       return SC_Register;
4322   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4323     // Illegal SCSs map to None: error reporting is up to the caller.
4324   case DeclSpec::SCS_mutable:        // Fall through.
4325   case DeclSpec::SCS_typedef:        return SC_None;
4326   }
4327   llvm_unreachable("unknown storage class specifier");
4328 }
4329 
4330 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4331   assert(Record->hasInClassInitializer());
4332 
4333   for (const auto *I : Record->decls()) {
4334     const auto *FD = dyn_cast<FieldDecl>(I);
4335     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4336       FD = IFD->getAnonField();
4337     if (FD && FD->hasInClassInitializer())
4338       return FD->getLocation();
4339   }
4340 
4341   llvm_unreachable("couldn't find in-class initializer");
4342 }
4343 
4344 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4345                                       SourceLocation DefaultInitLoc) {
4346   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4347     return;
4348 
4349   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4350   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4351 }
4352 
4353 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4354                                       CXXRecordDecl *AnonUnion) {
4355   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4356     return;
4357 
4358   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4359 }
4360 
4361 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4362 /// anonymous structure or union. Anonymous unions are a C++ feature
4363 /// (C++ [class.union]) and a C11 feature; anonymous structures
4364 /// are a C11 feature and GNU C++ extension.
4365 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4366                                         AccessSpecifier AS,
4367                                         RecordDecl *Record,
4368                                         const PrintingPolicy &Policy) {
4369   DeclContext *Owner = Record->getDeclContext();
4370 
4371   // Diagnose whether this anonymous struct/union is an extension.
4372   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4373     Diag(Record->getLocation(), diag::ext_anonymous_union);
4374   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4375     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4376   else if (!Record->isUnion() && !getLangOpts().C11)
4377     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4378 
4379   // C and C++ require different kinds of checks for anonymous
4380   // structs/unions.
4381   bool Invalid = false;
4382   if (getLangOpts().CPlusPlus) {
4383     const char *PrevSpec = nullptr;
4384     unsigned DiagID;
4385     if (Record->isUnion()) {
4386       // C++ [class.union]p6:
4387       //   Anonymous unions declared in a named namespace or in the
4388       //   global namespace shall be declared static.
4389       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4390           (isa<TranslationUnitDecl>(Owner) ||
4391            (isa<NamespaceDecl>(Owner) &&
4392             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4393         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4394           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4395 
4396         // Recover by adding 'static'.
4397         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4398                                PrevSpec, DiagID, Policy);
4399       }
4400       // C++ [class.union]p6:
4401       //   A storage class is not allowed in a declaration of an
4402       //   anonymous union in a class scope.
4403       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4404                isa<RecordDecl>(Owner)) {
4405         Diag(DS.getStorageClassSpecLoc(),
4406              diag::err_anonymous_union_with_storage_spec)
4407           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4408 
4409         // Recover by removing the storage specifier.
4410         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4411                                SourceLocation(),
4412                                PrevSpec, DiagID, Context.getPrintingPolicy());
4413       }
4414     }
4415 
4416     // Ignore const/volatile/restrict qualifiers.
4417     if (DS.getTypeQualifiers()) {
4418       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4419         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4420           << Record->isUnion() << "const"
4421           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4422       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4423         Diag(DS.getVolatileSpecLoc(),
4424              diag::ext_anonymous_struct_union_qualified)
4425           << Record->isUnion() << "volatile"
4426           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4427       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4428         Diag(DS.getRestrictSpecLoc(),
4429              diag::ext_anonymous_struct_union_qualified)
4430           << Record->isUnion() << "restrict"
4431           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4432       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4433         Diag(DS.getAtomicSpecLoc(),
4434              diag::ext_anonymous_struct_union_qualified)
4435           << Record->isUnion() << "_Atomic"
4436           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4437       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4438         Diag(DS.getUnalignedSpecLoc(),
4439              diag::ext_anonymous_struct_union_qualified)
4440           << Record->isUnion() << "__unaligned"
4441           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4442 
4443       DS.ClearTypeQualifiers();
4444     }
4445 
4446     // C++ [class.union]p2:
4447     //   The member-specification of an anonymous union shall only
4448     //   define non-static data members. [Note: nested types and
4449     //   functions cannot be declared within an anonymous union. ]
4450     for (auto *Mem : Record->decls()) {
4451       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4452         // C++ [class.union]p3:
4453         //   An anonymous union shall not have private or protected
4454         //   members (clause 11).
4455         assert(FD->getAccess() != AS_none);
4456         if (FD->getAccess() != AS_public) {
4457           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4458             << Record->isUnion() << (FD->getAccess() == AS_protected);
4459           Invalid = true;
4460         }
4461 
4462         // C++ [class.union]p1
4463         //   An object of a class with a non-trivial constructor, a non-trivial
4464         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4465         //   assignment operator cannot be a member of a union, nor can an
4466         //   array of such objects.
4467         if (CheckNontrivialField(FD))
4468           Invalid = true;
4469       } else if (Mem->isImplicit()) {
4470         // Any implicit members are fine.
4471       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4472         // This is a type that showed up in an
4473         // elaborated-type-specifier inside the anonymous struct or
4474         // union, but which actually declares a type outside of the
4475         // anonymous struct or union. It's okay.
4476       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4477         if (!MemRecord->isAnonymousStructOrUnion() &&
4478             MemRecord->getDeclName()) {
4479           // Visual C++ allows type definition in anonymous struct or union.
4480           if (getLangOpts().MicrosoftExt)
4481             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4482               << Record->isUnion();
4483           else {
4484             // This is a nested type declaration.
4485             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4486               << Record->isUnion();
4487             Invalid = true;
4488           }
4489         } else {
4490           // This is an anonymous type definition within another anonymous type.
4491           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4492           // not part of standard C++.
4493           Diag(MemRecord->getLocation(),
4494                diag::ext_anonymous_record_with_anonymous_type)
4495             << Record->isUnion();
4496         }
4497       } else if (isa<AccessSpecDecl>(Mem)) {
4498         // Any access specifier is fine.
4499       } else if (isa<StaticAssertDecl>(Mem)) {
4500         // In C++1z, static_assert declarations are also fine.
4501       } else {
4502         // We have something that isn't a non-static data
4503         // member. Complain about it.
4504         unsigned DK = diag::err_anonymous_record_bad_member;
4505         if (isa<TypeDecl>(Mem))
4506           DK = diag::err_anonymous_record_with_type;
4507         else if (isa<FunctionDecl>(Mem))
4508           DK = diag::err_anonymous_record_with_function;
4509         else if (isa<VarDecl>(Mem))
4510           DK = diag::err_anonymous_record_with_static;
4511 
4512         // Visual C++ allows type definition in anonymous struct or union.
4513         if (getLangOpts().MicrosoftExt &&
4514             DK == diag::err_anonymous_record_with_type)
4515           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4516             << Record->isUnion();
4517         else {
4518           Diag(Mem->getLocation(), DK) << Record->isUnion();
4519           Invalid = true;
4520         }
4521       }
4522     }
4523 
4524     // C++11 [class.union]p8 (DR1460):
4525     //   At most one variant member of a union may have a
4526     //   brace-or-equal-initializer.
4527     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4528         Owner->isRecord())
4529       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4530                                 cast<CXXRecordDecl>(Record));
4531   }
4532 
4533   if (!Record->isUnion() && !Owner->isRecord()) {
4534     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4535       << getLangOpts().CPlusPlus;
4536     Invalid = true;
4537   }
4538 
4539   // Mock up a declarator.
4540   Declarator Dc(DS, Declarator::MemberContext);
4541   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4542   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4543 
4544   // Create a declaration for this anonymous struct/union.
4545   NamedDecl *Anon = nullptr;
4546   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4547     Anon = FieldDecl::Create(Context, OwningClass,
4548                              DS.getLocStart(),
4549                              Record->getLocation(),
4550                              /*IdentifierInfo=*/nullptr,
4551                              Context.getTypeDeclType(Record),
4552                              TInfo,
4553                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4554                              /*InitStyle=*/ICIS_NoInit);
4555     Anon->setAccess(AS);
4556     if (getLangOpts().CPlusPlus)
4557       FieldCollector->Add(cast<FieldDecl>(Anon));
4558   } else {
4559     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4560     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4561     if (SCSpec == DeclSpec::SCS_mutable) {
4562       // mutable can only appear on non-static class members, so it's always
4563       // an error here
4564       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4565       Invalid = true;
4566       SC = SC_None;
4567     }
4568 
4569     Anon = VarDecl::Create(Context, Owner,
4570                            DS.getLocStart(),
4571                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4572                            Context.getTypeDeclType(Record),
4573                            TInfo, SC);
4574 
4575     // Default-initialize the implicit variable. This initialization will be
4576     // trivial in almost all cases, except if a union member has an in-class
4577     // initializer:
4578     //   union { int n = 0; };
4579     ActOnUninitializedDecl(Anon);
4580   }
4581   Anon->setImplicit();
4582 
4583   // Mark this as an anonymous struct/union type.
4584   Record->setAnonymousStructOrUnion(true);
4585 
4586   // Add the anonymous struct/union object to the current
4587   // context. We'll be referencing this object when we refer to one of
4588   // its members.
4589   Owner->addDecl(Anon);
4590 
4591   // Inject the members of the anonymous struct/union into the owning
4592   // context and into the identifier resolver chain for name lookup
4593   // purposes.
4594   SmallVector<NamedDecl*, 2> Chain;
4595   Chain.push_back(Anon);
4596 
4597   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4598     Invalid = true;
4599 
4600   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4601     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4602       Decl *ManglingContextDecl;
4603       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4604               NewVD->getDeclContext(), ManglingContextDecl)) {
4605         Context.setManglingNumber(
4606             NewVD, MCtx->getManglingNumber(
4607                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4608         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4609       }
4610     }
4611   }
4612 
4613   if (Invalid)
4614     Anon->setInvalidDecl();
4615 
4616   return Anon;
4617 }
4618 
4619 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4620 /// Microsoft C anonymous structure.
4621 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4622 /// Example:
4623 ///
4624 /// struct A { int a; };
4625 /// struct B { struct A; int b; };
4626 ///
4627 /// void foo() {
4628 ///   B var;
4629 ///   var.a = 3;
4630 /// }
4631 ///
4632 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4633                                            RecordDecl *Record) {
4634   assert(Record && "expected a record!");
4635 
4636   // Mock up a declarator.
4637   Declarator Dc(DS, Declarator::TypeNameContext);
4638   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4639   assert(TInfo && "couldn't build declarator info for anonymous struct");
4640 
4641   auto *ParentDecl = cast<RecordDecl>(CurContext);
4642   QualType RecTy = Context.getTypeDeclType(Record);
4643 
4644   // Create a declaration for this anonymous struct.
4645   NamedDecl *Anon = FieldDecl::Create(Context,
4646                              ParentDecl,
4647                              DS.getLocStart(),
4648                              DS.getLocStart(),
4649                              /*IdentifierInfo=*/nullptr,
4650                              RecTy,
4651                              TInfo,
4652                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4653                              /*InitStyle=*/ICIS_NoInit);
4654   Anon->setImplicit();
4655 
4656   // Add the anonymous struct object to the current context.
4657   CurContext->addDecl(Anon);
4658 
4659   // Inject the members of the anonymous struct into the current
4660   // context and into the identifier resolver chain for name lookup
4661   // purposes.
4662   SmallVector<NamedDecl*, 2> Chain;
4663   Chain.push_back(Anon);
4664 
4665   RecordDecl *RecordDef = Record->getDefinition();
4666   if (RequireCompleteType(Anon->getLocation(), RecTy,
4667                           diag::err_field_incomplete) ||
4668       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4669                                           AS_none, Chain)) {
4670     Anon->setInvalidDecl();
4671     ParentDecl->setInvalidDecl();
4672   }
4673 
4674   return Anon;
4675 }
4676 
4677 /// GetNameForDeclarator - Determine the full declaration name for the
4678 /// given Declarator.
4679 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4680   return GetNameFromUnqualifiedId(D.getName());
4681 }
4682 
4683 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4684 DeclarationNameInfo
4685 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4686   DeclarationNameInfo NameInfo;
4687   NameInfo.setLoc(Name.StartLocation);
4688 
4689   switch (Name.getKind()) {
4690 
4691   case UnqualifiedId::IK_ImplicitSelfParam:
4692   case UnqualifiedId::IK_Identifier:
4693     NameInfo.setName(Name.Identifier);
4694     NameInfo.setLoc(Name.StartLocation);
4695     return NameInfo;
4696 
4697   case UnqualifiedId::IK_DeductionGuideName: {
4698     // C++ [temp.deduct.guide]p3:
4699     //   The simple-template-id shall name a class template specialization.
4700     //   The template-name shall be the same identifier as the template-name
4701     //   of the simple-template-id.
4702     // These together intend to imply that the template-name shall name a
4703     // class template.
4704     // FIXME: template<typename T> struct X {};
4705     //        template<typename T> using Y = X<T>;
4706     //        Y(int) -> Y<int>;
4707     //   satisfies these rules but does not name a class template.
4708     TemplateName TN = Name.TemplateName.get().get();
4709     auto *Template = TN.getAsTemplateDecl();
4710     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4711       Diag(Name.StartLocation,
4712            diag::err_deduction_guide_name_not_class_template)
4713         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4714       if (Template)
4715         Diag(Template->getLocation(), diag::note_template_decl_here);
4716       return DeclarationNameInfo();
4717     }
4718 
4719     NameInfo.setName(
4720         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4721     NameInfo.setLoc(Name.StartLocation);
4722     return NameInfo;
4723   }
4724 
4725   case UnqualifiedId::IK_OperatorFunctionId:
4726     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4727                                            Name.OperatorFunctionId.Operator));
4728     NameInfo.setLoc(Name.StartLocation);
4729     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4730       = Name.OperatorFunctionId.SymbolLocations[0];
4731     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4732       = Name.EndLocation.getRawEncoding();
4733     return NameInfo;
4734 
4735   case UnqualifiedId::IK_LiteralOperatorId:
4736     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4737                                                            Name.Identifier));
4738     NameInfo.setLoc(Name.StartLocation);
4739     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4740     return NameInfo;
4741 
4742   case UnqualifiedId::IK_ConversionFunctionId: {
4743     TypeSourceInfo *TInfo;
4744     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4745     if (Ty.isNull())
4746       return DeclarationNameInfo();
4747     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4748                                                Context.getCanonicalType(Ty)));
4749     NameInfo.setLoc(Name.StartLocation);
4750     NameInfo.setNamedTypeInfo(TInfo);
4751     return NameInfo;
4752   }
4753 
4754   case UnqualifiedId::IK_ConstructorName: {
4755     TypeSourceInfo *TInfo;
4756     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4757     if (Ty.isNull())
4758       return DeclarationNameInfo();
4759     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4760                                               Context.getCanonicalType(Ty)));
4761     NameInfo.setLoc(Name.StartLocation);
4762     NameInfo.setNamedTypeInfo(TInfo);
4763     return NameInfo;
4764   }
4765 
4766   case UnqualifiedId::IK_ConstructorTemplateId: {
4767     // In well-formed code, we can only have a constructor
4768     // template-id that refers to the current context, so go there
4769     // to find the actual type being constructed.
4770     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4771     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4772       return DeclarationNameInfo();
4773 
4774     // Determine the type of the class being constructed.
4775     QualType CurClassType = Context.getTypeDeclType(CurClass);
4776 
4777     // FIXME: Check two things: that the template-id names the same type as
4778     // CurClassType, and that the template-id does not occur when the name
4779     // was qualified.
4780 
4781     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4782                                     Context.getCanonicalType(CurClassType)));
4783     NameInfo.setLoc(Name.StartLocation);
4784     // FIXME: should we retrieve TypeSourceInfo?
4785     NameInfo.setNamedTypeInfo(nullptr);
4786     return NameInfo;
4787   }
4788 
4789   case UnqualifiedId::IK_DestructorName: {
4790     TypeSourceInfo *TInfo;
4791     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4792     if (Ty.isNull())
4793       return DeclarationNameInfo();
4794     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4795                                               Context.getCanonicalType(Ty)));
4796     NameInfo.setLoc(Name.StartLocation);
4797     NameInfo.setNamedTypeInfo(TInfo);
4798     return NameInfo;
4799   }
4800 
4801   case UnqualifiedId::IK_TemplateId: {
4802     TemplateName TName = Name.TemplateId->Template.get();
4803     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4804     return Context.getNameForTemplate(TName, TNameLoc);
4805   }
4806 
4807   } // switch (Name.getKind())
4808 
4809   llvm_unreachable("Unknown name kind");
4810 }
4811 
4812 static QualType getCoreType(QualType Ty) {
4813   do {
4814     if (Ty->isPointerType() || Ty->isReferenceType())
4815       Ty = Ty->getPointeeType();
4816     else if (Ty->isArrayType())
4817       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4818     else
4819       return Ty.withoutLocalFastQualifiers();
4820   } while (true);
4821 }
4822 
4823 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4824 /// and Definition have "nearly" matching parameters. This heuristic is
4825 /// used to improve diagnostics in the case where an out-of-line function
4826 /// definition doesn't match any declaration within the class or namespace.
4827 /// Also sets Params to the list of indices to the parameters that differ
4828 /// between the declaration and the definition. If hasSimilarParameters
4829 /// returns true and Params is empty, then all of the parameters match.
4830 static bool hasSimilarParameters(ASTContext &Context,
4831                                      FunctionDecl *Declaration,
4832                                      FunctionDecl *Definition,
4833                                      SmallVectorImpl<unsigned> &Params) {
4834   Params.clear();
4835   if (Declaration->param_size() != Definition->param_size())
4836     return false;
4837   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4838     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4839     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4840 
4841     // The parameter types are identical
4842     if (Context.hasSameType(DefParamTy, DeclParamTy))
4843       continue;
4844 
4845     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4846     QualType DefParamBaseTy = getCoreType(DefParamTy);
4847     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4848     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4849 
4850     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4851         (DeclTyName && DeclTyName == DefTyName))
4852       Params.push_back(Idx);
4853     else  // The two parameters aren't even close
4854       return false;
4855   }
4856 
4857   return true;
4858 }
4859 
4860 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4861 /// declarator needs to be rebuilt in the current instantiation.
4862 /// Any bits of declarator which appear before the name are valid for
4863 /// consideration here.  That's specifically the type in the decl spec
4864 /// and the base type in any member-pointer chunks.
4865 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4866                                                     DeclarationName Name) {
4867   // The types we specifically need to rebuild are:
4868   //   - typenames, typeofs, and decltypes
4869   //   - types which will become injected class names
4870   // Of course, we also need to rebuild any type referencing such a
4871   // type.  It's safest to just say "dependent", but we call out a
4872   // few cases here.
4873 
4874   DeclSpec &DS = D.getMutableDeclSpec();
4875   switch (DS.getTypeSpecType()) {
4876   case DeclSpec::TST_typename:
4877   case DeclSpec::TST_typeofType:
4878   case DeclSpec::TST_underlyingType:
4879   case DeclSpec::TST_atomic: {
4880     // Grab the type from the parser.
4881     TypeSourceInfo *TSI = nullptr;
4882     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4883     if (T.isNull() || !T->isDependentType()) break;
4884 
4885     // Make sure there's a type source info.  This isn't really much
4886     // of a waste; most dependent types should have type source info
4887     // attached already.
4888     if (!TSI)
4889       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4890 
4891     // Rebuild the type in the current instantiation.
4892     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4893     if (!TSI) return true;
4894 
4895     // Store the new type back in the decl spec.
4896     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4897     DS.UpdateTypeRep(LocType);
4898     break;
4899   }
4900 
4901   case DeclSpec::TST_decltype:
4902   case DeclSpec::TST_typeofExpr: {
4903     Expr *E = DS.getRepAsExpr();
4904     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4905     if (Result.isInvalid()) return true;
4906     DS.UpdateExprRep(Result.get());
4907     break;
4908   }
4909 
4910   default:
4911     // Nothing to do for these decl specs.
4912     break;
4913   }
4914 
4915   // It doesn't matter what order we do this in.
4916   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4917     DeclaratorChunk &Chunk = D.getTypeObject(I);
4918 
4919     // The only type information in the declarator which can come
4920     // before the declaration name is the base type of a member
4921     // pointer.
4922     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4923       continue;
4924 
4925     // Rebuild the scope specifier in-place.
4926     CXXScopeSpec &SS = Chunk.Mem.Scope();
4927     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4928       return true;
4929   }
4930 
4931   return false;
4932 }
4933 
4934 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4935   D.setFunctionDefinitionKind(FDK_Declaration);
4936   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4937 
4938   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4939       Dcl && Dcl->getDeclContext()->isFileContext())
4940     Dcl->setTopLevelDeclInObjCContainer();
4941 
4942   if (getLangOpts().OpenCL)
4943     setCurrentOpenCLExtensionForDecl(Dcl);
4944 
4945   return Dcl;
4946 }
4947 
4948 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4949 ///   If T is the name of a class, then each of the following shall have a
4950 ///   name different from T:
4951 ///     - every static data member of class T;
4952 ///     - every member function of class T
4953 ///     - every member of class T that is itself a type;
4954 /// \returns true if the declaration name violates these rules.
4955 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4956                                    DeclarationNameInfo NameInfo) {
4957   DeclarationName Name = NameInfo.getName();
4958 
4959   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
4960   while (Record && Record->isAnonymousStructOrUnion())
4961     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
4962   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
4963     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4964     return true;
4965   }
4966 
4967   return false;
4968 }
4969 
4970 /// \brief Diagnose a declaration whose declarator-id has the given
4971 /// nested-name-specifier.
4972 ///
4973 /// \param SS The nested-name-specifier of the declarator-id.
4974 ///
4975 /// \param DC The declaration context to which the nested-name-specifier
4976 /// resolves.
4977 ///
4978 /// \param Name The name of the entity being declared.
4979 ///
4980 /// \param Loc The location of the name of the entity being declared.
4981 ///
4982 /// \returns true if we cannot safely recover from this error, false otherwise.
4983 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4984                                         DeclarationName Name,
4985                                         SourceLocation Loc) {
4986   DeclContext *Cur = CurContext;
4987   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4988     Cur = Cur->getParent();
4989 
4990   // If the user provided a superfluous scope specifier that refers back to the
4991   // class in which the entity is already declared, diagnose and ignore it.
4992   //
4993   // class X {
4994   //   void X::f();
4995   // };
4996   //
4997   // Note, it was once ill-formed to give redundant qualification in all
4998   // contexts, but that rule was removed by DR482.
4999   if (Cur->Equals(DC)) {
5000     if (Cur->isRecord()) {
5001       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5002                                       : diag::err_member_extra_qualification)
5003         << Name << FixItHint::CreateRemoval(SS.getRange());
5004       SS.clear();
5005     } else {
5006       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5007     }
5008     return false;
5009   }
5010 
5011   // Check whether the qualifying scope encloses the scope of the original
5012   // declaration.
5013   if (!Cur->Encloses(DC)) {
5014     if (Cur->isRecord())
5015       Diag(Loc, diag::err_member_qualification)
5016         << Name << SS.getRange();
5017     else if (isa<TranslationUnitDecl>(DC))
5018       Diag(Loc, diag::err_invalid_declarator_global_scope)
5019         << Name << SS.getRange();
5020     else if (isa<FunctionDecl>(Cur))
5021       Diag(Loc, diag::err_invalid_declarator_in_function)
5022         << Name << SS.getRange();
5023     else if (isa<BlockDecl>(Cur))
5024       Diag(Loc, diag::err_invalid_declarator_in_block)
5025         << Name << SS.getRange();
5026     else
5027       Diag(Loc, diag::err_invalid_declarator_scope)
5028       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5029 
5030     return true;
5031   }
5032 
5033   if (Cur->isRecord()) {
5034     // Cannot qualify members within a class.
5035     Diag(Loc, diag::err_member_qualification)
5036       << Name << SS.getRange();
5037     SS.clear();
5038 
5039     // C++ constructors and destructors with incorrect scopes can break
5040     // our AST invariants by having the wrong underlying types. If
5041     // that's the case, then drop this declaration entirely.
5042     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5043          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5044         !Context.hasSameType(Name.getCXXNameType(),
5045                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5046       return true;
5047 
5048     return false;
5049   }
5050 
5051   // C++11 [dcl.meaning]p1:
5052   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5053   //   not begin with a decltype-specifer"
5054   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5055   while (SpecLoc.getPrefix())
5056     SpecLoc = SpecLoc.getPrefix();
5057   if (dyn_cast_or_null<DecltypeType>(
5058         SpecLoc.getNestedNameSpecifier()->getAsType()))
5059     Diag(Loc, diag::err_decltype_in_declarator)
5060       << SpecLoc.getTypeLoc().getSourceRange();
5061 
5062   return false;
5063 }
5064 
5065 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5066                                   MultiTemplateParamsArg TemplateParamLists) {
5067   // TODO: consider using NameInfo for diagnostic.
5068   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5069   DeclarationName Name = NameInfo.getName();
5070 
5071   // All of these full declarators require an identifier.  If it doesn't have
5072   // one, the ParsedFreeStandingDeclSpec action should be used.
5073   if (D.isDecompositionDeclarator()) {
5074     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5075   } else if (!Name) {
5076     if (!D.isInvalidType())  // Reject this if we think it is valid.
5077       Diag(D.getDeclSpec().getLocStart(),
5078            diag::err_declarator_need_ident)
5079         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5080     return nullptr;
5081   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5082     return nullptr;
5083 
5084   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5085   // we find one that is.
5086   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5087          (S->getFlags() & Scope::TemplateParamScope) != 0)
5088     S = S->getParent();
5089 
5090   DeclContext *DC = CurContext;
5091   if (D.getCXXScopeSpec().isInvalid())
5092     D.setInvalidType();
5093   else if (D.getCXXScopeSpec().isSet()) {
5094     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5095                                         UPPC_DeclarationQualifier))
5096       return nullptr;
5097 
5098     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5099     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5100     if (!DC || isa<EnumDecl>(DC)) {
5101       // If we could not compute the declaration context, it's because the
5102       // declaration context is dependent but does not refer to a class,
5103       // class template, or class template partial specialization. Complain
5104       // and return early, to avoid the coming semantic disaster.
5105       Diag(D.getIdentifierLoc(),
5106            diag::err_template_qualified_declarator_no_match)
5107         << D.getCXXScopeSpec().getScopeRep()
5108         << D.getCXXScopeSpec().getRange();
5109       return nullptr;
5110     }
5111     bool IsDependentContext = DC->isDependentContext();
5112 
5113     if (!IsDependentContext &&
5114         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5115       return nullptr;
5116 
5117     // If a class is incomplete, do not parse entities inside it.
5118     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5119       Diag(D.getIdentifierLoc(),
5120            diag::err_member_def_undefined_record)
5121         << Name << DC << D.getCXXScopeSpec().getRange();
5122       return nullptr;
5123     }
5124     if (!D.getDeclSpec().isFriendSpecified()) {
5125       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
5126                                       Name, D.getIdentifierLoc())) {
5127         if (DC->isRecord())
5128           return nullptr;
5129 
5130         D.setInvalidType();
5131       }
5132     }
5133 
5134     // Check whether we need to rebuild the type of the given
5135     // declaration in the current instantiation.
5136     if (EnteringContext && IsDependentContext &&
5137         TemplateParamLists.size() != 0) {
5138       ContextRAII SavedContext(*this, DC);
5139       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5140         D.setInvalidType();
5141     }
5142   }
5143 
5144   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5145   QualType R = TInfo->getType();
5146 
5147   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5148     // If this is a typedef, we'll end up spewing multiple diagnostics.
5149     // Just return early; it's safer. If this is a function, let the
5150     // "constructor cannot have a return type" diagnostic handle it.
5151     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5152       return nullptr;
5153 
5154   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5155                                       UPPC_DeclarationType))
5156     D.setInvalidType();
5157 
5158   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5159                         ForRedeclaration);
5160 
5161   // See if this is a redefinition of a variable in the same scope.
5162   if (!D.getCXXScopeSpec().isSet()) {
5163     bool IsLinkageLookup = false;
5164     bool CreateBuiltins = false;
5165 
5166     // If the declaration we're planning to build will be a function
5167     // or object with linkage, then look for another declaration with
5168     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5169     //
5170     // If the declaration we're planning to build will be declared with
5171     // external linkage in the translation unit, create any builtin with
5172     // the same name.
5173     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5174       /* Do nothing*/;
5175     else if (CurContext->isFunctionOrMethod() &&
5176              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5177               R->isFunctionType())) {
5178       IsLinkageLookup = true;
5179       CreateBuiltins =
5180           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5181     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5182                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5183       CreateBuiltins = true;
5184 
5185     if (IsLinkageLookup)
5186       Previous.clear(LookupRedeclarationWithLinkage);
5187 
5188     LookupName(Previous, S, CreateBuiltins);
5189   } else { // Something like "int foo::x;"
5190     LookupQualifiedName(Previous, DC);
5191 
5192     // C++ [dcl.meaning]p1:
5193     //   When the declarator-id is qualified, the declaration shall refer to a
5194     //  previously declared member of the class or namespace to which the
5195     //  qualifier refers (or, in the case of a namespace, of an element of the
5196     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5197     //  thereof; [...]
5198     //
5199     // Note that we already checked the context above, and that we do not have
5200     // enough information to make sure that Previous contains the declaration
5201     // we want to match. For example, given:
5202     //
5203     //   class X {
5204     //     void f();
5205     //     void f(float);
5206     //   };
5207     //
5208     //   void X::f(int) { } // ill-formed
5209     //
5210     // In this case, Previous will point to the overload set
5211     // containing the two f's declared in X, but neither of them
5212     // matches.
5213 
5214     // C++ [dcl.meaning]p1:
5215     //   [...] the member shall not merely have been introduced by a
5216     //   using-declaration in the scope of the class or namespace nominated by
5217     //   the nested-name-specifier of the declarator-id.
5218     RemoveUsingDecls(Previous);
5219   }
5220 
5221   if (Previous.isSingleResult() &&
5222       Previous.getFoundDecl()->isTemplateParameter()) {
5223     // Maybe we will complain about the shadowed template parameter.
5224     if (!D.isInvalidType())
5225       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5226                                       Previous.getFoundDecl());
5227 
5228     // Just pretend that we didn't see the previous declaration.
5229     Previous.clear();
5230   }
5231 
5232   // In C++, the previous declaration we find might be a tag type
5233   // (class or enum). In this case, the new declaration will hide the
5234   // tag type. Note that this does does not apply if we're declaring a
5235   // typedef (C++ [dcl.typedef]p4).
5236   if (Previous.isSingleTagDecl() &&
5237       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5238     Previous.clear();
5239 
5240   // Check that there are no default arguments other than in the parameters
5241   // of a function declaration (C++ only).
5242   if (getLangOpts().CPlusPlus)
5243     CheckExtraCXXDefaultArguments(D);
5244 
5245   if (D.getDeclSpec().isConceptSpecified()) {
5246     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5247     // applied only to the definition of a function template or variable
5248     // template, declared in namespace scope
5249     if (!TemplateParamLists.size()) {
5250       Diag(D.getDeclSpec().getConceptSpecLoc(),
5251            diag:: err_concept_wrong_decl_kind);
5252       return nullptr;
5253     }
5254 
5255     if (!DC->getRedeclContext()->isFileContext()) {
5256       Diag(D.getIdentifierLoc(),
5257            diag::err_concept_decls_may_only_appear_in_namespace_scope);
5258       return nullptr;
5259     }
5260   }
5261 
5262   NamedDecl *New;
5263 
5264   bool AddToScope = true;
5265   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5266     if (TemplateParamLists.size()) {
5267       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5268       return nullptr;
5269     }
5270 
5271     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5272   } else if (R->isFunctionType()) {
5273     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5274                                   TemplateParamLists,
5275                                   AddToScope);
5276   } else {
5277     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5278                                   AddToScope);
5279   }
5280 
5281   if (!New)
5282     return nullptr;
5283 
5284   // If this has an identifier and is not a function template specialization,
5285   // add it to the scope stack.
5286   if (New->getDeclName() && AddToScope) {
5287     // Only make a locally-scoped extern declaration visible if it is the first
5288     // declaration of this entity. Qualified lookup for such an entity should
5289     // only find this declaration if there is no visible declaration of it.
5290     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5291     PushOnScopeChains(New, S, AddToContext);
5292     if (!AddToContext)
5293       CurContext->addHiddenDecl(New);
5294   }
5295 
5296   if (isInOpenMPDeclareTargetContext())
5297     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5298 
5299   return New;
5300 }
5301 
5302 /// Helper method to turn variable array types into constant array
5303 /// types in certain situations which would otherwise be errors (for
5304 /// GCC compatibility).
5305 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5306                                                     ASTContext &Context,
5307                                                     bool &SizeIsNegative,
5308                                                     llvm::APSInt &Oversized) {
5309   // This method tries to turn a variable array into a constant
5310   // array even when the size isn't an ICE.  This is necessary
5311   // for compatibility with code that depends on gcc's buggy
5312   // constant expression folding, like struct {char x[(int)(char*)2];}
5313   SizeIsNegative = false;
5314   Oversized = 0;
5315 
5316   if (T->isDependentType())
5317     return QualType();
5318 
5319   QualifierCollector Qs;
5320   const Type *Ty = Qs.strip(T);
5321 
5322   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5323     QualType Pointee = PTy->getPointeeType();
5324     QualType FixedType =
5325         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5326                                             Oversized);
5327     if (FixedType.isNull()) return FixedType;
5328     FixedType = Context.getPointerType(FixedType);
5329     return Qs.apply(Context, FixedType);
5330   }
5331   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5332     QualType Inner = PTy->getInnerType();
5333     QualType FixedType =
5334         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5335                                             Oversized);
5336     if (FixedType.isNull()) return FixedType;
5337     FixedType = Context.getParenType(FixedType);
5338     return Qs.apply(Context, FixedType);
5339   }
5340 
5341   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5342   if (!VLATy)
5343     return QualType();
5344   // FIXME: We should probably handle this case
5345   if (VLATy->getElementType()->isVariablyModifiedType())
5346     return QualType();
5347 
5348   llvm::APSInt Res;
5349   if (!VLATy->getSizeExpr() ||
5350       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5351     return QualType();
5352 
5353   // Check whether the array size is negative.
5354   if (Res.isSigned() && Res.isNegative()) {
5355     SizeIsNegative = true;
5356     return QualType();
5357   }
5358 
5359   // Check whether the array is too large to be addressed.
5360   unsigned ActiveSizeBits
5361     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5362                                               Res);
5363   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5364     Oversized = Res;
5365     return QualType();
5366   }
5367 
5368   return Context.getConstantArrayType(VLATy->getElementType(),
5369                                       Res, ArrayType::Normal, 0);
5370 }
5371 
5372 static void
5373 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5374   SrcTL = SrcTL.getUnqualifiedLoc();
5375   DstTL = DstTL.getUnqualifiedLoc();
5376   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5377     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5378     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5379                                       DstPTL.getPointeeLoc());
5380     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5381     return;
5382   }
5383   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5384     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5385     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5386                                       DstPTL.getInnerLoc());
5387     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5388     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5389     return;
5390   }
5391   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5392   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5393   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5394   TypeLoc DstElemTL = DstATL.getElementLoc();
5395   DstElemTL.initializeFullCopy(SrcElemTL);
5396   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5397   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5398   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5399 }
5400 
5401 /// Helper method to turn variable array types into constant array
5402 /// types in certain situations which would otherwise be errors (for
5403 /// GCC compatibility).
5404 static TypeSourceInfo*
5405 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5406                                               ASTContext &Context,
5407                                               bool &SizeIsNegative,
5408                                               llvm::APSInt &Oversized) {
5409   QualType FixedTy
5410     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5411                                           SizeIsNegative, Oversized);
5412   if (FixedTy.isNull())
5413     return nullptr;
5414   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5415   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5416                                     FixedTInfo->getTypeLoc());
5417   return FixedTInfo;
5418 }
5419 
5420 /// \brief Register the given locally-scoped extern "C" declaration so
5421 /// that it can be found later for redeclarations. We include any extern "C"
5422 /// declaration that is not visible in the translation unit here, not just
5423 /// function-scope declarations.
5424 void
5425 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5426   if (!getLangOpts().CPlusPlus &&
5427       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5428     // Don't need to track declarations in the TU in C.
5429     return;
5430 
5431   // Note that we have a locally-scoped external with this name.
5432   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5433 }
5434 
5435 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5436   // FIXME: We can have multiple results via __attribute__((overloadable)).
5437   auto Result = Context.getExternCContextDecl()->lookup(Name);
5438   return Result.empty() ? nullptr : *Result.begin();
5439 }
5440 
5441 /// \brief Diagnose function specifiers on a declaration of an identifier that
5442 /// does not identify a function.
5443 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5444   // FIXME: We should probably indicate the identifier in question to avoid
5445   // confusion for constructs like "virtual int a(), b;"
5446   if (DS.isVirtualSpecified())
5447     Diag(DS.getVirtualSpecLoc(),
5448          diag::err_virtual_non_function);
5449 
5450   if (DS.isExplicitSpecified())
5451     Diag(DS.getExplicitSpecLoc(),
5452          diag::err_explicit_non_function);
5453 
5454   if (DS.isNoreturnSpecified())
5455     Diag(DS.getNoreturnSpecLoc(),
5456          diag::err_noreturn_non_function);
5457 }
5458 
5459 NamedDecl*
5460 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5461                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5462   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5463   if (D.getCXXScopeSpec().isSet()) {
5464     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5465       << D.getCXXScopeSpec().getRange();
5466     D.setInvalidType();
5467     // Pretend we didn't see the scope specifier.
5468     DC = CurContext;
5469     Previous.clear();
5470   }
5471 
5472   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5473 
5474   if (D.getDeclSpec().isInlineSpecified())
5475     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5476         << getLangOpts().CPlusPlus1z;
5477   if (D.getDeclSpec().isConstexprSpecified())
5478     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5479       << 1;
5480   if (D.getDeclSpec().isConceptSpecified())
5481     Diag(D.getDeclSpec().getConceptSpecLoc(),
5482          diag::err_concept_wrong_decl_kind);
5483 
5484   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5485     if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName)
5486       Diag(D.getName().StartLocation,
5487            diag::err_deduction_guide_invalid_specifier)
5488           << "typedef";
5489     else
5490       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5491           << D.getName().getSourceRange();
5492     return nullptr;
5493   }
5494 
5495   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5496   if (!NewTD) return nullptr;
5497 
5498   // Handle attributes prior to checking for duplicates in MergeVarDecl
5499   ProcessDeclAttributes(S, NewTD, D);
5500 
5501   CheckTypedefForVariablyModifiedType(S, NewTD);
5502 
5503   bool Redeclaration = D.isRedeclaration();
5504   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5505   D.setRedeclaration(Redeclaration);
5506   return ND;
5507 }
5508 
5509 void
5510 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5511   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5512   // then it shall have block scope.
5513   // Note that variably modified types must be fixed before merging the decl so
5514   // that redeclarations will match.
5515   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5516   QualType T = TInfo->getType();
5517   if (T->isVariablyModifiedType()) {
5518     getCurFunction()->setHasBranchProtectedScope();
5519 
5520     if (S->getFnParent() == nullptr) {
5521       bool SizeIsNegative;
5522       llvm::APSInt Oversized;
5523       TypeSourceInfo *FixedTInfo =
5524         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5525                                                       SizeIsNegative,
5526                                                       Oversized);
5527       if (FixedTInfo) {
5528         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5529         NewTD->setTypeSourceInfo(FixedTInfo);
5530       } else {
5531         if (SizeIsNegative)
5532           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5533         else if (T->isVariableArrayType())
5534           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5535         else if (Oversized.getBoolValue())
5536           Diag(NewTD->getLocation(), diag::err_array_too_large)
5537             << Oversized.toString(10);
5538         else
5539           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5540         NewTD->setInvalidDecl();
5541       }
5542     }
5543   }
5544 }
5545 
5546 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5547 /// declares a typedef-name, either using the 'typedef' type specifier or via
5548 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5549 NamedDecl*
5550 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5551                            LookupResult &Previous, bool &Redeclaration) {
5552 
5553   // Find the shadowed declaration before filtering for scope.
5554   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5555 
5556   // Merge the decl with the existing one if appropriate. If the decl is
5557   // in an outer scope, it isn't the same thing.
5558   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5559                        /*AllowInlineNamespace*/false);
5560   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5561   if (!Previous.empty()) {
5562     Redeclaration = true;
5563     MergeTypedefNameDecl(S, NewTD, Previous);
5564   }
5565 
5566   if (ShadowedDecl && !Redeclaration)
5567     CheckShadow(NewTD, ShadowedDecl, Previous);
5568 
5569   // If this is the C FILE type, notify the AST context.
5570   if (IdentifierInfo *II = NewTD->getIdentifier())
5571     if (!NewTD->isInvalidDecl() &&
5572         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5573       if (II->isStr("FILE"))
5574         Context.setFILEDecl(NewTD);
5575       else if (II->isStr("jmp_buf"))
5576         Context.setjmp_bufDecl(NewTD);
5577       else if (II->isStr("sigjmp_buf"))
5578         Context.setsigjmp_bufDecl(NewTD);
5579       else if (II->isStr("ucontext_t"))
5580         Context.setucontext_tDecl(NewTD);
5581     }
5582 
5583   return NewTD;
5584 }
5585 
5586 /// \brief Determines whether the given declaration is an out-of-scope
5587 /// previous declaration.
5588 ///
5589 /// This routine should be invoked when name lookup has found a
5590 /// previous declaration (PrevDecl) that is not in the scope where a
5591 /// new declaration by the same name is being introduced. If the new
5592 /// declaration occurs in a local scope, previous declarations with
5593 /// linkage may still be considered previous declarations (C99
5594 /// 6.2.2p4-5, C++ [basic.link]p6).
5595 ///
5596 /// \param PrevDecl the previous declaration found by name
5597 /// lookup
5598 ///
5599 /// \param DC the context in which the new declaration is being
5600 /// declared.
5601 ///
5602 /// \returns true if PrevDecl is an out-of-scope previous declaration
5603 /// for a new delcaration with the same name.
5604 static bool
5605 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5606                                 ASTContext &Context) {
5607   if (!PrevDecl)
5608     return false;
5609 
5610   if (!PrevDecl->hasLinkage())
5611     return false;
5612 
5613   if (Context.getLangOpts().CPlusPlus) {
5614     // C++ [basic.link]p6:
5615     //   If there is a visible declaration of an entity with linkage
5616     //   having the same name and type, ignoring entities declared
5617     //   outside the innermost enclosing namespace scope, the block
5618     //   scope declaration declares that same entity and receives the
5619     //   linkage of the previous declaration.
5620     DeclContext *OuterContext = DC->getRedeclContext();
5621     if (!OuterContext->isFunctionOrMethod())
5622       // This rule only applies to block-scope declarations.
5623       return false;
5624 
5625     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5626     if (PrevOuterContext->isRecord())
5627       // We found a member function: ignore it.
5628       return false;
5629 
5630     // Find the innermost enclosing namespace for the new and
5631     // previous declarations.
5632     OuterContext = OuterContext->getEnclosingNamespaceContext();
5633     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5634 
5635     // The previous declaration is in a different namespace, so it
5636     // isn't the same function.
5637     if (!OuterContext->Equals(PrevOuterContext))
5638       return false;
5639   }
5640 
5641   return true;
5642 }
5643 
5644 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5645   CXXScopeSpec &SS = D.getCXXScopeSpec();
5646   if (!SS.isSet()) return;
5647   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5648 }
5649 
5650 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5651   QualType type = decl->getType();
5652   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5653   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5654     // Various kinds of declaration aren't allowed to be __autoreleasing.
5655     unsigned kind = -1U;
5656     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5657       if (var->hasAttr<BlocksAttr>())
5658         kind = 0; // __block
5659       else if (!var->hasLocalStorage())
5660         kind = 1; // global
5661     } else if (isa<ObjCIvarDecl>(decl)) {
5662       kind = 3; // ivar
5663     } else if (isa<FieldDecl>(decl)) {
5664       kind = 2; // field
5665     }
5666 
5667     if (kind != -1U) {
5668       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5669         << kind;
5670     }
5671   } else if (lifetime == Qualifiers::OCL_None) {
5672     // Try to infer lifetime.
5673     if (!type->isObjCLifetimeType())
5674       return false;
5675 
5676     lifetime = type->getObjCARCImplicitLifetime();
5677     type = Context.getLifetimeQualifiedType(type, lifetime);
5678     decl->setType(type);
5679   }
5680 
5681   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5682     // Thread-local variables cannot have lifetime.
5683     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5684         var->getTLSKind()) {
5685       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5686         << var->getType();
5687       return true;
5688     }
5689   }
5690 
5691   return false;
5692 }
5693 
5694 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5695   // Ensure that an auto decl is deduced otherwise the checks below might cache
5696   // the wrong linkage.
5697   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5698 
5699   // 'weak' only applies to declarations with external linkage.
5700   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5701     if (!ND.isExternallyVisible()) {
5702       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5703       ND.dropAttr<WeakAttr>();
5704     }
5705   }
5706   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5707     if (ND.isExternallyVisible()) {
5708       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5709       ND.dropAttr<WeakRefAttr>();
5710       ND.dropAttr<AliasAttr>();
5711     }
5712   }
5713 
5714   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5715     if (VD->hasInit()) {
5716       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5717         assert(VD->isThisDeclarationADefinition() &&
5718                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5719         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5720         VD->dropAttr<AliasAttr>();
5721       }
5722     }
5723   }
5724 
5725   // 'selectany' only applies to externally visible variable declarations.
5726   // It does not apply to functions.
5727   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5728     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5729       S.Diag(Attr->getLocation(),
5730              diag::err_attribute_selectany_non_extern_data);
5731       ND.dropAttr<SelectAnyAttr>();
5732     }
5733   }
5734 
5735   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5736     // dll attributes require external linkage. Static locals may have external
5737     // linkage but still cannot be explicitly imported or exported.
5738     auto *VD = dyn_cast<VarDecl>(&ND);
5739     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5740       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5741         << &ND << Attr;
5742       ND.setInvalidDecl();
5743     }
5744   }
5745 
5746   // Virtual functions cannot be marked as 'notail'.
5747   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5748     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5749       if (MD->isVirtual()) {
5750         S.Diag(ND.getLocation(),
5751                diag::err_invalid_attribute_on_virtual_function)
5752             << Attr;
5753         ND.dropAttr<NotTailCalledAttr>();
5754       }
5755 }
5756 
5757 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5758                                            NamedDecl *NewDecl,
5759                                            bool IsSpecialization,
5760                                            bool IsDefinition) {
5761   if (OldDecl->isInvalidDecl())
5762     return;
5763 
5764   bool IsTemplate = false;
5765   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5766     OldDecl = OldTD->getTemplatedDecl();
5767     IsTemplate = true;
5768     if (!IsSpecialization)
5769       IsDefinition = false;
5770   }
5771   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
5772     NewDecl = NewTD->getTemplatedDecl();
5773     IsTemplate = true;
5774   }
5775 
5776   if (!OldDecl || !NewDecl)
5777     return;
5778 
5779   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5780   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5781   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5782   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5783 
5784   // dllimport and dllexport are inheritable attributes so we have to exclude
5785   // inherited attribute instances.
5786   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5787                     (NewExportAttr && !NewExportAttr->isInherited());
5788 
5789   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5790   // the only exception being explicit specializations.
5791   // Implicitly generated declarations are also excluded for now because there
5792   // is no other way to switch these to use dllimport or dllexport.
5793   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5794 
5795   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5796     // Allow with a warning for free functions and global variables.
5797     bool JustWarn = false;
5798     if (!OldDecl->isCXXClassMember()) {
5799       auto *VD = dyn_cast<VarDecl>(OldDecl);
5800       if (VD && !VD->getDescribedVarTemplate())
5801         JustWarn = true;
5802       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5803       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5804         JustWarn = true;
5805     }
5806 
5807     // We cannot change a declaration that's been used because IR has already
5808     // been emitted. Dllimported functions will still work though (modulo
5809     // address equality) as they can use the thunk.
5810     if (OldDecl->isUsed())
5811       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5812         JustWarn = false;
5813 
5814     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5815                                : diag::err_attribute_dll_redeclaration;
5816     S.Diag(NewDecl->getLocation(), DiagID)
5817         << NewDecl
5818         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5819     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5820     if (!JustWarn) {
5821       NewDecl->setInvalidDecl();
5822       return;
5823     }
5824   }
5825 
5826   // A redeclaration is not allowed to drop a dllimport attribute, the only
5827   // exceptions being inline function definitions (except for function
5828   // templates), local extern declarations, qualified friend declarations or
5829   // special MSVC extension: in the last case, the declaration is treated as if
5830   // it were marked dllexport.
5831   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5832   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5833   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5834     // Ignore static data because out-of-line definitions are diagnosed
5835     // separately.
5836     IsStaticDataMember = VD->isStaticDataMember();
5837     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5838                    VarDecl::DeclarationOnly;
5839   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5840     IsInline = FD->isInlined();
5841     IsQualifiedFriend = FD->getQualifier() &&
5842                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5843   }
5844 
5845   if (OldImportAttr && !HasNewAttr &&
5846       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
5847       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5848     if (IsMicrosoft && IsDefinition) {
5849       S.Diag(NewDecl->getLocation(),
5850              diag::warn_redeclaration_without_import_attribute)
5851           << NewDecl;
5852       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5853       NewDecl->dropAttr<DLLImportAttr>();
5854       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
5855           NewImportAttr->getRange(), S.Context,
5856           NewImportAttr->getSpellingListIndex()));
5857     } else {
5858       S.Diag(NewDecl->getLocation(),
5859              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5860           << NewDecl << OldImportAttr;
5861       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5862       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5863       OldDecl->dropAttr<DLLImportAttr>();
5864       NewDecl->dropAttr<DLLImportAttr>();
5865     }
5866   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
5867     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5868     OldDecl->dropAttr<DLLImportAttr>();
5869     NewDecl->dropAttr<DLLImportAttr>();
5870     S.Diag(NewDecl->getLocation(),
5871            diag::warn_dllimport_dropped_from_inline_function)
5872         << NewDecl << OldImportAttr;
5873   }
5874 }
5875 
5876 /// Given that we are within the definition of the given function,
5877 /// will that definition behave like C99's 'inline', where the
5878 /// definition is discarded except for optimization purposes?
5879 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5880   // Try to avoid calling GetGVALinkageForFunction.
5881 
5882   // All cases of this require the 'inline' keyword.
5883   if (!FD->isInlined()) return false;
5884 
5885   // This is only possible in C++ with the gnu_inline attribute.
5886   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5887     return false;
5888 
5889   // Okay, go ahead and call the relatively-more-expensive function.
5890   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5891 }
5892 
5893 /// Determine whether a variable is extern "C" prior to attaching
5894 /// an initializer. We can't just call isExternC() here, because that
5895 /// will also compute and cache whether the declaration is externally
5896 /// visible, which might change when we attach the initializer.
5897 ///
5898 /// This can only be used if the declaration is known to not be a
5899 /// redeclaration of an internal linkage declaration.
5900 ///
5901 /// For instance:
5902 ///
5903 ///   auto x = []{};
5904 ///
5905 /// Attaching the initializer here makes this declaration not externally
5906 /// visible, because its type has internal linkage.
5907 ///
5908 /// FIXME: This is a hack.
5909 template<typename T>
5910 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5911   if (S.getLangOpts().CPlusPlus) {
5912     // In C++, the overloadable attribute negates the effects of extern "C".
5913     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5914       return false;
5915 
5916     // So do CUDA's host/device attributes.
5917     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
5918                                  D->template hasAttr<CUDAHostAttr>()))
5919       return false;
5920   }
5921   return D->isExternC();
5922 }
5923 
5924 static bool shouldConsiderLinkage(const VarDecl *VD) {
5925   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5926   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
5927     return VD->hasExternalStorage();
5928   if (DC->isFileContext())
5929     return true;
5930   if (DC->isRecord())
5931     return false;
5932   llvm_unreachable("Unexpected context");
5933 }
5934 
5935 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5936   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5937   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
5938       isa<OMPDeclareReductionDecl>(DC))
5939     return true;
5940   if (DC->isRecord())
5941     return false;
5942   llvm_unreachable("Unexpected context");
5943 }
5944 
5945 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5946                           AttributeList::Kind Kind) {
5947   for (const AttributeList *L = AttrList; L; L = L->getNext())
5948     if (L->getKind() == Kind)
5949       return true;
5950   return false;
5951 }
5952 
5953 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5954                           AttributeList::Kind Kind) {
5955   // Check decl attributes on the DeclSpec.
5956   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5957     return true;
5958 
5959   // Walk the declarator structure, checking decl attributes that were in a type
5960   // position to the decl itself.
5961   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5962     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5963       return true;
5964   }
5965 
5966   // Finally, check attributes on the decl itself.
5967   return hasParsedAttr(S, PD.getAttributes(), Kind);
5968 }
5969 
5970 /// Adjust the \c DeclContext for a function or variable that might be a
5971 /// function-local external declaration.
5972 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5973   if (!DC->isFunctionOrMethod())
5974     return false;
5975 
5976   // If this is a local extern function or variable declared within a function
5977   // template, don't add it into the enclosing namespace scope until it is
5978   // instantiated; it might have a dependent type right now.
5979   if (DC->isDependentContext())
5980     return true;
5981 
5982   // C++11 [basic.link]p7:
5983   //   When a block scope declaration of an entity with linkage is not found to
5984   //   refer to some other declaration, then that entity is a member of the
5985   //   innermost enclosing namespace.
5986   //
5987   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5988   // semantically-enclosing namespace, not a lexically-enclosing one.
5989   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5990     DC = DC->getParent();
5991   return true;
5992 }
5993 
5994 /// \brief Returns true if given declaration has external C language linkage.
5995 static bool isDeclExternC(const Decl *D) {
5996   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5997     return FD->isExternC();
5998   if (const auto *VD = dyn_cast<VarDecl>(D))
5999     return VD->isExternC();
6000 
6001   llvm_unreachable("Unknown type of decl!");
6002 }
6003 
6004 NamedDecl *Sema::ActOnVariableDeclarator(
6005     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6006     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6007     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6008   QualType R = TInfo->getType();
6009   DeclarationName Name = GetNameForDeclarator(D).getName();
6010 
6011   IdentifierInfo *II = Name.getAsIdentifierInfo();
6012 
6013   if (D.isDecompositionDeclarator()) {
6014     AddToScope = false;
6015     // Take the name of the first declarator as our name for diagnostic
6016     // purposes.
6017     auto &Decomp = D.getDecompositionDeclarator();
6018     if (!Decomp.bindings().empty()) {
6019       II = Decomp.bindings()[0].Name;
6020       Name = II;
6021     }
6022   } else if (!II) {
6023     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6024     return nullptr;
6025   }
6026 
6027   if (getLangOpts().OpenCL) {
6028     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6029     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6030     // argument.
6031     if (R->isImageType() || R->isPipeType()) {
6032       Diag(D.getIdentifierLoc(),
6033            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6034           << R;
6035       D.setInvalidType();
6036       return nullptr;
6037     }
6038 
6039     // OpenCL v1.2 s6.9.r:
6040     // The event type cannot be used to declare a program scope variable.
6041     // OpenCL v2.0 s6.9.q:
6042     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6043     if (NULL == S->getParent()) {
6044       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6045         Diag(D.getIdentifierLoc(),
6046              diag::err_invalid_type_for_program_scope_var) << R;
6047         D.setInvalidType();
6048         return nullptr;
6049       }
6050     }
6051 
6052     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6053     QualType NR = R;
6054     while (NR->isPointerType()) {
6055       if (NR->isFunctionPointerType()) {
6056         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
6057         D.setInvalidType();
6058         break;
6059       }
6060       NR = NR->getPointeeType();
6061     }
6062 
6063     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6064       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6065       // half array type (unless the cl_khr_fp16 extension is enabled).
6066       if (Context.getBaseElementType(R)->isHalfType()) {
6067         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6068         D.setInvalidType();
6069       }
6070     }
6071 
6072     // OpenCL v1.2 s6.9.b p4:
6073     // The sampler type cannot be used with the __local and __global address
6074     // space qualifiers.
6075     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
6076       R.getAddressSpace() == LangAS::opencl_global)) {
6077       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6078     }
6079 
6080     // OpenCL v1.2 s6.9.r:
6081     // The event type cannot be used with the __local, __constant and __global
6082     // address space qualifiers.
6083     if (R->isEventT()) {
6084       if (R.getAddressSpace()) {
6085         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6086         D.setInvalidType();
6087       }
6088     }
6089   }
6090 
6091   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6092   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6093 
6094   // dllimport globals without explicit storage class are treated as extern. We
6095   // have to change the storage class this early to get the right DeclContext.
6096   if (SC == SC_None && !DC->isRecord() &&
6097       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
6098       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
6099     SC = SC_Extern;
6100 
6101   DeclContext *OriginalDC = DC;
6102   bool IsLocalExternDecl = SC == SC_Extern &&
6103                            adjustContextForLocalExternDecl(DC);
6104 
6105   if (SCSpec == DeclSpec::SCS_mutable) {
6106     // mutable can only appear on non-static class members, so it's always
6107     // an error here
6108     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6109     D.setInvalidType();
6110     SC = SC_None;
6111   }
6112 
6113   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6114       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6115                               D.getDeclSpec().getStorageClassSpecLoc())) {
6116     // In C++11, the 'register' storage class specifier is deprecated.
6117     // Suppress the warning in system macros, it's used in macros in some
6118     // popular C system headers, such as in glibc's htonl() macro.
6119     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6120          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
6121                                    : diag::warn_deprecated_register)
6122       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6123   }
6124 
6125   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6126 
6127   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6128     // C99 6.9p2: The storage-class specifiers auto and register shall not
6129     // appear in the declaration specifiers in an external declaration.
6130     // Global Register+Asm is a GNU extension we support.
6131     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6132       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6133       D.setInvalidType();
6134     }
6135   }
6136 
6137   bool IsMemberSpecialization = false;
6138   bool IsVariableTemplateSpecialization = false;
6139   bool IsPartialSpecialization = false;
6140   bool IsVariableTemplate = false;
6141   VarDecl *NewVD = nullptr;
6142   VarTemplateDecl *NewTemplate = nullptr;
6143   TemplateParameterList *TemplateParams = nullptr;
6144   if (!getLangOpts().CPlusPlus) {
6145     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6146                             D.getIdentifierLoc(), II,
6147                             R, TInfo, SC);
6148 
6149     if (R->getContainedDeducedType())
6150       ParsingInitForAutoVars.insert(NewVD);
6151 
6152     if (D.isInvalidType())
6153       NewVD->setInvalidDecl();
6154   } else {
6155     bool Invalid = false;
6156 
6157     if (DC->isRecord() && !CurContext->isRecord()) {
6158       // This is an out-of-line definition of a static data member.
6159       switch (SC) {
6160       case SC_None:
6161         break;
6162       case SC_Static:
6163         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6164              diag::err_static_out_of_line)
6165           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6166         break;
6167       case SC_Auto:
6168       case SC_Register:
6169       case SC_Extern:
6170         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6171         // to names of variables declared in a block or to function parameters.
6172         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6173         // of class members
6174 
6175         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6176              diag::err_storage_class_for_static_member)
6177           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6178         break;
6179       case SC_PrivateExtern:
6180         llvm_unreachable("C storage class in c++!");
6181       }
6182     }
6183 
6184     if (SC == SC_Static && CurContext->isRecord()) {
6185       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6186         if (RD->isLocalClass())
6187           Diag(D.getIdentifierLoc(),
6188                diag::err_static_data_member_not_allowed_in_local_class)
6189             << Name << RD->getDeclName();
6190 
6191         // C++98 [class.union]p1: If a union contains a static data member,
6192         // the program is ill-formed. C++11 drops this restriction.
6193         if (RD->isUnion())
6194           Diag(D.getIdentifierLoc(),
6195                getLangOpts().CPlusPlus11
6196                  ? diag::warn_cxx98_compat_static_data_member_in_union
6197                  : diag::ext_static_data_member_in_union) << Name;
6198         // We conservatively disallow static data members in anonymous structs.
6199         else if (!RD->getDeclName())
6200           Diag(D.getIdentifierLoc(),
6201                diag::err_static_data_member_not_allowed_in_anon_struct)
6202             << Name << RD->isUnion();
6203       }
6204     }
6205 
6206     // Match up the template parameter lists with the scope specifier, then
6207     // determine whether we have a template or a template specialization.
6208     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6209         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6210         D.getCXXScopeSpec(),
6211         D.getName().getKind() == UnqualifiedId::IK_TemplateId
6212             ? D.getName().TemplateId
6213             : nullptr,
6214         TemplateParamLists,
6215         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6216 
6217     if (TemplateParams) {
6218       if (!TemplateParams->size() &&
6219           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6220         // There is an extraneous 'template<>' for this variable. Complain
6221         // about it, but allow the declaration of the variable.
6222         Diag(TemplateParams->getTemplateLoc(),
6223              diag::err_template_variable_noparams)
6224           << II
6225           << SourceRange(TemplateParams->getTemplateLoc(),
6226                          TemplateParams->getRAngleLoc());
6227         TemplateParams = nullptr;
6228       } else {
6229         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6230           // This is an explicit specialization or a partial specialization.
6231           // FIXME: Check that we can declare a specialization here.
6232           IsVariableTemplateSpecialization = true;
6233           IsPartialSpecialization = TemplateParams->size() > 0;
6234         } else { // if (TemplateParams->size() > 0)
6235           // This is a template declaration.
6236           IsVariableTemplate = true;
6237 
6238           // Check that we can declare a template here.
6239           if (CheckTemplateDeclScope(S, TemplateParams))
6240             return nullptr;
6241 
6242           // Only C++1y supports variable templates (N3651).
6243           Diag(D.getIdentifierLoc(),
6244                getLangOpts().CPlusPlus14
6245                    ? diag::warn_cxx11_compat_variable_template
6246                    : diag::ext_variable_template);
6247         }
6248       }
6249     } else {
6250       assert(
6251           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6252           "should have a 'template<>' for this decl");
6253     }
6254 
6255     if (IsVariableTemplateSpecialization) {
6256       SourceLocation TemplateKWLoc =
6257           TemplateParamLists.size() > 0
6258               ? TemplateParamLists[0]->getTemplateLoc()
6259               : SourceLocation();
6260       DeclResult Res = ActOnVarTemplateSpecialization(
6261           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6262           IsPartialSpecialization);
6263       if (Res.isInvalid())
6264         return nullptr;
6265       NewVD = cast<VarDecl>(Res.get());
6266       AddToScope = false;
6267     } else if (D.isDecompositionDeclarator()) {
6268       NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6269                                         D.getIdentifierLoc(), R, TInfo, SC,
6270                                         Bindings);
6271     } else
6272       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6273                               D.getIdentifierLoc(), II, R, TInfo, SC);
6274 
6275     // If this is supposed to be a variable template, create it as such.
6276     if (IsVariableTemplate) {
6277       NewTemplate =
6278           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6279                                   TemplateParams, NewVD);
6280       NewVD->setDescribedVarTemplate(NewTemplate);
6281     }
6282 
6283     // If this decl has an auto type in need of deduction, make a note of the
6284     // Decl so we can diagnose uses of it in its own initializer.
6285     if (R->getContainedDeducedType())
6286       ParsingInitForAutoVars.insert(NewVD);
6287 
6288     if (D.isInvalidType() || Invalid) {
6289       NewVD->setInvalidDecl();
6290       if (NewTemplate)
6291         NewTemplate->setInvalidDecl();
6292     }
6293 
6294     SetNestedNameSpecifier(NewVD, D);
6295 
6296     // If we have any template parameter lists that don't directly belong to
6297     // the variable (matching the scope specifier), store them.
6298     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6299     if (TemplateParamLists.size() > VDTemplateParamLists)
6300       NewVD->setTemplateParameterListsInfo(
6301           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6302 
6303     if (D.getDeclSpec().isConstexprSpecified()) {
6304       NewVD->setConstexpr(true);
6305       // C++1z [dcl.spec.constexpr]p1:
6306       //   A static data member declared with the constexpr specifier is
6307       //   implicitly an inline variable.
6308       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6309         NewVD->setImplicitlyInline();
6310     }
6311 
6312     if (D.getDeclSpec().isConceptSpecified()) {
6313       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6314         VTD->setConcept();
6315 
6316       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6317       // be declared with the thread_local, inline, friend, or constexpr
6318       // specifiers, [...]
6319       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6320         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6321              diag::err_concept_decl_invalid_specifiers)
6322             << 0 << 0;
6323         NewVD->setInvalidDecl(true);
6324       }
6325 
6326       if (D.getDeclSpec().isConstexprSpecified()) {
6327         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6328              diag::err_concept_decl_invalid_specifiers)
6329             << 0 << 3;
6330         NewVD->setInvalidDecl(true);
6331       }
6332 
6333       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6334       // applied only to the definition of a function template or variable
6335       // template, declared in namespace scope.
6336       if (IsVariableTemplateSpecialization) {
6337         Diag(D.getDeclSpec().getConceptSpecLoc(),
6338              diag::err_concept_specified_specialization)
6339             << (IsPartialSpecialization ? 2 : 1);
6340       }
6341 
6342       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6343       // following restrictions:
6344       // - The declared type shall have the type bool.
6345       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6346           !NewVD->isInvalidDecl()) {
6347         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6348         NewVD->setInvalidDecl(true);
6349       }
6350     }
6351   }
6352 
6353   if (D.getDeclSpec().isInlineSpecified()) {
6354     if (!getLangOpts().CPlusPlus) {
6355       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6356           << 0;
6357     } else if (CurContext->isFunctionOrMethod()) {
6358       // 'inline' is not allowed on block scope variable declaration.
6359       Diag(D.getDeclSpec().getInlineSpecLoc(),
6360            diag::err_inline_declaration_block_scope) << Name
6361         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6362     } else {
6363       Diag(D.getDeclSpec().getInlineSpecLoc(),
6364            getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6365                                      : diag::ext_inline_variable);
6366       NewVD->setInlineSpecified();
6367     }
6368   }
6369 
6370   // Set the lexical context. If the declarator has a C++ scope specifier, the
6371   // lexical context will be different from the semantic context.
6372   NewVD->setLexicalDeclContext(CurContext);
6373   if (NewTemplate)
6374     NewTemplate->setLexicalDeclContext(CurContext);
6375 
6376   if (IsLocalExternDecl) {
6377     if (D.isDecompositionDeclarator())
6378       for (auto *B : Bindings)
6379         B->setLocalExternDecl();
6380     else
6381       NewVD->setLocalExternDecl();
6382   }
6383 
6384   bool EmitTLSUnsupportedError = false;
6385   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6386     // C++11 [dcl.stc]p4:
6387     //   When thread_local is applied to a variable of block scope the
6388     //   storage-class-specifier static is implied if it does not appear
6389     //   explicitly.
6390     // Core issue: 'static' is not implied if the variable is declared
6391     //   'extern'.
6392     if (NewVD->hasLocalStorage() &&
6393         (SCSpec != DeclSpec::SCS_unspecified ||
6394          TSCS != DeclSpec::TSCS_thread_local ||
6395          !DC->isFunctionOrMethod()))
6396       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6397            diag::err_thread_non_global)
6398         << DeclSpec::getSpecifierName(TSCS);
6399     else if (!Context.getTargetInfo().isTLSSupported()) {
6400       if (getLangOpts().CUDA) {
6401         // Postpone error emission until we've collected attributes required to
6402         // figure out whether it's a host or device variable and whether the
6403         // error should be ignored.
6404         EmitTLSUnsupportedError = true;
6405         // We still need to mark the variable as TLS so it shows up in AST with
6406         // proper storage class for other tools to use even if we're not going
6407         // to emit any code for it.
6408         NewVD->setTSCSpec(TSCS);
6409       } else
6410         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6411              diag::err_thread_unsupported);
6412     } else
6413       NewVD->setTSCSpec(TSCS);
6414   }
6415 
6416   // C99 6.7.4p3
6417   //   An inline definition of a function with external linkage shall
6418   //   not contain a definition of a modifiable object with static or
6419   //   thread storage duration...
6420   // We only apply this when the function is required to be defined
6421   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6422   // that a local variable with thread storage duration still has to
6423   // be marked 'static'.  Also note that it's possible to get these
6424   // semantics in C++ using __attribute__((gnu_inline)).
6425   if (SC == SC_Static && S->getFnParent() != nullptr &&
6426       !NewVD->getType().isConstQualified()) {
6427     FunctionDecl *CurFD = getCurFunctionDecl();
6428     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6429       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6430            diag::warn_static_local_in_extern_inline);
6431       MaybeSuggestAddingStaticToDecl(CurFD);
6432     }
6433   }
6434 
6435   if (D.getDeclSpec().isModulePrivateSpecified()) {
6436     if (IsVariableTemplateSpecialization)
6437       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6438           << (IsPartialSpecialization ? 1 : 0)
6439           << FixItHint::CreateRemoval(
6440                  D.getDeclSpec().getModulePrivateSpecLoc());
6441     else if (IsMemberSpecialization)
6442       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6443         << 2
6444         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6445     else if (NewVD->hasLocalStorage())
6446       Diag(NewVD->getLocation(), diag::err_module_private_local)
6447         << 0 << NewVD->getDeclName()
6448         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6449         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6450     else {
6451       NewVD->setModulePrivate();
6452       if (NewTemplate)
6453         NewTemplate->setModulePrivate();
6454       for (auto *B : Bindings)
6455         B->setModulePrivate();
6456     }
6457   }
6458 
6459   // Handle attributes prior to checking for duplicates in MergeVarDecl
6460   ProcessDeclAttributes(S, NewVD, D);
6461 
6462   if (getLangOpts().CUDA) {
6463     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6464       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6465            diag::err_thread_unsupported);
6466     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6467     // storage [duration]."
6468     if (SC == SC_None && S->getFnParent() != nullptr &&
6469         (NewVD->hasAttr<CUDASharedAttr>() ||
6470          NewVD->hasAttr<CUDAConstantAttr>())) {
6471       NewVD->setStorageClass(SC_Static);
6472     }
6473   }
6474 
6475   // Ensure that dllimport globals without explicit storage class are treated as
6476   // extern. The storage class is set above using parsed attributes. Now we can
6477   // check the VarDecl itself.
6478   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6479          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6480          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6481 
6482   // In auto-retain/release, infer strong retension for variables of
6483   // retainable type.
6484   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6485     NewVD->setInvalidDecl();
6486 
6487   // Handle GNU asm-label extension (encoded as an attribute).
6488   if (Expr *E = (Expr*)D.getAsmLabel()) {
6489     // The parser guarantees this is a string.
6490     StringLiteral *SE = cast<StringLiteral>(E);
6491     StringRef Label = SE->getString();
6492     if (S->getFnParent() != nullptr) {
6493       switch (SC) {
6494       case SC_None:
6495       case SC_Auto:
6496         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6497         break;
6498       case SC_Register:
6499         // Local Named register
6500         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6501             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6502           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6503         break;
6504       case SC_Static:
6505       case SC_Extern:
6506       case SC_PrivateExtern:
6507         break;
6508       }
6509     } else if (SC == SC_Register) {
6510       // Global Named register
6511       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6512         const auto &TI = Context.getTargetInfo();
6513         bool HasSizeMismatch;
6514 
6515         if (!TI.isValidGCCRegisterName(Label))
6516           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6517         else if (!TI.validateGlobalRegisterVariable(Label,
6518                                                     Context.getTypeSize(R),
6519                                                     HasSizeMismatch))
6520           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6521         else if (HasSizeMismatch)
6522           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6523       }
6524 
6525       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6526         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6527         NewVD->setInvalidDecl(true);
6528       }
6529     }
6530 
6531     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6532                                                 Context, Label, 0));
6533   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6534     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6535       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6536     if (I != ExtnameUndeclaredIdentifiers.end()) {
6537       if (isDeclExternC(NewVD)) {
6538         NewVD->addAttr(I->second);
6539         ExtnameUndeclaredIdentifiers.erase(I);
6540       } else
6541         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6542             << /*Variable*/1 << NewVD;
6543     }
6544   }
6545 
6546   // Find the shadowed declaration before filtering for scope.
6547   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6548                                 ? getShadowedDeclaration(NewVD, Previous)
6549                                 : nullptr;
6550 
6551   // Don't consider existing declarations that are in a different
6552   // scope and are out-of-semantic-context declarations (if the new
6553   // declaration has linkage).
6554   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6555                        D.getCXXScopeSpec().isNotEmpty() ||
6556                        IsMemberSpecialization ||
6557                        IsVariableTemplateSpecialization);
6558 
6559   // Check whether the previous declaration is in the same block scope. This
6560   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6561   if (getLangOpts().CPlusPlus &&
6562       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6563     NewVD->setPreviousDeclInSameBlockScope(
6564         Previous.isSingleResult() && !Previous.isShadowed() &&
6565         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6566 
6567   if (!getLangOpts().CPlusPlus) {
6568     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6569   } else {
6570     // If this is an explicit specialization of a static data member, check it.
6571     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6572         CheckMemberSpecialization(NewVD, Previous))
6573       NewVD->setInvalidDecl();
6574 
6575     // Merge the decl with the existing one if appropriate.
6576     if (!Previous.empty()) {
6577       if (Previous.isSingleResult() &&
6578           isa<FieldDecl>(Previous.getFoundDecl()) &&
6579           D.getCXXScopeSpec().isSet()) {
6580         // The user tried to define a non-static data member
6581         // out-of-line (C++ [dcl.meaning]p1).
6582         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6583           << D.getCXXScopeSpec().getRange();
6584         Previous.clear();
6585         NewVD->setInvalidDecl();
6586       }
6587     } else if (D.getCXXScopeSpec().isSet()) {
6588       // No previous declaration in the qualifying scope.
6589       Diag(D.getIdentifierLoc(), diag::err_no_member)
6590         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6591         << D.getCXXScopeSpec().getRange();
6592       NewVD->setInvalidDecl();
6593     }
6594 
6595     if (!IsVariableTemplateSpecialization)
6596       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6597 
6598     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6599     // an explicit specialization (14.8.3) or a partial specialization of a
6600     // concept definition.
6601     if (IsVariableTemplateSpecialization &&
6602         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6603         Previous.isSingleResult()) {
6604       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6605       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6606         if (VarTmpl->isConcept()) {
6607           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6608               << 1                            /*variable*/
6609               << (IsPartialSpecialization ? 2 /*partially specialized*/
6610                                           : 1 /*explicitly specialized*/);
6611           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6612           NewVD->setInvalidDecl();
6613         }
6614       }
6615     }
6616 
6617     if (NewTemplate) {
6618       VarTemplateDecl *PrevVarTemplate =
6619           NewVD->getPreviousDecl()
6620               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6621               : nullptr;
6622 
6623       // Check the template parameter list of this declaration, possibly
6624       // merging in the template parameter list from the previous variable
6625       // template declaration.
6626       if (CheckTemplateParameterList(
6627               TemplateParams,
6628               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6629                               : nullptr,
6630               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6631                DC->isDependentContext())
6632                   ? TPC_ClassTemplateMember
6633                   : TPC_VarTemplate))
6634         NewVD->setInvalidDecl();
6635 
6636       // If we are providing an explicit specialization of a static variable
6637       // template, make a note of that.
6638       if (PrevVarTemplate &&
6639           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6640         PrevVarTemplate->setMemberSpecialization();
6641     }
6642   }
6643 
6644   // Diagnose shadowed variables iff this isn't a redeclaration.
6645   if (ShadowedDecl && !D.isRedeclaration())
6646     CheckShadow(NewVD, ShadowedDecl, Previous);
6647 
6648   ProcessPragmaWeak(S, NewVD);
6649 
6650   // If this is the first declaration of an extern C variable, update
6651   // the map of such variables.
6652   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6653       isIncompleteDeclExternC(*this, NewVD))
6654     RegisterLocallyScopedExternCDecl(NewVD, S);
6655 
6656   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6657     Decl *ManglingContextDecl;
6658     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6659             NewVD->getDeclContext(), ManglingContextDecl)) {
6660       Context.setManglingNumber(
6661           NewVD, MCtx->getManglingNumber(
6662                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6663       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6664     }
6665   }
6666 
6667   // Special handling of variable named 'main'.
6668   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6669       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6670       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6671 
6672     // C++ [basic.start.main]p3
6673     // A program that declares a variable main at global scope is ill-formed.
6674     if (getLangOpts().CPlusPlus)
6675       Diag(D.getLocStart(), diag::err_main_global_variable);
6676 
6677     // In C, and external-linkage variable named main results in undefined
6678     // behavior.
6679     else if (NewVD->hasExternalFormalLinkage())
6680       Diag(D.getLocStart(), diag::warn_main_redefined);
6681   }
6682 
6683   if (D.isRedeclaration() && !Previous.empty()) {
6684     checkDLLAttributeRedeclaration(
6685         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6686         IsMemberSpecialization, D.isFunctionDefinition());
6687   }
6688 
6689   if (NewTemplate) {
6690     if (NewVD->isInvalidDecl())
6691       NewTemplate->setInvalidDecl();
6692     ActOnDocumentableDecl(NewTemplate);
6693     return NewTemplate;
6694   }
6695 
6696   return NewVD;
6697 }
6698 
6699 /// Enum describing the %select options in diag::warn_decl_shadow.
6700 enum ShadowedDeclKind {
6701   SDK_Local,
6702   SDK_Global,
6703   SDK_StaticMember,
6704   SDK_Field,
6705   SDK_Typedef,
6706   SDK_Using
6707 };
6708 
6709 /// Determine what kind of declaration we're shadowing.
6710 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6711                                                 const DeclContext *OldDC) {
6712   if (isa<TypeAliasDecl>(ShadowedDecl))
6713     return SDK_Using;
6714   else if (isa<TypedefDecl>(ShadowedDecl))
6715     return SDK_Typedef;
6716   else if (isa<RecordDecl>(OldDC))
6717     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6718 
6719   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6720 }
6721 
6722 /// Return the location of the capture if the given lambda captures the given
6723 /// variable \p VD, or an invalid source location otherwise.
6724 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6725                                          const VarDecl *VD) {
6726   for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
6727     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6728       return Capture.getLocation();
6729   }
6730   return SourceLocation();
6731 }
6732 
6733 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6734                                      const LookupResult &R) {
6735   // Only diagnose if we're shadowing an unambiguous field or variable.
6736   if (R.getResultKind() != LookupResult::Found)
6737     return false;
6738 
6739   // Return false if warning is ignored.
6740   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6741 }
6742 
6743 /// \brief Return the declaration shadowed by the given variable \p D, or null
6744 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6745 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6746                                         const LookupResult &R) {
6747   if (!shouldWarnIfShadowedDecl(Diags, R))
6748     return nullptr;
6749 
6750   // Don't diagnose declarations at file scope.
6751   if (D->hasGlobalStorage())
6752     return nullptr;
6753 
6754   NamedDecl *ShadowedDecl = R.getFoundDecl();
6755   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6756              ? ShadowedDecl
6757              : nullptr;
6758 }
6759 
6760 /// \brief Return the declaration shadowed by the given typedef \p D, or null
6761 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6762 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
6763                                         const LookupResult &R) {
6764   // Don't warn if typedef declaration is part of a class
6765   if (D->getDeclContext()->isRecord())
6766     return nullptr;
6767 
6768   if (!shouldWarnIfShadowedDecl(Diags, R))
6769     return nullptr;
6770 
6771   NamedDecl *ShadowedDecl = R.getFoundDecl();
6772   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
6773 }
6774 
6775 /// \brief Diagnose variable or built-in function shadowing.  Implements
6776 /// -Wshadow.
6777 ///
6778 /// This method is called whenever a VarDecl is added to a "useful"
6779 /// scope.
6780 ///
6781 /// \param ShadowedDecl the declaration that is shadowed by the given variable
6782 /// \param R the lookup of the name
6783 ///
6784 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
6785                        const LookupResult &R) {
6786   DeclContext *NewDC = D->getDeclContext();
6787 
6788   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6789     // Fields are not shadowed by variables in C++ static methods.
6790     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6791       if (MD->isStatic())
6792         return;
6793 
6794     // Fields shadowed by constructor parameters are a special case. Usually
6795     // the constructor initializes the field with the parameter.
6796     if (isa<CXXConstructorDecl>(NewDC))
6797       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
6798         // Remember that this was shadowed so we can either warn about its
6799         // modification or its existence depending on warning settings.
6800         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
6801         return;
6802       }
6803   }
6804 
6805   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6806     if (shadowedVar->isExternC()) {
6807       // For shadowing external vars, make sure that we point to the global
6808       // declaration, not a locally scoped extern declaration.
6809       for (auto I : shadowedVar->redecls())
6810         if (I->isFileVarDecl()) {
6811           ShadowedDecl = I;
6812           break;
6813         }
6814     }
6815 
6816   DeclContext *OldDC = ShadowedDecl->getDeclContext();
6817 
6818   unsigned WarningDiag = diag::warn_decl_shadow;
6819   SourceLocation CaptureLoc;
6820   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
6821       isa<CXXMethodDecl>(NewDC)) {
6822     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
6823       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
6824         if (RD->getLambdaCaptureDefault() == LCD_None) {
6825           // Try to avoid warnings for lambdas with an explicit capture list.
6826           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
6827           // Warn only when the lambda captures the shadowed decl explicitly.
6828           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
6829           if (CaptureLoc.isInvalid())
6830             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
6831         } else {
6832           // Remember that this was shadowed so we can avoid the warning if the
6833           // shadowed decl isn't captured and the warning settings allow it.
6834           cast<LambdaScopeInfo>(getCurFunction())
6835               ->ShadowingDecls.push_back(
6836                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
6837           return;
6838         }
6839       }
6840     }
6841   }
6842 
6843   // Only warn about certain kinds of shadowing for class members.
6844   if (NewDC && NewDC->isRecord()) {
6845     // In particular, don't warn about shadowing non-class members.
6846     if (!OldDC->isRecord())
6847       return;
6848 
6849     // TODO: should we warn about static data members shadowing
6850     // static data members from base classes?
6851 
6852     // TODO: don't diagnose for inaccessible shadowed members.
6853     // This is hard to do perfectly because we might friend the
6854     // shadowing context, but that's just a false negative.
6855   }
6856 
6857 
6858   DeclarationName Name = R.getLookupName();
6859 
6860   // Emit warning and note.
6861   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6862     return;
6863   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
6864   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
6865   if (!CaptureLoc.isInvalid())
6866     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
6867         << Name << /*explicitly*/ 1;
6868   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6869 }
6870 
6871 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
6872 /// when these variables are captured by the lambda.
6873 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
6874   for (const auto &Shadow : LSI->ShadowingDecls) {
6875     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
6876     // Try to avoid the warning when the shadowed decl isn't captured.
6877     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
6878     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6879     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
6880                                        ? diag::warn_decl_shadow_uncaptured_local
6881                                        : diag::warn_decl_shadow)
6882         << Shadow.VD->getDeclName()
6883         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
6884     if (!CaptureLoc.isInvalid())
6885       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
6886           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
6887     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6888   }
6889 }
6890 
6891 /// \brief Check -Wshadow without the advantage of a previous lookup.
6892 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6893   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6894     return;
6895 
6896   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6897                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6898   LookupName(R, S);
6899   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
6900     CheckShadow(D, ShadowedDecl, R);
6901 }
6902 
6903 /// Check if 'E', which is an expression that is about to be modified, refers
6904 /// to a constructor parameter that shadows a field.
6905 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
6906   // Quickly ignore expressions that can't be shadowing ctor parameters.
6907   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
6908     return;
6909   E = E->IgnoreParenImpCasts();
6910   auto *DRE = dyn_cast<DeclRefExpr>(E);
6911   if (!DRE)
6912     return;
6913   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
6914   auto I = ShadowingDecls.find(D);
6915   if (I == ShadowingDecls.end())
6916     return;
6917   const NamedDecl *ShadowedDecl = I->second;
6918   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6919   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
6920   Diag(D->getLocation(), diag::note_var_declared_here) << D;
6921   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6922 
6923   // Avoid issuing multiple warnings about the same decl.
6924   ShadowingDecls.erase(I);
6925 }
6926 
6927 /// Check for conflict between this global or extern "C" declaration and
6928 /// previous global or extern "C" declarations. This is only used in C++.
6929 template<typename T>
6930 static bool checkGlobalOrExternCConflict(
6931     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6932   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6933   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6934 
6935   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6936     // The common case: this global doesn't conflict with any extern "C"
6937     // declaration.
6938     return false;
6939   }
6940 
6941   if (Prev) {
6942     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6943       // Both the old and new declarations have C language linkage. This is a
6944       // redeclaration.
6945       Previous.clear();
6946       Previous.addDecl(Prev);
6947       return true;
6948     }
6949 
6950     // This is a global, non-extern "C" declaration, and there is a previous
6951     // non-global extern "C" declaration. Diagnose if this is a variable
6952     // declaration.
6953     if (!isa<VarDecl>(ND))
6954       return false;
6955   } else {
6956     // The declaration is extern "C". Check for any declaration in the
6957     // translation unit which might conflict.
6958     if (IsGlobal) {
6959       // We have already performed the lookup into the translation unit.
6960       IsGlobal = false;
6961       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6962            I != E; ++I) {
6963         if (isa<VarDecl>(*I)) {
6964           Prev = *I;
6965           break;
6966         }
6967       }
6968     } else {
6969       DeclContext::lookup_result R =
6970           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6971       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6972            I != E; ++I) {
6973         if (isa<VarDecl>(*I)) {
6974           Prev = *I;
6975           break;
6976         }
6977         // FIXME: If we have any other entity with this name in global scope,
6978         // the declaration is ill-formed, but that is a defect: it breaks the
6979         // 'stat' hack, for instance. Only variables can have mangled name
6980         // clashes with extern "C" declarations, so only they deserve a
6981         // diagnostic.
6982       }
6983     }
6984 
6985     if (!Prev)
6986       return false;
6987   }
6988 
6989   // Use the first declaration's location to ensure we point at something which
6990   // is lexically inside an extern "C" linkage-spec.
6991   assert(Prev && "should have found a previous declaration to diagnose");
6992   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6993     Prev = FD->getFirstDecl();
6994   else
6995     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6996 
6997   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6998     << IsGlobal << ND;
6999   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7000     << IsGlobal;
7001   return false;
7002 }
7003 
7004 /// Apply special rules for handling extern "C" declarations. Returns \c true
7005 /// if we have found that this is a redeclaration of some prior entity.
7006 ///
7007 /// Per C++ [dcl.link]p6:
7008 ///   Two declarations [for a function or variable] with C language linkage
7009 ///   with the same name that appear in different scopes refer to the same
7010 ///   [entity]. An entity with C language linkage shall not be declared with
7011 ///   the same name as an entity in global scope.
7012 template<typename T>
7013 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7014                                                   LookupResult &Previous) {
7015   if (!S.getLangOpts().CPlusPlus) {
7016     // In C, when declaring a global variable, look for a corresponding 'extern'
7017     // variable declared in function scope. We don't need this in C++, because
7018     // we find local extern decls in the surrounding file-scope DeclContext.
7019     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7020       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7021         Previous.clear();
7022         Previous.addDecl(Prev);
7023         return true;
7024       }
7025     }
7026     return false;
7027   }
7028 
7029   // A declaration in the translation unit can conflict with an extern "C"
7030   // declaration.
7031   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7032     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7033 
7034   // An extern "C" declaration can conflict with a declaration in the
7035   // translation unit or can be a redeclaration of an extern "C" declaration
7036   // in another scope.
7037   if (isIncompleteDeclExternC(S,ND))
7038     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7039 
7040   // Neither global nor extern "C": nothing to do.
7041   return false;
7042 }
7043 
7044 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7045   // If the decl is already known invalid, don't check it.
7046   if (NewVD->isInvalidDecl())
7047     return;
7048 
7049   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
7050   QualType T = TInfo->getType();
7051 
7052   // Defer checking an 'auto' type until its initializer is attached.
7053   if (T->isUndeducedType())
7054     return;
7055 
7056   if (NewVD->hasAttrs())
7057     CheckAlignasUnderalignment(NewVD);
7058 
7059   if (T->isObjCObjectType()) {
7060     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7061       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7062     T = Context.getObjCObjectPointerType(T);
7063     NewVD->setType(T);
7064   }
7065 
7066   // Emit an error if an address space was applied to decl with local storage.
7067   // This includes arrays of objects with address space qualifiers, but not
7068   // automatic variables that point to other address spaces.
7069   // ISO/IEC TR 18037 S5.1.2
7070   if (!getLangOpts().OpenCL
7071       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
7072     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
7073     NewVD->setInvalidDecl();
7074     return;
7075   }
7076 
7077   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7078   // scope.
7079   if (getLangOpts().OpenCLVersion == 120 &&
7080       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7081       NewVD->isStaticLocal()) {
7082     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7083     NewVD->setInvalidDecl();
7084     return;
7085   }
7086 
7087   if (getLangOpts().OpenCL) {
7088     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7089     if (NewVD->hasAttr<BlocksAttr>()) {
7090       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7091       return;
7092     }
7093 
7094     if (T->isBlockPointerType()) {
7095       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7096       // can't use 'extern' storage class.
7097       if (!T.isConstQualified()) {
7098         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7099             << 0 /*const*/;
7100         NewVD->setInvalidDecl();
7101         return;
7102       }
7103       if (NewVD->hasExternalStorage()) {
7104         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7105         NewVD->setInvalidDecl();
7106         return;
7107       }
7108     }
7109     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7110     // __constant address space.
7111     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7112     // variables inside a function can also be declared in the global
7113     // address space.
7114     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7115         NewVD->hasExternalStorage()) {
7116       if (!T->isSamplerT() &&
7117           !(T.getAddressSpace() == LangAS::opencl_constant ||
7118             (T.getAddressSpace() == LangAS::opencl_global &&
7119              getLangOpts().OpenCLVersion == 200))) {
7120         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7121         if (getLangOpts().OpenCLVersion == 200)
7122           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7123               << Scope << "global or constant";
7124         else
7125           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7126               << Scope << "constant";
7127         NewVD->setInvalidDecl();
7128         return;
7129       }
7130     } else {
7131       if (T.getAddressSpace() == LangAS::opencl_global) {
7132         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7133             << 1 /*is any function*/ << "global";
7134         NewVD->setInvalidDecl();
7135         return;
7136       }
7137       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
7138       // in functions.
7139       if (T.getAddressSpace() == LangAS::opencl_constant ||
7140           T.getAddressSpace() == LangAS::opencl_local) {
7141         FunctionDecl *FD = getCurFunctionDecl();
7142         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7143           if (T.getAddressSpace() == LangAS::opencl_constant)
7144             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7145                 << 0 /*non-kernel only*/ << "constant";
7146           else
7147             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7148                 << 0 /*non-kernel only*/ << "local";
7149           NewVD->setInvalidDecl();
7150           return;
7151         }
7152       }
7153     }
7154   }
7155 
7156   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7157       && !NewVD->hasAttr<BlocksAttr>()) {
7158     if (getLangOpts().getGC() != LangOptions::NonGC)
7159       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7160     else {
7161       assert(!getLangOpts().ObjCAutoRefCount);
7162       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7163     }
7164   }
7165 
7166   bool isVM = T->isVariablyModifiedType();
7167   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7168       NewVD->hasAttr<BlocksAttr>())
7169     getCurFunction()->setHasBranchProtectedScope();
7170 
7171   if ((isVM && NewVD->hasLinkage()) ||
7172       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7173     bool SizeIsNegative;
7174     llvm::APSInt Oversized;
7175     TypeSourceInfo *FixedTInfo =
7176       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7177                                                     SizeIsNegative, Oversized);
7178     if (!FixedTInfo && T->isVariableArrayType()) {
7179       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7180       // FIXME: This won't give the correct result for
7181       // int a[10][n];
7182       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7183 
7184       if (NewVD->isFileVarDecl())
7185         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7186         << SizeRange;
7187       else if (NewVD->isStaticLocal())
7188         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7189         << SizeRange;
7190       else
7191         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7192         << SizeRange;
7193       NewVD->setInvalidDecl();
7194       return;
7195     }
7196 
7197     if (!FixedTInfo) {
7198       if (NewVD->isFileVarDecl())
7199         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7200       else
7201         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7202       NewVD->setInvalidDecl();
7203       return;
7204     }
7205 
7206     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7207     NewVD->setType(FixedTInfo->getType());
7208     NewVD->setTypeSourceInfo(FixedTInfo);
7209   }
7210 
7211   if (T->isVoidType()) {
7212     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7213     //                    of objects and functions.
7214     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7215       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7216         << T;
7217       NewVD->setInvalidDecl();
7218       return;
7219     }
7220   }
7221 
7222   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7223     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7224     NewVD->setInvalidDecl();
7225     return;
7226   }
7227 
7228   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7229     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7230     NewVD->setInvalidDecl();
7231     return;
7232   }
7233 
7234   if (NewVD->isConstexpr() && !T->isDependentType() &&
7235       RequireLiteralType(NewVD->getLocation(), T,
7236                          diag::err_constexpr_var_non_literal)) {
7237     NewVD->setInvalidDecl();
7238     return;
7239   }
7240 }
7241 
7242 /// \brief Perform semantic checking on a newly-created variable
7243 /// declaration.
7244 ///
7245 /// This routine performs all of the type-checking required for a
7246 /// variable declaration once it has been built. It is used both to
7247 /// check variables after they have been parsed and their declarators
7248 /// have been translated into a declaration, and to check variables
7249 /// that have been instantiated from a template.
7250 ///
7251 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7252 ///
7253 /// Returns true if the variable declaration is a redeclaration.
7254 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7255   CheckVariableDeclarationType(NewVD);
7256 
7257   // If the decl is already known invalid, don't check it.
7258   if (NewVD->isInvalidDecl())
7259     return false;
7260 
7261   // If we did not find anything by this name, look for a non-visible
7262   // extern "C" declaration with the same name.
7263   if (Previous.empty() &&
7264       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7265     Previous.setShadowed();
7266 
7267   if (!Previous.empty()) {
7268     MergeVarDecl(NewVD, Previous);
7269     return true;
7270   }
7271   return false;
7272 }
7273 
7274 namespace {
7275 struct FindOverriddenMethod {
7276   Sema *S;
7277   CXXMethodDecl *Method;
7278 
7279   /// Member lookup function that determines whether a given C++
7280   /// method overrides a method in a base class, to be used with
7281   /// CXXRecordDecl::lookupInBases().
7282   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7283     RecordDecl *BaseRecord =
7284         Specifier->getType()->getAs<RecordType>()->getDecl();
7285 
7286     DeclarationName Name = Method->getDeclName();
7287 
7288     // FIXME: Do we care about other names here too?
7289     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7290       // We really want to find the base class destructor here.
7291       QualType T = S->Context.getTypeDeclType(BaseRecord);
7292       CanQualType CT = S->Context.getCanonicalType(T);
7293 
7294       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7295     }
7296 
7297     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7298          Path.Decls = Path.Decls.slice(1)) {
7299       NamedDecl *D = Path.Decls.front();
7300       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7301         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7302           return true;
7303       }
7304     }
7305 
7306     return false;
7307   }
7308 };
7309 
7310 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7311 } // end anonymous namespace
7312 
7313 /// \brief Report an error regarding overriding, along with any relevant
7314 /// overriden methods.
7315 ///
7316 /// \param DiagID the primary error to report.
7317 /// \param MD the overriding method.
7318 /// \param OEK which overrides to include as notes.
7319 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7320                             OverrideErrorKind OEK = OEK_All) {
7321   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7322   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7323                                       E = MD->end_overridden_methods();
7324        I != E; ++I) {
7325     // This check (& the OEK parameter) could be replaced by a predicate, but
7326     // without lambdas that would be overkill. This is still nicer than writing
7327     // out the diag loop 3 times.
7328     if ((OEK == OEK_All) ||
7329         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7330         (OEK == OEK_Deleted && (*I)->isDeleted()))
7331       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7332   }
7333 }
7334 
7335 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7336 /// and if so, check that it's a valid override and remember it.
7337 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7338   // Look for methods in base classes that this method might override.
7339   CXXBasePaths Paths;
7340   FindOverriddenMethod FOM;
7341   FOM.Method = MD;
7342   FOM.S = this;
7343   bool hasDeletedOverridenMethods = false;
7344   bool hasNonDeletedOverridenMethods = false;
7345   bool AddedAny = false;
7346   if (DC->lookupInBases(FOM, Paths)) {
7347     for (auto *I : Paths.found_decls()) {
7348       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7349         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7350         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7351             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7352             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7353             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7354           hasDeletedOverridenMethods |= OldMD->isDeleted();
7355           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7356           AddedAny = true;
7357         }
7358       }
7359     }
7360   }
7361 
7362   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7363     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7364   }
7365   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7366     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7367   }
7368 
7369   return AddedAny;
7370 }
7371 
7372 namespace {
7373   // Struct for holding all of the extra arguments needed by
7374   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7375   struct ActOnFDArgs {
7376     Scope *S;
7377     Declarator &D;
7378     MultiTemplateParamsArg TemplateParamLists;
7379     bool AddToScope;
7380   };
7381 } // end anonymous namespace
7382 
7383 namespace {
7384 
7385 // Callback to only accept typo corrections that have a non-zero edit distance.
7386 // Also only accept corrections that have the same parent decl.
7387 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7388  public:
7389   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7390                             CXXRecordDecl *Parent)
7391       : Context(Context), OriginalFD(TypoFD),
7392         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7393 
7394   bool ValidateCandidate(const TypoCorrection &candidate) override {
7395     if (candidate.getEditDistance() == 0)
7396       return false;
7397 
7398     SmallVector<unsigned, 1> MismatchedParams;
7399     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7400                                           CDeclEnd = candidate.end();
7401          CDecl != CDeclEnd; ++CDecl) {
7402       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7403 
7404       if (FD && !FD->hasBody() &&
7405           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7406         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7407           CXXRecordDecl *Parent = MD->getParent();
7408           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7409             return true;
7410         } else if (!ExpectedParent) {
7411           return true;
7412         }
7413       }
7414     }
7415 
7416     return false;
7417   }
7418 
7419  private:
7420   ASTContext &Context;
7421   FunctionDecl *OriginalFD;
7422   CXXRecordDecl *ExpectedParent;
7423 };
7424 
7425 } // end anonymous namespace
7426 
7427 /// \brief Generate diagnostics for an invalid function redeclaration.
7428 ///
7429 /// This routine handles generating the diagnostic messages for an invalid
7430 /// function redeclaration, including finding possible similar declarations
7431 /// or performing typo correction if there are no previous declarations with
7432 /// the same name.
7433 ///
7434 /// Returns a NamedDecl iff typo correction was performed and substituting in
7435 /// the new declaration name does not cause new errors.
7436 static NamedDecl *DiagnoseInvalidRedeclaration(
7437     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7438     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7439   DeclarationName Name = NewFD->getDeclName();
7440   DeclContext *NewDC = NewFD->getDeclContext();
7441   SmallVector<unsigned, 1> MismatchedParams;
7442   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7443   TypoCorrection Correction;
7444   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7445   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7446                                    : diag::err_member_decl_does_not_match;
7447   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7448                     IsLocalFriend ? Sema::LookupLocalFriendName
7449                                   : Sema::LookupOrdinaryName,
7450                     Sema::ForRedeclaration);
7451 
7452   NewFD->setInvalidDecl();
7453   if (IsLocalFriend)
7454     SemaRef.LookupName(Prev, S);
7455   else
7456     SemaRef.LookupQualifiedName(Prev, NewDC);
7457   assert(!Prev.isAmbiguous() &&
7458          "Cannot have an ambiguity in previous-declaration lookup");
7459   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7460   if (!Prev.empty()) {
7461     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7462          Func != FuncEnd; ++Func) {
7463       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7464       if (FD &&
7465           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7466         // Add 1 to the index so that 0 can mean the mismatch didn't
7467         // involve a parameter
7468         unsigned ParamNum =
7469             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7470         NearMatches.push_back(std::make_pair(FD, ParamNum));
7471       }
7472     }
7473   // If the qualified name lookup yielded nothing, try typo correction
7474   } else if ((Correction = SemaRef.CorrectTypo(
7475                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7476                   &ExtraArgs.D.getCXXScopeSpec(),
7477                   llvm::make_unique<DifferentNameValidatorCCC>(
7478                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7479                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7480     // Set up everything for the call to ActOnFunctionDeclarator
7481     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7482                               ExtraArgs.D.getIdentifierLoc());
7483     Previous.clear();
7484     Previous.setLookupName(Correction.getCorrection());
7485     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7486                                     CDeclEnd = Correction.end();
7487          CDecl != CDeclEnd; ++CDecl) {
7488       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7489       if (FD && !FD->hasBody() &&
7490           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7491         Previous.addDecl(FD);
7492       }
7493     }
7494     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7495 
7496     NamedDecl *Result;
7497     // Retry building the function declaration with the new previous
7498     // declarations, and with errors suppressed.
7499     {
7500       // Trap errors.
7501       Sema::SFINAETrap Trap(SemaRef);
7502 
7503       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7504       // pieces need to verify the typo-corrected C++ declaration and hopefully
7505       // eliminate the need for the parameter pack ExtraArgs.
7506       Result = SemaRef.ActOnFunctionDeclarator(
7507           ExtraArgs.S, ExtraArgs.D,
7508           Correction.getCorrectionDecl()->getDeclContext(),
7509           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7510           ExtraArgs.AddToScope);
7511 
7512       if (Trap.hasErrorOccurred())
7513         Result = nullptr;
7514     }
7515 
7516     if (Result) {
7517       // Determine which correction we picked.
7518       Decl *Canonical = Result->getCanonicalDecl();
7519       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7520            I != E; ++I)
7521         if ((*I)->getCanonicalDecl() == Canonical)
7522           Correction.setCorrectionDecl(*I);
7523 
7524       SemaRef.diagnoseTypo(
7525           Correction,
7526           SemaRef.PDiag(IsLocalFriend
7527                           ? diag::err_no_matching_local_friend_suggest
7528                           : diag::err_member_decl_does_not_match_suggest)
7529             << Name << NewDC << IsDefinition);
7530       return Result;
7531     }
7532 
7533     // Pretend the typo correction never occurred
7534     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7535                               ExtraArgs.D.getIdentifierLoc());
7536     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7537     Previous.clear();
7538     Previous.setLookupName(Name);
7539   }
7540 
7541   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7542       << Name << NewDC << IsDefinition << NewFD->getLocation();
7543 
7544   bool NewFDisConst = false;
7545   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7546     NewFDisConst = NewMD->isConst();
7547 
7548   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7549        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7550        NearMatch != NearMatchEnd; ++NearMatch) {
7551     FunctionDecl *FD = NearMatch->first;
7552     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7553     bool FDisConst = MD && MD->isConst();
7554     bool IsMember = MD || !IsLocalFriend;
7555 
7556     // FIXME: These notes are poorly worded for the local friend case.
7557     if (unsigned Idx = NearMatch->second) {
7558       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7559       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7560       if (Loc.isInvalid()) Loc = FD->getLocation();
7561       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7562                                  : diag::note_local_decl_close_param_match)
7563         << Idx << FDParam->getType()
7564         << NewFD->getParamDecl(Idx - 1)->getType();
7565     } else if (FDisConst != NewFDisConst) {
7566       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7567           << NewFDisConst << FD->getSourceRange().getEnd();
7568     } else
7569       SemaRef.Diag(FD->getLocation(),
7570                    IsMember ? diag::note_member_def_close_match
7571                             : diag::note_local_decl_close_match);
7572   }
7573   return nullptr;
7574 }
7575 
7576 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7577   switch (D.getDeclSpec().getStorageClassSpec()) {
7578   default: llvm_unreachable("Unknown storage class!");
7579   case DeclSpec::SCS_auto:
7580   case DeclSpec::SCS_register:
7581   case DeclSpec::SCS_mutable:
7582     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7583                  diag::err_typecheck_sclass_func);
7584     D.getMutableDeclSpec().ClearStorageClassSpecs();
7585     D.setInvalidType();
7586     break;
7587   case DeclSpec::SCS_unspecified: break;
7588   case DeclSpec::SCS_extern:
7589     if (D.getDeclSpec().isExternInLinkageSpec())
7590       return SC_None;
7591     return SC_Extern;
7592   case DeclSpec::SCS_static: {
7593     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7594       // C99 6.7.1p5:
7595       //   The declaration of an identifier for a function that has
7596       //   block scope shall have no explicit storage-class specifier
7597       //   other than extern
7598       // See also (C++ [dcl.stc]p4).
7599       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7600                    diag::err_static_block_func);
7601       break;
7602     } else
7603       return SC_Static;
7604   }
7605   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7606   }
7607 
7608   // No explicit storage class has already been returned
7609   return SC_None;
7610 }
7611 
7612 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7613                                            DeclContext *DC, QualType &R,
7614                                            TypeSourceInfo *TInfo,
7615                                            StorageClass SC,
7616                                            bool &IsVirtualOkay) {
7617   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7618   DeclarationName Name = NameInfo.getName();
7619 
7620   FunctionDecl *NewFD = nullptr;
7621   bool isInline = D.getDeclSpec().isInlineSpecified();
7622 
7623   if (!SemaRef.getLangOpts().CPlusPlus) {
7624     // Determine whether the function was written with a
7625     // prototype. This true when:
7626     //   - there is a prototype in the declarator, or
7627     //   - the type R of the function is some kind of typedef or other non-
7628     //     attributed reference to a type name (which eventually refers to a
7629     //     function type).
7630     bool HasPrototype =
7631       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7632       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7633 
7634     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7635                                  D.getLocStart(), NameInfo, R,
7636                                  TInfo, SC, isInline,
7637                                  HasPrototype, false);
7638     if (D.isInvalidType())
7639       NewFD->setInvalidDecl();
7640 
7641     return NewFD;
7642   }
7643 
7644   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7645   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7646 
7647   // Check that the return type is not an abstract class type.
7648   // For record types, this is done by the AbstractClassUsageDiagnoser once
7649   // the class has been completely parsed.
7650   if (!DC->isRecord() &&
7651       SemaRef.RequireNonAbstractType(
7652           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7653           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7654     D.setInvalidType();
7655 
7656   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7657     // This is a C++ constructor declaration.
7658     assert(DC->isRecord() &&
7659            "Constructors can only be declared in a member context");
7660 
7661     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7662     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7663                                       D.getLocStart(), NameInfo,
7664                                       R, TInfo, isExplicit, isInline,
7665                                       /*isImplicitlyDeclared=*/false,
7666                                       isConstexpr);
7667 
7668   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7669     // This is a C++ destructor declaration.
7670     if (DC->isRecord()) {
7671       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7672       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7673       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7674                                         SemaRef.Context, Record,
7675                                         D.getLocStart(),
7676                                         NameInfo, R, TInfo, isInline,
7677                                         /*isImplicitlyDeclared=*/false);
7678 
7679       // If the class is complete, then we now create the implicit exception
7680       // specification. If the class is incomplete or dependent, we can't do
7681       // it yet.
7682       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7683           Record->getDefinition() && !Record->isBeingDefined() &&
7684           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7685         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7686       }
7687 
7688       IsVirtualOkay = true;
7689       return NewDD;
7690 
7691     } else {
7692       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7693       D.setInvalidType();
7694 
7695       // Create a FunctionDecl to satisfy the function definition parsing
7696       // code path.
7697       return FunctionDecl::Create(SemaRef.Context, DC,
7698                                   D.getLocStart(),
7699                                   D.getIdentifierLoc(), Name, R, TInfo,
7700                                   SC, isInline,
7701                                   /*hasPrototype=*/true, isConstexpr);
7702     }
7703 
7704   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7705     if (!DC->isRecord()) {
7706       SemaRef.Diag(D.getIdentifierLoc(),
7707            diag::err_conv_function_not_member);
7708       return nullptr;
7709     }
7710 
7711     SemaRef.CheckConversionDeclarator(D, R, SC);
7712     IsVirtualOkay = true;
7713     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7714                                      D.getLocStart(), NameInfo,
7715                                      R, TInfo, isInline, isExplicit,
7716                                      isConstexpr, SourceLocation());
7717 
7718   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7719     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7720 
7721     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
7722                                          isExplicit, NameInfo, R, TInfo,
7723                                          D.getLocEnd());
7724   } else if (DC->isRecord()) {
7725     // If the name of the function is the same as the name of the record,
7726     // then this must be an invalid constructor that has a return type.
7727     // (The parser checks for a return type and makes the declarator a
7728     // constructor if it has no return type).
7729     if (Name.getAsIdentifierInfo() &&
7730         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7731       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7732         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7733         << SourceRange(D.getIdentifierLoc());
7734       return nullptr;
7735     }
7736 
7737     // This is a C++ method declaration.
7738     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7739                                                cast<CXXRecordDecl>(DC),
7740                                                D.getLocStart(), NameInfo, R,
7741                                                TInfo, SC, isInline,
7742                                                isConstexpr, SourceLocation());
7743     IsVirtualOkay = !Ret->isStatic();
7744     return Ret;
7745   } else {
7746     bool isFriend =
7747         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7748     if (!isFriend && SemaRef.CurContext->isRecord())
7749       return nullptr;
7750 
7751     // Determine whether the function was written with a
7752     // prototype. This true when:
7753     //   - we're in C++ (where every function has a prototype),
7754     return FunctionDecl::Create(SemaRef.Context, DC,
7755                                 D.getLocStart(),
7756                                 NameInfo, R, TInfo, SC, isInline,
7757                                 true/*HasPrototype*/, isConstexpr);
7758   }
7759 }
7760 
7761 enum OpenCLParamType {
7762   ValidKernelParam,
7763   PtrPtrKernelParam,
7764   PtrKernelParam,
7765   InvalidAddrSpacePtrKernelParam,
7766   InvalidKernelParam,
7767   RecordKernelParam
7768 };
7769 
7770 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
7771   if (PT->isPointerType()) {
7772     QualType PointeeType = PT->getPointeeType();
7773     if (PointeeType->isPointerType())
7774       return PtrPtrKernelParam;
7775     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
7776         PointeeType.getAddressSpace() == 0)
7777       return InvalidAddrSpacePtrKernelParam;
7778     return PtrKernelParam;
7779   }
7780 
7781   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7782   // be used as builtin types.
7783 
7784   if (PT->isImageType())
7785     return PtrKernelParam;
7786 
7787   if (PT->isBooleanType())
7788     return InvalidKernelParam;
7789 
7790   if (PT->isEventT())
7791     return InvalidKernelParam;
7792 
7793   // OpenCL extension spec v1.2 s9.5:
7794   // This extension adds support for half scalar and vector types as built-in
7795   // types that can be used for arithmetic operations, conversions etc.
7796   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
7797     return InvalidKernelParam;
7798 
7799   if (PT->isRecordType())
7800     return RecordKernelParam;
7801 
7802   return ValidKernelParam;
7803 }
7804 
7805 static void checkIsValidOpenCLKernelParameter(
7806   Sema &S,
7807   Declarator &D,
7808   ParmVarDecl *Param,
7809   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7810   QualType PT = Param->getType();
7811 
7812   // Cache the valid types we encounter to avoid rechecking structs that are
7813   // used again
7814   if (ValidTypes.count(PT.getTypePtr()))
7815     return;
7816 
7817   switch (getOpenCLKernelParameterType(S, PT)) {
7818   case PtrPtrKernelParam:
7819     // OpenCL v1.2 s6.9.a:
7820     // A kernel function argument cannot be declared as a
7821     // pointer to a pointer type.
7822     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7823     D.setInvalidType();
7824     return;
7825 
7826   case InvalidAddrSpacePtrKernelParam:
7827     // OpenCL v1.0 s6.5:
7828     // __kernel function arguments declared to be a pointer of a type can point
7829     // to one of the following address spaces only : __global, __local or
7830     // __constant.
7831     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
7832     D.setInvalidType();
7833     return;
7834 
7835     // OpenCL v1.2 s6.9.k:
7836     // Arguments to kernel functions in a program cannot be declared with the
7837     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7838     // uintptr_t or a struct and/or union that contain fields declared to be
7839     // one of these built-in scalar types.
7840 
7841   case InvalidKernelParam:
7842     // OpenCL v1.2 s6.8 n:
7843     // A kernel function argument cannot be declared
7844     // of event_t type.
7845     // Do not diagnose half type since it is diagnosed as invalid argument
7846     // type for any function elsewhere.
7847     if (!PT->isHalfType())
7848       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7849     D.setInvalidType();
7850     return;
7851 
7852   case PtrKernelParam:
7853   case ValidKernelParam:
7854     ValidTypes.insert(PT.getTypePtr());
7855     return;
7856 
7857   case RecordKernelParam:
7858     break;
7859   }
7860 
7861   // Track nested structs we will inspect
7862   SmallVector<const Decl *, 4> VisitStack;
7863 
7864   // Track where we are in the nested structs. Items will migrate from
7865   // VisitStack to HistoryStack as we do the DFS for bad field.
7866   SmallVector<const FieldDecl *, 4> HistoryStack;
7867   HistoryStack.push_back(nullptr);
7868 
7869   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7870   VisitStack.push_back(PD);
7871 
7872   assert(VisitStack.back() && "First decl null?");
7873 
7874   do {
7875     const Decl *Next = VisitStack.pop_back_val();
7876     if (!Next) {
7877       assert(!HistoryStack.empty());
7878       // Found a marker, we have gone up a level
7879       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7880         ValidTypes.insert(Hist->getType().getTypePtr());
7881 
7882       continue;
7883     }
7884 
7885     // Adds everything except the original parameter declaration (which is not a
7886     // field itself) to the history stack.
7887     const RecordDecl *RD;
7888     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7889       HistoryStack.push_back(Field);
7890       RD = Field->getType()->castAs<RecordType>()->getDecl();
7891     } else {
7892       RD = cast<RecordDecl>(Next);
7893     }
7894 
7895     // Add a null marker so we know when we've gone back up a level
7896     VisitStack.push_back(nullptr);
7897 
7898     for (const auto *FD : RD->fields()) {
7899       QualType QT = FD->getType();
7900 
7901       if (ValidTypes.count(QT.getTypePtr()))
7902         continue;
7903 
7904       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
7905       if (ParamType == ValidKernelParam)
7906         continue;
7907 
7908       if (ParamType == RecordKernelParam) {
7909         VisitStack.push_back(FD);
7910         continue;
7911       }
7912 
7913       // OpenCL v1.2 s6.9.p:
7914       // Arguments to kernel functions that are declared to be a struct or union
7915       // do not allow OpenCL objects to be passed as elements of the struct or
7916       // union.
7917       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7918           ParamType == InvalidAddrSpacePtrKernelParam) {
7919         S.Diag(Param->getLocation(),
7920                diag::err_record_with_pointers_kernel_param)
7921           << PT->isUnionType()
7922           << PT;
7923       } else {
7924         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7925       }
7926 
7927       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7928         << PD->getDeclName();
7929 
7930       // We have an error, now let's go back up through history and show where
7931       // the offending field came from
7932       for (ArrayRef<const FieldDecl *>::const_iterator
7933                I = HistoryStack.begin() + 1,
7934                E = HistoryStack.end();
7935            I != E; ++I) {
7936         const FieldDecl *OuterField = *I;
7937         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7938           << OuterField->getType();
7939       }
7940 
7941       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7942         << QT->isPointerType()
7943         << QT;
7944       D.setInvalidType();
7945       return;
7946     }
7947   } while (!VisitStack.empty());
7948 }
7949 
7950 /// Find the DeclContext in which a tag is implicitly declared if we see an
7951 /// elaborated type specifier in the specified context, and lookup finds
7952 /// nothing.
7953 static DeclContext *getTagInjectionContext(DeclContext *DC) {
7954   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
7955     DC = DC->getParent();
7956   return DC;
7957 }
7958 
7959 /// Find the Scope in which a tag is implicitly declared if we see an
7960 /// elaborated type specifier in the specified context, and lookup finds
7961 /// nothing.
7962 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
7963   while (S->isClassScope() ||
7964          (LangOpts.CPlusPlus &&
7965           S->isFunctionPrototypeScope()) ||
7966          ((S->getFlags() & Scope::DeclScope) == 0) ||
7967          (S->getEntity() && S->getEntity()->isTransparentContext()))
7968     S = S->getParent();
7969   return S;
7970 }
7971 
7972 NamedDecl*
7973 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7974                               TypeSourceInfo *TInfo, LookupResult &Previous,
7975                               MultiTemplateParamsArg TemplateParamLists,
7976                               bool &AddToScope) {
7977   QualType R = TInfo->getType();
7978 
7979   assert(R.getTypePtr()->isFunctionType());
7980 
7981   // TODO: consider using NameInfo for diagnostic.
7982   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7983   DeclarationName Name = NameInfo.getName();
7984   StorageClass SC = getFunctionStorageClass(*this, D);
7985 
7986   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7987     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7988          diag::err_invalid_thread)
7989       << DeclSpec::getSpecifierName(TSCS);
7990 
7991   if (D.isFirstDeclarationOfMember())
7992     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7993                            D.getIdentifierLoc());
7994 
7995   bool isFriend = false;
7996   FunctionTemplateDecl *FunctionTemplate = nullptr;
7997   bool isMemberSpecialization = false;
7998   bool isFunctionTemplateSpecialization = false;
7999 
8000   bool isDependentClassScopeExplicitSpecialization = false;
8001   bool HasExplicitTemplateArgs = false;
8002   TemplateArgumentListInfo TemplateArgs;
8003 
8004   bool isVirtualOkay = false;
8005 
8006   DeclContext *OriginalDC = DC;
8007   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8008 
8009   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8010                                               isVirtualOkay);
8011   if (!NewFD) return nullptr;
8012 
8013   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8014     NewFD->setTopLevelDeclInObjCContainer();
8015 
8016   // Set the lexical context. If this is a function-scope declaration, or has a
8017   // C++ scope specifier, or is the object of a friend declaration, the lexical
8018   // context will be different from the semantic context.
8019   NewFD->setLexicalDeclContext(CurContext);
8020 
8021   if (IsLocalExternDecl)
8022     NewFD->setLocalExternDecl();
8023 
8024   if (getLangOpts().CPlusPlus) {
8025     bool isInline = D.getDeclSpec().isInlineSpecified();
8026     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8027     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8028     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8029     bool isConcept = D.getDeclSpec().isConceptSpecified();
8030     isFriend = D.getDeclSpec().isFriendSpecified();
8031     if (isFriend && !isInline && D.isFunctionDefinition()) {
8032       // C++ [class.friend]p5
8033       //   A function can be defined in a friend declaration of a
8034       //   class . . . . Such a function is implicitly inline.
8035       NewFD->setImplicitlyInline();
8036     }
8037 
8038     // If this is a method defined in an __interface, and is not a constructor
8039     // or an overloaded operator, then set the pure flag (isVirtual will already
8040     // return true).
8041     if (const CXXRecordDecl *Parent =
8042           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8043       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8044         NewFD->setPure(true);
8045 
8046       // C++ [class.union]p2
8047       //   A union can have member functions, but not virtual functions.
8048       if (isVirtual && Parent->isUnion())
8049         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8050     }
8051 
8052     SetNestedNameSpecifier(NewFD, D);
8053     isMemberSpecialization = false;
8054     isFunctionTemplateSpecialization = false;
8055     if (D.isInvalidType())
8056       NewFD->setInvalidDecl();
8057 
8058     // Match up the template parameter lists with the scope specifier, then
8059     // determine whether we have a template or a template specialization.
8060     bool Invalid = false;
8061     if (TemplateParameterList *TemplateParams =
8062             MatchTemplateParametersToScopeSpecifier(
8063                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
8064                 D.getCXXScopeSpec(),
8065                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
8066                     ? D.getName().TemplateId
8067                     : nullptr,
8068                 TemplateParamLists, isFriend, isMemberSpecialization,
8069                 Invalid)) {
8070       if (TemplateParams->size() > 0) {
8071         // This is a function template
8072 
8073         // Check that we can declare a template here.
8074         if (CheckTemplateDeclScope(S, TemplateParams))
8075           NewFD->setInvalidDecl();
8076 
8077         // A destructor cannot be a template.
8078         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8079           Diag(NewFD->getLocation(), diag::err_destructor_template);
8080           NewFD->setInvalidDecl();
8081         }
8082 
8083         // If we're adding a template to a dependent context, we may need to
8084         // rebuilding some of the types used within the template parameter list,
8085         // now that we know what the current instantiation is.
8086         if (DC->isDependentContext()) {
8087           ContextRAII SavedContext(*this, DC);
8088           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8089             Invalid = true;
8090         }
8091 
8092         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8093                                                         NewFD->getLocation(),
8094                                                         Name, TemplateParams,
8095                                                         NewFD);
8096         FunctionTemplate->setLexicalDeclContext(CurContext);
8097         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8098 
8099         // For source fidelity, store the other template param lists.
8100         if (TemplateParamLists.size() > 1) {
8101           NewFD->setTemplateParameterListsInfo(Context,
8102                                                TemplateParamLists.drop_back(1));
8103         }
8104       } else {
8105         // This is a function template specialization.
8106         isFunctionTemplateSpecialization = true;
8107         // For source fidelity, store all the template param lists.
8108         if (TemplateParamLists.size() > 0)
8109           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8110 
8111         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8112         if (isFriend) {
8113           // We want to remove the "template<>", found here.
8114           SourceRange RemoveRange = TemplateParams->getSourceRange();
8115 
8116           // If we remove the template<> and the name is not a
8117           // template-id, we're actually silently creating a problem:
8118           // the friend declaration will refer to an untemplated decl,
8119           // and clearly the user wants a template specialization.  So
8120           // we need to insert '<>' after the name.
8121           SourceLocation InsertLoc;
8122           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8123             InsertLoc = D.getName().getSourceRange().getEnd();
8124             InsertLoc = getLocForEndOfToken(InsertLoc);
8125           }
8126 
8127           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8128             << Name << RemoveRange
8129             << FixItHint::CreateRemoval(RemoveRange)
8130             << FixItHint::CreateInsertion(InsertLoc, "<>");
8131         }
8132       }
8133     }
8134     else {
8135       // All template param lists were matched against the scope specifier:
8136       // this is NOT (an explicit specialization of) a template.
8137       if (TemplateParamLists.size() > 0)
8138         // For source fidelity, store all the template param lists.
8139         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8140     }
8141 
8142     if (Invalid) {
8143       NewFD->setInvalidDecl();
8144       if (FunctionTemplate)
8145         FunctionTemplate->setInvalidDecl();
8146     }
8147 
8148     // C++ [dcl.fct.spec]p5:
8149     //   The virtual specifier shall only be used in declarations of
8150     //   nonstatic class member functions that appear within a
8151     //   member-specification of a class declaration; see 10.3.
8152     //
8153     if (isVirtual && !NewFD->isInvalidDecl()) {
8154       if (!isVirtualOkay) {
8155         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8156              diag::err_virtual_non_function);
8157       } else if (!CurContext->isRecord()) {
8158         // 'virtual' was specified outside of the class.
8159         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8160              diag::err_virtual_out_of_class)
8161           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8162       } else if (NewFD->getDescribedFunctionTemplate()) {
8163         // C++ [temp.mem]p3:
8164         //  A member function template shall not be virtual.
8165         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8166              diag::err_virtual_member_function_template)
8167           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8168       } else {
8169         // Okay: Add virtual to the method.
8170         NewFD->setVirtualAsWritten(true);
8171       }
8172 
8173       if (getLangOpts().CPlusPlus14 &&
8174           NewFD->getReturnType()->isUndeducedType())
8175         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8176     }
8177 
8178     if (getLangOpts().CPlusPlus14 &&
8179         (NewFD->isDependentContext() ||
8180          (isFriend && CurContext->isDependentContext())) &&
8181         NewFD->getReturnType()->isUndeducedType()) {
8182       // If the function template is referenced directly (for instance, as a
8183       // member of the current instantiation), pretend it has a dependent type.
8184       // This is not really justified by the standard, but is the only sane
8185       // thing to do.
8186       // FIXME: For a friend function, we have not marked the function as being
8187       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8188       const FunctionProtoType *FPT =
8189           NewFD->getType()->castAs<FunctionProtoType>();
8190       QualType Result =
8191           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8192       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8193                                              FPT->getExtProtoInfo()));
8194     }
8195 
8196     // C++ [dcl.fct.spec]p3:
8197     //  The inline specifier shall not appear on a block scope function
8198     //  declaration.
8199     if (isInline && !NewFD->isInvalidDecl()) {
8200       if (CurContext->isFunctionOrMethod()) {
8201         // 'inline' is not allowed on block scope function declaration.
8202         Diag(D.getDeclSpec().getInlineSpecLoc(),
8203              diag::err_inline_declaration_block_scope) << Name
8204           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8205       }
8206     }
8207 
8208     // C++ [dcl.fct.spec]p6:
8209     //  The explicit specifier shall be used only in the declaration of a
8210     //  constructor or conversion function within its class definition;
8211     //  see 12.3.1 and 12.3.2.
8212     if (isExplicit && !NewFD->isInvalidDecl() &&
8213         !isa<CXXDeductionGuideDecl>(NewFD)) {
8214       if (!CurContext->isRecord()) {
8215         // 'explicit' was specified outside of the class.
8216         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8217              diag::err_explicit_out_of_class)
8218           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8219       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8220                  !isa<CXXConversionDecl>(NewFD)) {
8221         // 'explicit' was specified on a function that wasn't a constructor
8222         // or conversion function.
8223         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8224              diag::err_explicit_non_ctor_or_conv_function)
8225           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8226       }
8227     }
8228 
8229     if (isConstexpr) {
8230       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8231       // are implicitly inline.
8232       NewFD->setImplicitlyInline();
8233 
8234       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8235       // be either constructors or to return a literal type. Therefore,
8236       // destructors cannot be declared constexpr.
8237       if (isa<CXXDestructorDecl>(NewFD))
8238         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8239     }
8240 
8241     if (isConcept) {
8242       // This is a function concept.
8243       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
8244         FTD->setConcept();
8245 
8246       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8247       // applied only to the definition of a function template [...]
8248       if (!D.isFunctionDefinition()) {
8249         Diag(D.getDeclSpec().getConceptSpecLoc(),
8250              diag::err_function_concept_not_defined);
8251         NewFD->setInvalidDecl();
8252       }
8253 
8254       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
8255       // have no exception-specification and is treated as if it were specified
8256       // with noexcept(true) (15.4). [...]
8257       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
8258         if (FPT->hasExceptionSpec()) {
8259           SourceRange Range;
8260           if (D.isFunctionDeclarator())
8261             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
8262           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
8263               << FixItHint::CreateRemoval(Range);
8264           NewFD->setInvalidDecl();
8265         } else {
8266           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
8267         }
8268 
8269         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8270         // following restrictions:
8271         // - The declared return type shall have the type bool.
8272         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
8273           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
8274           NewFD->setInvalidDecl();
8275         }
8276 
8277         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8278         // following restrictions:
8279         // - The declaration's parameter list shall be equivalent to an empty
8280         //   parameter list.
8281         if (FPT->getNumParams() > 0 || FPT->isVariadic())
8282           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
8283       }
8284 
8285       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
8286       // implicity defined to be a constexpr declaration (implicitly inline)
8287       NewFD->setImplicitlyInline();
8288 
8289       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
8290       // be declared with the thread_local, inline, friend, or constexpr
8291       // specifiers, [...]
8292       if (isInline) {
8293         Diag(D.getDeclSpec().getInlineSpecLoc(),
8294              diag::err_concept_decl_invalid_specifiers)
8295             << 1 << 1;
8296         NewFD->setInvalidDecl(true);
8297       }
8298 
8299       if (isFriend) {
8300         Diag(D.getDeclSpec().getFriendSpecLoc(),
8301              diag::err_concept_decl_invalid_specifiers)
8302             << 1 << 2;
8303         NewFD->setInvalidDecl(true);
8304       }
8305 
8306       if (isConstexpr) {
8307         Diag(D.getDeclSpec().getConstexprSpecLoc(),
8308              diag::err_concept_decl_invalid_specifiers)
8309             << 1 << 3;
8310         NewFD->setInvalidDecl(true);
8311       }
8312 
8313       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8314       // applied only to the definition of a function template or variable
8315       // template, declared in namespace scope.
8316       if (isFunctionTemplateSpecialization) {
8317         Diag(D.getDeclSpec().getConceptSpecLoc(),
8318              diag::err_concept_specified_specialization) << 1;
8319         NewFD->setInvalidDecl(true);
8320         return NewFD;
8321       }
8322     }
8323 
8324     // If __module_private__ was specified, mark the function accordingly.
8325     if (D.getDeclSpec().isModulePrivateSpecified()) {
8326       if (isFunctionTemplateSpecialization) {
8327         SourceLocation ModulePrivateLoc
8328           = D.getDeclSpec().getModulePrivateSpecLoc();
8329         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8330           << 0
8331           << FixItHint::CreateRemoval(ModulePrivateLoc);
8332       } else {
8333         NewFD->setModulePrivate();
8334         if (FunctionTemplate)
8335           FunctionTemplate->setModulePrivate();
8336       }
8337     }
8338 
8339     if (isFriend) {
8340       if (FunctionTemplate) {
8341         FunctionTemplate->setObjectOfFriendDecl();
8342         FunctionTemplate->setAccess(AS_public);
8343       }
8344       NewFD->setObjectOfFriendDecl();
8345       NewFD->setAccess(AS_public);
8346     }
8347 
8348     // If a function is defined as defaulted or deleted, mark it as such now.
8349     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8350     // definition kind to FDK_Definition.
8351     switch (D.getFunctionDefinitionKind()) {
8352       case FDK_Declaration:
8353       case FDK_Definition:
8354         break;
8355 
8356       case FDK_Defaulted:
8357         NewFD->setDefaulted();
8358         break;
8359 
8360       case FDK_Deleted:
8361         NewFD->setDeletedAsWritten();
8362         break;
8363     }
8364 
8365     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8366         D.isFunctionDefinition()) {
8367       // C++ [class.mfct]p2:
8368       //   A member function may be defined (8.4) in its class definition, in
8369       //   which case it is an inline member function (7.1.2)
8370       NewFD->setImplicitlyInline();
8371     }
8372 
8373     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8374         !CurContext->isRecord()) {
8375       // C++ [class.static]p1:
8376       //   A data or function member of a class may be declared static
8377       //   in a class definition, in which case it is a static member of
8378       //   the class.
8379 
8380       // Complain about the 'static' specifier if it's on an out-of-line
8381       // member function definition.
8382       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8383            diag::err_static_out_of_line)
8384         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8385     }
8386 
8387     // C++11 [except.spec]p15:
8388     //   A deallocation function with no exception-specification is treated
8389     //   as if it were specified with noexcept(true).
8390     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8391     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8392          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8393         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8394       NewFD->setType(Context.getFunctionType(
8395           FPT->getReturnType(), FPT->getParamTypes(),
8396           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8397   }
8398 
8399   // Filter out previous declarations that don't match the scope.
8400   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8401                        D.getCXXScopeSpec().isNotEmpty() ||
8402                        isMemberSpecialization ||
8403                        isFunctionTemplateSpecialization);
8404 
8405   // Handle GNU asm-label extension (encoded as an attribute).
8406   if (Expr *E = (Expr*) D.getAsmLabel()) {
8407     // The parser guarantees this is a string.
8408     StringLiteral *SE = cast<StringLiteral>(E);
8409     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8410                                                 SE->getString(), 0));
8411   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8412     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8413       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8414     if (I != ExtnameUndeclaredIdentifiers.end()) {
8415       if (isDeclExternC(NewFD)) {
8416         NewFD->addAttr(I->second);
8417         ExtnameUndeclaredIdentifiers.erase(I);
8418       } else
8419         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8420             << /*Variable*/0 << NewFD;
8421     }
8422   }
8423 
8424   // Copy the parameter declarations from the declarator D to the function
8425   // declaration NewFD, if they are available.  First scavenge them into Params.
8426   SmallVector<ParmVarDecl*, 16> Params;
8427   unsigned FTIIdx;
8428   if (D.isFunctionDeclarator(FTIIdx)) {
8429     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8430 
8431     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8432     // function that takes no arguments, not a function that takes a
8433     // single void argument.
8434     // We let through "const void" here because Sema::GetTypeForDeclarator
8435     // already checks for that case.
8436     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8437       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8438         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8439         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8440         Param->setDeclContext(NewFD);
8441         Params.push_back(Param);
8442 
8443         if (Param->isInvalidDecl())
8444           NewFD->setInvalidDecl();
8445       }
8446     }
8447 
8448     if (!getLangOpts().CPlusPlus) {
8449       // In C, find all the tag declarations from the prototype and move them
8450       // into the function DeclContext. Remove them from the surrounding tag
8451       // injection context of the function, which is typically but not always
8452       // the TU.
8453       DeclContext *PrototypeTagContext =
8454           getTagInjectionContext(NewFD->getLexicalDeclContext());
8455       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8456         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8457 
8458         // We don't want to reparent enumerators. Look at their parent enum
8459         // instead.
8460         if (!TD) {
8461           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8462             TD = cast<EnumDecl>(ECD->getDeclContext());
8463         }
8464         if (!TD)
8465           continue;
8466         DeclContext *TagDC = TD->getLexicalDeclContext();
8467         if (!TagDC->containsDecl(TD))
8468           continue;
8469         TagDC->removeDecl(TD);
8470         TD->setDeclContext(NewFD);
8471         NewFD->addDecl(TD);
8472 
8473         // Preserve the lexical DeclContext if it is not the surrounding tag
8474         // injection context of the FD. In this example, the semantic context of
8475         // E will be f and the lexical context will be S, while both the
8476         // semantic and lexical contexts of S will be f:
8477         //   void f(struct S { enum E { a } f; } s);
8478         if (TagDC != PrototypeTagContext)
8479           TD->setLexicalDeclContext(TagDC);
8480       }
8481     }
8482   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8483     // When we're declaring a function with a typedef, typeof, etc as in the
8484     // following example, we'll need to synthesize (unnamed)
8485     // parameters for use in the declaration.
8486     //
8487     // @code
8488     // typedef void fn(int);
8489     // fn f;
8490     // @endcode
8491 
8492     // Synthesize a parameter for each argument type.
8493     for (const auto &AI : FT->param_types()) {
8494       ParmVarDecl *Param =
8495           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8496       Param->setScopeInfo(0, Params.size());
8497       Params.push_back(Param);
8498     }
8499   } else {
8500     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8501            "Should not need args for typedef of non-prototype fn");
8502   }
8503 
8504   // Finally, we know we have the right number of parameters, install them.
8505   NewFD->setParams(Params);
8506 
8507   if (D.getDeclSpec().isNoreturnSpecified())
8508     NewFD->addAttr(
8509         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8510                                        Context, 0));
8511 
8512   // Functions returning a variably modified type violate C99 6.7.5.2p2
8513   // because all functions have linkage.
8514   if (!NewFD->isInvalidDecl() &&
8515       NewFD->getReturnType()->isVariablyModifiedType()) {
8516     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8517     NewFD->setInvalidDecl();
8518   }
8519 
8520   // Apply an implicit SectionAttr if #pragma code_seg is active.
8521   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8522       !NewFD->hasAttr<SectionAttr>()) {
8523     NewFD->addAttr(
8524         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8525                                     CodeSegStack.CurrentValue->getString(),
8526                                     CodeSegStack.CurrentPragmaLocation));
8527     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8528                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8529                          ASTContext::PSF_Read,
8530                      NewFD))
8531       NewFD->dropAttr<SectionAttr>();
8532   }
8533 
8534   // Handle attributes.
8535   ProcessDeclAttributes(S, NewFD, D);
8536 
8537   if (getLangOpts().OpenCL) {
8538     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8539     // type declaration will generate a compilation error.
8540     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8541     if (AddressSpace == LangAS::opencl_local ||
8542         AddressSpace == LangAS::opencl_global ||
8543         AddressSpace == LangAS::opencl_constant) {
8544       Diag(NewFD->getLocation(),
8545            diag::err_opencl_return_value_with_address_space);
8546       NewFD->setInvalidDecl();
8547     }
8548   }
8549 
8550   if (!getLangOpts().CPlusPlus) {
8551     // Perform semantic checking on the function declaration.
8552     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8553       CheckMain(NewFD, D.getDeclSpec());
8554 
8555     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8556       CheckMSVCRTEntryPoint(NewFD);
8557 
8558     if (!NewFD->isInvalidDecl())
8559       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8560                                                   isMemberSpecialization));
8561     else if (!Previous.empty())
8562       // Recover gracefully from an invalid redeclaration.
8563       D.setRedeclaration(true);
8564     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8565             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8566            "previous declaration set still overloaded");
8567 
8568     // Diagnose no-prototype function declarations with calling conventions that
8569     // don't support variadic calls. Only do this in C and do it after merging
8570     // possibly prototyped redeclarations.
8571     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8572     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8573       CallingConv CC = FT->getExtInfo().getCC();
8574       if (!supportsVariadicCall(CC)) {
8575         // Windows system headers sometimes accidentally use stdcall without
8576         // (void) parameters, so we relax this to a warning.
8577         int DiagID =
8578             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8579         Diag(NewFD->getLocation(), DiagID)
8580             << FunctionType::getNameForCallConv(CC);
8581       }
8582     }
8583   } else {
8584     // C++11 [replacement.functions]p3:
8585     //  The program's definitions shall not be specified as inline.
8586     //
8587     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8588     //
8589     // Suppress the diagnostic if the function is __attribute__((used)), since
8590     // that forces an external definition to be emitted.
8591     if (D.getDeclSpec().isInlineSpecified() &&
8592         NewFD->isReplaceableGlobalAllocationFunction() &&
8593         !NewFD->hasAttr<UsedAttr>())
8594       Diag(D.getDeclSpec().getInlineSpecLoc(),
8595            diag::ext_operator_new_delete_declared_inline)
8596         << NewFD->getDeclName();
8597 
8598     // If the declarator is a template-id, translate the parser's template
8599     // argument list into our AST format.
8600     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8601       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8602       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8603       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8604       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8605                                          TemplateId->NumArgs);
8606       translateTemplateArguments(TemplateArgsPtr,
8607                                  TemplateArgs);
8608 
8609       HasExplicitTemplateArgs = true;
8610 
8611       if (NewFD->isInvalidDecl()) {
8612         HasExplicitTemplateArgs = false;
8613       } else if (FunctionTemplate) {
8614         // Function template with explicit template arguments.
8615         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8616           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8617 
8618         HasExplicitTemplateArgs = false;
8619       } else {
8620         assert((isFunctionTemplateSpecialization ||
8621                 D.getDeclSpec().isFriendSpecified()) &&
8622                "should have a 'template<>' for this decl");
8623         // "friend void foo<>(int);" is an implicit specialization decl.
8624         isFunctionTemplateSpecialization = true;
8625       }
8626     } else if (isFriend && isFunctionTemplateSpecialization) {
8627       // This combination is only possible in a recovery case;  the user
8628       // wrote something like:
8629       //   template <> friend void foo(int);
8630       // which we're recovering from as if the user had written:
8631       //   friend void foo<>(int);
8632       // Go ahead and fake up a template id.
8633       HasExplicitTemplateArgs = true;
8634       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8635       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8636     }
8637 
8638     // We do not add HD attributes to specializations here because
8639     // they may have different constexpr-ness compared to their
8640     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8641     // may end up with different effective targets. Instead, a
8642     // specialization inherits its target attributes from its template
8643     // in the CheckFunctionTemplateSpecialization() call below.
8644     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8645       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8646 
8647     // If it's a friend (and only if it's a friend), it's possible
8648     // that either the specialized function type or the specialized
8649     // template is dependent, and therefore matching will fail.  In
8650     // this case, don't check the specialization yet.
8651     bool InstantiationDependent = false;
8652     if (isFunctionTemplateSpecialization && isFriend &&
8653         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8654          TemplateSpecializationType::anyDependentTemplateArguments(
8655             TemplateArgs,
8656             InstantiationDependent))) {
8657       assert(HasExplicitTemplateArgs &&
8658              "friend function specialization without template args");
8659       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8660                                                        Previous))
8661         NewFD->setInvalidDecl();
8662     } else if (isFunctionTemplateSpecialization) {
8663       if (CurContext->isDependentContext() && CurContext->isRecord()
8664           && !isFriend) {
8665         isDependentClassScopeExplicitSpecialization = true;
8666         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8667           diag::ext_function_specialization_in_class :
8668           diag::err_function_specialization_in_class)
8669           << NewFD->getDeclName();
8670       } else if (CheckFunctionTemplateSpecialization(NewFD,
8671                                   (HasExplicitTemplateArgs ? &TemplateArgs
8672                                                            : nullptr),
8673                                                      Previous))
8674         NewFD->setInvalidDecl();
8675 
8676       // C++ [dcl.stc]p1:
8677       //   A storage-class-specifier shall not be specified in an explicit
8678       //   specialization (14.7.3)
8679       FunctionTemplateSpecializationInfo *Info =
8680           NewFD->getTemplateSpecializationInfo();
8681       if (Info && SC != SC_None) {
8682         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8683           Diag(NewFD->getLocation(),
8684                diag::err_explicit_specialization_inconsistent_storage_class)
8685             << SC
8686             << FixItHint::CreateRemoval(
8687                                       D.getDeclSpec().getStorageClassSpecLoc());
8688 
8689         else
8690           Diag(NewFD->getLocation(),
8691                diag::ext_explicit_specialization_storage_class)
8692             << FixItHint::CreateRemoval(
8693                                       D.getDeclSpec().getStorageClassSpecLoc());
8694       }
8695     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8696       if (CheckMemberSpecialization(NewFD, Previous))
8697           NewFD->setInvalidDecl();
8698     }
8699 
8700     // Perform semantic checking on the function declaration.
8701     if (!isDependentClassScopeExplicitSpecialization) {
8702       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8703         CheckMain(NewFD, D.getDeclSpec());
8704 
8705       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8706         CheckMSVCRTEntryPoint(NewFD);
8707 
8708       if (!NewFD->isInvalidDecl())
8709         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8710                                                     isMemberSpecialization));
8711       else if (!Previous.empty())
8712         // Recover gracefully from an invalid redeclaration.
8713         D.setRedeclaration(true);
8714     }
8715 
8716     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8717             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8718            "previous declaration set still overloaded");
8719 
8720     NamedDecl *PrincipalDecl = (FunctionTemplate
8721                                 ? cast<NamedDecl>(FunctionTemplate)
8722                                 : NewFD);
8723 
8724     if (isFriend && NewFD->getPreviousDecl()) {
8725       AccessSpecifier Access = AS_public;
8726       if (!NewFD->isInvalidDecl())
8727         Access = NewFD->getPreviousDecl()->getAccess();
8728 
8729       NewFD->setAccess(Access);
8730       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8731     }
8732 
8733     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8734         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8735       PrincipalDecl->setNonMemberOperator();
8736 
8737     // If we have a function template, check the template parameter
8738     // list. This will check and merge default template arguments.
8739     if (FunctionTemplate) {
8740       FunctionTemplateDecl *PrevTemplate =
8741                                      FunctionTemplate->getPreviousDecl();
8742       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8743                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8744                                     : nullptr,
8745                             D.getDeclSpec().isFriendSpecified()
8746                               ? (D.isFunctionDefinition()
8747                                    ? TPC_FriendFunctionTemplateDefinition
8748                                    : TPC_FriendFunctionTemplate)
8749                               : (D.getCXXScopeSpec().isSet() &&
8750                                  DC && DC->isRecord() &&
8751                                  DC->isDependentContext())
8752                                   ? TPC_ClassTemplateMember
8753                                   : TPC_FunctionTemplate);
8754     }
8755 
8756     if (NewFD->isInvalidDecl()) {
8757       // Ignore all the rest of this.
8758     } else if (!D.isRedeclaration()) {
8759       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8760                                        AddToScope };
8761       // Fake up an access specifier if it's supposed to be a class member.
8762       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8763         NewFD->setAccess(AS_public);
8764 
8765       // Qualified decls generally require a previous declaration.
8766       if (D.getCXXScopeSpec().isSet()) {
8767         // ...with the major exception of templated-scope or
8768         // dependent-scope friend declarations.
8769 
8770         // TODO: we currently also suppress this check in dependent
8771         // contexts because (1) the parameter depth will be off when
8772         // matching friend templates and (2) we might actually be
8773         // selecting a friend based on a dependent factor.  But there
8774         // are situations where these conditions don't apply and we
8775         // can actually do this check immediately.
8776         if (isFriend &&
8777             (TemplateParamLists.size() ||
8778              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8779              CurContext->isDependentContext())) {
8780           // ignore these
8781         } else {
8782           // The user tried to provide an out-of-line definition for a
8783           // function that is a member of a class or namespace, but there
8784           // was no such member function declared (C++ [class.mfct]p2,
8785           // C++ [namespace.memdef]p2). For example:
8786           //
8787           // class X {
8788           //   void f() const;
8789           // };
8790           //
8791           // void X::f() { } // ill-formed
8792           //
8793           // Complain about this problem, and attempt to suggest close
8794           // matches (e.g., those that differ only in cv-qualifiers and
8795           // whether the parameter types are references).
8796 
8797           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8798                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8799             AddToScope = ExtraArgs.AddToScope;
8800             return Result;
8801           }
8802         }
8803 
8804         // Unqualified local friend declarations are required to resolve
8805         // to something.
8806       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8807         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8808                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8809           AddToScope = ExtraArgs.AddToScope;
8810           return Result;
8811         }
8812       }
8813     } else if (!D.isFunctionDefinition() &&
8814                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8815                !isFriend && !isFunctionTemplateSpecialization &&
8816                !isMemberSpecialization) {
8817       // An out-of-line member function declaration must also be a
8818       // definition (C++ [class.mfct]p2).
8819       // Note that this is not the case for explicit specializations of
8820       // function templates or member functions of class templates, per
8821       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8822       // extension for compatibility with old SWIG code which likes to
8823       // generate them.
8824       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8825         << D.getCXXScopeSpec().getRange();
8826     }
8827   }
8828 
8829   ProcessPragmaWeak(S, NewFD);
8830   checkAttributesAfterMerging(*this, *NewFD);
8831 
8832   AddKnownFunctionAttributes(NewFD);
8833 
8834   if (NewFD->hasAttr<OverloadableAttr>() &&
8835       !NewFD->getType()->getAs<FunctionProtoType>()) {
8836     Diag(NewFD->getLocation(),
8837          diag::err_attribute_overloadable_no_prototype)
8838       << NewFD;
8839 
8840     // Turn this into a variadic function with no parameters.
8841     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8842     FunctionProtoType::ExtProtoInfo EPI(
8843         Context.getDefaultCallingConvention(true, false));
8844     EPI.Variadic = true;
8845     EPI.ExtInfo = FT->getExtInfo();
8846 
8847     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8848     NewFD->setType(R);
8849   }
8850 
8851   // If there's a #pragma GCC visibility in scope, and this isn't a class
8852   // member, set the visibility of this function.
8853   if (!DC->isRecord() && NewFD->isExternallyVisible())
8854     AddPushedVisibilityAttribute(NewFD);
8855 
8856   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8857   // marking the function.
8858   AddCFAuditedAttribute(NewFD);
8859 
8860   // If this is a function definition, check if we have to apply optnone due to
8861   // a pragma.
8862   if(D.isFunctionDefinition())
8863     AddRangeBasedOptnone(NewFD);
8864 
8865   // If this is the first declaration of an extern C variable, update
8866   // the map of such variables.
8867   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8868       isIncompleteDeclExternC(*this, NewFD))
8869     RegisterLocallyScopedExternCDecl(NewFD, S);
8870 
8871   // Set this FunctionDecl's range up to the right paren.
8872   NewFD->setRangeEnd(D.getSourceRange().getEnd());
8873 
8874   if (D.isRedeclaration() && !Previous.empty()) {
8875     checkDLLAttributeRedeclaration(
8876         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8877         isMemberSpecialization || isFunctionTemplateSpecialization,
8878         D.isFunctionDefinition());
8879   }
8880 
8881   if (getLangOpts().CUDA) {
8882     IdentifierInfo *II = NewFD->getIdentifier();
8883     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
8884         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8885       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8886         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8887 
8888       Context.setcudaConfigureCallDecl(NewFD);
8889     }
8890 
8891     // Variadic functions, other than a *declaration* of printf, are not allowed
8892     // in device-side CUDA code, unless someone passed
8893     // -fcuda-allow-variadic-functions.
8894     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
8895         (NewFD->hasAttr<CUDADeviceAttr>() ||
8896          NewFD->hasAttr<CUDAGlobalAttr>()) &&
8897         !(II && II->isStr("printf") && NewFD->isExternC() &&
8898           !D.isFunctionDefinition())) {
8899       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
8900     }
8901   }
8902 
8903   if (getLangOpts().CPlusPlus) {
8904     if (FunctionTemplate) {
8905       if (NewFD->isInvalidDecl())
8906         FunctionTemplate->setInvalidDecl();
8907       return FunctionTemplate;
8908     }
8909   }
8910 
8911   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8912     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8913     if ((getLangOpts().OpenCLVersion >= 120)
8914         && (SC == SC_Static)) {
8915       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8916       D.setInvalidType();
8917     }
8918 
8919     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8920     if (!NewFD->getReturnType()->isVoidType()) {
8921       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8922       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8923           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8924                                 : FixItHint());
8925       D.setInvalidType();
8926     }
8927 
8928     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8929     for (auto Param : NewFD->parameters())
8930       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8931   }
8932   for (const ParmVarDecl *Param : NewFD->parameters()) {
8933     QualType PT = Param->getType();
8934 
8935     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8936     // types.
8937     if (getLangOpts().OpenCLVersion >= 200) {
8938       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8939         QualType ElemTy = PipeTy->getElementType();
8940           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8941             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8942             D.setInvalidType();
8943           }
8944       }
8945     }
8946   }
8947 
8948   MarkUnusedFileScopedDecl(NewFD);
8949 
8950   // Here we have an function template explicit specialization at class scope.
8951   // The actually specialization will be postponed to template instatiation
8952   // time via the ClassScopeFunctionSpecializationDecl node.
8953   if (isDependentClassScopeExplicitSpecialization) {
8954     ClassScopeFunctionSpecializationDecl *NewSpec =
8955                          ClassScopeFunctionSpecializationDecl::Create(
8956                                 Context, CurContext, SourceLocation(),
8957                                 cast<CXXMethodDecl>(NewFD),
8958                                 HasExplicitTemplateArgs, TemplateArgs);
8959     CurContext->addDecl(NewSpec);
8960     AddToScope = false;
8961   }
8962 
8963   return NewFD;
8964 }
8965 
8966 /// \brief Checks if the new declaration declared in dependent context must be
8967 /// put in the same redeclaration chain as the specified declaration.
8968 ///
8969 /// \param D Declaration that is checked.
8970 /// \param PrevDecl Previous declaration found with proper lookup method for the
8971 ///                 same declaration name.
8972 /// \returns True if D must be added to the redeclaration chain which PrevDecl
8973 ///          belongs to.
8974 ///
8975 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
8976   // Any declarations should be put into redeclaration chains except for
8977   // friend declaration in a dependent context that names a function in
8978   // namespace scope.
8979   //
8980   // This allows to compile code like:
8981   //
8982   //       void func();
8983   //       template<typename T> class C1 { friend void func() { } };
8984   //       template<typename T> class C2 { friend void func() { } };
8985   //
8986   // This code snippet is a valid code unless both templates are instantiated.
8987   return !(D->getLexicalDeclContext()->isDependentContext() &&
8988            D->getDeclContext()->isFileContext() &&
8989            D->getFriendObjectKind() != Decl::FOK_None);
8990 }
8991 
8992 /// \brief Perform semantic checking of a new function declaration.
8993 ///
8994 /// Performs semantic analysis of the new function declaration
8995 /// NewFD. This routine performs all semantic checking that does not
8996 /// require the actual declarator involved in the declaration, and is
8997 /// used both for the declaration of functions as they are parsed
8998 /// (called via ActOnDeclarator) and for the declaration of functions
8999 /// that have been instantiated via C++ template instantiation (called
9000 /// via InstantiateDecl).
9001 ///
9002 /// \param IsMemberSpecialization whether this new function declaration is
9003 /// a member specialization (that replaces any definition provided by the
9004 /// previous declaration).
9005 ///
9006 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9007 ///
9008 /// \returns true if the function declaration is a redeclaration.
9009 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9010                                     LookupResult &Previous,
9011                                     bool IsMemberSpecialization) {
9012   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9013          "Variably modified return types are not handled here");
9014 
9015   // Determine whether the type of this function should be merged with
9016   // a previous visible declaration. This never happens for functions in C++,
9017   // and always happens in C if the previous declaration was visible.
9018   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9019                                !Previous.isShadowed();
9020 
9021   bool Redeclaration = false;
9022   NamedDecl *OldDecl = nullptr;
9023 
9024   // Merge or overload the declaration with an existing declaration of
9025   // the same name, if appropriate.
9026   if (!Previous.empty()) {
9027     // Determine whether NewFD is an overload of PrevDecl or
9028     // a declaration that requires merging. If it's an overload,
9029     // there's no more work to do here; we'll just add the new
9030     // function to the scope.
9031     if (!AllowOverloadingOfFunction(Previous, Context)) {
9032       NamedDecl *Candidate = Previous.getRepresentativeDecl();
9033       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9034         Redeclaration = true;
9035         OldDecl = Candidate;
9036       }
9037     } else {
9038       switch (CheckOverload(S, NewFD, Previous, OldDecl,
9039                             /*NewIsUsingDecl*/ false)) {
9040       case Ovl_Match:
9041         Redeclaration = true;
9042         break;
9043 
9044       case Ovl_NonFunction:
9045         Redeclaration = true;
9046         break;
9047 
9048       case Ovl_Overload:
9049         Redeclaration = false;
9050         break;
9051       }
9052 
9053       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
9054         // If a function name is overloadable in C, then every function
9055         // with that name must be marked "overloadable".
9056         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
9057           << Redeclaration << NewFD;
9058         NamedDecl *OverloadedDecl =
9059             Redeclaration ? OldDecl : Previous.getRepresentativeDecl();
9060         Diag(OverloadedDecl->getLocation(),
9061              diag::note_attribute_overloadable_prev_overload);
9062         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9063       }
9064     }
9065   }
9066 
9067   // Check for a previous extern "C" declaration with this name.
9068   if (!Redeclaration &&
9069       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9070     if (!Previous.empty()) {
9071       // This is an extern "C" declaration with the same name as a previous
9072       // declaration, and thus redeclares that entity...
9073       Redeclaration = true;
9074       OldDecl = Previous.getFoundDecl();
9075       MergeTypeWithPrevious = false;
9076 
9077       // ... except in the presence of __attribute__((overloadable)).
9078       if (OldDecl->hasAttr<OverloadableAttr>()) {
9079         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
9080           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
9081             << Redeclaration << NewFD;
9082           Diag(Previous.getFoundDecl()->getLocation(),
9083                diag::note_attribute_overloadable_prev_overload);
9084           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9085         }
9086         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9087           Redeclaration = false;
9088           OldDecl = nullptr;
9089         }
9090       }
9091     }
9092   }
9093 
9094   // C++11 [dcl.constexpr]p8:
9095   //   A constexpr specifier for a non-static member function that is not
9096   //   a constructor declares that member function to be const.
9097   //
9098   // This needs to be delayed until we know whether this is an out-of-line
9099   // definition of a static member function.
9100   //
9101   // This rule is not present in C++1y, so we produce a backwards
9102   // compatibility warning whenever it happens in C++11.
9103   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9104   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9105       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9106       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9107     CXXMethodDecl *OldMD = nullptr;
9108     if (OldDecl)
9109       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9110     if (!OldMD || !OldMD->isStatic()) {
9111       const FunctionProtoType *FPT =
9112         MD->getType()->castAs<FunctionProtoType>();
9113       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9114       EPI.TypeQuals |= Qualifiers::Const;
9115       MD->setType(Context.getFunctionType(FPT->getReturnType(),
9116                                           FPT->getParamTypes(), EPI));
9117 
9118       // Warn that we did this, if we're not performing template instantiation.
9119       // In that case, we'll have warned already when the template was defined.
9120       if (!inTemplateInstantiation()) {
9121         SourceLocation AddConstLoc;
9122         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
9123                 .IgnoreParens().getAs<FunctionTypeLoc>())
9124           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
9125 
9126         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
9127           << FixItHint::CreateInsertion(AddConstLoc, " const");
9128       }
9129     }
9130   }
9131 
9132   if (Redeclaration) {
9133     // NewFD and OldDecl represent declarations that need to be
9134     // merged.
9135     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
9136       NewFD->setInvalidDecl();
9137       return Redeclaration;
9138     }
9139 
9140     Previous.clear();
9141     Previous.addDecl(OldDecl);
9142 
9143     if (FunctionTemplateDecl *OldTemplateDecl
9144                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
9145       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
9146       FunctionTemplateDecl *NewTemplateDecl
9147         = NewFD->getDescribedFunctionTemplate();
9148       assert(NewTemplateDecl && "Template/non-template mismatch");
9149       if (CXXMethodDecl *Method
9150             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
9151         Method->setAccess(OldTemplateDecl->getAccess());
9152         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
9153       }
9154 
9155       // If this is an explicit specialization of a member that is a function
9156       // template, mark it as a member specialization.
9157       if (IsMemberSpecialization &&
9158           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
9159         NewTemplateDecl->setMemberSpecialization();
9160         assert(OldTemplateDecl->isMemberSpecialization());
9161         // Explicit specializations of a member template do not inherit deleted
9162         // status from the parent member template that they are specializing.
9163         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
9164           FunctionDecl *const OldTemplatedDecl =
9165               OldTemplateDecl->getTemplatedDecl();
9166           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
9167           OldTemplatedDecl->setDeletedAsWritten(false);
9168         }
9169       }
9170 
9171     } else {
9172       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9173         // This needs to happen first so that 'inline' propagates.
9174         NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
9175         if (isa<CXXMethodDecl>(NewFD))
9176           NewFD->setAccess(OldDecl->getAccess());
9177       }
9178     }
9179   }
9180 
9181   // Semantic checking for this function declaration (in isolation).
9182 
9183   if (getLangOpts().CPlusPlus) {
9184     // C++-specific checks.
9185     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9186       CheckConstructor(Constructor);
9187     } else if (CXXDestructorDecl *Destructor =
9188                 dyn_cast<CXXDestructorDecl>(NewFD)) {
9189       CXXRecordDecl *Record = Destructor->getParent();
9190       QualType ClassType = Context.getTypeDeclType(Record);
9191 
9192       // FIXME: Shouldn't we be able to perform this check even when the class
9193       // type is dependent? Both gcc and edg can handle that.
9194       if (!ClassType->isDependentType()) {
9195         DeclarationName Name
9196           = Context.DeclarationNames.getCXXDestructorName(
9197                                         Context.getCanonicalType(ClassType));
9198         if (NewFD->getDeclName() != Name) {
9199           Diag(NewFD->getLocation(), diag::err_destructor_name);
9200           NewFD->setInvalidDecl();
9201           return Redeclaration;
9202         }
9203       }
9204     } else if (CXXConversionDecl *Conversion
9205                = dyn_cast<CXXConversionDecl>(NewFD)) {
9206       ActOnConversionDeclarator(Conversion);
9207     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
9208       if (auto *TD = Guide->getDescribedFunctionTemplate())
9209         CheckDeductionGuideTemplate(TD);
9210 
9211       // A deduction guide is not on the list of entities that can be
9212       // explicitly specialized.
9213       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
9214         Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
9215             << /*explicit specialization*/ 1;
9216     }
9217 
9218     // Find any virtual functions that this function overrides.
9219     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9220       if (!Method->isFunctionTemplateSpecialization() &&
9221           !Method->getDescribedFunctionTemplate() &&
9222           Method->isCanonicalDecl()) {
9223         if (AddOverriddenMethods(Method->getParent(), Method)) {
9224           // If the function was marked as "static", we have a problem.
9225           if (NewFD->getStorageClass() == SC_Static) {
9226             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
9227           }
9228         }
9229       }
9230 
9231       if (Method->isStatic())
9232         checkThisInStaticMemberFunctionType(Method);
9233     }
9234 
9235     // Extra checking for C++ overloaded operators (C++ [over.oper]).
9236     if (NewFD->isOverloadedOperator() &&
9237         CheckOverloadedOperatorDeclaration(NewFD)) {
9238       NewFD->setInvalidDecl();
9239       return Redeclaration;
9240     }
9241 
9242     // Extra checking for C++0x literal operators (C++0x [over.literal]).
9243     if (NewFD->getLiteralIdentifier() &&
9244         CheckLiteralOperatorDeclaration(NewFD)) {
9245       NewFD->setInvalidDecl();
9246       return Redeclaration;
9247     }
9248 
9249     // In C++, check default arguments now that we have merged decls. Unless
9250     // the lexical context is the class, because in this case this is done
9251     // during delayed parsing anyway.
9252     if (!CurContext->isRecord())
9253       CheckCXXDefaultArguments(NewFD);
9254 
9255     // If this function declares a builtin function, check the type of this
9256     // declaration against the expected type for the builtin.
9257     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9258       ASTContext::GetBuiltinTypeError Error;
9259       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9260       QualType T = Context.GetBuiltinType(BuiltinID, Error);
9261       // If the type of the builtin differs only in its exception
9262       // specification, that's OK.
9263       // FIXME: If the types do differ in this way, it would be better to
9264       // retain the 'noexcept' form of the type.
9265       if (!T.isNull() &&
9266           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
9267                                                             NewFD->getType()))
9268         // The type of this function differs from the type of the builtin,
9269         // so forget about the builtin entirely.
9270         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9271     }
9272 
9273     // If this function is declared as being extern "C", then check to see if
9274     // the function returns a UDT (class, struct, or union type) that is not C
9275     // compatible, and if it does, warn the user.
9276     // But, issue any diagnostic on the first declaration only.
9277     if (Previous.empty() && NewFD->isExternC()) {
9278       QualType R = NewFD->getReturnType();
9279       if (R->isIncompleteType() && !R->isVoidType())
9280         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9281             << NewFD << R;
9282       else if (!R.isPODType(Context) && !R->isVoidType() &&
9283                !R->isObjCObjectPointerType())
9284         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9285     }
9286 
9287     // C++1z [dcl.fct]p6:
9288     //   [...] whether the function has a non-throwing exception-specification
9289     //   [is] part of the function type
9290     //
9291     // This results in an ABI break between C++14 and C++17 for functions whose
9292     // declared type includes an exception-specification in a parameter or
9293     // return type. (Exception specifications on the function itself are OK in
9294     // most cases, and exception specifications are not permitted in most other
9295     // contexts where they could make it into a mangling.)
9296     if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) {
9297       auto HasNoexcept = [&](QualType T) -> bool {
9298         // Strip off declarator chunks that could be between us and a function
9299         // type. We don't need to look far, exception specifications are very
9300         // restricted prior to C++17.
9301         if (auto *RT = T->getAs<ReferenceType>())
9302           T = RT->getPointeeType();
9303         else if (T->isAnyPointerType())
9304           T = T->getPointeeType();
9305         else if (auto *MPT = T->getAs<MemberPointerType>())
9306           T = MPT->getPointeeType();
9307         if (auto *FPT = T->getAs<FunctionProtoType>())
9308           if (FPT->isNothrow(Context))
9309             return true;
9310         return false;
9311       };
9312 
9313       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9314       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9315       for (QualType T : FPT->param_types())
9316         AnyNoexcept |= HasNoexcept(T);
9317       if (AnyNoexcept)
9318         Diag(NewFD->getLocation(),
9319              diag::warn_cxx1z_compat_exception_spec_in_signature)
9320             << NewFD;
9321     }
9322 
9323     if (!Redeclaration && LangOpts.CUDA)
9324       checkCUDATargetOverload(NewFD, Previous);
9325   }
9326   return Redeclaration;
9327 }
9328 
9329 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9330   // C++11 [basic.start.main]p3:
9331   //   A program that [...] declares main to be inline, static or
9332   //   constexpr is ill-formed.
9333   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
9334   //   appear in a declaration of main.
9335   // static main is not an error under C99, but we should warn about it.
9336   // We accept _Noreturn main as an extension.
9337   if (FD->getStorageClass() == SC_Static)
9338     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9339          ? diag::err_static_main : diag::warn_static_main)
9340       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9341   if (FD->isInlineSpecified())
9342     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9343       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9344   if (DS.isNoreturnSpecified()) {
9345     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9346     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9347     Diag(NoreturnLoc, diag::ext_noreturn_main);
9348     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9349       << FixItHint::CreateRemoval(NoreturnRange);
9350   }
9351   if (FD->isConstexpr()) {
9352     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9353       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9354     FD->setConstexpr(false);
9355   }
9356 
9357   if (getLangOpts().OpenCL) {
9358     Diag(FD->getLocation(), diag::err_opencl_no_main)
9359         << FD->hasAttr<OpenCLKernelAttr>();
9360     FD->setInvalidDecl();
9361     return;
9362   }
9363 
9364   QualType T = FD->getType();
9365   assert(T->isFunctionType() && "function decl is not of function type");
9366   const FunctionType* FT = T->castAs<FunctionType>();
9367 
9368   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9369     // In C with GNU extensions we allow main() to have non-integer return
9370     // type, but we should warn about the extension, and we disable the
9371     // implicit-return-zero rule.
9372 
9373     // GCC in C mode accepts qualified 'int'.
9374     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9375       FD->setHasImplicitReturnZero(true);
9376     else {
9377       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9378       SourceRange RTRange = FD->getReturnTypeSourceRange();
9379       if (RTRange.isValid())
9380         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9381             << FixItHint::CreateReplacement(RTRange, "int");
9382     }
9383   } else {
9384     // In C and C++, main magically returns 0 if you fall off the end;
9385     // set the flag which tells us that.
9386     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9387 
9388     // All the standards say that main() should return 'int'.
9389     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9390       FD->setHasImplicitReturnZero(true);
9391     else {
9392       // Otherwise, this is just a flat-out error.
9393       SourceRange RTRange = FD->getReturnTypeSourceRange();
9394       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9395           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9396                                 : FixItHint());
9397       FD->setInvalidDecl(true);
9398     }
9399   }
9400 
9401   // Treat protoless main() as nullary.
9402   if (isa<FunctionNoProtoType>(FT)) return;
9403 
9404   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9405   unsigned nparams = FTP->getNumParams();
9406   assert(FD->getNumParams() == nparams);
9407 
9408   bool HasExtraParameters = (nparams > 3);
9409 
9410   if (FTP->isVariadic()) {
9411     Diag(FD->getLocation(), diag::ext_variadic_main);
9412     // FIXME: if we had information about the location of the ellipsis, we
9413     // could add a FixIt hint to remove it as a parameter.
9414   }
9415 
9416   // Darwin passes an undocumented fourth argument of type char**.  If
9417   // other platforms start sprouting these, the logic below will start
9418   // getting shifty.
9419   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9420     HasExtraParameters = false;
9421 
9422   if (HasExtraParameters) {
9423     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9424     FD->setInvalidDecl(true);
9425     nparams = 3;
9426   }
9427 
9428   // FIXME: a lot of the following diagnostics would be improved
9429   // if we had some location information about types.
9430 
9431   QualType CharPP =
9432     Context.getPointerType(Context.getPointerType(Context.CharTy));
9433   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9434 
9435   for (unsigned i = 0; i < nparams; ++i) {
9436     QualType AT = FTP->getParamType(i);
9437 
9438     bool mismatch = true;
9439 
9440     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9441       mismatch = false;
9442     else if (Expected[i] == CharPP) {
9443       // As an extension, the following forms are okay:
9444       //   char const **
9445       //   char const * const *
9446       //   char * const *
9447 
9448       QualifierCollector qs;
9449       const PointerType* PT;
9450       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9451           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9452           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9453                               Context.CharTy)) {
9454         qs.removeConst();
9455         mismatch = !qs.empty();
9456       }
9457     }
9458 
9459     if (mismatch) {
9460       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9461       // TODO: suggest replacing given type with expected type
9462       FD->setInvalidDecl(true);
9463     }
9464   }
9465 
9466   if (nparams == 1 && !FD->isInvalidDecl()) {
9467     Diag(FD->getLocation(), diag::warn_main_one_arg);
9468   }
9469 
9470   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9471     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9472     FD->setInvalidDecl();
9473   }
9474 }
9475 
9476 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9477   QualType T = FD->getType();
9478   assert(T->isFunctionType() && "function decl is not of function type");
9479   const FunctionType *FT = T->castAs<FunctionType>();
9480 
9481   // Set an implicit return of 'zero' if the function can return some integral,
9482   // enumeration, pointer or nullptr type.
9483   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9484       FT->getReturnType()->isAnyPointerType() ||
9485       FT->getReturnType()->isNullPtrType())
9486     // DllMain is exempt because a return value of zero means it failed.
9487     if (FD->getName() != "DllMain")
9488       FD->setHasImplicitReturnZero(true);
9489 
9490   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9491     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9492     FD->setInvalidDecl();
9493   }
9494 }
9495 
9496 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9497   // FIXME: Need strict checking.  In C89, we need to check for
9498   // any assignment, increment, decrement, function-calls, or
9499   // commas outside of a sizeof.  In C99, it's the same list,
9500   // except that the aforementioned are allowed in unevaluated
9501   // expressions.  Everything else falls under the
9502   // "may accept other forms of constant expressions" exception.
9503   // (We never end up here for C++, so the constant expression
9504   // rules there don't matter.)
9505   const Expr *Culprit;
9506   if (Init->isConstantInitializer(Context, false, &Culprit))
9507     return false;
9508   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9509     << Culprit->getSourceRange();
9510   return true;
9511 }
9512 
9513 namespace {
9514   // Visits an initialization expression to see if OrigDecl is evaluated in
9515   // its own initialization and throws a warning if it does.
9516   class SelfReferenceChecker
9517       : public EvaluatedExprVisitor<SelfReferenceChecker> {
9518     Sema &S;
9519     Decl *OrigDecl;
9520     bool isRecordType;
9521     bool isPODType;
9522     bool isReferenceType;
9523 
9524     bool isInitList;
9525     llvm::SmallVector<unsigned, 4> InitFieldIndex;
9526 
9527   public:
9528     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9529 
9530     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9531                                                     S(S), OrigDecl(OrigDecl) {
9532       isPODType = false;
9533       isRecordType = false;
9534       isReferenceType = false;
9535       isInitList = false;
9536       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9537         isPODType = VD->getType().isPODType(S.Context);
9538         isRecordType = VD->getType()->isRecordType();
9539         isReferenceType = VD->getType()->isReferenceType();
9540       }
9541     }
9542 
9543     // For most expressions, just call the visitor.  For initializer lists,
9544     // track the index of the field being initialized since fields are
9545     // initialized in order allowing use of previously initialized fields.
9546     void CheckExpr(Expr *E) {
9547       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9548       if (!InitList) {
9549         Visit(E);
9550         return;
9551       }
9552 
9553       // Track and increment the index here.
9554       isInitList = true;
9555       InitFieldIndex.push_back(0);
9556       for (auto Child : InitList->children()) {
9557         CheckExpr(cast<Expr>(Child));
9558         ++InitFieldIndex.back();
9559       }
9560       InitFieldIndex.pop_back();
9561     }
9562 
9563     // Returns true if MemberExpr is checked and no further checking is needed.
9564     // Returns false if additional checking is required.
9565     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9566       llvm::SmallVector<FieldDecl*, 4> Fields;
9567       Expr *Base = E;
9568       bool ReferenceField = false;
9569 
9570       // Get the field memebers used.
9571       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9572         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9573         if (!FD)
9574           return false;
9575         Fields.push_back(FD);
9576         if (FD->getType()->isReferenceType())
9577           ReferenceField = true;
9578         Base = ME->getBase()->IgnoreParenImpCasts();
9579       }
9580 
9581       // Keep checking only if the base Decl is the same.
9582       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9583       if (!DRE || DRE->getDecl() != OrigDecl)
9584         return false;
9585 
9586       // A reference field can be bound to an unininitialized field.
9587       if (CheckReference && !ReferenceField)
9588         return true;
9589 
9590       // Convert FieldDecls to their index number.
9591       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9592       for (const FieldDecl *I : llvm::reverse(Fields))
9593         UsedFieldIndex.push_back(I->getFieldIndex());
9594 
9595       // See if a warning is needed by checking the first difference in index
9596       // numbers.  If field being used has index less than the field being
9597       // initialized, then the use is safe.
9598       for (auto UsedIter = UsedFieldIndex.begin(),
9599                 UsedEnd = UsedFieldIndex.end(),
9600                 OrigIter = InitFieldIndex.begin(),
9601                 OrigEnd = InitFieldIndex.end();
9602            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9603         if (*UsedIter < *OrigIter)
9604           return true;
9605         if (*UsedIter > *OrigIter)
9606           break;
9607       }
9608 
9609       // TODO: Add a different warning which will print the field names.
9610       HandleDeclRefExpr(DRE);
9611       return true;
9612     }
9613 
9614     // For most expressions, the cast is directly above the DeclRefExpr.
9615     // For conditional operators, the cast can be outside the conditional
9616     // operator if both expressions are DeclRefExpr's.
9617     void HandleValue(Expr *E) {
9618       E = E->IgnoreParens();
9619       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9620         HandleDeclRefExpr(DRE);
9621         return;
9622       }
9623 
9624       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9625         Visit(CO->getCond());
9626         HandleValue(CO->getTrueExpr());
9627         HandleValue(CO->getFalseExpr());
9628         return;
9629       }
9630 
9631       if (BinaryConditionalOperator *BCO =
9632               dyn_cast<BinaryConditionalOperator>(E)) {
9633         Visit(BCO->getCond());
9634         HandleValue(BCO->getFalseExpr());
9635         return;
9636       }
9637 
9638       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9639         HandleValue(OVE->getSourceExpr());
9640         return;
9641       }
9642 
9643       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9644         if (BO->getOpcode() == BO_Comma) {
9645           Visit(BO->getLHS());
9646           HandleValue(BO->getRHS());
9647           return;
9648         }
9649       }
9650 
9651       if (isa<MemberExpr>(E)) {
9652         if (isInitList) {
9653           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9654                                       false /*CheckReference*/))
9655             return;
9656         }
9657 
9658         Expr *Base = E->IgnoreParenImpCasts();
9659         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9660           // Check for static member variables and don't warn on them.
9661           if (!isa<FieldDecl>(ME->getMemberDecl()))
9662             return;
9663           Base = ME->getBase()->IgnoreParenImpCasts();
9664         }
9665         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9666           HandleDeclRefExpr(DRE);
9667         return;
9668       }
9669 
9670       Visit(E);
9671     }
9672 
9673     // Reference types not handled in HandleValue are handled here since all
9674     // uses of references are bad, not just r-value uses.
9675     void VisitDeclRefExpr(DeclRefExpr *E) {
9676       if (isReferenceType)
9677         HandleDeclRefExpr(E);
9678     }
9679 
9680     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9681       if (E->getCastKind() == CK_LValueToRValue) {
9682         HandleValue(E->getSubExpr());
9683         return;
9684       }
9685 
9686       Inherited::VisitImplicitCastExpr(E);
9687     }
9688 
9689     void VisitMemberExpr(MemberExpr *E) {
9690       if (isInitList) {
9691         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9692           return;
9693       }
9694 
9695       // Don't warn on arrays since they can be treated as pointers.
9696       if (E->getType()->canDecayToPointerType()) return;
9697 
9698       // Warn when a non-static method call is followed by non-static member
9699       // field accesses, which is followed by a DeclRefExpr.
9700       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9701       bool Warn = (MD && !MD->isStatic());
9702       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9703       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9704         if (!isa<FieldDecl>(ME->getMemberDecl()))
9705           Warn = false;
9706         Base = ME->getBase()->IgnoreParenImpCasts();
9707       }
9708 
9709       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9710         if (Warn)
9711           HandleDeclRefExpr(DRE);
9712         return;
9713       }
9714 
9715       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9716       // Visit that expression.
9717       Visit(Base);
9718     }
9719 
9720     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9721       Expr *Callee = E->getCallee();
9722 
9723       if (isa<UnresolvedLookupExpr>(Callee))
9724         return Inherited::VisitCXXOperatorCallExpr(E);
9725 
9726       Visit(Callee);
9727       for (auto Arg: E->arguments())
9728         HandleValue(Arg->IgnoreParenImpCasts());
9729     }
9730 
9731     void VisitUnaryOperator(UnaryOperator *E) {
9732       // For POD record types, addresses of its own members are well-defined.
9733       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9734           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9735         if (!isPODType)
9736           HandleValue(E->getSubExpr());
9737         return;
9738       }
9739 
9740       if (E->isIncrementDecrementOp()) {
9741         HandleValue(E->getSubExpr());
9742         return;
9743       }
9744 
9745       Inherited::VisitUnaryOperator(E);
9746     }
9747 
9748     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9749 
9750     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9751       if (E->getConstructor()->isCopyConstructor()) {
9752         Expr *ArgExpr = E->getArg(0);
9753         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9754           if (ILE->getNumInits() == 1)
9755             ArgExpr = ILE->getInit(0);
9756         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9757           if (ICE->getCastKind() == CK_NoOp)
9758             ArgExpr = ICE->getSubExpr();
9759         HandleValue(ArgExpr);
9760         return;
9761       }
9762       Inherited::VisitCXXConstructExpr(E);
9763     }
9764 
9765     void VisitCallExpr(CallExpr *E) {
9766       // Treat std::move as a use.
9767       if (E->getNumArgs() == 1) {
9768         if (FunctionDecl *FD = E->getDirectCallee()) {
9769           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9770               FD->getIdentifier()->isStr("move")) {
9771             HandleValue(E->getArg(0));
9772             return;
9773           }
9774         }
9775       }
9776 
9777       Inherited::VisitCallExpr(E);
9778     }
9779 
9780     void VisitBinaryOperator(BinaryOperator *E) {
9781       if (E->isCompoundAssignmentOp()) {
9782         HandleValue(E->getLHS());
9783         Visit(E->getRHS());
9784         return;
9785       }
9786 
9787       Inherited::VisitBinaryOperator(E);
9788     }
9789 
9790     // A custom visitor for BinaryConditionalOperator is needed because the
9791     // regular visitor would check the condition and true expression separately
9792     // but both point to the same place giving duplicate diagnostics.
9793     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9794       Visit(E->getCond());
9795       Visit(E->getFalseExpr());
9796     }
9797 
9798     void HandleDeclRefExpr(DeclRefExpr *DRE) {
9799       Decl* ReferenceDecl = DRE->getDecl();
9800       if (OrigDecl != ReferenceDecl) return;
9801       unsigned diag;
9802       if (isReferenceType) {
9803         diag = diag::warn_uninit_self_reference_in_reference_init;
9804       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9805         diag = diag::warn_static_self_reference_in_init;
9806       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9807                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9808                  DRE->getDecl()->getType()->isRecordType()) {
9809         diag = diag::warn_uninit_self_reference_in_init;
9810       } else {
9811         // Local variables will be handled by the CFG analysis.
9812         return;
9813       }
9814 
9815       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9816                             S.PDiag(diag)
9817                               << DRE->getNameInfo().getName()
9818                               << OrigDecl->getLocation()
9819                               << DRE->getSourceRange());
9820     }
9821   };
9822 
9823   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9824   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9825                                  bool DirectInit) {
9826     // Parameters arguments are occassionially constructed with itself,
9827     // for instance, in recursive functions.  Skip them.
9828     if (isa<ParmVarDecl>(OrigDecl))
9829       return;
9830 
9831     E = E->IgnoreParens();
9832 
9833     // Skip checking T a = a where T is not a record or reference type.
9834     // Doing so is a way to silence uninitialized warnings.
9835     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9836       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9837         if (ICE->getCastKind() == CK_LValueToRValue)
9838           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9839             if (DRE->getDecl() == OrigDecl)
9840               return;
9841 
9842     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9843   }
9844 } // end anonymous namespace
9845 
9846 namespace {
9847   // Simple wrapper to add the name of a variable or (if no variable is
9848   // available) a DeclarationName into a diagnostic.
9849   struct VarDeclOrName {
9850     VarDecl *VDecl;
9851     DeclarationName Name;
9852 
9853     friend const Sema::SemaDiagnosticBuilder &
9854     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
9855       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
9856     }
9857   };
9858 } // end anonymous namespace
9859 
9860 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9861                                             DeclarationName Name, QualType Type,
9862                                             TypeSourceInfo *TSI,
9863                                             SourceRange Range, bool DirectInit,
9864                                             Expr *Init) {
9865   bool IsInitCapture = !VDecl;
9866   assert((!VDecl || !VDecl->isInitCapture()) &&
9867          "init captures are expected to be deduced prior to initialization");
9868 
9869   VarDeclOrName VN{VDecl, Name};
9870 
9871   DeducedType *Deduced = Type->getContainedDeducedType();
9872   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
9873 
9874   // C++11 [dcl.spec.auto]p3
9875   if (!Init) {
9876     assert(VDecl && "no init for init capture deduction?");
9877     Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
9878       << VDecl->getDeclName() << Type;
9879     return QualType();
9880   }
9881 
9882   ArrayRef<Expr*> DeduceInits = Init;
9883   if (DirectInit) {
9884     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
9885       DeduceInits = PL->exprs();
9886   }
9887 
9888   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
9889     assert(VDecl && "non-auto type for init capture deduction?");
9890     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9891     InitializationKind Kind = InitializationKind::CreateForInit(
9892         VDecl->getLocation(), DirectInit, Init);
9893     // FIXME: Initialization should not be taking a mutable list of inits.
9894     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
9895     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
9896                                                        InitsCopy);
9897   }
9898 
9899   if (DirectInit) {
9900     if (auto *IL = dyn_cast<InitListExpr>(Init))
9901       DeduceInits = IL->inits();
9902   }
9903 
9904   // Deduction only works if we have exactly one source expression.
9905   if (DeduceInits.empty()) {
9906     // It isn't possible to write this directly, but it is possible to
9907     // end up in this situation with "auto x(some_pack...);"
9908     Diag(Init->getLocStart(), IsInitCapture
9909                                   ? diag::err_init_capture_no_expression
9910                                   : diag::err_auto_var_init_no_expression)
9911         << VN << Type << Range;
9912     return QualType();
9913   }
9914 
9915   if (DeduceInits.size() > 1) {
9916     Diag(DeduceInits[1]->getLocStart(),
9917          IsInitCapture ? diag::err_init_capture_multiple_expressions
9918                        : diag::err_auto_var_init_multiple_expressions)
9919         << VN << Type << Range;
9920     return QualType();
9921   }
9922 
9923   Expr *DeduceInit = DeduceInits[0];
9924   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9925     Diag(Init->getLocStart(), IsInitCapture
9926                                   ? diag::err_init_capture_paren_braces
9927                                   : diag::err_auto_var_init_paren_braces)
9928         << isa<InitListExpr>(Init) << VN << Type << Range;
9929     return QualType();
9930   }
9931 
9932   // Expressions default to 'id' when we're in a debugger.
9933   bool DefaultedAnyToId = false;
9934   if (getLangOpts().DebuggerCastResultToId &&
9935       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9936     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9937     if (Result.isInvalid()) {
9938       return QualType();
9939     }
9940     Init = Result.get();
9941     DefaultedAnyToId = true;
9942   }
9943 
9944   // C++ [dcl.decomp]p1:
9945   //   If the assignment-expression [...] has array type A and no ref-qualifier
9946   //   is present, e has type cv A
9947   if (VDecl && isa<DecompositionDecl>(VDecl) &&
9948       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
9949       DeduceInit->getType()->isConstantArrayType())
9950     return Context.getQualifiedType(DeduceInit->getType(),
9951                                     Type.getQualifiers());
9952 
9953   QualType DeducedType;
9954   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9955     if (!IsInitCapture)
9956       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9957     else if (isa<InitListExpr>(Init))
9958       Diag(Range.getBegin(),
9959            diag::err_init_capture_deduction_failure_from_init_list)
9960           << VN
9961           << (DeduceInit->getType().isNull() ? TSI->getType()
9962                                              : DeduceInit->getType())
9963           << DeduceInit->getSourceRange();
9964     else
9965       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9966           << VN << TSI->getType()
9967           << (DeduceInit->getType().isNull() ? TSI->getType()
9968                                              : DeduceInit->getType())
9969           << DeduceInit->getSourceRange();
9970   }
9971 
9972   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9973   // 'id' instead of a specific object type prevents most of our usual
9974   // checks.
9975   // We only want to warn outside of template instantiations, though:
9976   // inside a template, the 'id' could have come from a parameter.
9977   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
9978       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9979     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9980     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
9981   }
9982 
9983   return DeducedType;
9984 }
9985 
9986 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
9987                                          Expr *Init) {
9988   QualType DeducedType = deduceVarTypeFromInitializer(
9989       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
9990       VDecl->getSourceRange(), DirectInit, Init);
9991   if (DeducedType.isNull()) {
9992     VDecl->setInvalidDecl();
9993     return true;
9994   }
9995 
9996   VDecl->setType(DeducedType);
9997   assert(VDecl->isLinkageValid());
9998 
9999   // In ARC, infer lifetime.
10000   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10001     VDecl->setInvalidDecl();
10002 
10003   // If this is a redeclaration, check that the type we just deduced matches
10004   // the previously declared type.
10005   if (VarDecl *Old = VDecl->getPreviousDecl()) {
10006     // We never need to merge the type, because we cannot form an incomplete
10007     // array of auto, nor deduce such a type.
10008     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
10009   }
10010 
10011   // Check the deduced type is valid for a variable declaration.
10012   CheckVariableDeclarationType(VDecl);
10013   return VDecl->isInvalidDecl();
10014 }
10015 
10016 /// AddInitializerToDecl - Adds the initializer Init to the
10017 /// declaration dcl. If DirectInit is true, this is C++ direct
10018 /// initialization rather than copy initialization.
10019 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10020   // If there is no declaration, there was an error parsing it.  Just ignore
10021   // the initializer.
10022   if (!RealDecl || RealDecl->isInvalidDecl()) {
10023     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10024     return;
10025   }
10026 
10027   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10028     // Pure-specifiers are handled in ActOnPureSpecifier.
10029     Diag(Method->getLocation(), diag::err_member_function_initialization)
10030       << Method->getDeclName() << Init->getSourceRange();
10031     Method->setInvalidDecl();
10032     return;
10033   }
10034 
10035   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
10036   if (!VDecl) {
10037     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
10038     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
10039     RealDecl->setInvalidDecl();
10040     return;
10041   }
10042 
10043   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
10044   if (VDecl->getType()->isUndeducedType()) {
10045     // Attempt typo correction early so that the type of the init expression can
10046     // be deduced based on the chosen correction if the original init contains a
10047     // TypoExpr.
10048     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
10049     if (!Res.isUsable()) {
10050       RealDecl->setInvalidDecl();
10051       return;
10052     }
10053     Init = Res.get();
10054 
10055     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
10056       return;
10057   }
10058 
10059   // dllimport cannot be used on variable definitions.
10060   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
10061     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
10062     VDecl->setInvalidDecl();
10063     return;
10064   }
10065 
10066   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
10067     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
10068     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
10069     VDecl->setInvalidDecl();
10070     return;
10071   }
10072 
10073   if (!VDecl->getType()->isDependentType()) {
10074     // A definition must end up with a complete type, which means it must be
10075     // complete with the restriction that an array type might be completed by
10076     // the initializer; note that later code assumes this restriction.
10077     QualType BaseDeclType = VDecl->getType();
10078     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
10079       BaseDeclType = Array->getElementType();
10080     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
10081                             diag::err_typecheck_decl_incomplete_type)) {
10082       RealDecl->setInvalidDecl();
10083       return;
10084     }
10085 
10086     // The variable can not have an abstract class type.
10087     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
10088                                diag::err_abstract_type_in_decl,
10089                                AbstractVariableType))
10090       VDecl->setInvalidDecl();
10091   }
10092 
10093   // If adding the initializer will turn this declaration into a definition,
10094   // and we already have a definition for this variable, diagnose or otherwise
10095   // handle the situation.
10096   VarDecl *Def;
10097   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
10098       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
10099       !VDecl->isThisDeclarationADemotedDefinition() &&
10100       checkVarDeclRedefinition(Def, VDecl))
10101     return;
10102 
10103   if (getLangOpts().CPlusPlus) {
10104     // C++ [class.static.data]p4
10105     //   If a static data member is of const integral or const
10106     //   enumeration type, its declaration in the class definition can
10107     //   specify a constant-initializer which shall be an integral
10108     //   constant expression (5.19). In that case, the member can appear
10109     //   in integral constant expressions. The member shall still be
10110     //   defined in a namespace scope if it is used in the program and the
10111     //   namespace scope definition shall not contain an initializer.
10112     //
10113     // We already performed a redefinition check above, but for static
10114     // data members we also need to check whether there was an in-class
10115     // declaration with an initializer.
10116     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
10117       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
10118           << VDecl->getDeclName();
10119       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
10120            diag::note_previous_initializer)
10121           << 0;
10122       return;
10123     }
10124 
10125     if (VDecl->hasLocalStorage())
10126       getCurFunction()->setHasBranchProtectedScope();
10127 
10128     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
10129       VDecl->setInvalidDecl();
10130       return;
10131     }
10132   }
10133 
10134   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
10135   // a kernel function cannot be initialized."
10136   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
10137     Diag(VDecl->getLocation(), diag::err_local_cant_init);
10138     VDecl->setInvalidDecl();
10139     return;
10140   }
10141 
10142   // Get the decls type and save a reference for later, since
10143   // CheckInitializerTypes may change it.
10144   QualType DclT = VDecl->getType(), SavT = DclT;
10145 
10146   // Expressions default to 'id' when we're in a debugger
10147   // and we are assigning it to a variable of Objective-C pointer type.
10148   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
10149       Init->getType() == Context.UnknownAnyTy) {
10150     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10151     if (Result.isInvalid()) {
10152       VDecl->setInvalidDecl();
10153       return;
10154     }
10155     Init = Result.get();
10156   }
10157 
10158   // Perform the initialization.
10159   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
10160   if (!VDecl->isInvalidDecl()) {
10161     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10162     InitializationKind Kind = InitializationKind::CreateForInit(
10163         VDecl->getLocation(), DirectInit, Init);
10164 
10165     MultiExprArg Args = Init;
10166     if (CXXDirectInit)
10167       Args = MultiExprArg(CXXDirectInit->getExprs(),
10168                           CXXDirectInit->getNumExprs());
10169 
10170     // Try to correct any TypoExprs in the initialization arguments.
10171     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
10172       ExprResult Res = CorrectDelayedTyposInExpr(
10173           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
10174             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
10175             return Init.Failed() ? ExprError() : E;
10176           });
10177       if (Res.isInvalid()) {
10178         VDecl->setInvalidDecl();
10179       } else if (Res.get() != Args[Idx]) {
10180         Args[Idx] = Res.get();
10181       }
10182     }
10183     if (VDecl->isInvalidDecl())
10184       return;
10185 
10186     InitializationSequence InitSeq(*this, Entity, Kind, Args,
10187                                    /*TopLevelOfInitList=*/false,
10188                                    /*TreatUnavailableAsInvalid=*/false);
10189     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
10190     if (Result.isInvalid()) {
10191       VDecl->setInvalidDecl();
10192       return;
10193     }
10194 
10195     Init = Result.getAs<Expr>();
10196   }
10197 
10198   // Check for self-references within variable initializers.
10199   // Variables declared within a function/method body (except for references)
10200   // are handled by a dataflow analysis.
10201   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
10202       VDecl->getType()->isReferenceType()) {
10203     CheckSelfReference(*this, RealDecl, Init, DirectInit);
10204   }
10205 
10206   // If the type changed, it means we had an incomplete type that was
10207   // completed by the initializer. For example:
10208   //   int ary[] = { 1, 3, 5 };
10209   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
10210   if (!VDecl->isInvalidDecl() && (DclT != SavT))
10211     VDecl->setType(DclT);
10212 
10213   if (!VDecl->isInvalidDecl()) {
10214     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
10215 
10216     if (VDecl->hasAttr<BlocksAttr>())
10217       checkRetainCycles(VDecl, Init);
10218 
10219     // It is safe to assign a weak reference into a strong variable.
10220     // Although this code can still have problems:
10221     //   id x = self.weakProp;
10222     //   id y = self.weakProp;
10223     // we do not warn to warn spuriously when 'x' and 'y' are on separate
10224     // paths through the function. This should be revisited if
10225     // -Wrepeated-use-of-weak is made flow-sensitive.
10226     if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
10227          VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
10228         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10229                          Init->getLocStart()))
10230       getCurFunction()->markSafeWeakUse(Init);
10231   }
10232 
10233   // The initialization is usually a full-expression.
10234   //
10235   // FIXME: If this is a braced initialization of an aggregate, it is not
10236   // an expression, and each individual field initializer is a separate
10237   // full-expression. For instance, in:
10238   //
10239   //   struct Temp { ~Temp(); };
10240   //   struct S { S(Temp); };
10241   //   struct T { S a, b; } t = { Temp(), Temp() }
10242   //
10243   // we should destroy the first Temp before constructing the second.
10244   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10245                                           false,
10246                                           VDecl->isConstexpr());
10247   if (Result.isInvalid()) {
10248     VDecl->setInvalidDecl();
10249     return;
10250   }
10251   Init = Result.get();
10252 
10253   // Attach the initializer to the decl.
10254   VDecl->setInit(Init);
10255 
10256   if (VDecl->isLocalVarDecl()) {
10257     // C99 6.7.8p4: All the expressions in an initializer for an object that has
10258     // static storage duration shall be constant expressions or string literals.
10259     // C++ does not have this restriction.
10260     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
10261       const Expr *Culprit;
10262       if (VDecl->getStorageClass() == SC_Static)
10263         CheckForConstantInitializer(Init, DclT);
10264       // C89 is stricter than C99 for non-static aggregate types.
10265       // C89 6.5.7p3: All the expressions [...] in an initializer list
10266       // for an object that has aggregate or union type shall be
10267       // constant expressions.
10268       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10269                isa<InitListExpr>(Init) &&
10270                !Init->isConstantInitializer(Context, false, &Culprit))
10271         Diag(Culprit->getExprLoc(),
10272              diag::ext_aggregate_init_not_constant)
10273           << Culprit->getSourceRange();
10274     }
10275   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10276              VDecl->getLexicalDeclContext()->isRecord()) {
10277     // This is an in-class initialization for a static data member, e.g.,
10278     //
10279     // struct S {
10280     //   static const int value = 17;
10281     // };
10282 
10283     // C++ [class.mem]p4:
10284     //   A member-declarator can contain a constant-initializer only
10285     //   if it declares a static member (9.4) of const integral or
10286     //   const enumeration type, see 9.4.2.
10287     //
10288     // C++11 [class.static.data]p3:
10289     //   If a non-volatile non-inline const static data member is of integral
10290     //   or enumeration type, its declaration in the class definition can
10291     //   specify a brace-or-equal-initializer in which every initializer-clause
10292     //   that is an assignment-expression is a constant expression. A static
10293     //   data member of literal type can be declared in the class definition
10294     //   with the constexpr specifier; if so, its declaration shall specify a
10295     //   brace-or-equal-initializer in which every initializer-clause that is
10296     //   an assignment-expression is a constant expression.
10297 
10298     // Do nothing on dependent types.
10299     if (DclT->isDependentType()) {
10300 
10301     // Allow any 'static constexpr' members, whether or not they are of literal
10302     // type. We separately check that every constexpr variable is of literal
10303     // type.
10304     } else if (VDecl->isConstexpr()) {
10305 
10306     // Require constness.
10307     } else if (!DclT.isConstQualified()) {
10308       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10309         << Init->getSourceRange();
10310       VDecl->setInvalidDecl();
10311 
10312     // We allow integer constant expressions in all cases.
10313     } else if (DclT->isIntegralOrEnumerationType()) {
10314       // Check whether the expression is a constant expression.
10315       SourceLocation Loc;
10316       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10317         // In C++11, a non-constexpr const static data member with an
10318         // in-class initializer cannot be volatile.
10319         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10320       else if (Init->isValueDependent())
10321         ; // Nothing to check.
10322       else if (Init->isIntegerConstantExpr(Context, &Loc))
10323         ; // Ok, it's an ICE!
10324       else if (Init->isEvaluatable(Context)) {
10325         // If we can constant fold the initializer through heroics, accept it,
10326         // but report this as a use of an extension for -pedantic.
10327         Diag(Loc, diag::ext_in_class_initializer_non_constant)
10328           << Init->getSourceRange();
10329       } else {
10330         // Otherwise, this is some crazy unknown case.  Report the issue at the
10331         // location provided by the isIntegerConstantExpr failed check.
10332         Diag(Loc, diag::err_in_class_initializer_non_constant)
10333           << Init->getSourceRange();
10334         VDecl->setInvalidDecl();
10335       }
10336 
10337     // We allow foldable floating-point constants as an extension.
10338     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10339       // In C++98, this is a GNU extension. In C++11, it is not, but we support
10340       // it anyway and provide a fixit to add the 'constexpr'.
10341       if (getLangOpts().CPlusPlus11) {
10342         Diag(VDecl->getLocation(),
10343              diag::ext_in_class_initializer_float_type_cxx11)
10344             << DclT << Init->getSourceRange();
10345         Diag(VDecl->getLocStart(),
10346              diag::note_in_class_initializer_float_type_cxx11)
10347             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10348       } else {
10349         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10350           << DclT << Init->getSourceRange();
10351 
10352         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10353           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10354             << Init->getSourceRange();
10355           VDecl->setInvalidDecl();
10356         }
10357       }
10358 
10359     // Suggest adding 'constexpr' in C++11 for literal types.
10360     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10361       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10362         << DclT << Init->getSourceRange()
10363         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10364       VDecl->setConstexpr(true);
10365 
10366     } else {
10367       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10368         << DclT << Init->getSourceRange();
10369       VDecl->setInvalidDecl();
10370     }
10371   } else if (VDecl->isFileVarDecl()) {
10372     // In C, extern is typically used to avoid tentative definitions when
10373     // declaring variables in headers, but adding an intializer makes it a
10374     // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
10375     // In C++, extern is often used to give implictly static const variables
10376     // external linkage, so don't warn in that case. If selectany is present,
10377     // this might be header code intended for C and C++ inclusion, so apply the
10378     // C++ rules.
10379     if (VDecl->getStorageClass() == SC_Extern &&
10380         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10381          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10382         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10383         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10384       Diag(VDecl->getLocation(), diag::warn_extern_init);
10385 
10386     // C99 6.7.8p4. All file scoped initializers need to be constant.
10387     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10388       CheckForConstantInitializer(Init, DclT);
10389   }
10390 
10391   // We will represent direct-initialization similarly to copy-initialization:
10392   //    int x(1);  -as-> int x = 1;
10393   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10394   //
10395   // Clients that want to distinguish between the two forms, can check for
10396   // direct initializer using VarDecl::getInitStyle().
10397   // A major benefit is that clients that don't particularly care about which
10398   // exactly form was it (like the CodeGen) can handle both cases without
10399   // special case code.
10400 
10401   // C++ 8.5p11:
10402   // The form of initialization (using parentheses or '=') is generally
10403   // insignificant, but does matter when the entity being initialized has a
10404   // class type.
10405   if (CXXDirectInit) {
10406     assert(DirectInit && "Call-style initializer must be direct init.");
10407     VDecl->setInitStyle(VarDecl::CallInit);
10408   } else if (DirectInit) {
10409     // This must be list-initialization. No other way is direct-initialization.
10410     VDecl->setInitStyle(VarDecl::ListInit);
10411   }
10412 
10413   CheckCompleteVariableDeclaration(VDecl);
10414 }
10415 
10416 /// ActOnInitializerError - Given that there was an error parsing an
10417 /// initializer for the given declaration, try to return to some form
10418 /// of sanity.
10419 void Sema::ActOnInitializerError(Decl *D) {
10420   // Our main concern here is re-establishing invariants like "a
10421   // variable's type is either dependent or complete".
10422   if (!D || D->isInvalidDecl()) return;
10423 
10424   VarDecl *VD = dyn_cast<VarDecl>(D);
10425   if (!VD) return;
10426 
10427   // Bindings are not usable if we can't make sense of the initializer.
10428   if (auto *DD = dyn_cast<DecompositionDecl>(D))
10429     for (auto *BD : DD->bindings())
10430       BD->setInvalidDecl();
10431 
10432   // Auto types are meaningless if we can't make sense of the initializer.
10433   if (ParsingInitForAutoVars.count(D)) {
10434     D->setInvalidDecl();
10435     return;
10436   }
10437 
10438   QualType Ty = VD->getType();
10439   if (Ty->isDependentType()) return;
10440 
10441   // Require a complete type.
10442   if (RequireCompleteType(VD->getLocation(),
10443                           Context.getBaseElementType(Ty),
10444                           diag::err_typecheck_decl_incomplete_type)) {
10445     VD->setInvalidDecl();
10446     return;
10447   }
10448 
10449   // Require a non-abstract type.
10450   if (RequireNonAbstractType(VD->getLocation(), Ty,
10451                              diag::err_abstract_type_in_decl,
10452                              AbstractVariableType)) {
10453     VD->setInvalidDecl();
10454     return;
10455   }
10456 
10457   // Don't bother complaining about constructors or destructors,
10458   // though.
10459 }
10460 
10461 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
10462   // If there is no declaration, there was an error parsing it. Just ignore it.
10463   if (!RealDecl)
10464     return;
10465 
10466   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
10467     QualType Type = Var->getType();
10468 
10469     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
10470     if (isa<DecompositionDecl>(RealDecl)) {
10471       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
10472       Var->setInvalidDecl();
10473       return;
10474     }
10475 
10476     if (Type->isUndeducedType() &&
10477         DeduceVariableDeclarationType(Var, false, nullptr))
10478       return;
10479 
10480     // C++11 [class.static.data]p3: A static data member can be declared with
10481     // the constexpr specifier; if so, its declaration shall specify
10482     // a brace-or-equal-initializer.
10483     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10484     // the definition of a variable [...] or the declaration of a static data
10485     // member.
10486     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
10487         !Var->isThisDeclarationADemotedDefinition()) {
10488       if (Var->isStaticDataMember()) {
10489         // C++1z removes the relevant rule; the in-class declaration is always
10490         // a definition there.
10491         if (!getLangOpts().CPlusPlus1z) {
10492           Diag(Var->getLocation(),
10493                diag::err_constexpr_static_mem_var_requires_init)
10494             << Var->getDeclName();
10495           Var->setInvalidDecl();
10496           return;
10497         }
10498       } else {
10499         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10500         Var->setInvalidDecl();
10501         return;
10502       }
10503     }
10504 
10505     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
10506     // definition having the concept specifier is called a variable concept. A
10507     // concept definition refers to [...] a variable concept and its initializer.
10508     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10509       if (VTD->isConcept()) {
10510         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10511         Var->setInvalidDecl();
10512         return;
10513       }
10514     }
10515 
10516     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10517     // be initialized.
10518     if (!Var->isInvalidDecl() &&
10519         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10520         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10521       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10522       Var->setInvalidDecl();
10523       return;
10524     }
10525 
10526     switch (Var->isThisDeclarationADefinition()) {
10527     case VarDecl::Definition:
10528       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10529         break;
10530 
10531       // We have an out-of-line definition of a static data member
10532       // that has an in-class initializer, so we type-check this like
10533       // a declaration.
10534       //
10535       // Fall through
10536 
10537     case VarDecl::DeclarationOnly:
10538       // It's only a declaration.
10539 
10540       // Block scope. C99 6.7p7: If an identifier for an object is
10541       // declared with no linkage (C99 6.2.2p6), the type for the
10542       // object shall be complete.
10543       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10544           !Var->hasLinkage() && !Var->isInvalidDecl() &&
10545           RequireCompleteType(Var->getLocation(), Type,
10546                               diag::err_typecheck_decl_incomplete_type))
10547         Var->setInvalidDecl();
10548 
10549       // Make sure that the type is not abstract.
10550       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10551           RequireNonAbstractType(Var->getLocation(), Type,
10552                                  diag::err_abstract_type_in_decl,
10553                                  AbstractVariableType))
10554         Var->setInvalidDecl();
10555       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10556           Var->getStorageClass() == SC_PrivateExtern) {
10557         Diag(Var->getLocation(), diag::warn_private_extern);
10558         Diag(Var->getLocation(), diag::note_private_extern);
10559       }
10560 
10561       return;
10562 
10563     case VarDecl::TentativeDefinition:
10564       // File scope. C99 6.9.2p2: A declaration of an identifier for an
10565       // object that has file scope without an initializer, and without a
10566       // storage-class specifier or with the storage-class specifier "static",
10567       // constitutes a tentative definition. Note: A tentative definition with
10568       // external linkage is valid (C99 6.2.2p5).
10569       if (!Var->isInvalidDecl()) {
10570         if (const IncompleteArrayType *ArrayT
10571                                     = Context.getAsIncompleteArrayType(Type)) {
10572           if (RequireCompleteType(Var->getLocation(),
10573                                   ArrayT->getElementType(),
10574                                   diag::err_illegal_decl_array_incomplete_type))
10575             Var->setInvalidDecl();
10576         } else if (Var->getStorageClass() == SC_Static) {
10577           // C99 6.9.2p3: If the declaration of an identifier for an object is
10578           // a tentative definition and has internal linkage (C99 6.2.2p3), the
10579           // declared type shall not be an incomplete type.
10580           // NOTE: code such as the following
10581           //     static struct s;
10582           //     struct s { int a; };
10583           // is accepted by gcc. Hence here we issue a warning instead of
10584           // an error and we do not invalidate the static declaration.
10585           // NOTE: to avoid multiple warnings, only check the first declaration.
10586           if (Var->isFirstDecl())
10587             RequireCompleteType(Var->getLocation(), Type,
10588                                 diag::ext_typecheck_decl_incomplete_type);
10589         }
10590       }
10591 
10592       // Record the tentative definition; we're done.
10593       if (!Var->isInvalidDecl())
10594         TentativeDefinitions.push_back(Var);
10595       return;
10596     }
10597 
10598     // Provide a specific diagnostic for uninitialized variable
10599     // definitions with incomplete array type.
10600     if (Type->isIncompleteArrayType()) {
10601       Diag(Var->getLocation(),
10602            diag::err_typecheck_incomplete_array_needs_initializer);
10603       Var->setInvalidDecl();
10604       return;
10605     }
10606 
10607     // Provide a specific diagnostic for uninitialized variable
10608     // definitions with reference type.
10609     if (Type->isReferenceType()) {
10610       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10611         << Var->getDeclName()
10612         << SourceRange(Var->getLocation(), Var->getLocation());
10613       Var->setInvalidDecl();
10614       return;
10615     }
10616 
10617     // Do not attempt to type-check the default initializer for a
10618     // variable with dependent type.
10619     if (Type->isDependentType())
10620       return;
10621 
10622     if (Var->isInvalidDecl())
10623       return;
10624 
10625     if (!Var->hasAttr<AliasAttr>()) {
10626       if (RequireCompleteType(Var->getLocation(),
10627                               Context.getBaseElementType(Type),
10628                               diag::err_typecheck_decl_incomplete_type)) {
10629         Var->setInvalidDecl();
10630         return;
10631       }
10632     } else {
10633       return;
10634     }
10635 
10636     // The variable can not have an abstract class type.
10637     if (RequireNonAbstractType(Var->getLocation(), Type,
10638                                diag::err_abstract_type_in_decl,
10639                                AbstractVariableType)) {
10640       Var->setInvalidDecl();
10641       return;
10642     }
10643 
10644     // Check for jumps past the implicit initializer.  C++0x
10645     // clarifies that this applies to a "variable with automatic
10646     // storage duration", not a "local variable".
10647     // C++11 [stmt.dcl]p3
10648     //   A program that jumps from a point where a variable with automatic
10649     //   storage duration is not in scope to a point where it is in scope is
10650     //   ill-formed unless the variable has scalar type, class type with a
10651     //   trivial default constructor and a trivial destructor, a cv-qualified
10652     //   version of one of these types, or an array of one of the preceding
10653     //   types and is declared without an initializer.
10654     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10655       if (const RecordType *Record
10656             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10657         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10658         // Mark the function for further checking even if the looser rules of
10659         // C++11 do not require such checks, so that we can diagnose
10660         // incompatibilities with C++98.
10661         if (!CXXRecord->isPOD())
10662           getCurFunction()->setHasBranchProtectedScope();
10663       }
10664     }
10665 
10666     // C++03 [dcl.init]p9:
10667     //   If no initializer is specified for an object, and the
10668     //   object is of (possibly cv-qualified) non-POD class type (or
10669     //   array thereof), the object shall be default-initialized; if
10670     //   the object is of const-qualified type, the underlying class
10671     //   type shall have a user-declared default
10672     //   constructor. Otherwise, if no initializer is specified for
10673     //   a non- static object, the object and its subobjects, if
10674     //   any, have an indeterminate initial value); if the object
10675     //   or any of its subobjects are of const-qualified type, the
10676     //   program is ill-formed.
10677     // C++0x [dcl.init]p11:
10678     //   If no initializer is specified for an object, the object is
10679     //   default-initialized; [...].
10680     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10681     InitializationKind Kind
10682       = InitializationKind::CreateDefault(Var->getLocation());
10683 
10684     InitializationSequence InitSeq(*this, Entity, Kind, None);
10685     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10686     if (Init.isInvalid())
10687       Var->setInvalidDecl();
10688     else if (Init.get()) {
10689       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10690       // This is important for template substitution.
10691       Var->setInitStyle(VarDecl::CallInit);
10692     }
10693 
10694     CheckCompleteVariableDeclaration(Var);
10695   }
10696 }
10697 
10698 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10699   // If there is no declaration, there was an error parsing it. Ignore it.
10700   if (!D)
10701     return;
10702 
10703   VarDecl *VD = dyn_cast<VarDecl>(D);
10704   if (!VD) {
10705     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10706     D->setInvalidDecl();
10707     return;
10708   }
10709 
10710   VD->setCXXForRangeDecl(true);
10711 
10712   // for-range-declaration cannot be given a storage class specifier.
10713   int Error = -1;
10714   switch (VD->getStorageClass()) {
10715   case SC_None:
10716     break;
10717   case SC_Extern:
10718     Error = 0;
10719     break;
10720   case SC_Static:
10721     Error = 1;
10722     break;
10723   case SC_PrivateExtern:
10724     Error = 2;
10725     break;
10726   case SC_Auto:
10727     Error = 3;
10728     break;
10729   case SC_Register:
10730     Error = 4;
10731     break;
10732   }
10733   if (Error != -1) {
10734     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10735       << VD->getDeclName() << Error;
10736     D->setInvalidDecl();
10737   }
10738 }
10739 
10740 StmtResult
10741 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10742                                  IdentifierInfo *Ident,
10743                                  ParsedAttributes &Attrs,
10744                                  SourceLocation AttrEnd) {
10745   // C++1y [stmt.iter]p1:
10746   //   A range-based for statement of the form
10747   //      for ( for-range-identifier : for-range-initializer ) statement
10748   //   is equivalent to
10749   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
10750   DeclSpec DS(Attrs.getPool().getFactory());
10751 
10752   const char *PrevSpec;
10753   unsigned DiagID;
10754   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10755                      getPrintingPolicy());
10756 
10757   Declarator D(DS, Declarator::ForContext);
10758   D.SetIdentifier(Ident, IdentLoc);
10759   D.takeAttributes(Attrs, AttrEnd);
10760 
10761   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10762   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10763                 EmptyAttrs, IdentLoc);
10764   Decl *Var = ActOnDeclarator(S, D);
10765   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10766   FinalizeDeclaration(Var);
10767   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10768                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
10769 }
10770 
10771 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10772   if (var->isInvalidDecl()) return;
10773 
10774   if (getLangOpts().OpenCL) {
10775     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10776     // initialiser
10777     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10778         !var->hasInit()) {
10779       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10780           << 1 /*Init*/;
10781       var->setInvalidDecl();
10782       return;
10783     }
10784   }
10785 
10786   // In Objective-C, don't allow jumps past the implicit initialization of a
10787   // local retaining variable.
10788   if (getLangOpts().ObjC1 &&
10789       var->hasLocalStorage()) {
10790     switch (var->getType().getObjCLifetime()) {
10791     case Qualifiers::OCL_None:
10792     case Qualifiers::OCL_ExplicitNone:
10793     case Qualifiers::OCL_Autoreleasing:
10794       break;
10795 
10796     case Qualifiers::OCL_Weak:
10797     case Qualifiers::OCL_Strong:
10798       getCurFunction()->setHasBranchProtectedScope();
10799       break;
10800     }
10801   }
10802 
10803   // Warn about externally-visible variables being defined without a
10804   // prior declaration.  We only want to do this for global
10805   // declarations, but we also specifically need to avoid doing it for
10806   // class members because the linkage of an anonymous class can
10807   // change if it's later given a typedef name.
10808   if (var->isThisDeclarationADefinition() &&
10809       var->getDeclContext()->getRedeclContext()->isFileContext() &&
10810       var->isExternallyVisible() && var->hasLinkage() &&
10811       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10812                                   var->getLocation())) {
10813     // Find a previous declaration that's not a definition.
10814     VarDecl *prev = var->getPreviousDecl();
10815     while (prev && prev->isThisDeclarationADefinition())
10816       prev = prev->getPreviousDecl();
10817 
10818     if (!prev)
10819       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10820   }
10821 
10822   // Cache the result of checking for constant initialization.
10823   Optional<bool> CacheHasConstInit;
10824   const Expr *CacheCulprit;
10825   auto checkConstInit = [&]() mutable {
10826     if (!CacheHasConstInit)
10827       CacheHasConstInit = var->getInit()->isConstantInitializer(
10828             Context, var->getType()->isReferenceType(), &CacheCulprit);
10829     return *CacheHasConstInit;
10830   };
10831 
10832   if (var->getTLSKind() == VarDecl::TLS_Static) {
10833     if (var->getType().isDestructedType()) {
10834       // GNU C++98 edits for __thread, [basic.start.term]p3:
10835       //   The type of an object with thread storage duration shall not
10836       //   have a non-trivial destructor.
10837       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10838       if (getLangOpts().CPlusPlus11)
10839         Diag(var->getLocation(), diag::note_use_thread_local);
10840     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
10841       if (!checkConstInit()) {
10842         // GNU C++98 edits for __thread, [basic.start.init]p4:
10843         //   An object of thread storage duration shall not require dynamic
10844         //   initialization.
10845         // FIXME: Need strict checking here.
10846         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
10847           << CacheCulprit->getSourceRange();
10848         if (getLangOpts().CPlusPlus11)
10849           Diag(var->getLocation(), diag::note_use_thread_local);
10850       }
10851     }
10852   }
10853 
10854   // Apply section attributes and pragmas to global variables.
10855   bool GlobalStorage = var->hasGlobalStorage();
10856   if (GlobalStorage && var->isThisDeclarationADefinition() &&
10857       !inTemplateInstantiation()) {
10858     PragmaStack<StringLiteral *> *Stack = nullptr;
10859     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10860     if (var->getType().isConstQualified())
10861       Stack = &ConstSegStack;
10862     else if (!var->getInit()) {
10863       Stack = &BSSSegStack;
10864       SectionFlags |= ASTContext::PSF_Write;
10865     } else {
10866       Stack = &DataSegStack;
10867       SectionFlags |= ASTContext::PSF_Write;
10868     }
10869     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10870       var->addAttr(SectionAttr::CreateImplicit(
10871           Context, SectionAttr::Declspec_allocate,
10872           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10873     }
10874     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10875       if (UnifySection(SA->getName(), SectionFlags, var))
10876         var->dropAttr<SectionAttr>();
10877 
10878     // Apply the init_seg attribute if this has an initializer.  If the
10879     // initializer turns out to not be dynamic, we'll end up ignoring this
10880     // attribute.
10881     if (CurInitSeg && var->getInit())
10882       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10883                                                CurInitSegLoc));
10884   }
10885 
10886   // All the following checks are C++ only.
10887   if (!getLangOpts().CPlusPlus) {
10888       // If this variable must be emitted, add it as an initializer for the
10889       // current module.
10890      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
10891        Context.addModuleInitializer(ModuleScopes.back().Module, var);
10892      return;
10893   }
10894 
10895   if (auto *DD = dyn_cast<DecompositionDecl>(var))
10896     CheckCompleteDecompositionDeclaration(DD);
10897 
10898   QualType type = var->getType();
10899   if (type->isDependentType()) return;
10900 
10901   // __block variables might require us to capture a copy-initializer.
10902   if (var->hasAttr<BlocksAttr>()) {
10903     // It's currently invalid to ever have a __block variable with an
10904     // array type; should we diagnose that here?
10905 
10906     // Regardless, we don't want to ignore array nesting when
10907     // constructing this copy.
10908     if (type->isStructureOrClassType()) {
10909       EnterExpressionEvaluationContext scope(
10910           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
10911       SourceLocation poi = var->getLocation();
10912       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10913       ExprResult result
10914         = PerformMoveOrCopyInitialization(
10915             InitializedEntity::InitializeBlock(poi, type, false),
10916             var, var->getType(), varRef, /*AllowNRVO=*/true);
10917       if (!result.isInvalid()) {
10918         result = MaybeCreateExprWithCleanups(result);
10919         Expr *init = result.getAs<Expr>();
10920         Context.setBlockVarCopyInits(var, init);
10921       }
10922     }
10923   }
10924 
10925   Expr *Init = var->getInit();
10926   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10927   QualType baseType = Context.getBaseElementType(type);
10928 
10929   if (!var->getDeclContext()->isDependentContext() &&
10930       Init && !Init->isValueDependent()) {
10931 
10932     if (var->isConstexpr()) {
10933       SmallVector<PartialDiagnosticAt, 8> Notes;
10934       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10935         SourceLocation DiagLoc = var->getLocation();
10936         // If the note doesn't add any useful information other than a source
10937         // location, fold it into the primary diagnostic.
10938         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10939               diag::note_invalid_subexpr_in_const_expr) {
10940           DiagLoc = Notes[0].first;
10941           Notes.clear();
10942         }
10943         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10944           << var << Init->getSourceRange();
10945         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10946           Diag(Notes[I].first, Notes[I].second);
10947       }
10948     } else if (var->isUsableInConstantExpressions(Context)) {
10949       // Check whether the initializer of a const variable of integral or
10950       // enumeration type is an ICE now, since we can't tell whether it was
10951       // initialized by a constant expression if we check later.
10952       var->checkInitIsICE();
10953     }
10954 
10955     // Don't emit further diagnostics about constexpr globals since they
10956     // were just diagnosed.
10957     if (!var->isConstexpr() && GlobalStorage &&
10958             var->hasAttr<RequireConstantInitAttr>()) {
10959       // FIXME: Need strict checking in C++03 here.
10960       bool DiagErr = getLangOpts().CPlusPlus11
10961           ? !var->checkInitIsICE() : !checkConstInit();
10962       if (DiagErr) {
10963         auto attr = var->getAttr<RequireConstantInitAttr>();
10964         Diag(var->getLocation(), diag::err_require_constant_init_failed)
10965           << Init->getSourceRange();
10966         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
10967           << attr->getRange();
10968       }
10969     }
10970     else if (!var->isConstexpr() && IsGlobal &&
10971              !getDiagnostics().isIgnored(diag::warn_global_constructor,
10972                                     var->getLocation())) {
10973       // Warn about globals which don't have a constant initializer.  Don't
10974       // warn about globals with a non-trivial destructor because we already
10975       // warned about them.
10976       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10977       if (!(RD && !RD->hasTrivialDestructor())) {
10978         if (!checkConstInit())
10979           Diag(var->getLocation(), diag::warn_global_constructor)
10980             << Init->getSourceRange();
10981       }
10982     }
10983   }
10984 
10985   // Require the destructor.
10986   if (const RecordType *recordType = baseType->getAs<RecordType>())
10987     FinalizeVarWithDestructor(var, recordType);
10988 
10989   // If this variable must be emitted, add it as an initializer for the current
10990   // module.
10991   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
10992     Context.addModuleInitializer(ModuleScopes.back().Module, var);
10993 }
10994 
10995 /// \brief Determines if a variable's alignment is dependent.
10996 static bool hasDependentAlignment(VarDecl *VD) {
10997   if (VD->getType()->isDependentType())
10998     return true;
10999   for (auto *I : VD->specific_attrs<AlignedAttr>())
11000     if (I->isAlignmentDependent())
11001       return true;
11002   return false;
11003 }
11004 
11005 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
11006 /// any semantic actions necessary after any initializer has been attached.
11007 void
11008 Sema::FinalizeDeclaration(Decl *ThisDecl) {
11009   // Note that we are no longer parsing the initializer for this declaration.
11010   ParsingInitForAutoVars.erase(ThisDecl);
11011 
11012   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
11013   if (!VD)
11014     return;
11015 
11016   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
11017     for (auto *BD : DD->bindings()) {
11018       FinalizeDeclaration(BD);
11019     }
11020   }
11021 
11022   checkAttributesAfterMerging(*this, *VD);
11023 
11024   // Perform TLS alignment check here after attributes attached to the variable
11025   // which may affect the alignment have been processed. Only perform the check
11026   // if the target has a maximum TLS alignment (zero means no constraints).
11027   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
11028     // Protect the check so that it's not performed on dependent types and
11029     // dependent alignments (we can't determine the alignment in that case).
11030     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
11031         !VD->isInvalidDecl()) {
11032       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
11033       if (Context.getDeclAlign(VD) > MaxAlignChars) {
11034         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
11035           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
11036           << (unsigned)MaxAlignChars.getQuantity();
11037       }
11038     }
11039   }
11040 
11041   if (VD->isStaticLocal()) {
11042     if (FunctionDecl *FD =
11043             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
11044       // Static locals inherit dll attributes from their function.
11045       if (Attr *A = getDLLAttr(FD)) {
11046         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11047         NewAttr->setInherited(true);
11048         VD->addAttr(NewAttr);
11049       }
11050       // CUDA E.2.9.4: Within the body of a __device__ or __global__
11051       // function, only __shared__ variables may be declared with
11052       // static storage class.
11053       if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
11054           CUDADiagIfDeviceCode(VD->getLocation(),
11055                                diag::err_device_static_local_var)
11056               << CurrentCUDATarget())
11057         VD->setInvalidDecl();
11058     }
11059   }
11060 
11061   // Perform check for initializers of device-side global variables.
11062   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
11063   // 7.5). We must also apply the same checks to all __shared__
11064   // variables whether they are local or not. CUDA also allows
11065   // constant initializers for __constant__ and __device__ variables.
11066   if (getLangOpts().CUDA) {
11067     const Expr *Init = VD->getInit();
11068     if (Init && VD->hasGlobalStorage()) {
11069       if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
11070           VD->hasAttr<CUDASharedAttr>()) {
11071         assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
11072         bool AllowedInit = false;
11073         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
11074           AllowedInit =
11075               isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
11076         // We'll allow constant initializers even if it's a non-empty
11077         // constructor according to CUDA rules. This deviates from NVCC,
11078         // but allows us to handle things like constexpr constructors.
11079         if (!AllowedInit &&
11080             (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
11081           AllowedInit = VD->getInit()->isConstantInitializer(
11082               Context, VD->getType()->isReferenceType());
11083 
11084         // Also make sure that destructor, if there is one, is empty.
11085         if (AllowedInit)
11086           if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
11087             AllowedInit =
11088                 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
11089 
11090         if (!AllowedInit) {
11091           Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
11092                                       ? diag::err_shared_var_init
11093                                       : diag::err_dynamic_var_init)
11094               << Init->getSourceRange();
11095           VD->setInvalidDecl();
11096         }
11097       } else {
11098         // This is a host-side global variable.  Check that the initializer is
11099         // callable from the host side.
11100         const FunctionDecl *InitFn = nullptr;
11101         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
11102           InitFn = CE->getConstructor();
11103         } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
11104           InitFn = CE->getDirectCallee();
11105         }
11106         if (InitFn) {
11107           CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
11108           if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
11109             Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
11110                 << InitFnTarget << InitFn;
11111             Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
11112             VD->setInvalidDecl();
11113           }
11114         }
11115       }
11116     }
11117   }
11118 
11119   // Grab the dllimport or dllexport attribute off of the VarDecl.
11120   const InheritableAttr *DLLAttr = getDLLAttr(VD);
11121 
11122   // Imported static data members cannot be defined out-of-line.
11123   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
11124     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
11125         VD->isThisDeclarationADefinition()) {
11126       // We allow definitions of dllimport class template static data members
11127       // with a warning.
11128       CXXRecordDecl *Context =
11129         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
11130       bool IsClassTemplateMember =
11131           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
11132           Context->getDescribedClassTemplate();
11133 
11134       Diag(VD->getLocation(),
11135            IsClassTemplateMember
11136                ? diag::warn_attribute_dllimport_static_field_definition
11137                : diag::err_attribute_dllimport_static_field_definition);
11138       Diag(IA->getLocation(), diag::note_attribute);
11139       if (!IsClassTemplateMember)
11140         VD->setInvalidDecl();
11141     }
11142   }
11143 
11144   // dllimport/dllexport variables cannot be thread local, their TLS index
11145   // isn't exported with the variable.
11146   if (DLLAttr && VD->getTLSKind()) {
11147     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11148     if (F && getDLLAttr(F)) {
11149       assert(VD->isStaticLocal());
11150       // But if this is a static local in a dlimport/dllexport function, the
11151       // function will never be inlined, which means the var would never be
11152       // imported, so having it marked import/export is safe.
11153     } else {
11154       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
11155                                                                     << DLLAttr;
11156       VD->setInvalidDecl();
11157     }
11158   }
11159 
11160   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
11161     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
11162       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11163       VD->dropAttr<UsedAttr>();
11164     }
11165   }
11166 
11167   const DeclContext *DC = VD->getDeclContext();
11168   // If there's a #pragma GCC visibility in scope, and this isn't a class
11169   // member, set the visibility of this variable.
11170   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11171     AddPushedVisibilityAttribute(VD);
11172 
11173   // FIXME: Warn on unused templates.
11174   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
11175       !isa<VarTemplatePartialSpecializationDecl>(VD))
11176     MarkUnusedFileScopedDecl(VD);
11177 
11178   // Now we have parsed the initializer and can update the table of magic
11179   // tag values.
11180   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11181       !VD->getType()->isIntegralOrEnumerationType())
11182     return;
11183 
11184   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11185     const Expr *MagicValueExpr = VD->getInit();
11186     if (!MagicValueExpr) {
11187       continue;
11188     }
11189     llvm::APSInt MagicValueInt;
11190     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11191       Diag(I->getRange().getBegin(),
11192            diag::err_type_tag_for_datatype_not_ice)
11193         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11194       continue;
11195     }
11196     if (MagicValueInt.getActiveBits() > 64) {
11197       Diag(I->getRange().getBegin(),
11198            diag::err_type_tag_for_datatype_too_large)
11199         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11200       continue;
11201     }
11202     uint64_t MagicValue = MagicValueInt.getZExtValue();
11203     RegisterTypeTagForDatatype(I->getArgumentKind(),
11204                                MagicValue,
11205                                I->getMatchingCType(),
11206                                I->getLayoutCompatible(),
11207                                I->getMustBeNull());
11208   }
11209 }
11210 
11211 static bool hasDeducedAuto(DeclaratorDecl *DD) {
11212   auto *VD = dyn_cast<VarDecl>(DD);
11213   return VD && !VD->getType()->hasAutoForTrailingReturnType();
11214 }
11215 
11216 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
11217                                                    ArrayRef<Decl *> Group) {
11218   SmallVector<Decl*, 8> Decls;
11219 
11220   if (DS.isTypeSpecOwned())
11221     Decls.push_back(DS.getRepAsDecl());
11222 
11223   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11224   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11225   bool DiagnosedMultipleDecomps = false;
11226   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
11227   bool DiagnosedNonDeducedAuto = false;
11228 
11229   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11230     if (Decl *D = Group[i]) {
11231       // For declarators, there are some additional syntactic-ish checks we need
11232       // to perform.
11233       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11234         if (!FirstDeclaratorInGroup)
11235           FirstDeclaratorInGroup = DD;
11236         if (!FirstDecompDeclaratorInGroup)
11237           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
11238         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
11239             !hasDeducedAuto(DD))
11240           FirstNonDeducedAutoInGroup = DD;
11241 
11242         if (FirstDeclaratorInGroup != DD) {
11243           // A decomposition declaration cannot be combined with any other
11244           // declaration in the same group.
11245           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
11246             Diag(FirstDecompDeclaratorInGroup->getLocation(),
11247                  diag::err_decomp_decl_not_alone)
11248                 << FirstDeclaratorInGroup->getSourceRange()
11249                 << DD->getSourceRange();
11250             DiagnosedMultipleDecomps = true;
11251           }
11252 
11253           // A declarator that uses 'auto' in any way other than to declare a
11254           // variable with a deduced type cannot be combined with any other
11255           // declarator in the same group.
11256           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
11257             Diag(FirstNonDeducedAutoInGroup->getLocation(),
11258                  diag::err_auto_non_deduced_not_alone)
11259                 << FirstNonDeducedAutoInGroup->getType()
11260                        ->hasAutoForTrailingReturnType()
11261                 << FirstDeclaratorInGroup->getSourceRange()
11262                 << DD->getSourceRange();
11263             DiagnosedNonDeducedAuto = true;
11264           }
11265         }
11266       }
11267 
11268       Decls.push_back(D);
11269     }
11270   }
11271 
11272   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11273     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11274       handleTagNumbering(Tag, S);
11275       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11276           getLangOpts().CPlusPlus)
11277         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11278     }
11279   }
11280 
11281   return BuildDeclaratorGroup(Decls);
11282 }
11283 
11284 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11285 /// group, performing any necessary semantic checking.
11286 Sema::DeclGroupPtrTy
11287 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
11288   // C++14 [dcl.spec.auto]p7: (DR1347)
11289   //   If the type that replaces the placeholder type is not the same in each
11290   //   deduction, the program is ill-formed.
11291   if (Group.size() > 1) {
11292     QualType Deduced;
11293     VarDecl *DeducedDecl = nullptr;
11294     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11295       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
11296       if (!D || D->isInvalidDecl())
11297         break;
11298       DeducedType *DT = D->getType()->getContainedDeducedType();
11299       if (!DT || DT->getDeducedType().isNull())
11300         continue;
11301       if (Deduced.isNull()) {
11302         Deduced = DT->getDeducedType();
11303         DeducedDecl = D;
11304       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
11305         auto *AT = dyn_cast<AutoType>(DT);
11306         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11307              diag::err_auto_different_deductions)
11308           << (AT ? (unsigned)AT->getKeyword() : 3)
11309           << Deduced << DeducedDecl->getDeclName()
11310           << DT->getDeducedType() << D->getDeclName()
11311           << DeducedDecl->getInit()->getSourceRange()
11312           << D->getInit()->getSourceRange();
11313         D->setInvalidDecl();
11314         break;
11315       }
11316     }
11317   }
11318 
11319   ActOnDocumentableDecls(Group);
11320 
11321   return DeclGroupPtrTy::make(
11322       DeclGroupRef::Create(Context, Group.data(), Group.size()));
11323 }
11324 
11325 void Sema::ActOnDocumentableDecl(Decl *D) {
11326   ActOnDocumentableDecls(D);
11327 }
11328 
11329 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11330   // Don't parse the comment if Doxygen diagnostics are ignored.
11331   if (Group.empty() || !Group[0])
11332     return;
11333 
11334   if (Diags.isIgnored(diag::warn_doc_param_not_found,
11335                       Group[0]->getLocation()) &&
11336       Diags.isIgnored(diag::warn_unknown_comment_command_name,
11337                       Group[0]->getLocation()))
11338     return;
11339 
11340   if (Group.size() >= 2) {
11341     // This is a decl group.  Normally it will contain only declarations
11342     // produced from declarator list.  But in case we have any definitions or
11343     // additional declaration references:
11344     //   'typedef struct S {} S;'
11345     //   'typedef struct S *S;'
11346     //   'struct S *pS;'
11347     // FinalizeDeclaratorGroup adds these as separate declarations.
11348     Decl *MaybeTagDecl = Group[0];
11349     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11350       Group = Group.slice(1);
11351     }
11352   }
11353 
11354   // See if there are any new comments that are not attached to a decl.
11355   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11356   if (!Comments.empty() &&
11357       !Comments.back()->isAttached()) {
11358     // There is at least one comment that not attached to a decl.
11359     // Maybe it should be attached to one of these decls?
11360     //
11361     // Note that this way we pick up not only comments that precede the
11362     // declaration, but also comments that *follow* the declaration -- thanks to
11363     // the lookahead in the lexer: we've consumed the semicolon and looked
11364     // ahead through comments.
11365     for (unsigned i = 0, e = Group.size(); i != e; ++i)
11366       Context.getCommentForDecl(Group[i], &PP);
11367   }
11368 }
11369 
11370 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11371 /// to introduce parameters into function prototype scope.
11372 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11373   const DeclSpec &DS = D.getDeclSpec();
11374 
11375   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11376 
11377   // C++03 [dcl.stc]p2 also permits 'auto'.
11378   StorageClass SC = SC_None;
11379   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11380     SC = SC_Register;
11381   } else if (getLangOpts().CPlusPlus &&
11382              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11383     SC = SC_Auto;
11384   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11385     Diag(DS.getStorageClassSpecLoc(),
11386          diag::err_invalid_storage_class_in_func_decl);
11387     D.getMutableDeclSpec().ClearStorageClassSpecs();
11388   }
11389 
11390   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11391     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11392       << DeclSpec::getSpecifierName(TSCS);
11393   if (DS.isInlineSpecified())
11394     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11395         << getLangOpts().CPlusPlus1z;
11396   if (DS.isConstexprSpecified())
11397     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11398       << 0;
11399   if (DS.isConceptSpecified())
11400     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
11401 
11402   DiagnoseFunctionSpecifiers(DS);
11403 
11404   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11405   QualType parmDeclType = TInfo->getType();
11406 
11407   if (getLangOpts().CPlusPlus) {
11408     // Check that there are no default arguments inside the type of this
11409     // parameter.
11410     CheckExtraCXXDefaultArguments(D);
11411 
11412     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11413     if (D.getCXXScopeSpec().isSet()) {
11414       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11415         << D.getCXXScopeSpec().getRange();
11416       D.getCXXScopeSpec().clear();
11417     }
11418   }
11419 
11420   // Ensure we have a valid name
11421   IdentifierInfo *II = nullptr;
11422   if (D.hasName()) {
11423     II = D.getIdentifier();
11424     if (!II) {
11425       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11426         << GetNameForDeclarator(D).getName();
11427       D.setInvalidType(true);
11428     }
11429   }
11430 
11431   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11432   if (II) {
11433     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
11434                    ForRedeclaration);
11435     LookupName(R, S);
11436     if (R.isSingleResult()) {
11437       NamedDecl *PrevDecl = R.getFoundDecl();
11438       if (PrevDecl->isTemplateParameter()) {
11439         // Maybe we will complain about the shadowed template parameter.
11440         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11441         // Just pretend that we didn't see the previous declaration.
11442         PrevDecl = nullptr;
11443       } else if (S->isDeclScope(PrevDecl)) {
11444         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
11445         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11446 
11447         // Recover by removing the name
11448         II = nullptr;
11449         D.SetIdentifier(nullptr, D.getIdentifierLoc());
11450         D.setInvalidType(true);
11451       }
11452     }
11453   }
11454 
11455   // Temporarily put parameter variables in the translation unit, not
11456   // the enclosing context.  This prevents them from accidentally
11457   // looking like class members in C++.
11458   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
11459                                     D.getLocStart(),
11460                                     D.getIdentifierLoc(), II,
11461                                     parmDeclType, TInfo,
11462                                     SC);
11463 
11464   if (D.isInvalidType())
11465     New->setInvalidDecl();
11466 
11467   assert(S->isFunctionPrototypeScope());
11468   assert(S->getFunctionPrototypeDepth() >= 1);
11469   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
11470                     S->getNextFunctionPrototypeIndex());
11471 
11472   // Add the parameter declaration into this scope.
11473   S->AddDecl(New);
11474   if (II)
11475     IdResolver.AddDecl(New);
11476 
11477   ProcessDeclAttributes(S, New, D);
11478 
11479   if (D.getDeclSpec().isModulePrivateSpecified())
11480     Diag(New->getLocation(), diag::err_module_private_local)
11481       << 1 << New->getDeclName()
11482       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11483       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11484 
11485   if (New->hasAttr<BlocksAttr>()) {
11486     Diag(New->getLocation(), diag::err_block_on_nonlocal);
11487   }
11488   return New;
11489 }
11490 
11491 /// \brief Synthesizes a variable for a parameter arising from a
11492 /// typedef.
11493 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
11494                                               SourceLocation Loc,
11495                                               QualType T) {
11496   /* FIXME: setting StartLoc == Loc.
11497      Would it be worth to modify callers so as to provide proper source
11498      location for the unnamed parameters, embedding the parameter's type? */
11499   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
11500                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
11501                                            SC_None, nullptr);
11502   Param->setImplicit();
11503   return Param;
11504 }
11505 
11506 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
11507   // Don't diagnose unused-parameter errors in template instantiations; we
11508   // will already have done so in the template itself.
11509   if (inTemplateInstantiation())
11510     return;
11511 
11512   for (const ParmVarDecl *Parameter : Parameters) {
11513     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
11514         !Parameter->hasAttr<UnusedAttr>()) {
11515       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
11516         << Parameter->getDeclName();
11517     }
11518   }
11519 }
11520 
11521 void Sema::DiagnoseSizeOfParametersAndReturnValue(
11522     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
11523   if (LangOpts.NumLargeByValueCopy == 0) // No check.
11524     return;
11525 
11526   // Warn if the return value is pass-by-value and larger than the specified
11527   // threshold.
11528   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
11529     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
11530     if (Size > LangOpts.NumLargeByValueCopy)
11531       Diag(D->getLocation(), diag::warn_return_value_size)
11532           << D->getDeclName() << Size;
11533   }
11534 
11535   // Warn if any parameter is pass-by-value and larger than the specified
11536   // threshold.
11537   for (const ParmVarDecl *Parameter : Parameters) {
11538     QualType T = Parameter->getType();
11539     if (T->isDependentType() || !T.isPODType(Context))
11540       continue;
11541     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
11542     if (Size > LangOpts.NumLargeByValueCopy)
11543       Diag(Parameter->getLocation(), diag::warn_parameter_size)
11544           << Parameter->getDeclName() << Size;
11545   }
11546 }
11547 
11548 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
11549                                   SourceLocation NameLoc, IdentifierInfo *Name,
11550                                   QualType T, TypeSourceInfo *TSInfo,
11551                                   StorageClass SC) {
11552   // In ARC, infer a lifetime qualifier for appropriate parameter types.
11553   if (getLangOpts().ObjCAutoRefCount &&
11554       T.getObjCLifetime() == Qualifiers::OCL_None &&
11555       T->isObjCLifetimeType()) {
11556 
11557     Qualifiers::ObjCLifetime lifetime;
11558 
11559     // Special cases for arrays:
11560     //   - if it's const, use __unsafe_unretained
11561     //   - otherwise, it's an error
11562     if (T->isArrayType()) {
11563       if (!T.isConstQualified()) {
11564         DelayedDiagnostics.add(
11565             sema::DelayedDiagnostic::makeForbiddenType(
11566             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
11567       }
11568       lifetime = Qualifiers::OCL_ExplicitNone;
11569     } else {
11570       lifetime = T->getObjCARCImplicitLifetime();
11571     }
11572     T = Context.getLifetimeQualifiedType(T, lifetime);
11573   }
11574 
11575   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
11576                                          Context.getAdjustedParameterType(T),
11577                                          TSInfo, SC, nullptr);
11578 
11579   // Parameters can not be abstract class types.
11580   // For record types, this is done by the AbstractClassUsageDiagnoser once
11581   // the class has been completely parsed.
11582   if (!CurContext->isRecord() &&
11583       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11584                              AbstractParamType))
11585     New->setInvalidDecl();
11586 
11587   // Parameter declarators cannot be interface types. All ObjC objects are
11588   // passed by reference.
11589   if (T->isObjCObjectType()) {
11590     SourceLocation TypeEndLoc =
11591         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11592     Diag(NameLoc,
11593          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11594       << FixItHint::CreateInsertion(TypeEndLoc, "*");
11595     T = Context.getObjCObjectPointerType(T);
11596     New->setType(T);
11597   }
11598 
11599   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11600   // duration shall not be qualified by an address-space qualifier."
11601   // Since all parameters have automatic store duration, they can not have
11602   // an address space.
11603   if (T.getAddressSpace() != 0) {
11604     // OpenCL allows function arguments declared to be an array of a type
11605     // to be qualified with an address space.
11606     if (!(getLangOpts().OpenCL && T->isArrayType())) {
11607       Diag(NameLoc, diag::err_arg_with_address_space);
11608       New->setInvalidDecl();
11609     }
11610   }
11611 
11612   return New;
11613 }
11614 
11615 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11616                                            SourceLocation LocAfterDecls) {
11617   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11618 
11619   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11620   // for a K&R function.
11621   if (!FTI.hasPrototype) {
11622     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11623       --i;
11624       if (FTI.Params[i].Param == nullptr) {
11625         SmallString<256> Code;
11626         llvm::raw_svector_ostream(Code)
11627             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
11628         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11629             << FTI.Params[i].Ident
11630             << FixItHint::CreateInsertion(LocAfterDecls, Code);
11631 
11632         // Implicitly declare the argument as type 'int' for lack of a better
11633         // type.
11634         AttributeFactory attrs;
11635         DeclSpec DS(attrs);
11636         const char* PrevSpec; // unused
11637         unsigned DiagID; // unused
11638         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11639                            DiagID, Context.getPrintingPolicy());
11640         // Use the identifier location for the type source range.
11641         DS.SetRangeStart(FTI.Params[i].IdentLoc);
11642         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11643         Declarator ParamD(DS, Declarator::KNRTypeListContext);
11644         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11645         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11646       }
11647     }
11648   }
11649 }
11650 
11651 Decl *
11652 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11653                               MultiTemplateParamsArg TemplateParameterLists,
11654                               SkipBodyInfo *SkipBody) {
11655   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11656   assert(D.isFunctionDeclarator() && "Not a function declarator!");
11657   Scope *ParentScope = FnBodyScope->getParent();
11658 
11659   D.setFunctionDefinitionKind(FDK_Definition);
11660   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11661   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11662 }
11663 
11664 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11665   Consumer.HandleInlineFunctionDefinition(D);
11666 }
11667 
11668 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11669                              const FunctionDecl*& PossibleZeroParamPrototype) {
11670   // Don't warn about invalid declarations.
11671   if (FD->isInvalidDecl())
11672     return false;
11673 
11674   // Or declarations that aren't global.
11675   if (!FD->isGlobal())
11676     return false;
11677 
11678   // Don't warn about C++ member functions.
11679   if (isa<CXXMethodDecl>(FD))
11680     return false;
11681 
11682   // Don't warn about 'main'.
11683   if (FD->isMain())
11684     return false;
11685 
11686   // Don't warn about inline functions.
11687   if (FD->isInlined())
11688     return false;
11689 
11690   // Don't warn about function templates.
11691   if (FD->getDescribedFunctionTemplate())
11692     return false;
11693 
11694   // Don't warn about function template specializations.
11695   if (FD->isFunctionTemplateSpecialization())
11696     return false;
11697 
11698   // Don't warn for OpenCL kernels.
11699   if (FD->hasAttr<OpenCLKernelAttr>())
11700     return false;
11701 
11702   // Don't warn on explicitly deleted functions.
11703   if (FD->isDeleted())
11704     return false;
11705 
11706   bool MissingPrototype = true;
11707   for (const FunctionDecl *Prev = FD->getPreviousDecl();
11708        Prev; Prev = Prev->getPreviousDecl()) {
11709     // Ignore any declarations that occur in function or method
11710     // scope, because they aren't visible from the header.
11711     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11712       continue;
11713 
11714     MissingPrototype = !Prev->getType()->isFunctionProtoType();
11715     if (FD->getNumParams() == 0)
11716       PossibleZeroParamPrototype = Prev;
11717     break;
11718   }
11719 
11720   return MissingPrototype;
11721 }
11722 
11723 void
11724 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11725                                    const FunctionDecl *EffectiveDefinition,
11726                                    SkipBodyInfo *SkipBody) {
11727   const FunctionDecl *Definition = EffectiveDefinition;
11728   if (!Definition)
11729     if (!FD->isDefined(Definition))
11730       return;
11731 
11732   if (canRedefineFunction(Definition, getLangOpts()))
11733     return;
11734 
11735   // If we don't have a visible definition of the function, and it's inline or
11736   // a template, skip the new definition.
11737   if (SkipBody && !hasVisibleDefinition(Definition) &&
11738       (Definition->getFormalLinkage() == InternalLinkage ||
11739        Definition->isInlined() ||
11740        Definition->getDescribedFunctionTemplate() ||
11741        Definition->getNumTemplateParameterLists())) {
11742     SkipBody->ShouldSkip = true;
11743     if (auto *TD = Definition->getDescribedFunctionTemplate())
11744       makeMergedDefinitionVisible(TD, FD->getLocation());
11745     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
11746                                 FD->getLocation());
11747     return;
11748   }
11749 
11750   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11751       Definition->getStorageClass() == SC_Extern)
11752     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11753         << FD->getDeclName() << getLangOpts().CPlusPlus;
11754   else
11755     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11756 
11757   Diag(Definition->getLocation(), diag::note_previous_definition);
11758   FD->setInvalidDecl();
11759 }
11760 
11761 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11762                                    Sema &S) {
11763   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11764 
11765   LambdaScopeInfo *LSI = S.PushLambdaScope();
11766   LSI->CallOperator = CallOperator;
11767   LSI->Lambda = LambdaClass;
11768   LSI->ReturnType = CallOperator->getReturnType();
11769   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11770 
11771   if (LCD == LCD_None)
11772     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
11773   else if (LCD == LCD_ByCopy)
11774     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
11775   else if (LCD == LCD_ByRef)
11776     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
11777   DeclarationNameInfo DNI = CallOperator->getNameInfo();
11778 
11779   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
11780   LSI->Mutable = !CallOperator->isConst();
11781 
11782   // Add the captures to the LSI so they can be noted as already
11783   // captured within tryCaptureVar.
11784   auto I = LambdaClass->field_begin();
11785   for (const auto &C : LambdaClass->captures()) {
11786     if (C.capturesVariable()) {
11787       VarDecl *VD = C.getCapturedVar();
11788       if (VD->isInitCapture())
11789         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11790       QualType CaptureType = VD->getType();
11791       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11792       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11793           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11794           /*EllipsisLoc*/C.isPackExpansion()
11795                          ? C.getEllipsisLoc() : SourceLocation(),
11796           CaptureType, /*Expr*/ nullptr);
11797 
11798     } else if (C.capturesThis()) {
11799       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11800                               /*Expr*/ nullptr,
11801                               C.getCaptureKind() == LCK_StarThis);
11802     } else {
11803       LSI->addVLATypeCapture(C.getLocation(), I->getType());
11804     }
11805     ++I;
11806   }
11807 }
11808 
11809 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
11810                                     SkipBodyInfo *SkipBody) {
11811   if (!D)
11812     return D;
11813   FunctionDecl *FD = nullptr;
11814 
11815   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
11816     FD = FunTmpl->getTemplatedDecl();
11817   else
11818     FD = cast<FunctionDecl>(D);
11819 
11820   // Check for defining attributes before the check for redefinition.
11821   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
11822     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
11823     FD->dropAttr<AliasAttr>();
11824     FD->setInvalidDecl();
11825   }
11826   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
11827     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
11828     FD->dropAttr<IFuncAttr>();
11829     FD->setInvalidDecl();
11830   }
11831 
11832   // See if this is a redefinition.
11833   if (!FD->isLateTemplateParsed()) {
11834     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
11835 
11836     // If we're skipping the body, we're done. Don't enter the scope.
11837     if (SkipBody && SkipBody->ShouldSkip)
11838       return D;
11839   }
11840 
11841   // Mark this function as "will have a body eventually".  This lets users to
11842   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
11843   // this function.
11844   FD->setWillHaveBody();
11845 
11846   // If we are instantiating a generic lambda call operator, push
11847   // a LambdaScopeInfo onto the function stack.  But use the information
11848   // that's already been calculated (ActOnLambdaExpr) to prime the current
11849   // LambdaScopeInfo.
11850   // When the template operator is being specialized, the LambdaScopeInfo,
11851   // has to be properly restored so that tryCaptureVariable doesn't try
11852   // and capture any new variables. In addition when calculating potential
11853   // captures during transformation of nested lambdas, it is necessary to
11854   // have the LSI properly restored.
11855   if (isGenericLambdaCallOperatorSpecialization(FD)) {
11856     assert(inTemplateInstantiation() &&
11857            "There should be an active template instantiation on the stack "
11858            "when instantiating a generic lambda!");
11859     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
11860   } else {
11861     // Enter a new function scope
11862     PushFunctionScope();
11863   }
11864 
11865   // Builtin functions cannot be defined.
11866   if (unsigned BuiltinID = FD->getBuiltinID()) {
11867     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
11868         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
11869       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
11870       FD->setInvalidDecl();
11871     }
11872   }
11873 
11874   // The return type of a function definition must be complete
11875   // (C99 6.9.1p3, C++ [dcl.fct]p6).
11876   QualType ResultType = FD->getReturnType();
11877   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
11878       !FD->isInvalidDecl() &&
11879       RequireCompleteType(FD->getLocation(), ResultType,
11880                           diag::err_func_def_incomplete_result))
11881     FD->setInvalidDecl();
11882 
11883   if (FnBodyScope)
11884     PushDeclContext(FnBodyScope, FD);
11885 
11886   // Check the validity of our function parameters
11887   CheckParmsForFunctionDef(FD->parameters(),
11888                            /*CheckParameterNames=*/true);
11889 
11890   // Add non-parameter declarations already in the function to the current
11891   // scope.
11892   if (FnBodyScope) {
11893     for (Decl *NPD : FD->decls()) {
11894       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
11895       if (!NonParmDecl)
11896         continue;
11897       assert(!isa<ParmVarDecl>(NonParmDecl) &&
11898              "parameters should not be in newly created FD yet");
11899 
11900       // If the decl has a name, make it accessible in the current scope.
11901       if (NonParmDecl->getDeclName())
11902         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
11903 
11904       // Similarly, dive into enums and fish their constants out, making them
11905       // accessible in this scope.
11906       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
11907         for (auto *EI : ED->enumerators())
11908           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
11909       }
11910     }
11911   }
11912 
11913   // Introduce our parameters into the function scope
11914   for (auto Param : FD->parameters()) {
11915     Param->setOwningFunction(FD);
11916 
11917     // If this has an identifier, add it to the scope stack.
11918     if (Param->getIdentifier() && FnBodyScope) {
11919       CheckShadow(FnBodyScope, Param);
11920 
11921       PushOnScopeChains(Param, FnBodyScope);
11922     }
11923   }
11924 
11925   // Ensure that the function's exception specification is instantiated.
11926   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
11927     ResolveExceptionSpec(D->getLocation(), FPT);
11928 
11929   // dllimport cannot be applied to non-inline function definitions.
11930   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
11931       !FD->isTemplateInstantiation()) {
11932     assert(!FD->hasAttr<DLLExportAttr>());
11933     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
11934     FD->setInvalidDecl();
11935     return D;
11936   }
11937   // We want to attach documentation to original Decl (which might be
11938   // a function template).
11939   ActOnDocumentableDecl(D);
11940   if (getCurLexicalContext()->isObjCContainer() &&
11941       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
11942       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
11943     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
11944 
11945   return D;
11946 }
11947 
11948 /// \brief Given the set of return statements within a function body,
11949 /// compute the variables that are subject to the named return value
11950 /// optimization.
11951 ///
11952 /// Each of the variables that is subject to the named return value
11953 /// optimization will be marked as NRVO variables in the AST, and any
11954 /// return statement that has a marked NRVO variable as its NRVO candidate can
11955 /// use the named return value optimization.
11956 ///
11957 /// This function applies a very simplistic algorithm for NRVO: if every return
11958 /// statement in the scope of a variable has the same NRVO candidate, that
11959 /// candidate is an NRVO variable.
11960 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
11961   ReturnStmt **Returns = Scope->Returns.data();
11962 
11963   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
11964     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
11965       if (!NRVOCandidate->isNRVOVariable())
11966         Returns[I]->setNRVOCandidate(nullptr);
11967     }
11968   }
11969 }
11970 
11971 bool Sema::canDelayFunctionBody(const Declarator &D) {
11972   // We can't delay parsing the body of a constexpr function template (yet).
11973   if (D.getDeclSpec().isConstexprSpecified())
11974     return false;
11975 
11976   // We can't delay parsing the body of a function template with a deduced
11977   // return type (yet).
11978   if (D.getDeclSpec().hasAutoTypeSpec()) {
11979     // If the placeholder introduces a non-deduced trailing return type,
11980     // we can still delay parsing it.
11981     if (D.getNumTypeObjects()) {
11982       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11983       if (Outer.Kind == DeclaratorChunk::Function &&
11984           Outer.Fun.hasTrailingReturnType()) {
11985         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11986         return Ty.isNull() || !Ty->isUndeducedType();
11987       }
11988     }
11989     return false;
11990   }
11991 
11992   return true;
11993 }
11994 
11995 bool Sema::canSkipFunctionBody(Decl *D) {
11996   // We cannot skip the body of a function (or function template) which is
11997   // constexpr, since we may need to evaluate its body in order to parse the
11998   // rest of the file.
11999   // We cannot skip the body of a function with an undeduced return type,
12000   // because any callers of that function need to know the type.
12001   if (const FunctionDecl *FD = D->getAsFunction())
12002     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
12003       return false;
12004   return Consumer.shouldSkipFunctionBody(D);
12005 }
12006 
12007 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
12008   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
12009     FD->setHasSkippedBody();
12010   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
12011     MD->setHasSkippedBody();
12012   return Decl;
12013 }
12014 
12015 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
12016   return ActOnFinishFunctionBody(D, BodyArg, false);
12017 }
12018 
12019 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
12020                                     bool IsInstantiation) {
12021   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
12022 
12023   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12024   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
12025 
12026   if (getLangOpts().CoroutinesTS && getCurFunction()->CoroutinePromise)
12027     CheckCompletedCoroutineBody(FD, Body);
12028 
12029   if (FD) {
12030     FD->setBody(Body);
12031 
12032     if (getLangOpts().CPlusPlus14) {
12033       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
12034           FD->getReturnType()->isUndeducedType()) {
12035         // If the function has a deduced result type but contains no 'return'
12036         // statements, the result type as written must be exactly 'auto', and
12037         // the deduced result type is 'void'.
12038         if (!FD->getReturnType()->getAs<AutoType>()) {
12039           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
12040               << FD->getReturnType();
12041           FD->setInvalidDecl();
12042         } else {
12043           // Substitute 'void' for the 'auto' in the type.
12044           TypeLoc ResultType = getReturnTypeLoc(FD);
12045           Context.adjustDeducedFunctionResultType(
12046               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
12047         }
12048       }
12049     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
12050       // In C++11, we don't use 'auto' deduction rules for lambda call
12051       // operators because we don't support return type deduction.
12052       auto *LSI = getCurLambda();
12053       if (LSI->HasImplicitReturnType) {
12054         deduceClosureReturnType(*LSI);
12055 
12056         // C++11 [expr.prim.lambda]p4:
12057         //   [...] if there are no return statements in the compound-statement
12058         //   [the deduced type is] the type void
12059         QualType RetType =
12060             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
12061 
12062         // Update the return type to the deduced type.
12063         const FunctionProtoType *Proto =
12064             FD->getType()->getAs<FunctionProtoType>();
12065         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
12066                                             Proto->getExtProtoInfo()));
12067       }
12068     }
12069 
12070     // The only way to be included in UndefinedButUsed is if there is an
12071     // ODR use before the definition. Avoid the expensive map lookup if this
12072     // is the first declaration.
12073     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
12074       if (!FD->isExternallyVisible())
12075         UndefinedButUsed.erase(FD);
12076       else if (FD->isInlined() &&
12077                !LangOpts.GNUInline &&
12078                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
12079         UndefinedButUsed.erase(FD);
12080     }
12081 
12082     // If the function implicitly returns zero (like 'main') or is naked,
12083     // don't complain about missing return statements.
12084     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
12085       WP.disableCheckFallThrough();
12086 
12087     // MSVC permits the use of pure specifier (=0) on function definition,
12088     // defined at class scope, warn about this non-standard construct.
12089     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
12090       Diag(FD->getLocation(), diag::ext_pure_function_definition);
12091 
12092     if (!FD->isInvalidDecl()) {
12093       // Don't diagnose unused parameters of defaulted or deleted functions.
12094       if (!FD->isDeleted() && !FD->isDefaulted())
12095         DiagnoseUnusedParameters(FD->parameters());
12096       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
12097                                              FD->getReturnType(), FD);
12098 
12099       // If this is a structor, we need a vtable.
12100       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
12101         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
12102       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
12103         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
12104 
12105       // Try to apply the named return value optimization. We have to check
12106       // if we can do this here because lambdas keep return statements around
12107       // to deduce an implicit return type.
12108       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
12109           !FD->isDependentContext())
12110         computeNRVO(Body, getCurFunction());
12111     }
12112 
12113     // GNU warning -Wmissing-prototypes:
12114     //   Warn if a global function is defined without a previous
12115     //   prototype declaration. This warning is issued even if the
12116     //   definition itself provides a prototype. The aim is to detect
12117     //   global functions that fail to be declared in header files.
12118     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
12119     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
12120       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
12121 
12122       if (PossibleZeroParamPrototype) {
12123         // We found a declaration that is not a prototype,
12124         // but that could be a zero-parameter prototype
12125         if (TypeSourceInfo *TI =
12126                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
12127           TypeLoc TL = TI->getTypeLoc();
12128           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
12129             Diag(PossibleZeroParamPrototype->getLocation(),
12130                  diag::note_declaration_not_a_prototype)
12131                 << PossibleZeroParamPrototype
12132                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
12133         }
12134       }
12135 
12136       // GNU warning -Wstrict-prototypes
12137       //   Warn if K&R function is defined without a previous declaration.
12138       //   This warning is issued only if the definition itself does not provide
12139       //   a prototype. Only K&R definitions do not provide a prototype.
12140       //   An empty list in a function declarator that is part of a definition
12141       //   of that function specifies that the function has no parameters
12142       //   (C99 6.7.5.3p14)
12143       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
12144           !LangOpts.CPlusPlus) {
12145         TypeSourceInfo *TI = FD->getTypeSourceInfo();
12146         TypeLoc TL = TI->getTypeLoc();
12147         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
12148         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 1;
12149       }
12150     }
12151 
12152     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12153       const CXXMethodDecl *KeyFunction;
12154       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
12155           MD->isVirtual() &&
12156           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
12157           MD == KeyFunction->getCanonicalDecl()) {
12158         // Update the key-function state if necessary for this ABI.
12159         if (FD->isInlined() &&
12160             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12161           Context.setNonKeyFunction(MD);
12162 
12163           // If the newly-chosen key function is already defined, then we
12164           // need to mark the vtable as used retroactively.
12165           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
12166           const FunctionDecl *Definition;
12167           if (KeyFunction && KeyFunction->isDefined(Definition))
12168             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
12169         } else {
12170           // We just defined they key function; mark the vtable as used.
12171           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
12172         }
12173       }
12174     }
12175 
12176     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
12177            "Function parsing confused");
12178   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
12179     assert(MD == getCurMethodDecl() && "Method parsing confused");
12180     MD->setBody(Body);
12181     if (!MD->isInvalidDecl()) {
12182       DiagnoseUnusedParameters(MD->parameters());
12183       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
12184                                              MD->getReturnType(), MD);
12185 
12186       if (Body)
12187         computeNRVO(Body, getCurFunction());
12188     }
12189     if (getCurFunction()->ObjCShouldCallSuper) {
12190       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
12191         << MD->getSelector().getAsString();
12192       getCurFunction()->ObjCShouldCallSuper = false;
12193     }
12194     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12195       const ObjCMethodDecl *InitMethod = nullptr;
12196       bool isDesignated =
12197           MD->isDesignatedInitializerForTheInterface(&InitMethod);
12198       assert(isDesignated && InitMethod);
12199       (void)isDesignated;
12200 
12201       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12202         auto IFace = MD->getClassInterface();
12203         if (!IFace)
12204           return false;
12205         auto SuperD = IFace->getSuperClass();
12206         if (!SuperD)
12207           return false;
12208         return SuperD->getIdentifier() ==
12209             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12210       };
12211       // Don't issue this warning for unavailable inits or direct subclasses
12212       // of NSObject.
12213       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12214         Diag(MD->getLocation(),
12215              diag::warn_objc_designated_init_missing_super_call);
12216         Diag(InitMethod->getLocation(),
12217              diag::note_objc_designated_init_marked_here);
12218       }
12219       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12220     }
12221     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12222       // Don't issue this warning for unavaialable inits.
12223       if (!MD->isUnavailable())
12224         Diag(MD->getLocation(),
12225              diag::warn_objc_secondary_init_missing_init_call);
12226       getCurFunction()->ObjCWarnForNoInitDelegation = false;
12227     }
12228   } else {
12229     return nullptr;
12230   }
12231 
12232   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12233     DiagnoseUnguardedAvailabilityViolations(dcl);
12234 
12235   assert(!getCurFunction()->ObjCShouldCallSuper &&
12236          "This should only be set for ObjC methods, which should have been "
12237          "handled in the block above.");
12238 
12239   // Verify and clean out per-function state.
12240   if (Body && (!FD || !FD->isDefaulted())) {
12241     // C++ constructors that have function-try-blocks can't have return
12242     // statements in the handlers of that block. (C++ [except.handle]p14)
12243     // Verify this.
12244     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12245       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12246 
12247     // Verify that gotos and switch cases don't jump into scopes illegally.
12248     if (getCurFunction()->NeedsScopeChecking() &&
12249         !PP.isCodeCompletionEnabled())
12250       DiagnoseInvalidJumps(Body);
12251 
12252     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12253       if (!Destructor->getParent()->isDependentType())
12254         CheckDestructor(Destructor);
12255 
12256       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12257                                              Destructor->getParent());
12258     }
12259 
12260     // If any errors have occurred, clear out any temporaries that may have
12261     // been leftover. This ensures that these temporaries won't be picked up for
12262     // deletion in some later function.
12263     if (getDiagnostics().hasErrorOccurred() ||
12264         getDiagnostics().getSuppressAllDiagnostics()) {
12265       DiscardCleanupsInEvaluationContext();
12266     }
12267     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12268         !isa<FunctionTemplateDecl>(dcl)) {
12269       // Since the body is valid, issue any analysis-based warnings that are
12270       // enabled.
12271       ActivePolicy = &WP;
12272     }
12273 
12274     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12275         (!CheckConstexprFunctionDecl(FD) ||
12276          !CheckConstexprFunctionBody(FD, Body)))
12277       FD->setInvalidDecl();
12278 
12279     if (FD && FD->hasAttr<NakedAttr>()) {
12280       for (const Stmt *S : Body->children()) {
12281         // Allow local register variables without initializer as they don't
12282         // require prologue.
12283         bool RegisterVariables = false;
12284         if (auto *DS = dyn_cast<DeclStmt>(S)) {
12285           for (const auto *Decl : DS->decls()) {
12286             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12287               RegisterVariables =
12288                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12289               if (!RegisterVariables)
12290                 break;
12291             }
12292           }
12293         }
12294         if (RegisterVariables)
12295           continue;
12296         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12297           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12298           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12299           FD->setInvalidDecl();
12300           break;
12301         }
12302       }
12303     }
12304 
12305     assert(ExprCleanupObjects.size() ==
12306                ExprEvalContexts.back().NumCleanupObjects &&
12307            "Leftover temporaries in function");
12308     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12309     assert(MaybeODRUseExprs.empty() &&
12310            "Leftover expressions for odr-use checking");
12311   }
12312 
12313   if (!IsInstantiation)
12314     PopDeclContext();
12315 
12316   PopFunctionScopeInfo(ActivePolicy, dcl);
12317   // If any errors have occurred, clear out any temporaries that may have
12318   // been leftover. This ensures that these temporaries won't be picked up for
12319   // deletion in some later function.
12320   if (getDiagnostics().hasErrorOccurred()) {
12321     DiscardCleanupsInEvaluationContext();
12322   }
12323 
12324   return dcl;
12325 }
12326 
12327 /// When we finish delayed parsing of an attribute, we must attach it to the
12328 /// relevant Decl.
12329 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12330                                        ParsedAttributes &Attrs) {
12331   // Always attach attributes to the underlying decl.
12332   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12333     D = TD->getTemplatedDecl();
12334   ProcessDeclAttributeList(S, D, Attrs.getList());
12335 
12336   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12337     if (Method->isStatic())
12338       checkThisInStaticMemberFunctionAttributes(Method);
12339 }
12340 
12341 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12342 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12343 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12344                                           IdentifierInfo &II, Scope *S) {
12345   // Before we produce a declaration for an implicitly defined
12346   // function, see whether there was a locally-scoped declaration of
12347   // this name as a function or variable. If so, use that
12348   // (non-visible) declaration, and complain about it.
12349   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
12350     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
12351     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12352     return ExternCPrev;
12353   }
12354 
12355   // Extension in C99.  Legal in C90, but warn about it.
12356   unsigned diag_id;
12357   if (II.getName().startswith("__builtin_"))
12358     diag_id = diag::warn_builtin_unknown;
12359   else if (getLangOpts().C99)
12360     diag_id = diag::ext_implicit_function_decl;
12361   else
12362     diag_id = diag::warn_implicit_function_decl;
12363   Diag(Loc, diag_id) << &II;
12364 
12365   // Because typo correction is expensive, only do it if the implicit
12366   // function declaration is going to be treated as an error.
12367   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
12368     TypoCorrection Corrected;
12369     if (S &&
12370         (Corrected = CorrectTypo(
12371              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
12372              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
12373       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
12374                    /*ErrorRecovery*/false);
12375   }
12376 
12377   // Set a Declarator for the implicit definition: int foo();
12378   const char *Dummy;
12379   AttributeFactory attrFactory;
12380   DeclSpec DS(attrFactory);
12381   unsigned DiagID;
12382   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
12383                                   Context.getPrintingPolicy());
12384   (void)Error; // Silence warning.
12385   assert(!Error && "Error setting up implicit decl!");
12386   SourceLocation NoLoc;
12387   Declarator D(DS, Declarator::BlockContext);
12388   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
12389                                              /*IsAmbiguous=*/false,
12390                                              /*LParenLoc=*/NoLoc,
12391                                              /*Params=*/nullptr,
12392                                              /*NumParams=*/0,
12393                                              /*EllipsisLoc=*/NoLoc,
12394                                              /*RParenLoc=*/NoLoc,
12395                                              /*TypeQuals=*/0,
12396                                              /*RefQualifierIsLvalueRef=*/true,
12397                                              /*RefQualifierLoc=*/NoLoc,
12398                                              /*ConstQualifierLoc=*/NoLoc,
12399                                              /*VolatileQualifierLoc=*/NoLoc,
12400                                              /*RestrictQualifierLoc=*/NoLoc,
12401                                              /*MutableLoc=*/NoLoc,
12402                                              EST_None,
12403                                              /*ESpecRange=*/SourceRange(),
12404                                              /*Exceptions=*/nullptr,
12405                                              /*ExceptionRanges=*/nullptr,
12406                                              /*NumExceptions=*/0,
12407                                              /*NoexceptExpr=*/nullptr,
12408                                              /*ExceptionSpecTokens=*/nullptr,
12409                                              /*DeclsInPrototype=*/None,
12410                                              Loc, Loc, D),
12411                 DS.getAttributes(),
12412                 SourceLocation());
12413   D.SetIdentifier(&II, Loc);
12414 
12415   // Insert this function into translation-unit scope.
12416 
12417   DeclContext *PrevDC = CurContext;
12418   CurContext = Context.getTranslationUnitDecl();
12419 
12420   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
12421   FD->setImplicit();
12422 
12423   CurContext = PrevDC;
12424 
12425   AddKnownFunctionAttributes(FD);
12426 
12427   return FD;
12428 }
12429 
12430 /// \brief Adds any function attributes that we know a priori based on
12431 /// the declaration of this function.
12432 ///
12433 /// These attributes can apply both to implicitly-declared builtins
12434 /// (like __builtin___printf_chk) or to library-declared functions
12435 /// like NSLog or printf.
12436 ///
12437 /// We need to check for duplicate attributes both here and where user-written
12438 /// attributes are applied to declarations.
12439 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
12440   if (FD->isInvalidDecl())
12441     return;
12442 
12443   // If this is a built-in function, map its builtin attributes to
12444   // actual attributes.
12445   if (unsigned BuiltinID = FD->getBuiltinID()) {
12446     // Handle printf-formatting attributes.
12447     unsigned FormatIdx;
12448     bool HasVAListArg;
12449     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
12450       if (!FD->hasAttr<FormatAttr>()) {
12451         const char *fmt = "printf";
12452         unsigned int NumParams = FD->getNumParams();
12453         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
12454             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
12455           fmt = "NSString";
12456         FD->addAttr(FormatAttr::CreateImplicit(Context,
12457                                                &Context.Idents.get(fmt),
12458                                                FormatIdx+1,
12459                                                HasVAListArg ? 0 : FormatIdx+2,
12460                                                FD->getLocation()));
12461       }
12462     }
12463     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
12464                                              HasVAListArg)) {
12465      if (!FD->hasAttr<FormatAttr>())
12466        FD->addAttr(FormatAttr::CreateImplicit(Context,
12467                                               &Context.Idents.get("scanf"),
12468                                               FormatIdx+1,
12469                                               HasVAListArg ? 0 : FormatIdx+2,
12470                                               FD->getLocation()));
12471     }
12472 
12473     // Mark const if we don't care about errno and that is the only
12474     // thing preventing the function from being const. This allows
12475     // IRgen to use LLVM intrinsics for such functions.
12476     if (!getLangOpts().MathErrno &&
12477         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
12478       if (!FD->hasAttr<ConstAttr>())
12479         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12480     }
12481 
12482     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
12483         !FD->hasAttr<ReturnsTwiceAttr>())
12484       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
12485                                          FD->getLocation()));
12486     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
12487       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12488     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
12489       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
12490     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
12491       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12492     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
12493         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
12494       // Add the appropriate attribute, depending on the CUDA compilation mode
12495       // and which target the builtin belongs to. For example, during host
12496       // compilation, aux builtins are __device__, while the rest are __host__.
12497       if (getLangOpts().CUDAIsDevice !=
12498           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
12499         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
12500       else
12501         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
12502     }
12503   }
12504 
12505   // If C++ exceptions are enabled but we are told extern "C" functions cannot
12506   // throw, add an implicit nothrow attribute to any extern "C" function we come
12507   // across.
12508   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
12509       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
12510     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
12511     if (!FPT || FPT->getExceptionSpecType() == EST_None)
12512       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12513   }
12514 
12515   IdentifierInfo *Name = FD->getIdentifier();
12516   if (!Name)
12517     return;
12518   if ((!getLangOpts().CPlusPlus &&
12519        FD->getDeclContext()->isTranslationUnit()) ||
12520       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
12521        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
12522        LinkageSpecDecl::lang_c)) {
12523     // Okay: this could be a libc/libm/Objective-C function we know
12524     // about.
12525   } else
12526     return;
12527 
12528   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
12529     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
12530     // target-specific builtins, perhaps?
12531     if (!FD->hasAttr<FormatAttr>())
12532       FD->addAttr(FormatAttr::CreateImplicit(Context,
12533                                              &Context.Idents.get("printf"), 2,
12534                                              Name->isStr("vasprintf") ? 0 : 3,
12535                                              FD->getLocation()));
12536   }
12537 
12538   if (Name->isStr("__CFStringMakeConstantString")) {
12539     // We already have a __builtin___CFStringMakeConstantString,
12540     // but builds that use -fno-constant-cfstrings don't go through that.
12541     if (!FD->hasAttr<FormatArgAttr>())
12542       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
12543                                                 FD->getLocation()));
12544   }
12545 }
12546 
12547 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
12548                                     TypeSourceInfo *TInfo) {
12549   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
12550   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
12551 
12552   if (!TInfo) {
12553     assert(D.isInvalidType() && "no declarator info for valid type");
12554     TInfo = Context.getTrivialTypeSourceInfo(T);
12555   }
12556 
12557   // Scope manipulation handled by caller.
12558   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
12559                                            D.getLocStart(),
12560                                            D.getIdentifierLoc(),
12561                                            D.getIdentifier(),
12562                                            TInfo);
12563 
12564   // Bail out immediately if we have an invalid declaration.
12565   if (D.isInvalidType()) {
12566     NewTD->setInvalidDecl();
12567     return NewTD;
12568   }
12569 
12570   if (D.getDeclSpec().isModulePrivateSpecified()) {
12571     if (CurContext->isFunctionOrMethod())
12572       Diag(NewTD->getLocation(), diag::err_module_private_local)
12573         << 2 << NewTD->getDeclName()
12574         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12575         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12576     else
12577       NewTD->setModulePrivate();
12578   }
12579 
12580   // C++ [dcl.typedef]p8:
12581   //   If the typedef declaration defines an unnamed class (or
12582   //   enum), the first typedef-name declared by the declaration
12583   //   to be that class type (or enum type) is used to denote the
12584   //   class type (or enum type) for linkage purposes only.
12585   // We need to check whether the type was declared in the declaration.
12586   switch (D.getDeclSpec().getTypeSpecType()) {
12587   case TST_enum:
12588   case TST_struct:
12589   case TST_interface:
12590   case TST_union:
12591   case TST_class: {
12592     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
12593     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
12594     break;
12595   }
12596 
12597   default:
12598     break;
12599   }
12600 
12601   return NewTD;
12602 }
12603 
12604 /// \brief Check that this is a valid underlying type for an enum declaration.
12605 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
12606   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
12607   QualType T = TI->getType();
12608 
12609   if (T->isDependentType())
12610     return false;
12611 
12612   if (const BuiltinType *BT = T->getAs<BuiltinType>())
12613     if (BT->isInteger())
12614       return false;
12615 
12616   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12617   return true;
12618 }
12619 
12620 /// Check whether this is a valid redeclaration of a previous enumeration.
12621 /// \return true if the redeclaration was invalid.
12622 bool Sema::CheckEnumRedeclaration(
12623     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12624     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12625   bool IsFixed = !EnumUnderlyingTy.isNull();
12626 
12627   if (IsScoped != Prev->isScoped()) {
12628     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12629       << Prev->isScoped();
12630     Diag(Prev->getLocation(), diag::note_previous_declaration);
12631     return true;
12632   }
12633 
12634   if (IsFixed && Prev->isFixed()) {
12635     if (!EnumUnderlyingTy->isDependentType() &&
12636         !Prev->getIntegerType()->isDependentType() &&
12637         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12638                                         Prev->getIntegerType())) {
12639       // TODO: Highlight the underlying type of the redeclaration.
12640       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12641         << EnumUnderlyingTy << Prev->getIntegerType();
12642       Diag(Prev->getLocation(), diag::note_previous_declaration)
12643           << Prev->getIntegerTypeRange();
12644       return true;
12645     }
12646   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12647     ;
12648   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12649     ;
12650   } else if (IsFixed != Prev->isFixed()) {
12651     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12652       << Prev->isFixed();
12653     Diag(Prev->getLocation(), diag::note_previous_declaration);
12654     return true;
12655   }
12656 
12657   return false;
12658 }
12659 
12660 /// \brief Get diagnostic %select index for tag kind for
12661 /// redeclaration diagnostic message.
12662 /// WARNING: Indexes apply to particular diagnostics only!
12663 ///
12664 /// \returns diagnostic %select index.
12665 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12666   switch (Tag) {
12667   case TTK_Struct: return 0;
12668   case TTK_Interface: return 1;
12669   case TTK_Class:  return 2;
12670   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12671   }
12672 }
12673 
12674 /// \brief Determine if tag kind is a class-key compatible with
12675 /// class for redeclaration (class, struct, or __interface).
12676 ///
12677 /// \returns true iff the tag kind is compatible.
12678 static bool isClassCompatTagKind(TagTypeKind Tag)
12679 {
12680   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12681 }
12682 
12683 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
12684                                              TagTypeKind TTK) {
12685   if (isa<TypedefDecl>(PrevDecl))
12686     return NTK_Typedef;
12687   else if (isa<TypeAliasDecl>(PrevDecl))
12688     return NTK_TypeAlias;
12689   else if (isa<ClassTemplateDecl>(PrevDecl))
12690     return NTK_Template;
12691   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
12692     return NTK_TypeAliasTemplate;
12693   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
12694     return NTK_TemplateTemplateArgument;
12695   switch (TTK) {
12696   case TTK_Struct:
12697   case TTK_Interface:
12698   case TTK_Class:
12699     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
12700   case TTK_Union:
12701     return NTK_NonUnion;
12702   case TTK_Enum:
12703     return NTK_NonEnum;
12704   }
12705   llvm_unreachable("invalid TTK");
12706 }
12707 
12708 /// \brief Determine whether a tag with a given kind is acceptable
12709 /// as a redeclaration of the given tag declaration.
12710 ///
12711 /// \returns true if the new tag kind is acceptable, false otherwise.
12712 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12713                                         TagTypeKind NewTag, bool isDefinition,
12714                                         SourceLocation NewTagLoc,
12715                                         const IdentifierInfo *Name) {
12716   // C++ [dcl.type.elab]p3:
12717   //   The class-key or enum keyword present in the
12718   //   elaborated-type-specifier shall agree in kind with the
12719   //   declaration to which the name in the elaborated-type-specifier
12720   //   refers. This rule also applies to the form of
12721   //   elaborated-type-specifier that declares a class-name or
12722   //   friend class since it can be construed as referring to the
12723   //   definition of the class. Thus, in any
12724   //   elaborated-type-specifier, the enum keyword shall be used to
12725   //   refer to an enumeration (7.2), the union class-key shall be
12726   //   used to refer to a union (clause 9), and either the class or
12727   //   struct class-key shall be used to refer to a class (clause 9)
12728   //   declared using the class or struct class-key.
12729   TagTypeKind OldTag = Previous->getTagKind();
12730   if (!isDefinition || !isClassCompatTagKind(NewTag))
12731     if (OldTag == NewTag)
12732       return true;
12733 
12734   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
12735     // Warn about the struct/class tag mismatch.
12736     bool isTemplate = false;
12737     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
12738       isTemplate = Record->getDescribedClassTemplate();
12739 
12740     if (inTemplateInstantiation()) {
12741       // In a template instantiation, do not offer fix-its for tag mismatches
12742       // since they usually mess up the template instead of fixing the problem.
12743       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12744         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12745         << getRedeclDiagFromTagKind(OldTag);
12746       return true;
12747     }
12748 
12749     if (isDefinition) {
12750       // On definitions, check previous tags and issue a fix-it for each
12751       // one that doesn't match the current tag.
12752       if (Previous->getDefinition()) {
12753         // Don't suggest fix-its for redefinitions.
12754         return true;
12755       }
12756 
12757       bool previousMismatch = false;
12758       for (auto I : Previous->redecls()) {
12759         if (I->getTagKind() != NewTag) {
12760           if (!previousMismatch) {
12761             previousMismatch = true;
12762             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
12763               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12764               << getRedeclDiagFromTagKind(I->getTagKind());
12765           }
12766           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
12767             << getRedeclDiagFromTagKind(NewTag)
12768             << FixItHint::CreateReplacement(I->getInnerLocStart(),
12769                  TypeWithKeyword::getTagTypeKindName(NewTag));
12770         }
12771       }
12772       return true;
12773     }
12774 
12775     // Check for a previous definition.  If current tag and definition
12776     // are same type, do nothing.  If no definition, but disagree with
12777     // with previous tag type, give a warning, but no fix-it.
12778     const TagDecl *Redecl = Previous->getDefinition() ?
12779                             Previous->getDefinition() : Previous;
12780     if (Redecl->getTagKind() == NewTag) {
12781       return true;
12782     }
12783 
12784     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12785       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12786       << getRedeclDiagFromTagKind(OldTag);
12787     Diag(Redecl->getLocation(), diag::note_previous_use);
12788 
12789     // If there is a previous definition, suggest a fix-it.
12790     if (Previous->getDefinition()) {
12791         Diag(NewTagLoc, diag::note_struct_class_suggestion)
12792           << getRedeclDiagFromTagKind(Redecl->getTagKind())
12793           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
12794                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
12795     }
12796 
12797     return true;
12798   }
12799   return false;
12800 }
12801 
12802 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
12803 /// from an outer enclosing namespace or file scope inside a friend declaration.
12804 /// This should provide the commented out code in the following snippet:
12805 ///   namespace N {
12806 ///     struct X;
12807 ///     namespace M {
12808 ///       struct Y { friend struct /*N::*/ X; };
12809 ///     }
12810 ///   }
12811 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
12812                                          SourceLocation NameLoc) {
12813   // While the decl is in a namespace, do repeated lookup of that name and see
12814   // if we get the same namespace back.  If we do not, continue until
12815   // translation unit scope, at which point we have a fully qualified NNS.
12816   SmallVector<IdentifierInfo *, 4> Namespaces;
12817   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12818   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
12819     // This tag should be declared in a namespace, which can only be enclosed by
12820     // other namespaces.  Bail if there's an anonymous namespace in the chain.
12821     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
12822     if (!Namespace || Namespace->isAnonymousNamespace())
12823       return FixItHint();
12824     IdentifierInfo *II = Namespace->getIdentifier();
12825     Namespaces.push_back(II);
12826     NamedDecl *Lookup = SemaRef.LookupSingleName(
12827         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
12828     if (Lookup == Namespace)
12829       break;
12830   }
12831 
12832   // Once we have all the namespaces, reverse them to go outermost first, and
12833   // build an NNS.
12834   SmallString<64> Insertion;
12835   llvm::raw_svector_ostream OS(Insertion);
12836   if (DC->isTranslationUnit())
12837     OS << "::";
12838   std::reverse(Namespaces.begin(), Namespaces.end());
12839   for (auto *II : Namespaces)
12840     OS << II->getName() << "::";
12841   return FixItHint::CreateInsertion(NameLoc, Insertion);
12842 }
12843 
12844 /// \brief Determine whether a tag originally declared in context \p OldDC can
12845 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
12846 /// found a declaration in \p OldDC as a previous decl, perhaps through a
12847 /// using-declaration).
12848 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
12849                                          DeclContext *NewDC) {
12850   OldDC = OldDC->getRedeclContext();
12851   NewDC = NewDC->getRedeclContext();
12852 
12853   if (OldDC->Equals(NewDC))
12854     return true;
12855 
12856   // In MSVC mode, we allow a redeclaration if the contexts are related (either
12857   // encloses the other).
12858   if (S.getLangOpts().MSVCCompat &&
12859       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
12860     return true;
12861 
12862   return false;
12863 }
12864 
12865 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
12866 /// former case, Name will be non-null.  In the later case, Name will be null.
12867 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
12868 /// reference/declaration/definition of a tag.
12869 ///
12870 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
12871 /// trailing-type-specifier) other than one in an alias-declaration.
12872 ///
12873 /// \param SkipBody If non-null, will be set to indicate if the caller should
12874 /// skip the definition of this tag and treat it as if it were a declaration.
12875 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12876                      SourceLocation KWLoc, CXXScopeSpec &SS,
12877                      IdentifierInfo *Name, SourceLocation NameLoc,
12878                      AttributeList *Attr, AccessSpecifier AS,
12879                      SourceLocation ModulePrivateLoc,
12880                      MultiTemplateParamsArg TemplateParameterLists,
12881                      bool &OwnedDecl, bool &IsDependent,
12882                      SourceLocation ScopedEnumKWLoc,
12883                      bool ScopedEnumUsesClassTag,
12884                      TypeResult UnderlyingType,
12885                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
12886   // If this is not a definition, it must have a name.
12887   IdentifierInfo *OrigName = Name;
12888   assert((Name != nullptr || TUK == TUK_Definition) &&
12889          "Nameless record must be a definition!");
12890   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
12891 
12892   OwnedDecl = false;
12893   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12894   bool ScopedEnum = ScopedEnumKWLoc.isValid();
12895 
12896   // FIXME: Check member specializations more carefully.
12897   bool isMemberSpecialization = false;
12898   bool Invalid = false;
12899 
12900   // We only need to do this matching if we have template parameters
12901   // or a scope specifier, which also conveniently avoids this work
12902   // for non-C++ cases.
12903   if (TemplateParameterLists.size() > 0 ||
12904       (SS.isNotEmpty() && TUK != TUK_Reference)) {
12905     if (TemplateParameterList *TemplateParams =
12906             MatchTemplateParametersToScopeSpecifier(
12907                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
12908                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
12909       if (Kind == TTK_Enum) {
12910         Diag(KWLoc, diag::err_enum_template);
12911         return nullptr;
12912       }
12913 
12914       if (TemplateParams->size() > 0) {
12915         // This is a declaration or definition of a class template (which may
12916         // be a member of another template).
12917 
12918         if (Invalid)
12919           return nullptr;
12920 
12921         OwnedDecl = false;
12922         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
12923                                                SS, Name, NameLoc, Attr,
12924                                                TemplateParams, AS,
12925                                                ModulePrivateLoc,
12926                                                /*FriendLoc*/SourceLocation(),
12927                                                TemplateParameterLists.size()-1,
12928                                                TemplateParameterLists.data(),
12929                                                SkipBody);
12930         return Result.get();
12931       } else {
12932         // The "template<>" header is extraneous.
12933         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12934           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12935         isMemberSpecialization = true;
12936       }
12937     }
12938   }
12939 
12940   // Figure out the underlying type if this a enum declaration. We need to do
12941   // this early, because it's needed to detect if this is an incompatible
12942   // redeclaration.
12943   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
12944   bool EnumUnderlyingIsImplicit = false;
12945 
12946   if (Kind == TTK_Enum) {
12947     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
12948       // No underlying type explicitly specified, or we failed to parse the
12949       // type, default to int.
12950       EnumUnderlying = Context.IntTy.getTypePtr();
12951     else if (UnderlyingType.get()) {
12952       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
12953       // integral type; any cv-qualification is ignored.
12954       TypeSourceInfo *TI = nullptr;
12955       GetTypeFromParser(UnderlyingType.get(), &TI);
12956       EnumUnderlying = TI;
12957 
12958       if (CheckEnumUnderlyingType(TI))
12959         // Recover by falling back to int.
12960         EnumUnderlying = Context.IntTy.getTypePtr();
12961 
12962       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
12963                                           UPPC_FixedUnderlyingType))
12964         EnumUnderlying = Context.IntTy.getTypePtr();
12965 
12966     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12967       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
12968         // Microsoft enums are always of int type.
12969         EnumUnderlying = Context.IntTy.getTypePtr();
12970         EnumUnderlyingIsImplicit = true;
12971       }
12972     }
12973   }
12974 
12975   DeclContext *SearchDC = CurContext;
12976   DeclContext *DC = CurContext;
12977   bool isStdBadAlloc = false;
12978   bool isStdAlignValT = false;
12979 
12980   RedeclarationKind Redecl = ForRedeclaration;
12981   if (TUK == TUK_Friend || TUK == TUK_Reference)
12982     Redecl = NotForRedeclaration;
12983 
12984   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
12985   if (Name && SS.isNotEmpty()) {
12986     // We have a nested-name tag ('struct foo::bar').
12987 
12988     // Check for invalid 'foo::'.
12989     if (SS.isInvalid()) {
12990       Name = nullptr;
12991       goto CreateNewDecl;
12992     }
12993 
12994     // If this is a friend or a reference to a class in a dependent
12995     // context, don't try to make a decl for it.
12996     if (TUK == TUK_Friend || TUK == TUK_Reference) {
12997       DC = computeDeclContext(SS, false);
12998       if (!DC) {
12999         IsDependent = true;
13000         return nullptr;
13001       }
13002     } else {
13003       DC = computeDeclContext(SS, true);
13004       if (!DC) {
13005         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
13006           << SS.getRange();
13007         return nullptr;
13008       }
13009     }
13010 
13011     if (RequireCompleteDeclContext(SS, DC))
13012       return nullptr;
13013 
13014     SearchDC = DC;
13015     // Look-up name inside 'foo::'.
13016     LookupQualifiedName(Previous, DC);
13017 
13018     if (Previous.isAmbiguous())
13019       return nullptr;
13020 
13021     if (Previous.empty()) {
13022       // Name lookup did not find anything. However, if the
13023       // nested-name-specifier refers to the current instantiation,
13024       // and that current instantiation has any dependent base
13025       // classes, we might find something at instantiation time: treat
13026       // this as a dependent elaborated-type-specifier.
13027       // But this only makes any sense for reference-like lookups.
13028       if (Previous.wasNotFoundInCurrentInstantiation() &&
13029           (TUK == TUK_Reference || TUK == TUK_Friend)) {
13030         IsDependent = true;
13031         return nullptr;
13032       }
13033 
13034       // A tag 'foo::bar' must already exist.
13035       Diag(NameLoc, diag::err_not_tag_in_scope)
13036         << Kind << Name << DC << SS.getRange();
13037       Name = nullptr;
13038       Invalid = true;
13039       goto CreateNewDecl;
13040     }
13041   } else if (Name) {
13042     // C++14 [class.mem]p14:
13043     //   If T is the name of a class, then each of the following shall have a
13044     //   name different from T:
13045     //    -- every member of class T that is itself a type
13046     if (TUK != TUK_Reference && TUK != TUK_Friend &&
13047         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
13048       return nullptr;
13049 
13050     // If this is a named struct, check to see if there was a previous forward
13051     // declaration or definition.
13052     // FIXME: We're looking into outer scopes here, even when we
13053     // shouldn't be. Doing so can result in ambiguities that we
13054     // shouldn't be diagnosing.
13055     LookupName(Previous, S);
13056 
13057     // When declaring or defining a tag, ignore ambiguities introduced
13058     // by types using'ed into this scope.
13059     if (Previous.isAmbiguous() &&
13060         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
13061       LookupResult::Filter F = Previous.makeFilter();
13062       while (F.hasNext()) {
13063         NamedDecl *ND = F.next();
13064         if (!ND->getDeclContext()->getRedeclContext()->Equals(
13065                 SearchDC->getRedeclContext()))
13066           F.erase();
13067       }
13068       F.done();
13069     }
13070 
13071     // C++11 [namespace.memdef]p3:
13072     //   If the name in a friend declaration is neither qualified nor
13073     //   a template-id and the declaration is a function or an
13074     //   elaborated-type-specifier, the lookup to determine whether
13075     //   the entity has been previously declared shall not consider
13076     //   any scopes outside the innermost enclosing namespace.
13077     //
13078     // MSVC doesn't implement the above rule for types, so a friend tag
13079     // declaration may be a redeclaration of a type declared in an enclosing
13080     // scope.  They do implement this rule for friend functions.
13081     //
13082     // Does it matter that this should be by scope instead of by
13083     // semantic context?
13084     if (!Previous.empty() && TUK == TUK_Friend) {
13085       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
13086       LookupResult::Filter F = Previous.makeFilter();
13087       bool FriendSawTagOutsideEnclosingNamespace = false;
13088       while (F.hasNext()) {
13089         NamedDecl *ND = F.next();
13090         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13091         if (DC->isFileContext() &&
13092             !EnclosingNS->Encloses(ND->getDeclContext())) {
13093           if (getLangOpts().MSVCCompat)
13094             FriendSawTagOutsideEnclosingNamespace = true;
13095           else
13096             F.erase();
13097         }
13098       }
13099       F.done();
13100 
13101       // Diagnose this MSVC extension in the easy case where lookup would have
13102       // unambiguously found something outside the enclosing namespace.
13103       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
13104         NamedDecl *ND = Previous.getFoundDecl();
13105         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
13106             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
13107       }
13108     }
13109 
13110     // Note:  there used to be some attempt at recovery here.
13111     if (Previous.isAmbiguous())
13112       return nullptr;
13113 
13114     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
13115       // FIXME: This makes sure that we ignore the contexts associated
13116       // with C structs, unions, and enums when looking for a matching
13117       // tag declaration or definition. See the similar lookup tweak
13118       // in Sema::LookupName; is there a better way to deal with this?
13119       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
13120         SearchDC = SearchDC->getParent();
13121     }
13122   }
13123 
13124   if (Previous.isSingleResult() &&
13125       Previous.getFoundDecl()->isTemplateParameter()) {
13126     // Maybe we will complain about the shadowed template parameter.
13127     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
13128     // Just pretend that we didn't see the previous declaration.
13129     Previous.clear();
13130   }
13131 
13132   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
13133       DC->Equals(getStdNamespace())) {
13134     if (Name->isStr("bad_alloc")) {
13135       // This is a declaration of or a reference to "std::bad_alloc".
13136       isStdBadAlloc = true;
13137 
13138       // If std::bad_alloc has been implicitly declared (but made invisible to
13139       // name lookup), fill in this implicit declaration as the previous
13140       // declaration, so that the declarations get chained appropriately.
13141       if (Previous.empty() && StdBadAlloc)
13142         Previous.addDecl(getStdBadAlloc());
13143     } else if (Name->isStr("align_val_t")) {
13144       isStdAlignValT = true;
13145       if (Previous.empty() && StdAlignValT)
13146         Previous.addDecl(getStdAlignValT());
13147     }
13148   }
13149 
13150   // If we didn't find a previous declaration, and this is a reference
13151   // (or friend reference), move to the correct scope.  In C++, we
13152   // also need to do a redeclaration lookup there, just in case
13153   // there's a shadow friend decl.
13154   if (Name && Previous.empty() &&
13155       (TUK == TUK_Reference || TUK == TUK_Friend)) {
13156     if (Invalid) goto CreateNewDecl;
13157     assert(SS.isEmpty());
13158 
13159     if (TUK == TUK_Reference) {
13160       // C++ [basic.scope.pdecl]p5:
13161       //   -- for an elaborated-type-specifier of the form
13162       //
13163       //          class-key identifier
13164       //
13165       //      if the elaborated-type-specifier is used in the
13166       //      decl-specifier-seq or parameter-declaration-clause of a
13167       //      function defined in namespace scope, the identifier is
13168       //      declared as a class-name in the namespace that contains
13169       //      the declaration; otherwise, except as a friend
13170       //      declaration, the identifier is declared in the smallest
13171       //      non-class, non-function-prototype scope that contains the
13172       //      declaration.
13173       //
13174       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
13175       // C structs and unions.
13176       //
13177       // It is an error in C++ to declare (rather than define) an enum
13178       // type, including via an elaborated type specifier.  We'll
13179       // diagnose that later; for now, declare the enum in the same
13180       // scope as we would have picked for any other tag type.
13181       //
13182       // GNU C also supports this behavior as part of its incomplete
13183       // enum types extension, while GNU C++ does not.
13184       //
13185       // Find the context where we'll be declaring the tag.
13186       // FIXME: We would like to maintain the current DeclContext as the
13187       // lexical context,
13188       SearchDC = getTagInjectionContext(SearchDC);
13189 
13190       // Find the scope where we'll be declaring the tag.
13191       S = getTagInjectionScope(S, getLangOpts());
13192     } else {
13193       assert(TUK == TUK_Friend);
13194       // C++ [namespace.memdef]p3:
13195       //   If a friend declaration in a non-local class first declares a
13196       //   class or function, the friend class or function is a member of
13197       //   the innermost enclosing namespace.
13198       SearchDC = SearchDC->getEnclosingNamespaceContext();
13199     }
13200 
13201     // In C++, we need to do a redeclaration lookup to properly
13202     // diagnose some problems.
13203     // FIXME: redeclaration lookup is also used (with and without C++) to find a
13204     // hidden declaration so that we don't get ambiguity errors when using a
13205     // type declared by an elaborated-type-specifier.  In C that is not correct
13206     // and we should instead merge compatible types found by lookup.
13207     if (getLangOpts().CPlusPlus) {
13208       Previous.setRedeclarationKind(ForRedeclaration);
13209       LookupQualifiedName(Previous, SearchDC);
13210     } else {
13211       Previous.setRedeclarationKind(ForRedeclaration);
13212       LookupName(Previous, S);
13213     }
13214   }
13215 
13216   // If we have a known previous declaration to use, then use it.
13217   if (Previous.empty() && SkipBody && SkipBody->Previous)
13218     Previous.addDecl(SkipBody->Previous);
13219 
13220   if (!Previous.empty()) {
13221     NamedDecl *PrevDecl = Previous.getFoundDecl();
13222     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13223 
13224     // It's okay to have a tag decl in the same scope as a typedef
13225     // which hides a tag decl in the same scope.  Finding this
13226     // insanity with a redeclaration lookup can only actually happen
13227     // in C++.
13228     //
13229     // This is also okay for elaborated-type-specifiers, which is
13230     // technically forbidden by the current standard but which is
13231     // okay according to the likely resolution of an open issue;
13232     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13233     if (getLangOpts().CPlusPlus) {
13234       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13235         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13236           TagDecl *Tag = TT->getDecl();
13237           if (Tag->getDeclName() == Name &&
13238               Tag->getDeclContext()->getRedeclContext()
13239                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
13240             PrevDecl = Tag;
13241             Previous.clear();
13242             Previous.addDecl(Tag);
13243             Previous.resolveKind();
13244           }
13245         }
13246       }
13247     }
13248 
13249     // If this is a redeclaration of a using shadow declaration, it must
13250     // declare a tag in the same context. In MSVC mode, we allow a
13251     // redefinition if either context is within the other.
13252     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13253       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13254       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13255           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
13256           !(OldTag && isAcceptableTagRedeclContext(
13257                           *this, OldTag->getDeclContext(), SearchDC))) {
13258         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13259         Diag(Shadow->getTargetDecl()->getLocation(),
13260              diag::note_using_decl_target);
13261         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13262             << 0;
13263         // Recover by ignoring the old declaration.
13264         Previous.clear();
13265         goto CreateNewDecl;
13266       }
13267     }
13268 
13269     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13270       // If this is a use of a previous tag, or if the tag is already declared
13271       // in the same scope (so that the definition/declaration completes or
13272       // rementions the tag), reuse the decl.
13273       if (TUK == TUK_Reference || TUK == TUK_Friend ||
13274           isDeclInScope(DirectPrevDecl, SearchDC, S,
13275                         SS.isNotEmpty() || isMemberSpecialization)) {
13276         // Make sure that this wasn't declared as an enum and now used as a
13277         // struct or something similar.
13278         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13279                                           TUK == TUK_Definition, KWLoc,
13280                                           Name)) {
13281           bool SafeToContinue
13282             = (PrevTagDecl->getTagKind() != TTK_Enum &&
13283                Kind != TTK_Enum);
13284           if (SafeToContinue)
13285             Diag(KWLoc, diag::err_use_with_wrong_tag)
13286               << Name
13287               << FixItHint::CreateReplacement(SourceRange(KWLoc),
13288                                               PrevTagDecl->getKindName());
13289           else
13290             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13291           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13292 
13293           if (SafeToContinue)
13294             Kind = PrevTagDecl->getTagKind();
13295           else {
13296             // Recover by making this an anonymous redefinition.
13297             Name = nullptr;
13298             Previous.clear();
13299             Invalid = true;
13300           }
13301         }
13302 
13303         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
13304           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
13305 
13306           // If this is an elaborated-type-specifier for a scoped enumeration,
13307           // the 'class' keyword is not necessary and not permitted.
13308           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13309             if (ScopedEnum)
13310               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
13311                 << PrevEnum->isScoped()
13312                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
13313             return PrevTagDecl;
13314           }
13315 
13316           QualType EnumUnderlyingTy;
13317           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13318             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
13319           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
13320             EnumUnderlyingTy = QualType(T, 0);
13321 
13322           // All conflicts with previous declarations are recovered by
13323           // returning the previous declaration, unless this is a definition,
13324           // in which case we want the caller to bail out.
13325           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
13326                                      ScopedEnum, EnumUnderlyingTy,
13327                                      EnumUnderlyingIsImplicit, PrevEnum))
13328             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
13329         }
13330 
13331         // C++11 [class.mem]p1:
13332         //   A member shall not be declared twice in the member-specification,
13333         //   except that a nested class or member class template can be declared
13334         //   and then later defined.
13335         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
13336             S->isDeclScope(PrevDecl)) {
13337           Diag(NameLoc, diag::ext_member_redeclared);
13338           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
13339         }
13340 
13341         if (!Invalid) {
13342           // If this is a use, just return the declaration we found, unless
13343           // we have attributes.
13344           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13345             if (Attr) {
13346               // FIXME: Diagnose these attributes. For now, we create a new
13347               // declaration to hold them.
13348             } else if (TUK == TUK_Reference &&
13349                        (PrevTagDecl->getFriendObjectKind() ==
13350                             Decl::FOK_Undeclared ||
13351                         PP.getModuleContainingLocation(
13352                             PrevDecl->getLocation()) !=
13353                             PP.getModuleContainingLocation(KWLoc)) &&
13354                        SS.isEmpty()) {
13355               // This declaration is a reference to an existing entity, but
13356               // has different visibility from that entity: it either makes
13357               // a friend visible or it makes a type visible in a new module.
13358               // In either case, create a new declaration. We only do this if
13359               // the declaration would have meant the same thing if no prior
13360               // declaration were found, that is, if it was found in the same
13361               // scope where we would have injected a declaration.
13362               if (!getTagInjectionContext(CurContext)->getRedeclContext()
13363                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
13364                 return PrevTagDecl;
13365               // This is in the injected scope, create a new declaration in
13366               // that scope.
13367               S = getTagInjectionScope(S, getLangOpts());
13368             } else {
13369               return PrevTagDecl;
13370             }
13371           }
13372 
13373           // Diagnose attempts to redefine a tag.
13374           if (TUK == TUK_Definition) {
13375             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
13376               // If we're defining a specialization and the previous definition
13377               // is from an implicit instantiation, don't emit an error
13378               // here; we'll catch this in the general case below.
13379               bool IsExplicitSpecializationAfterInstantiation = false;
13380               if (isMemberSpecialization) {
13381                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
13382                   IsExplicitSpecializationAfterInstantiation =
13383                     RD->getTemplateSpecializationKind() !=
13384                     TSK_ExplicitSpecialization;
13385                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
13386                   IsExplicitSpecializationAfterInstantiation =
13387                     ED->getTemplateSpecializationKind() !=
13388                     TSK_ExplicitSpecialization;
13389               }
13390 
13391               NamedDecl *Hidden = nullptr;
13392               if (SkipBody && getLangOpts().CPlusPlus &&
13393                   !hasVisibleDefinition(Def, &Hidden)) {
13394                 // There is a definition of this tag, but it is not visible. We
13395                 // explicitly make use of C++'s one definition rule here, and
13396                 // assume that this definition is identical to the hidden one
13397                 // we already have. Make the existing definition visible and
13398                 // use it in place of this one.
13399                 SkipBody->ShouldSkip = true;
13400                 makeMergedDefinitionVisible(Hidden, KWLoc);
13401                 return Def;
13402               } else if (!IsExplicitSpecializationAfterInstantiation) {
13403                 // A redeclaration in function prototype scope in C isn't
13404                 // visible elsewhere, so merely issue a warning.
13405                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
13406                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
13407                 else
13408                   Diag(NameLoc, diag::err_redefinition) << Name;
13409                 Diag(Def->getLocation(), diag::note_previous_definition);
13410                 // If this is a redefinition, recover by making this
13411                 // struct be anonymous, which will make any later
13412                 // references get the previous definition.
13413                 Name = nullptr;
13414                 Previous.clear();
13415                 Invalid = true;
13416               }
13417             } else {
13418               // If the type is currently being defined, complain
13419               // about a nested redefinition.
13420               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
13421               if (TD->isBeingDefined()) {
13422                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
13423                 Diag(PrevTagDecl->getLocation(),
13424                      diag::note_previous_definition);
13425                 Name = nullptr;
13426                 Previous.clear();
13427                 Invalid = true;
13428               }
13429             }
13430 
13431             // Okay, this is definition of a previously declared or referenced
13432             // tag. We're going to create a new Decl for it.
13433           }
13434 
13435           // Okay, we're going to make a redeclaration.  If this is some kind
13436           // of reference, make sure we build the redeclaration in the same DC
13437           // as the original, and ignore the current access specifier.
13438           if (TUK == TUK_Friend || TUK == TUK_Reference) {
13439             SearchDC = PrevTagDecl->getDeclContext();
13440             AS = AS_none;
13441           }
13442         }
13443         // If we get here we have (another) forward declaration or we
13444         // have a definition.  Just create a new decl.
13445 
13446       } else {
13447         // If we get here, this is a definition of a new tag type in a nested
13448         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
13449         // new decl/type.  We set PrevDecl to NULL so that the entities
13450         // have distinct types.
13451         Previous.clear();
13452       }
13453       // If we get here, we're going to create a new Decl. If PrevDecl
13454       // is non-NULL, it's a definition of the tag declared by
13455       // PrevDecl. If it's NULL, we have a new definition.
13456 
13457     // Otherwise, PrevDecl is not a tag, but was found with tag
13458     // lookup.  This is only actually possible in C++, where a few
13459     // things like templates still live in the tag namespace.
13460     } else {
13461       // Use a better diagnostic if an elaborated-type-specifier
13462       // found the wrong kind of type on the first
13463       // (non-redeclaration) lookup.
13464       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
13465           !Previous.isForRedeclaration()) {
13466         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13467         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
13468                                                        << Kind;
13469         Diag(PrevDecl->getLocation(), diag::note_declared_at);
13470         Invalid = true;
13471 
13472       // Otherwise, only diagnose if the declaration is in scope.
13473       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
13474                                 SS.isNotEmpty() || isMemberSpecialization)) {
13475         // do nothing
13476 
13477       // Diagnose implicit declarations introduced by elaborated types.
13478       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
13479         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13480         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
13481         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13482         Invalid = true;
13483 
13484       // Otherwise it's a declaration.  Call out a particularly common
13485       // case here.
13486       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13487         unsigned Kind = 0;
13488         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
13489         Diag(NameLoc, diag::err_tag_definition_of_typedef)
13490           << Name << Kind << TND->getUnderlyingType();
13491         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13492         Invalid = true;
13493 
13494       // Otherwise, diagnose.
13495       } else {
13496         // The tag name clashes with something else in the target scope,
13497         // issue an error and recover by making this tag be anonymous.
13498         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
13499         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13500         Name = nullptr;
13501         Invalid = true;
13502       }
13503 
13504       // The existing declaration isn't relevant to us; we're in a
13505       // new scope, so clear out the previous declaration.
13506       Previous.clear();
13507     }
13508   }
13509 
13510 CreateNewDecl:
13511 
13512   TagDecl *PrevDecl = nullptr;
13513   if (Previous.isSingleResult())
13514     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
13515 
13516   // If there is an identifier, use the location of the identifier as the
13517   // location of the decl, otherwise use the location of the struct/union
13518   // keyword.
13519   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13520 
13521   // Otherwise, create a new declaration. If there is a previous
13522   // declaration of the same entity, the two will be linked via
13523   // PrevDecl.
13524   TagDecl *New;
13525 
13526   bool IsForwardReference = false;
13527   if (Kind == TTK_Enum) {
13528     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13529     // enum X { A, B, C } D;    D should chain to X.
13530     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
13531                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
13532                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
13533 
13534     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
13535       StdAlignValT = cast<EnumDecl>(New);
13536 
13537     // If this is an undefined enum, warn.
13538     if (TUK != TUK_Definition && !Invalid) {
13539       TagDecl *Def;
13540       if (!EnumUnderlyingIsImplicit &&
13541           (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
13542           cast<EnumDecl>(New)->isFixed()) {
13543         // C++0x: 7.2p2: opaque-enum-declaration.
13544         // Conflicts are diagnosed above. Do nothing.
13545       }
13546       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
13547         Diag(Loc, diag::ext_forward_ref_enum_def)
13548           << New;
13549         Diag(Def->getLocation(), diag::note_previous_definition);
13550       } else {
13551         unsigned DiagID = diag::ext_forward_ref_enum;
13552         if (getLangOpts().MSVCCompat)
13553           DiagID = diag::ext_ms_forward_ref_enum;
13554         else if (getLangOpts().CPlusPlus)
13555           DiagID = diag::err_forward_ref_enum;
13556         Diag(Loc, DiagID);
13557 
13558         // If this is a forward-declared reference to an enumeration, make a
13559         // note of it; we won't actually be introducing the declaration into
13560         // the declaration context.
13561         if (TUK == TUK_Reference)
13562           IsForwardReference = true;
13563       }
13564     }
13565 
13566     if (EnumUnderlying) {
13567       EnumDecl *ED = cast<EnumDecl>(New);
13568       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13569         ED->setIntegerTypeSourceInfo(TI);
13570       else
13571         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
13572       ED->setPromotionType(ED->getIntegerType());
13573     }
13574   } else {
13575     // struct/union/class
13576 
13577     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13578     // struct X { int A; } D;    D should chain to X.
13579     if (getLangOpts().CPlusPlus) {
13580       // FIXME: Look for a way to use RecordDecl for simple structs.
13581       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13582                                   cast_or_null<CXXRecordDecl>(PrevDecl));
13583 
13584       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
13585         StdBadAlloc = cast<CXXRecordDecl>(New);
13586     } else
13587       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13588                                cast_or_null<RecordDecl>(PrevDecl));
13589   }
13590 
13591   // C++11 [dcl.type]p3:
13592   //   A type-specifier-seq shall not define a class or enumeration [...].
13593   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
13594     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
13595       << Context.getTagDeclType(New);
13596     Invalid = true;
13597   }
13598 
13599   // Maybe add qualifier info.
13600   if (SS.isNotEmpty()) {
13601     if (SS.isSet()) {
13602       // If this is either a declaration or a definition, check the
13603       // nested-name-specifier against the current context. We don't do this
13604       // for explicit specializations, because they have similar checking
13605       // (with more specific diagnostics) in the call to
13606       // CheckMemberSpecialization, below.
13607       if (!isMemberSpecialization &&
13608           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
13609           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
13610         Invalid = true;
13611 
13612       New->setQualifierInfo(SS.getWithLocInContext(Context));
13613       if (TemplateParameterLists.size() > 0) {
13614         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
13615       }
13616     }
13617     else
13618       Invalid = true;
13619   }
13620 
13621   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13622     // Add alignment attributes if necessary; these attributes are checked when
13623     // the ASTContext lays out the structure.
13624     //
13625     // It is important for implementing the correct semantics that this
13626     // happen here (in act on tag decl). The #pragma pack stack is
13627     // maintained as a result of parser callbacks which can occur at
13628     // many points during the parsing of a struct declaration (because
13629     // the #pragma tokens are effectively skipped over during the
13630     // parsing of the struct).
13631     if (TUK == TUK_Definition) {
13632       AddAlignmentAttributesForRecord(RD);
13633       AddMsStructLayoutForRecord(RD);
13634     }
13635   }
13636 
13637   if (ModulePrivateLoc.isValid()) {
13638     if (isMemberSpecialization)
13639       Diag(New->getLocation(), diag::err_module_private_specialization)
13640         << 2
13641         << FixItHint::CreateRemoval(ModulePrivateLoc);
13642     // __module_private__ does not apply to local classes. However, we only
13643     // diagnose this as an error when the declaration specifiers are
13644     // freestanding. Here, we just ignore the __module_private__.
13645     else if (!SearchDC->isFunctionOrMethod())
13646       New->setModulePrivate();
13647   }
13648 
13649   // If this is a specialization of a member class (of a class template),
13650   // check the specialization.
13651   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
13652     Invalid = true;
13653 
13654   // If we're declaring or defining a tag in function prototype scope in C,
13655   // note that this type can only be used within the function and add it to
13656   // the list of decls to inject into the function definition scope.
13657   if ((Name || Kind == TTK_Enum) &&
13658       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
13659     if (getLangOpts().CPlusPlus) {
13660       // C++ [dcl.fct]p6:
13661       //   Types shall not be defined in return or parameter types.
13662       if (TUK == TUK_Definition && !IsTypeSpecifier) {
13663         Diag(Loc, diag::err_type_defined_in_param_type)
13664             << Name;
13665         Invalid = true;
13666       }
13667     } else if (!PrevDecl) {
13668       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
13669     }
13670   }
13671 
13672   if (Invalid)
13673     New->setInvalidDecl();
13674 
13675   // Set the lexical context. If the tag has a C++ scope specifier, the
13676   // lexical context will be different from the semantic context.
13677   New->setLexicalDeclContext(CurContext);
13678 
13679   // Mark this as a friend decl if applicable.
13680   // In Microsoft mode, a friend declaration also acts as a forward
13681   // declaration so we always pass true to setObjectOfFriendDecl to make
13682   // the tag name visible.
13683   if (TUK == TUK_Friend)
13684     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
13685 
13686   // Set the access specifier.
13687   if (!Invalid && SearchDC->isRecord())
13688     SetMemberAccessSpecifier(New, PrevDecl, AS);
13689 
13690   if (TUK == TUK_Definition)
13691     New->startDefinition();
13692 
13693   if (Attr)
13694     ProcessDeclAttributeList(S, New, Attr);
13695   AddPragmaAttributes(S, New);
13696 
13697   // If this has an identifier, add it to the scope stack.
13698   if (TUK == TUK_Friend) {
13699     // We might be replacing an existing declaration in the lookup tables;
13700     // if so, borrow its access specifier.
13701     if (PrevDecl)
13702       New->setAccess(PrevDecl->getAccess());
13703 
13704     DeclContext *DC = New->getDeclContext()->getRedeclContext();
13705     DC->makeDeclVisibleInContext(New);
13706     if (Name) // can be null along some error paths
13707       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13708         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
13709   } else if (Name) {
13710     S = getNonFieldDeclScope(S);
13711     PushOnScopeChains(New, S, !IsForwardReference);
13712     if (IsForwardReference)
13713       SearchDC->makeDeclVisibleInContext(New);
13714   } else {
13715     CurContext->addDecl(New);
13716   }
13717 
13718   // If this is the C FILE type, notify the AST context.
13719   if (IdentifierInfo *II = New->getIdentifier())
13720     if (!New->isInvalidDecl() &&
13721         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
13722         II->isStr("FILE"))
13723       Context.setFILEDecl(New);
13724 
13725   if (PrevDecl)
13726     mergeDeclAttributes(New, PrevDecl);
13727 
13728   // If there's a #pragma GCC visibility in scope, set the visibility of this
13729   // record.
13730   AddPushedVisibilityAttribute(New);
13731 
13732   OwnedDecl = true;
13733   // In C++, don't return an invalid declaration. We can't recover well from
13734   // the cases where we make the type anonymous.
13735   if (Invalid && getLangOpts().CPlusPlus) {
13736     if (New->isBeingDefined())
13737       if (auto RD = dyn_cast<RecordDecl>(New))
13738         RD->completeDefinition();
13739     return nullptr;
13740   } else {
13741     return New;
13742   }
13743 }
13744 
13745 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
13746   AdjustDeclIfTemplate(TagD);
13747   TagDecl *Tag = cast<TagDecl>(TagD);
13748 
13749   // Enter the tag context.
13750   PushDeclContext(S, Tag);
13751 
13752   ActOnDocumentableDecl(TagD);
13753 
13754   // If there's a #pragma GCC visibility in scope, set the visibility of this
13755   // record.
13756   AddPushedVisibilityAttribute(Tag);
13757 }
13758 
13759 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
13760   assert(isa<ObjCContainerDecl>(IDecl) &&
13761          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
13762   DeclContext *OCD = cast<DeclContext>(IDecl);
13763   assert(getContainingDC(OCD) == CurContext &&
13764       "The next DeclContext should be lexically contained in the current one.");
13765   CurContext = OCD;
13766   return IDecl;
13767 }
13768 
13769 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
13770                                            SourceLocation FinalLoc,
13771                                            bool IsFinalSpelledSealed,
13772                                            SourceLocation LBraceLoc) {
13773   AdjustDeclIfTemplate(TagD);
13774   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
13775 
13776   FieldCollector->StartClass();
13777 
13778   if (!Record->getIdentifier())
13779     return;
13780 
13781   if (FinalLoc.isValid())
13782     Record->addAttr(new (Context)
13783                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
13784 
13785   // C++ [class]p2:
13786   //   [...] The class-name is also inserted into the scope of the
13787   //   class itself; this is known as the injected-class-name. For
13788   //   purposes of access checking, the injected-class-name is treated
13789   //   as if it were a public member name.
13790   CXXRecordDecl *InjectedClassName
13791     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
13792                             Record->getLocStart(), Record->getLocation(),
13793                             Record->getIdentifier(),
13794                             /*PrevDecl=*/nullptr,
13795                             /*DelayTypeCreation=*/true);
13796   Context.getTypeDeclType(InjectedClassName, Record);
13797   InjectedClassName->setImplicit();
13798   InjectedClassName->setAccess(AS_public);
13799   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
13800       InjectedClassName->setDescribedClassTemplate(Template);
13801   PushOnScopeChains(InjectedClassName, S);
13802   assert(InjectedClassName->isInjectedClassName() &&
13803          "Broken injected-class-name");
13804 }
13805 
13806 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
13807                                     SourceRange BraceRange) {
13808   AdjustDeclIfTemplate(TagD);
13809   TagDecl *Tag = cast<TagDecl>(TagD);
13810   Tag->setBraceRange(BraceRange);
13811 
13812   // Make sure we "complete" the definition even it is invalid.
13813   if (Tag->isBeingDefined()) {
13814     assert(Tag->isInvalidDecl() && "We should already have completed it");
13815     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13816       RD->completeDefinition();
13817   }
13818 
13819   if (isa<CXXRecordDecl>(Tag)) {
13820     FieldCollector->FinishClass();
13821   }
13822 
13823   // Exit this scope of this tag's definition.
13824   PopDeclContext();
13825 
13826   if (getCurLexicalContext()->isObjCContainer() &&
13827       Tag->getDeclContext()->isFileContext())
13828     Tag->setTopLevelDeclInObjCContainer();
13829 
13830   // Notify the consumer that we've defined a tag.
13831   if (!Tag->isInvalidDecl())
13832     Consumer.HandleTagDeclDefinition(Tag);
13833 }
13834 
13835 void Sema::ActOnObjCContainerFinishDefinition() {
13836   // Exit this scope of this interface definition.
13837   PopDeclContext();
13838 }
13839 
13840 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
13841   assert(DC == CurContext && "Mismatch of container contexts");
13842   OriginalLexicalContext = DC;
13843   ActOnObjCContainerFinishDefinition();
13844 }
13845 
13846 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
13847   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
13848   OriginalLexicalContext = nullptr;
13849 }
13850 
13851 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
13852   AdjustDeclIfTemplate(TagD);
13853   TagDecl *Tag = cast<TagDecl>(TagD);
13854   Tag->setInvalidDecl();
13855 
13856   // Make sure we "complete" the definition even it is invalid.
13857   if (Tag->isBeingDefined()) {
13858     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13859       RD->completeDefinition();
13860   }
13861 
13862   // We're undoing ActOnTagStartDefinition here, not
13863   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
13864   // the FieldCollector.
13865 
13866   PopDeclContext();
13867 }
13868 
13869 // Note that FieldName may be null for anonymous bitfields.
13870 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
13871                                 IdentifierInfo *FieldName,
13872                                 QualType FieldTy, bool IsMsStruct,
13873                                 Expr *BitWidth, bool *ZeroWidth) {
13874   // Default to true; that shouldn't confuse checks for emptiness
13875   if (ZeroWidth)
13876     *ZeroWidth = true;
13877 
13878   // C99 6.7.2.1p4 - verify the field type.
13879   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
13880   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
13881     // Handle incomplete types with specific error.
13882     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
13883       return ExprError();
13884     if (FieldName)
13885       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
13886         << FieldName << FieldTy << BitWidth->getSourceRange();
13887     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
13888       << FieldTy << BitWidth->getSourceRange();
13889   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
13890                                              UPPC_BitFieldWidth))
13891     return ExprError();
13892 
13893   // If the bit-width is type- or value-dependent, don't try to check
13894   // it now.
13895   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
13896     return BitWidth;
13897 
13898   llvm::APSInt Value;
13899   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
13900   if (ICE.isInvalid())
13901     return ICE;
13902   BitWidth = ICE.get();
13903 
13904   if (Value != 0 && ZeroWidth)
13905     *ZeroWidth = false;
13906 
13907   // Zero-width bitfield is ok for anonymous field.
13908   if (Value == 0 && FieldName)
13909     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
13910 
13911   if (Value.isSigned() && Value.isNegative()) {
13912     if (FieldName)
13913       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
13914                << FieldName << Value.toString(10);
13915     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
13916       << Value.toString(10);
13917   }
13918 
13919   if (!FieldTy->isDependentType()) {
13920     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
13921     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
13922     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
13923 
13924     // Over-wide bitfields are an error in C or when using the MSVC bitfield
13925     // ABI.
13926     bool CStdConstraintViolation =
13927         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
13928     bool MSBitfieldViolation =
13929         Value.ugt(TypeStorageSize) &&
13930         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
13931     if (CStdConstraintViolation || MSBitfieldViolation) {
13932       unsigned DiagWidth =
13933           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
13934       if (FieldName)
13935         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
13936                << FieldName << (unsigned)Value.getZExtValue()
13937                << !CStdConstraintViolation << DiagWidth;
13938 
13939       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
13940              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
13941              << DiagWidth;
13942     }
13943 
13944     // Warn on types where the user might conceivably expect to get all
13945     // specified bits as value bits: that's all integral types other than
13946     // 'bool'.
13947     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
13948       if (FieldName)
13949         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
13950             << FieldName << (unsigned)Value.getZExtValue()
13951             << (unsigned)TypeWidth;
13952       else
13953         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
13954             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
13955     }
13956   }
13957 
13958   return BitWidth;
13959 }
13960 
13961 /// ActOnField - Each field of a C struct/union is passed into this in order
13962 /// to create a FieldDecl object for it.
13963 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
13964                        Declarator &D, Expr *BitfieldWidth) {
13965   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
13966                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
13967                                /*InitStyle=*/ICIS_NoInit, AS_public);
13968   return Res;
13969 }
13970 
13971 /// HandleField - Analyze a field of a C struct or a C++ data member.
13972 ///
13973 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
13974                              SourceLocation DeclStart,
13975                              Declarator &D, Expr *BitWidth,
13976                              InClassInitStyle InitStyle,
13977                              AccessSpecifier AS) {
13978   if (D.isDecompositionDeclarator()) {
13979     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
13980     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
13981       << Decomp.getSourceRange();
13982     return nullptr;
13983   }
13984 
13985   IdentifierInfo *II = D.getIdentifier();
13986   SourceLocation Loc = DeclStart;
13987   if (II) Loc = D.getIdentifierLoc();
13988 
13989   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13990   QualType T = TInfo->getType();
13991   if (getLangOpts().CPlusPlus) {
13992     CheckExtraCXXDefaultArguments(D);
13993 
13994     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13995                                         UPPC_DataMemberType)) {
13996       D.setInvalidType();
13997       T = Context.IntTy;
13998       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13999     }
14000   }
14001 
14002   // TR 18037 does not allow fields to be declared with address spaces.
14003   if (T.getQualifiers().hasAddressSpace()) {
14004     Diag(Loc, diag::err_field_with_address_space);
14005     D.setInvalidType();
14006   }
14007 
14008   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
14009   // used as structure or union field: image, sampler, event or block types.
14010   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
14011                           T->isSamplerT() || T->isBlockPointerType())) {
14012     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
14013     D.setInvalidType();
14014   }
14015 
14016   DiagnoseFunctionSpecifiers(D.getDeclSpec());
14017 
14018   if (D.getDeclSpec().isInlineSpecified())
14019     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14020         << getLangOpts().CPlusPlus1z;
14021   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14022     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14023          diag::err_invalid_thread)
14024       << DeclSpec::getSpecifierName(TSCS);
14025 
14026   // Check to see if this name was declared as a member previously
14027   NamedDecl *PrevDecl = nullptr;
14028   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14029   LookupName(Previous, S);
14030   switch (Previous.getResultKind()) {
14031     case LookupResult::Found:
14032     case LookupResult::FoundUnresolvedValue:
14033       PrevDecl = Previous.getAsSingle<NamedDecl>();
14034       break;
14035 
14036     case LookupResult::FoundOverloaded:
14037       PrevDecl = Previous.getRepresentativeDecl();
14038       break;
14039 
14040     case LookupResult::NotFound:
14041     case LookupResult::NotFoundInCurrentInstantiation:
14042     case LookupResult::Ambiguous:
14043       break;
14044   }
14045   Previous.suppressDiagnostics();
14046 
14047   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14048     // Maybe we will complain about the shadowed template parameter.
14049     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14050     // Just pretend that we didn't see the previous declaration.
14051     PrevDecl = nullptr;
14052   }
14053 
14054   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14055     PrevDecl = nullptr;
14056 
14057   bool Mutable
14058     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
14059   SourceLocation TSSL = D.getLocStart();
14060   FieldDecl *NewFD
14061     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
14062                      TSSL, AS, PrevDecl, &D);
14063 
14064   if (NewFD->isInvalidDecl())
14065     Record->setInvalidDecl();
14066 
14067   if (D.getDeclSpec().isModulePrivateSpecified())
14068     NewFD->setModulePrivate();
14069 
14070   if (NewFD->isInvalidDecl() && PrevDecl) {
14071     // Don't introduce NewFD into scope; there's already something
14072     // with the same name in the same scope.
14073   } else if (II) {
14074     PushOnScopeChains(NewFD, S);
14075   } else
14076     Record->addDecl(NewFD);
14077 
14078   return NewFD;
14079 }
14080 
14081 /// \brief Build a new FieldDecl and check its well-formedness.
14082 ///
14083 /// This routine builds a new FieldDecl given the fields name, type,
14084 /// record, etc. \p PrevDecl should refer to any previous declaration
14085 /// with the same name and in the same scope as the field to be
14086 /// created.
14087 ///
14088 /// \returns a new FieldDecl.
14089 ///
14090 /// \todo The Declarator argument is a hack. It will be removed once
14091 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
14092                                 TypeSourceInfo *TInfo,
14093                                 RecordDecl *Record, SourceLocation Loc,
14094                                 bool Mutable, Expr *BitWidth,
14095                                 InClassInitStyle InitStyle,
14096                                 SourceLocation TSSL,
14097                                 AccessSpecifier AS, NamedDecl *PrevDecl,
14098                                 Declarator *D) {
14099   IdentifierInfo *II = Name.getAsIdentifierInfo();
14100   bool InvalidDecl = false;
14101   if (D) InvalidDecl = D->isInvalidType();
14102 
14103   // If we receive a broken type, recover by assuming 'int' and
14104   // marking this declaration as invalid.
14105   if (T.isNull()) {
14106     InvalidDecl = true;
14107     T = Context.IntTy;
14108   }
14109 
14110   QualType EltTy = Context.getBaseElementType(T);
14111   if (!EltTy->isDependentType()) {
14112     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
14113       // Fields of incomplete type force their record to be invalid.
14114       Record->setInvalidDecl();
14115       InvalidDecl = true;
14116     } else {
14117       NamedDecl *Def;
14118       EltTy->isIncompleteType(&Def);
14119       if (Def && Def->isInvalidDecl()) {
14120         Record->setInvalidDecl();
14121         InvalidDecl = true;
14122       }
14123     }
14124   }
14125 
14126   // OpenCL v1.2 s6.9.c: bitfields are not supported.
14127   if (BitWidth && getLangOpts().OpenCL) {
14128     Diag(Loc, diag::err_opencl_bitfields);
14129     InvalidDecl = true;
14130   }
14131 
14132   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14133   // than a variably modified type.
14134   if (!InvalidDecl && T->isVariablyModifiedType()) {
14135     bool SizeIsNegative;
14136     llvm::APSInt Oversized;
14137 
14138     TypeSourceInfo *FixedTInfo =
14139       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
14140                                                     SizeIsNegative,
14141                                                     Oversized);
14142     if (FixedTInfo) {
14143       Diag(Loc, diag::warn_illegal_constant_array_size);
14144       TInfo = FixedTInfo;
14145       T = FixedTInfo->getType();
14146     } else {
14147       if (SizeIsNegative)
14148         Diag(Loc, diag::err_typecheck_negative_array_size);
14149       else if (Oversized.getBoolValue())
14150         Diag(Loc, diag::err_array_too_large)
14151           << Oversized.toString(10);
14152       else
14153         Diag(Loc, diag::err_typecheck_field_variable_size);
14154       InvalidDecl = true;
14155     }
14156   }
14157 
14158   // Fields can not have abstract class types
14159   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
14160                                              diag::err_abstract_type_in_decl,
14161                                              AbstractFieldType))
14162     InvalidDecl = true;
14163 
14164   bool ZeroWidth = false;
14165   if (InvalidDecl)
14166     BitWidth = nullptr;
14167   // If this is declared as a bit-field, check the bit-field.
14168   if (BitWidth) {
14169     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
14170                               &ZeroWidth).get();
14171     if (!BitWidth) {
14172       InvalidDecl = true;
14173       BitWidth = nullptr;
14174       ZeroWidth = false;
14175     }
14176   }
14177 
14178   // Check that 'mutable' is consistent with the type of the declaration.
14179   if (!InvalidDecl && Mutable) {
14180     unsigned DiagID = 0;
14181     if (T->isReferenceType())
14182       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
14183                                         : diag::err_mutable_reference;
14184     else if (T.isConstQualified())
14185       DiagID = diag::err_mutable_const;
14186 
14187     if (DiagID) {
14188       SourceLocation ErrLoc = Loc;
14189       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
14190         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
14191       Diag(ErrLoc, DiagID);
14192       if (DiagID != diag::ext_mutable_reference) {
14193         Mutable = false;
14194         InvalidDecl = true;
14195       }
14196     }
14197   }
14198 
14199   // C++11 [class.union]p8 (DR1460):
14200   //   At most one variant member of a union may have a
14201   //   brace-or-equal-initializer.
14202   if (InitStyle != ICIS_NoInit)
14203     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14204 
14205   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14206                                        BitWidth, Mutable, InitStyle);
14207   if (InvalidDecl)
14208     NewFD->setInvalidDecl();
14209 
14210   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14211     Diag(Loc, diag::err_duplicate_member) << II;
14212     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14213     NewFD->setInvalidDecl();
14214   }
14215 
14216   if (!InvalidDecl && getLangOpts().CPlusPlus) {
14217     if (Record->isUnion()) {
14218       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14219         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14220         if (RDecl->getDefinition()) {
14221           // C++ [class.union]p1: An object of a class with a non-trivial
14222           // constructor, a non-trivial copy constructor, a non-trivial
14223           // destructor, or a non-trivial copy assignment operator
14224           // cannot be a member of a union, nor can an array of such
14225           // objects.
14226           if (CheckNontrivialField(NewFD))
14227             NewFD->setInvalidDecl();
14228         }
14229       }
14230 
14231       // C++ [class.union]p1: If a union contains a member of reference type,
14232       // the program is ill-formed, except when compiling with MSVC extensions
14233       // enabled.
14234       if (EltTy->isReferenceType()) {
14235         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14236                                     diag::ext_union_member_of_reference_type :
14237                                     diag::err_union_member_of_reference_type)
14238           << NewFD->getDeclName() << EltTy;
14239         if (!getLangOpts().MicrosoftExt)
14240           NewFD->setInvalidDecl();
14241       }
14242     }
14243   }
14244 
14245   // FIXME: We need to pass in the attributes given an AST
14246   // representation, not a parser representation.
14247   if (D) {
14248     // FIXME: The current scope is almost... but not entirely... correct here.
14249     ProcessDeclAttributes(getCurScope(), NewFD, *D);
14250 
14251     if (NewFD->hasAttrs())
14252       CheckAlignasUnderalignment(NewFD);
14253   }
14254 
14255   // In auto-retain/release, infer strong retension for fields of
14256   // retainable type.
14257   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
14258     NewFD->setInvalidDecl();
14259 
14260   if (T.isObjCGCWeak())
14261     Diag(Loc, diag::warn_attribute_weak_on_field);
14262 
14263   NewFD->setAccess(AS);
14264   return NewFD;
14265 }
14266 
14267 bool Sema::CheckNontrivialField(FieldDecl *FD) {
14268   assert(FD);
14269   assert(getLangOpts().CPlusPlus && "valid check only for C++");
14270 
14271   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
14272     return false;
14273 
14274   QualType EltTy = Context.getBaseElementType(FD->getType());
14275   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14276     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
14277     if (RDecl->getDefinition()) {
14278       // We check for copy constructors before constructors
14279       // because otherwise we'll never get complaints about
14280       // copy constructors.
14281 
14282       CXXSpecialMember member = CXXInvalid;
14283       // We're required to check for any non-trivial constructors. Since the
14284       // implicit default constructor is suppressed if there are any
14285       // user-declared constructors, we just need to check that there is a
14286       // trivial default constructor and a trivial copy constructor. (We don't
14287       // worry about move constructors here, since this is a C++98 check.)
14288       if (RDecl->hasNonTrivialCopyConstructor())
14289         member = CXXCopyConstructor;
14290       else if (!RDecl->hasTrivialDefaultConstructor())
14291         member = CXXDefaultConstructor;
14292       else if (RDecl->hasNonTrivialCopyAssignment())
14293         member = CXXCopyAssignment;
14294       else if (RDecl->hasNonTrivialDestructor())
14295         member = CXXDestructor;
14296 
14297       if (member != CXXInvalid) {
14298         if (!getLangOpts().CPlusPlus11 &&
14299             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
14300           // Objective-C++ ARC: it is an error to have a non-trivial field of
14301           // a union. However, system headers in Objective-C programs
14302           // occasionally have Objective-C lifetime objects within unions,
14303           // and rather than cause the program to fail, we make those
14304           // members unavailable.
14305           SourceLocation Loc = FD->getLocation();
14306           if (getSourceManager().isInSystemHeader(Loc)) {
14307             if (!FD->hasAttr<UnavailableAttr>())
14308               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14309                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
14310             return false;
14311           }
14312         }
14313 
14314         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
14315                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
14316                diag::err_illegal_union_or_anon_struct_member)
14317           << FD->getParent()->isUnion() << FD->getDeclName() << member;
14318         DiagnoseNontrivial(RDecl, member);
14319         return !getLangOpts().CPlusPlus11;
14320       }
14321     }
14322   }
14323 
14324   return false;
14325 }
14326 
14327 /// TranslateIvarVisibility - Translate visibility from a token ID to an
14328 ///  AST enum value.
14329 static ObjCIvarDecl::AccessControl
14330 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
14331   switch (ivarVisibility) {
14332   default: llvm_unreachable("Unknown visitibility kind");
14333   case tok::objc_private: return ObjCIvarDecl::Private;
14334   case tok::objc_public: return ObjCIvarDecl::Public;
14335   case tok::objc_protected: return ObjCIvarDecl::Protected;
14336   case tok::objc_package: return ObjCIvarDecl::Package;
14337   }
14338 }
14339 
14340 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
14341 /// in order to create an IvarDecl object for it.
14342 Decl *Sema::ActOnIvar(Scope *S,
14343                                 SourceLocation DeclStart,
14344                                 Declarator &D, Expr *BitfieldWidth,
14345                                 tok::ObjCKeywordKind Visibility) {
14346 
14347   IdentifierInfo *II = D.getIdentifier();
14348   Expr *BitWidth = (Expr*)BitfieldWidth;
14349   SourceLocation Loc = DeclStart;
14350   if (II) Loc = D.getIdentifierLoc();
14351 
14352   // FIXME: Unnamed fields can be handled in various different ways, for
14353   // example, unnamed unions inject all members into the struct namespace!
14354 
14355   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14356   QualType T = TInfo->getType();
14357 
14358   if (BitWidth) {
14359     // 6.7.2.1p3, 6.7.2.1p4
14360     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
14361     if (!BitWidth)
14362       D.setInvalidType();
14363   } else {
14364     // Not a bitfield.
14365 
14366     // validate II.
14367 
14368   }
14369   if (T->isReferenceType()) {
14370     Diag(Loc, diag::err_ivar_reference_type);
14371     D.setInvalidType();
14372   }
14373   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14374   // than a variably modified type.
14375   else if (T->isVariablyModifiedType()) {
14376     Diag(Loc, diag::err_typecheck_ivar_variable_size);
14377     D.setInvalidType();
14378   }
14379 
14380   // Get the visibility (access control) for this ivar.
14381   ObjCIvarDecl::AccessControl ac =
14382     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
14383                                         : ObjCIvarDecl::None;
14384   // Must set ivar's DeclContext to its enclosing interface.
14385   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
14386   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
14387     return nullptr;
14388   ObjCContainerDecl *EnclosingContext;
14389   if (ObjCImplementationDecl *IMPDecl =
14390       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14391     if (LangOpts.ObjCRuntime.isFragile()) {
14392     // Case of ivar declared in an implementation. Context is that of its class.
14393       EnclosingContext = IMPDecl->getClassInterface();
14394       assert(EnclosingContext && "Implementation has no class interface!");
14395     }
14396     else
14397       EnclosingContext = EnclosingDecl;
14398   } else {
14399     if (ObjCCategoryDecl *CDecl =
14400         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14401       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
14402         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
14403         return nullptr;
14404       }
14405     }
14406     EnclosingContext = EnclosingDecl;
14407   }
14408 
14409   // Construct the decl.
14410   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
14411                                              DeclStart, Loc, II, T,
14412                                              TInfo, ac, (Expr *)BitfieldWidth);
14413 
14414   if (II) {
14415     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
14416                                            ForRedeclaration);
14417     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
14418         && !isa<TagDecl>(PrevDecl)) {
14419       Diag(Loc, diag::err_duplicate_member) << II;
14420       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14421       NewID->setInvalidDecl();
14422     }
14423   }
14424 
14425   // Process attributes attached to the ivar.
14426   ProcessDeclAttributes(S, NewID, D);
14427 
14428   if (D.isInvalidType())
14429     NewID->setInvalidDecl();
14430 
14431   // In ARC, infer 'retaining' for ivars of retainable type.
14432   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
14433     NewID->setInvalidDecl();
14434 
14435   if (D.getDeclSpec().isModulePrivateSpecified())
14436     NewID->setModulePrivate();
14437 
14438   if (II) {
14439     // FIXME: When interfaces are DeclContexts, we'll need to add
14440     // these to the interface.
14441     S->AddDecl(NewID);
14442     IdResolver.AddDecl(NewID);
14443   }
14444 
14445   if (LangOpts.ObjCRuntime.isNonFragile() &&
14446       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
14447     Diag(Loc, diag::warn_ivars_in_interface);
14448 
14449   return NewID;
14450 }
14451 
14452 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
14453 /// class and class extensions. For every class \@interface and class
14454 /// extension \@interface, if the last ivar is a bitfield of any type,
14455 /// then add an implicit `char :0` ivar to the end of that interface.
14456 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
14457                              SmallVectorImpl<Decl *> &AllIvarDecls) {
14458   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
14459     return;
14460 
14461   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
14462   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
14463 
14464   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
14465     return;
14466   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
14467   if (!ID) {
14468     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
14469       if (!CD->IsClassExtension())
14470         return;
14471     }
14472     // No need to add this to end of @implementation.
14473     else
14474       return;
14475   }
14476   // All conditions are met. Add a new bitfield to the tail end of ivars.
14477   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
14478   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
14479 
14480   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
14481                               DeclLoc, DeclLoc, nullptr,
14482                               Context.CharTy,
14483                               Context.getTrivialTypeSourceInfo(Context.CharTy,
14484                                                                DeclLoc),
14485                               ObjCIvarDecl::Private, BW,
14486                               true);
14487   AllIvarDecls.push_back(Ivar);
14488 }
14489 
14490 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
14491                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
14492                        SourceLocation RBrac, AttributeList *Attr) {
14493   assert(EnclosingDecl && "missing record or interface decl");
14494 
14495   // If this is an Objective-C @implementation or category and we have
14496   // new fields here we should reset the layout of the interface since
14497   // it will now change.
14498   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
14499     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
14500     switch (DC->getKind()) {
14501     default: break;
14502     case Decl::ObjCCategory:
14503       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
14504       break;
14505     case Decl::ObjCImplementation:
14506       Context.
14507         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
14508       break;
14509     }
14510   }
14511 
14512   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
14513 
14514   // Start counting up the number of named members; make sure to include
14515   // members of anonymous structs and unions in the total.
14516   unsigned NumNamedMembers = 0;
14517   if (Record) {
14518     for (const auto *I : Record->decls()) {
14519       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
14520         if (IFD->getDeclName())
14521           ++NumNamedMembers;
14522     }
14523   }
14524 
14525   // Verify that all the fields are okay.
14526   SmallVector<FieldDecl*, 32> RecFields;
14527 
14528   bool ObjCFieldLifetimeErrReported = false;
14529   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
14530        i != end; ++i) {
14531     FieldDecl *FD = cast<FieldDecl>(*i);
14532 
14533     // Get the type for the field.
14534     const Type *FDTy = FD->getType().getTypePtr();
14535 
14536     if (!FD->isAnonymousStructOrUnion()) {
14537       // Remember all fields written by the user.
14538       RecFields.push_back(FD);
14539     }
14540 
14541     // If the field is already invalid for some reason, don't emit more
14542     // diagnostics about it.
14543     if (FD->isInvalidDecl()) {
14544       EnclosingDecl->setInvalidDecl();
14545       continue;
14546     }
14547 
14548     // C99 6.7.2.1p2:
14549     //   A structure or union shall not contain a member with
14550     //   incomplete or function type (hence, a structure shall not
14551     //   contain an instance of itself, but may contain a pointer to
14552     //   an instance of itself), except that the last member of a
14553     //   structure with more than one named member may have incomplete
14554     //   array type; such a structure (and any union containing,
14555     //   possibly recursively, a member that is such a structure)
14556     //   shall not be a member of a structure or an element of an
14557     //   array.
14558     if (FDTy->isFunctionType()) {
14559       // Field declared as a function.
14560       Diag(FD->getLocation(), diag::err_field_declared_as_function)
14561         << FD->getDeclName();
14562       FD->setInvalidDecl();
14563       EnclosingDecl->setInvalidDecl();
14564       continue;
14565     } else if (FDTy->isIncompleteArrayType() && Record &&
14566                ((i + 1 == Fields.end() && !Record->isUnion()) ||
14567                 ((getLangOpts().MicrosoftExt ||
14568                   getLangOpts().CPlusPlus) &&
14569                  (i + 1 == Fields.end() || Record->isUnion())))) {
14570       // Flexible array member.
14571       // Microsoft and g++ is more permissive regarding flexible array.
14572       // It will accept flexible array in union and also
14573       // as the sole element of a struct/class.
14574       unsigned DiagID = 0;
14575       if (Record->isUnion())
14576         DiagID = getLangOpts().MicrosoftExt
14577                      ? diag::ext_flexible_array_union_ms
14578                      : getLangOpts().CPlusPlus
14579                            ? diag::ext_flexible_array_union_gnu
14580                            : diag::err_flexible_array_union;
14581       else if (NumNamedMembers < 1)
14582         DiagID = getLangOpts().MicrosoftExt
14583                      ? diag::ext_flexible_array_empty_aggregate_ms
14584                      : getLangOpts().CPlusPlus
14585                            ? diag::ext_flexible_array_empty_aggregate_gnu
14586                            : diag::err_flexible_array_empty_aggregate;
14587 
14588       if (DiagID)
14589         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
14590                                         << Record->getTagKind();
14591       // While the layout of types that contain virtual bases is not specified
14592       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
14593       // virtual bases after the derived members.  This would make a flexible
14594       // array member declared at the end of an object not adjacent to the end
14595       // of the type.
14596       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
14597         if (RD->getNumVBases() != 0)
14598           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
14599             << FD->getDeclName() << Record->getTagKind();
14600       if (!getLangOpts().C99)
14601         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
14602           << FD->getDeclName() << Record->getTagKind();
14603 
14604       // If the element type has a non-trivial destructor, we would not
14605       // implicitly destroy the elements, so disallow it for now.
14606       //
14607       // FIXME: GCC allows this. We should probably either implicitly delete
14608       // the destructor of the containing class, or just allow this.
14609       QualType BaseElem = Context.getBaseElementType(FD->getType());
14610       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
14611         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
14612           << FD->getDeclName() << FD->getType();
14613         FD->setInvalidDecl();
14614         EnclosingDecl->setInvalidDecl();
14615         continue;
14616       }
14617       // Okay, we have a legal flexible array member at the end of the struct.
14618       Record->setHasFlexibleArrayMember(true);
14619     } else if (!FDTy->isDependentType() &&
14620                RequireCompleteType(FD->getLocation(), FD->getType(),
14621                                    diag::err_field_incomplete)) {
14622       // Incomplete type
14623       FD->setInvalidDecl();
14624       EnclosingDecl->setInvalidDecl();
14625       continue;
14626     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
14627       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
14628         // A type which contains a flexible array member is considered to be a
14629         // flexible array member.
14630         Record->setHasFlexibleArrayMember(true);
14631         if (!Record->isUnion()) {
14632           // If this is a struct/class and this is not the last element, reject
14633           // it.  Note that GCC supports variable sized arrays in the middle of
14634           // structures.
14635           if (i + 1 != Fields.end())
14636             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
14637               << FD->getDeclName() << FD->getType();
14638           else {
14639             // We support flexible arrays at the end of structs in
14640             // other structs as an extension.
14641             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
14642               << FD->getDeclName();
14643           }
14644         }
14645       }
14646       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
14647           RequireNonAbstractType(FD->getLocation(), FD->getType(),
14648                                  diag::err_abstract_type_in_decl,
14649                                  AbstractIvarType)) {
14650         // Ivars can not have abstract class types
14651         FD->setInvalidDecl();
14652       }
14653       if (Record && FDTTy->getDecl()->hasObjectMember())
14654         Record->setHasObjectMember(true);
14655       if (Record && FDTTy->getDecl()->hasVolatileMember())
14656         Record->setHasVolatileMember(true);
14657     } else if (FDTy->isObjCObjectType()) {
14658       /// A field cannot be an Objective-c object
14659       Diag(FD->getLocation(), diag::err_statically_allocated_object)
14660         << FixItHint::CreateInsertion(FD->getLocation(), "*");
14661       QualType T = Context.getObjCObjectPointerType(FD->getType());
14662       FD->setType(T);
14663     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
14664                Record && !ObjCFieldLifetimeErrReported &&
14665                (!getLangOpts().CPlusPlus || Record->isUnion())) {
14666       // It's an error in ARC or Weak if a field has lifetime.
14667       // We don't want to report this in a system header, though,
14668       // so we just make the field unavailable.
14669       // FIXME: that's really not sufficient; we need to make the type
14670       // itself invalid to, say, initialize or copy.
14671       QualType T = FD->getType();
14672       if (T.hasNonTrivialObjCLifetime()) {
14673         SourceLocation loc = FD->getLocation();
14674         if (getSourceManager().isInSystemHeader(loc)) {
14675           if (!FD->hasAttr<UnavailableAttr>()) {
14676             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14677                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
14678           }
14679         } else {
14680           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
14681             << T->isBlockPointerType() << Record->getTagKind();
14682         }
14683         ObjCFieldLifetimeErrReported = true;
14684       }
14685     } else if (getLangOpts().ObjC1 &&
14686                getLangOpts().getGC() != LangOptions::NonGC &&
14687                Record && !Record->hasObjectMember()) {
14688       if (FD->getType()->isObjCObjectPointerType() ||
14689           FD->getType().isObjCGCStrong())
14690         Record->setHasObjectMember(true);
14691       else if (Context.getAsArrayType(FD->getType())) {
14692         QualType BaseType = Context.getBaseElementType(FD->getType());
14693         if (BaseType->isRecordType() &&
14694             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
14695           Record->setHasObjectMember(true);
14696         else if (BaseType->isObjCObjectPointerType() ||
14697                  BaseType.isObjCGCStrong())
14698                Record->setHasObjectMember(true);
14699       }
14700     }
14701     if (Record && FD->getType().isVolatileQualified())
14702       Record->setHasVolatileMember(true);
14703     // Keep track of the number of named members.
14704     if (FD->getIdentifier())
14705       ++NumNamedMembers;
14706   }
14707 
14708   // Okay, we successfully defined 'Record'.
14709   if (Record) {
14710     bool Completed = false;
14711     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14712       if (!CXXRecord->isInvalidDecl()) {
14713         // Set access bits correctly on the directly-declared conversions.
14714         for (CXXRecordDecl::conversion_iterator
14715                I = CXXRecord->conversion_begin(),
14716                E = CXXRecord->conversion_end(); I != E; ++I)
14717           I.setAccess((*I)->getAccess());
14718       }
14719 
14720       if (!CXXRecord->isDependentType()) {
14721         if (CXXRecord->hasUserDeclaredDestructor()) {
14722           // Adjust user-defined destructor exception spec.
14723           if (getLangOpts().CPlusPlus11)
14724             AdjustDestructorExceptionSpec(CXXRecord,
14725                                           CXXRecord->getDestructor());
14726         }
14727 
14728         if (!CXXRecord->isInvalidDecl()) {
14729           // Add any implicitly-declared members to this class.
14730           AddImplicitlyDeclaredMembersToClass(CXXRecord);
14731 
14732           // If we have virtual base classes, we may end up finding multiple
14733           // final overriders for a given virtual function. Check for this
14734           // problem now.
14735           if (CXXRecord->getNumVBases()) {
14736             CXXFinalOverriderMap FinalOverriders;
14737             CXXRecord->getFinalOverriders(FinalOverriders);
14738 
14739             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
14740                                              MEnd = FinalOverriders.end();
14741                  M != MEnd; ++M) {
14742               for (OverridingMethods::iterator SO = M->second.begin(),
14743                                             SOEnd = M->second.end();
14744                    SO != SOEnd; ++SO) {
14745                 assert(SO->second.size() > 0 &&
14746                        "Virtual function without overridding functions?");
14747                 if (SO->second.size() == 1)
14748                   continue;
14749 
14750                 // C++ [class.virtual]p2:
14751                 //   In a derived class, if a virtual member function of a base
14752                 //   class subobject has more than one final overrider the
14753                 //   program is ill-formed.
14754                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
14755                   << (const NamedDecl *)M->first << Record;
14756                 Diag(M->first->getLocation(),
14757                      diag::note_overridden_virtual_function);
14758                 for (OverridingMethods::overriding_iterator
14759                           OM = SO->second.begin(),
14760                        OMEnd = SO->second.end();
14761                      OM != OMEnd; ++OM)
14762                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
14763                     << (const NamedDecl *)M->first << OM->Method->getParent();
14764 
14765                 Record->setInvalidDecl();
14766               }
14767             }
14768             CXXRecord->completeDefinition(&FinalOverriders);
14769             Completed = true;
14770           }
14771         }
14772       }
14773     }
14774 
14775     if (!Completed)
14776       Record->completeDefinition();
14777 
14778     // We may have deferred checking for a deleted destructor. Check now.
14779     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14780       auto *Dtor = CXXRecord->getDestructor();
14781       if (Dtor && Dtor->isImplicit() &&
14782           ShouldDeleteSpecialMember(Dtor, CXXDestructor))
14783         SetDeclDeleted(Dtor, CXXRecord->getLocation());
14784     }
14785 
14786     if (Record->hasAttrs()) {
14787       CheckAlignasUnderalignment(Record);
14788 
14789       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
14790         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
14791                                            IA->getRange(), IA->getBestCase(),
14792                                            IA->getSemanticSpelling());
14793     }
14794 
14795     // Check if the structure/union declaration is a type that can have zero
14796     // size in C. For C this is a language extension, for C++ it may cause
14797     // compatibility problems.
14798     bool CheckForZeroSize;
14799     if (!getLangOpts().CPlusPlus) {
14800       CheckForZeroSize = true;
14801     } else {
14802       // For C++ filter out types that cannot be referenced in C code.
14803       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
14804       CheckForZeroSize =
14805           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
14806           !CXXRecord->isDependentType() &&
14807           CXXRecord->isCLike();
14808     }
14809     if (CheckForZeroSize) {
14810       bool ZeroSize = true;
14811       bool IsEmpty = true;
14812       unsigned NonBitFields = 0;
14813       for (RecordDecl::field_iterator I = Record->field_begin(),
14814                                       E = Record->field_end();
14815            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
14816         IsEmpty = false;
14817         if (I->isUnnamedBitfield()) {
14818           if (I->getBitWidthValue(Context) > 0)
14819             ZeroSize = false;
14820         } else {
14821           ++NonBitFields;
14822           QualType FieldType = I->getType();
14823           if (FieldType->isIncompleteType() ||
14824               !Context.getTypeSizeInChars(FieldType).isZero())
14825             ZeroSize = false;
14826         }
14827       }
14828 
14829       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
14830       // allowed in C++, but warn if its declaration is inside
14831       // extern "C" block.
14832       if (ZeroSize) {
14833         Diag(RecLoc, getLangOpts().CPlusPlus ?
14834                          diag::warn_zero_size_struct_union_in_extern_c :
14835                          diag::warn_zero_size_struct_union_compat)
14836           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
14837       }
14838 
14839       // Structs without named members are extension in C (C99 6.7.2.1p7),
14840       // but are accepted by GCC.
14841       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
14842         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
14843                                diag::ext_no_named_members_in_struct_union)
14844           << Record->isUnion();
14845       }
14846     }
14847   } else {
14848     ObjCIvarDecl **ClsFields =
14849       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
14850     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
14851       ID->setEndOfDefinitionLoc(RBrac);
14852       // Add ivar's to class's DeclContext.
14853       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14854         ClsFields[i]->setLexicalDeclContext(ID);
14855         ID->addDecl(ClsFields[i]);
14856       }
14857       // Must enforce the rule that ivars in the base classes may not be
14858       // duplicates.
14859       if (ID->getSuperClass())
14860         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
14861     } else if (ObjCImplementationDecl *IMPDecl =
14862                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14863       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
14864       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
14865         // Ivar declared in @implementation never belongs to the implementation.
14866         // Only it is in implementation's lexical context.
14867         ClsFields[I]->setLexicalDeclContext(IMPDecl);
14868       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
14869       IMPDecl->setIvarLBraceLoc(LBrac);
14870       IMPDecl->setIvarRBraceLoc(RBrac);
14871     } else if (ObjCCategoryDecl *CDecl =
14872                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14873       // case of ivars in class extension; all other cases have been
14874       // reported as errors elsewhere.
14875       // FIXME. Class extension does not have a LocEnd field.
14876       // CDecl->setLocEnd(RBrac);
14877       // Add ivar's to class extension's DeclContext.
14878       // Diagnose redeclaration of private ivars.
14879       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
14880       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14881         if (IDecl) {
14882           if (const ObjCIvarDecl *ClsIvar =
14883               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
14884             Diag(ClsFields[i]->getLocation(),
14885                  diag::err_duplicate_ivar_declaration);
14886             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
14887             continue;
14888           }
14889           for (const auto *Ext : IDecl->known_extensions()) {
14890             if (const ObjCIvarDecl *ClsExtIvar
14891                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
14892               Diag(ClsFields[i]->getLocation(),
14893                    diag::err_duplicate_ivar_declaration);
14894               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
14895               continue;
14896             }
14897           }
14898         }
14899         ClsFields[i]->setLexicalDeclContext(CDecl);
14900         CDecl->addDecl(ClsFields[i]);
14901       }
14902       CDecl->setIvarLBraceLoc(LBrac);
14903       CDecl->setIvarRBraceLoc(RBrac);
14904     }
14905   }
14906 
14907   if (Attr)
14908     ProcessDeclAttributeList(S, Record, Attr);
14909 }
14910 
14911 /// \brief Determine whether the given integral value is representable within
14912 /// the given type T.
14913 static bool isRepresentableIntegerValue(ASTContext &Context,
14914                                         llvm::APSInt &Value,
14915                                         QualType T) {
14916   assert(T->isIntegralType(Context) && "Integral type required!");
14917   unsigned BitWidth = Context.getIntWidth(T);
14918 
14919   if (Value.isUnsigned() || Value.isNonNegative()) {
14920     if (T->isSignedIntegerOrEnumerationType())
14921       --BitWidth;
14922     return Value.getActiveBits() <= BitWidth;
14923   }
14924   return Value.getMinSignedBits() <= BitWidth;
14925 }
14926 
14927 // \brief Given an integral type, return the next larger integral type
14928 // (or a NULL type of no such type exists).
14929 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
14930   // FIXME: Int128/UInt128 support, which also needs to be introduced into
14931   // enum checking below.
14932   assert(T->isIntegralType(Context) && "Integral type required!");
14933   const unsigned NumTypes = 4;
14934   QualType SignedIntegralTypes[NumTypes] = {
14935     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
14936   };
14937   QualType UnsignedIntegralTypes[NumTypes] = {
14938     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
14939     Context.UnsignedLongLongTy
14940   };
14941 
14942   unsigned BitWidth = Context.getTypeSize(T);
14943   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
14944                                                         : UnsignedIntegralTypes;
14945   for (unsigned I = 0; I != NumTypes; ++I)
14946     if (Context.getTypeSize(Types[I]) > BitWidth)
14947       return Types[I];
14948 
14949   return QualType();
14950 }
14951 
14952 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
14953                                           EnumConstantDecl *LastEnumConst,
14954                                           SourceLocation IdLoc,
14955                                           IdentifierInfo *Id,
14956                                           Expr *Val) {
14957   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14958   llvm::APSInt EnumVal(IntWidth);
14959   QualType EltTy;
14960 
14961   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
14962     Val = nullptr;
14963 
14964   if (Val)
14965     Val = DefaultLvalueConversion(Val).get();
14966 
14967   if (Val) {
14968     if (Enum->isDependentType() || Val->isTypeDependent())
14969       EltTy = Context.DependentTy;
14970     else {
14971       SourceLocation ExpLoc;
14972       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
14973           !getLangOpts().MSVCCompat) {
14974         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
14975         // constant-expression in the enumerator-definition shall be a converted
14976         // constant expression of the underlying type.
14977         EltTy = Enum->getIntegerType();
14978         ExprResult Converted =
14979           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
14980                                            CCEK_Enumerator);
14981         if (Converted.isInvalid())
14982           Val = nullptr;
14983         else
14984           Val = Converted.get();
14985       } else if (!Val->isValueDependent() &&
14986                  !(Val = VerifyIntegerConstantExpression(Val,
14987                                                          &EnumVal).get())) {
14988         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
14989       } else {
14990         if (Enum->isFixed()) {
14991           EltTy = Enum->getIntegerType();
14992 
14993           // In Obj-C and Microsoft mode, require the enumeration value to be
14994           // representable in the underlying type of the enumeration. In C++11,
14995           // we perform a non-narrowing conversion as part of converted constant
14996           // expression checking.
14997           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14998             if (getLangOpts().MSVCCompat) {
14999               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
15000               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
15001             } else
15002               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
15003           } else
15004             Val = ImpCastExprToType(Val, EltTy,
15005                                     EltTy->isBooleanType() ?
15006                                     CK_IntegralToBoolean : CK_IntegralCast)
15007                     .get();
15008         } else if (getLangOpts().CPlusPlus) {
15009           // C++11 [dcl.enum]p5:
15010           //   If the underlying type is not fixed, the type of each enumerator
15011           //   is the type of its initializing value:
15012           //     - If an initializer is specified for an enumerator, the
15013           //       initializing value has the same type as the expression.
15014           EltTy = Val->getType();
15015         } else {
15016           // C99 6.7.2.2p2:
15017           //   The expression that defines the value of an enumeration constant
15018           //   shall be an integer constant expression that has a value
15019           //   representable as an int.
15020 
15021           // Complain if the value is not representable in an int.
15022           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
15023             Diag(IdLoc, diag::ext_enum_value_not_int)
15024               << EnumVal.toString(10) << Val->getSourceRange()
15025               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
15026           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
15027             // Force the type of the expression to 'int'.
15028             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
15029           }
15030           EltTy = Val->getType();
15031         }
15032       }
15033     }
15034   }
15035 
15036   if (!Val) {
15037     if (Enum->isDependentType())
15038       EltTy = Context.DependentTy;
15039     else if (!LastEnumConst) {
15040       // C++0x [dcl.enum]p5:
15041       //   If the underlying type is not fixed, the type of each enumerator
15042       //   is the type of its initializing value:
15043       //     - If no initializer is specified for the first enumerator, the
15044       //       initializing value has an unspecified integral type.
15045       //
15046       // GCC uses 'int' for its unspecified integral type, as does
15047       // C99 6.7.2.2p3.
15048       if (Enum->isFixed()) {
15049         EltTy = Enum->getIntegerType();
15050       }
15051       else {
15052         EltTy = Context.IntTy;
15053       }
15054     } else {
15055       // Assign the last value + 1.
15056       EnumVal = LastEnumConst->getInitVal();
15057       ++EnumVal;
15058       EltTy = LastEnumConst->getType();
15059 
15060       // Check for overflow on increment.
15061       if (EnumVal < LastEnumConst->getInitVal()) {
15062         // C++0x [dcl.enum]p5:
15063         //   If the underlying type is not fixed, the type of each enumerator
15064         //   is the type of its initializing value:
15065         //
15066         //     - Otherwise the type of the initializing value is the same as
15067         //       the type of the initializing value of the preceding enumerator
15068         //       unless the incremented value is not representable in that type,
15069         //       in which case the type is an unspecified integral type
15070         //       sufficient to contain the incremented value. If no such type
15071         //       exists, the program is ill-formed.
15072         QualType T = getNextLargerIntegralType(Context, EltTy);
15073         if (T.isNull() || Enum->isFixed()) {
15074           // There is no integral type larger enough to represent this
15075           // value. Complain, then allow the value to wrap around.
15076           EnumVal = LastEnumConst->getInitVal();
15077           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
15078           ++EnumVal;
15079           if (Enum->isFixed())
15080             // When the underlying type is fixed, this is ill-formed.
15081             Diag(IdLoc, diag::err_enumerator_wrapped)
15082               << EnumVal.toString(10)
15083               << EltTy;
15084           else
15085             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
15086               << EnumVal.toString(10);
15087         } else {
15088           EltTy = T;
15089         }
15090 
15091         // Retrieve the last enumerator's value, extent that type to the
15092         // type that is supposed to be large enough to represent the incremented
15093         // value, then increment.
15094         EnumVal = LastEnumConst->getInitVal();
15095         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15096         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
15097         ++EnumVal;
15098 
15099         // If we're not in C++, diagnose the overflow of enumerator values,
15100         // which in C99 means that the enumerator value is not representable in
15101         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
15102         // permits enumerator values that are representable in some larger
15103         // integral type.
15104         if (!getLangOpts().CPlusPlus && !T.isNull())
15105           Diag(IdLoc, diag::warn_enum_value_overflow);
15106       } else if (!getLangOpts().CPlusPlus &&
15107                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15108         // Enforce C99 6.7.2.2p2 even when we compute the next value.
15109         Diag(IdLoc, diag::ext_enum_value_not_int)
15110           << EnumVal.toString(10) << 1;
15111       }
15112     }
15113   }
15114 
15115   if (!EltTy->isDependentType()) {
15116     // Make the enumerator value match the signedness and size of the
15117     // enumerator's type.
15118     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
15119     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15120   }
15121 
15122   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
15123                                   Val, EnumVal);
15124 }
15125 
15126 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
15127                                                 SourceLocation IILoc) {
15128   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
15129       !getLangOpts().CPlusPlus)
15130     return SkipBodyInfo();
15131 
15132   // We have an anonymous enum definition. Look up the first enumerator to
15133   // determine if we should merge the definition with an existing one and
15134   // skip the body.
15135   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
15136                                          ForRedeclaration);
15137   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
15138   if (!PrevECD)
15139     return SkipBodyInfo();
15140 
15141   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
15142   NamedDecl *Hidden;
15143   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
15144     SkipBodyInfo Skip;
15145     Skip.Previous = Hidden;
15146     return Skip;
15147   }
15148 
15149   return SkipBodyInfo();
15150 }
15151 
15152 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
15153                               SourceLocation IdLoc, IdentifierInfo *Id,
15154                               AttributeList *Attr,
15155                               SourceLocation EqualLoc, Expr *Val) {
15156   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
15157   EnumConstantDecl *LastEnumConst =
15158     cast_or_null<EnumConstantDecl>(lastEnumConst);
15159 
15160   // The scope passed in may not be a decl scope.  Zip up the scope tree until
15161   // we find one that is.
15162   S = getNonFieldDeclScope(S);
15163 
15164   // Verify that there isn't already something declared with this name in this
15165   // scope.
15166   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
15167                                          ForRedeclaration);
15168   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15169     // Maybe we will complain about the shadowed template parameter.
15170     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
15171     // Just pretend that we didn't see the previous declaration.
15172     PrevDecl = nullptr;
15173   }
15174 
15175   // C++ [class.mem]p15:
15176   // If T is the name of a class, then each of the following shall have a name
15177   // different from T:
15178   // - every enumerator of every member of class T that is an unscoped
15179   // enumerated type
15180   if (!TheEnumDecl->isScoped())
15181     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
15182                             DeclarationNameInfo(Id, IdLoc));
15183 
15184   EnumConstantDecl *New =
15185     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
15186   if (!New)
15187     return nullptr;
15188 
15189   if (PrevDecl) {
15190     // When in C++, we may get a TagDecl with the same name; in this case the
15191     // enum constant will 'hide' the tag.
15192     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
15193            "Received TagDecl when not in C++!");
15194     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
15195         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
15196       if (isa<EnumConstantDecl>(PrevDecl))
15197         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15198       else
15199         Diag(IdLoc, diag::err_redefinition) << Id;
15200       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
15201       return nullptr;
15202     }
15203   }
15204 
15205   // Process attributes.
15206   if (Attr) ProcessDeclAttributeList(S, New, Attr);
15207   AddPragmaAttributes(S, New);
15208 
15209   // Register this decl in the current scope stack.
15210   New->setAccess(TheEnumDecl->getAccess());
15211   PushOnScopeChains(New, S);
15212 
15213   ActOnDocumentableDecl(New);
15214 
15215   return New;
15216 }
15217 
15218 // Returns true when the enum initial expression does not trigger the
15219 // duplicate enum warning.  A few common cases are exempted as follows:
15220 // Element2 = Element1
15221 // Element2 = Element1 + 1
15222 // Element2 = Element1 - 1
15223 // Where Element2 and Element1 are from the same enum.
15224 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
15225   Expr *InitExpr = ECD->getInitExpr();
15226   if (!InitExpr)
15227     return true;
15228   InitExpr = InitExpr->IgnoreImpCasts();
15229 
15230   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
15231     if (!BO->isAdditiveOp())
15232       return true;
15233     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
15234     if (!IL)
15235       return true;
15236     if (IL->getValue() != 1)
15237       return true;
15238 
15239     InitExpr = BO->getLHS();
15240   }
15241 
15242   // This checks if the elements are from the same enum.
15243   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
15244   if (!DRE)
15245     return true;
15246 
15247   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
15248   if (!EnumConstant)
15249     return true;
15250 
15251   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
15252       Enum)
15253     return true;
15254 
15255   return false;
15256 }
15257 
15258 namespace {
15259 struct DupKey {
15260   int64_t val;
15261   bool isTombstoneOrEmptyKey;
15262   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
15263     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
15264 };
15265 
15266 static DupKey GetDupKey(const llvm::APSInt& Val) {
15267   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
15268                 false);
15269 }
15270 
15271 struct DenseMapInfoDupKey {
15272   static DupKey getEmptyKey() { return DupKey(0, true); }
15273   static DupKey getTombstoneKey() { return DupKey(1, true); }
15274   static unsigned getHashValue(const DupKey Key) {
15275     return (unsigned)(Key.val * 37);
15276   }
15277   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
15278     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
15279            LHS.val == RHS.val;
15280   }
15281 };
15282 } // end anonymous namespace
15283 
15284 // Emits a warning when an element is implicitly set a value that
15285 // a previous element has already been set to.
15286 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
15287                                         EnumDecl *Enum,
15288                                         QualType EnumType) {
15289   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
15290     return;
15291   // Avoid anonymous enums
15292   if (!Enum->getIdentifier())
15293     return;
15294 
15295   // Only check for small enums.
15296   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
15297     return;
15298 
15299   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
15300   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
15301 
15302   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
15303   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
15304           ValueToVectorMap;
15305 
15306   DuplicatesVector DupVector;
15307   ValueToVectorMap EnumMap;
15308 
15309   // Populate the EnumMap with all values represented by enum constants without
15310   // an initialier.
15311   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15312     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
15313 
15314     // Null EnumConstantDecl means a previous diagnostic has been emitted for
15315     // this constant.  Skip this enum since it may be ill-formed.
15316     if (!ECD) {
15317       return;
15318     }
15319 
15320     if (ECD->getInitExpr())
15321       continue;
15322 
15323     DupKey Key = GetDupKey(ECD->getInitVal());
15324     DeclOrVector &Entry = EnumMap[Key];
15325 
15326     // First time encountering this value.
15327     if (Entry.isNull())
15328       Entry = ECD;
15329   }
15330 
15331   // Create vectors for any values that has duplicates.
15332   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15333     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
15334     if (!ValidDuplicateEnum(ECD, Enum))
15335       continue;
15336 
15337     DupKey Key = GetDupKey(ECD->getInitVal());
15338 
15339     DeclOrVector& Entry = EnumMap[Key];
15340     if (Entry.isNull())
15341       continue;
15342 
15343     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
15344       // Ensure constants are different.
15345       if (D == ECD)
15346         continue;
15347 
15348       // Create new vector and push values onto it.
15349       ECDVector *Vec = new ECDVector();
15350       Vec->push_back(D);
15351       Vec->push_back(ECD);
15352 
15353       // Update entry to point to the duplicates vector.
15354       Entry = Vec;
15355 
15356       // Store the vector somewhere we can consult later for quick emission of
15357       // diagnostics.
15358       DupVector.push_back(Vec);
15359       continue;
15360     }
15361 
15362     ECDVector *Vec = Entry.get<ECDVector*>();
15363     // Make sure constants are not added more than once.
15364     if (*Vec->begin() == ECD)
15365       continue;
15366 
15367     Vec->push_back(ECD);
15368   }
15369 
15370   // Emit diagnostics.
15371   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
15372                                   DupVectorEnd = DupVector.end();
15373        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
15374     ECDVector *Vec = *DupVectorIter;
15375     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
15376 
15377     // Emit warning for one enum constant.
15378     ECDVector::iterator I = Vec->begin();
15379     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
15380       << (*I)->getName() << (*I)->getInitVal().toString(10)
15381       << (*I)->getSourceRange();
15382     ++I;
15383 
15384     // Emit one note for each of the remaining enum constants with
15385     // the same value.
15386     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
15387       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
15388         << (*I)->getName() << (*I)->getInitVal().toString(10)
15389         << (*I)->getSourceRange();
15390     delete Vec;
15391   }
15392 }
15393 
15394 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
15395                              bool AllowMask) const {
15396   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
15397   assert(ED->isCompleteDefinition() && "expected enum definition");
15398 
15399   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
15400   llvm::APInt &FlagBits = R.first->second;
15401 
15402   if (R.second) {
15403     for (auto *E : ED->enumerators()) {
15404       const auto &EVal = E->getInitVal();
15405       // Only single-bit enumerators introduce new flag values.
15406       if (EVal.isPowerOf2())
15407         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
15408     }
15409   }
15410 
15411   // A value is in a flag enum if either its bits are a subset of the enum's
15412   // flag bits (the first condition) or we are allowing masks and the same is
15413   // true of its complement (the second condition). When masks are allowed, we
15414   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
15415   //
15416   // While it's true that any value could be used as a mask, the assumption is
15417   // that a mask will have all of the insignificant bits set. Anything else is
15418   // likely a logic error.
15419   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
15420   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
15421 }
15422 
15423 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
15424                          Decl *EnumDeclX,
15425                          ArrayRef<Decl *> Elements,
15426                          Scope *S, AttributeList *Attr) {
15427   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
15428   QualType EnumType = Context.getTypeDeclType(Enum);
15429 
15430   if (Attr)
15431     ProcessDeclAttributeList(S, Enum, Attr);
15432 
15433   if (Enum->isDependentType()) {
15434     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15435       EnumConstantDecl *ECD =
15436         cast_or_null<EnumConstantDecl>(Elements[i]);
15437       if (!ECD) continue;
15438 
15439       ECD->setType(EnumType);
15440     }
15441 
15442     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
15443     return;
15444   }
15445 
15446   // TODO: If the result value doesn't fit in an int, it must be a long or long
15447   // long value.  ISO C does not support this, but GCC does as an extension,
15448   // emit a warning.
15449   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15450   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
15451   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
15452 
15453   // Verify that all the values are okay, compute the size of the values, and
15454   // reverse the list.
15455   unsigned NumNegativeBits = 0;
15456   unsigned NumPositiveBits = 0;
15457 
15458   // Keep track of whether all elements have type int.
15459   bool AllElementsInt = true;
15460 
15461   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15462     EnumConstantDecl *ECD =
15463       cast_or_null<EnumConstantDecl>(Elements[i]);
15464     if (!ECD) continue;  // Already issued a diagnostic.
15465 
15466     const llvm::APSInt &InitVal = ECD->getInitVal();
15467 
15468     // Keep track of the size of positive and negative values.
15469     if (InitVal.isUnsigned() || InitVal.isNonNegative())
15470       NumPositiveBits = std::max(NumPositiveBits,
15471                                  (unsigned)InitVal.getActiveBits());
15472     else
15473       NumNegativeBits = std::max(NumNegativeBits,
15474                                  (unsigned)InitVal.getMinSignedBits());
15475 
15476     // Keep track of whether every enum element has type int (very commmon).
15477     if (AllElementsInt)
15478       AllElementsInt = ECD->getType() == Context.IntTy;
15479   }
15480 
15481   // Figure out the type that should be used for this enum.
15482   QualType BestType;
15483   unsigned BestWidth;
15484 
15485   // C++0x N3000 [conv.prom]p3:
15486   //   An rvalue of an unscoped enumeration type whose underlying
15487   //   type is not fixed can be converted to an rvalue of the first
15488   //   of the following types that can represent all the values of
15489   //   the enumeration: int, unsigned int, long int, unsigned long
15490   //   int, long long int, or unsigned long long int.
15491   // C99 6.4.4.3p2:
15492   //   An identifier declared as an enumeration constant has type int.
15493   // The C99 rule is modified by a gcc extension
15494   QualType BestPromotionType;
15495 
15496   bool Packed = Enum->hasAttr<PackedAttr>();
15497   // -fshort-enums is the equivalent to specifying the packed attribute on all
15498   // enum definitions.
15499   if (LangOpts.ShortEnums)
15500     Packed = true;
15501 
15502   if (Enum->isFixed()) {
15503     BestType = Enum->getIntegerType();
15504     if (BestType->isPromotableIntegerType())
15505       BestPromotionType = Context.getPromotedIntegerType(BestType);
15506     else
15507       BestPromotionType = BestType;
15508 
15509     BestWidth = Context.getIntWidth(BestType);
15510   }
15511   else if (NumNegativeBits) {
15512     // If there is a negative value, figure out the smallest integer type (of
15513     // int/long/longlong) that fits.
15514     // If it's packed, check also if it fits a char or a short.
15515     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
15516       BestType = Context.SignedCharTy;
15517       BestWidth = CharWidth;
15518     } else if (Packed && NumNegativeBits <= ShortWidth &&
15519                NumPositiveBits < ShortWidth) {
15520       BestType = Context.ShortTy;
15521       BestWidth = ShortWidth;
15522     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
15523       BestType = Context.IntTy;
15524       BestWidth = IntWidth;
15525     } else {
15526       BestWidth = Context.getTargetInfo().getLongWidth();
15527 
15528       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
15529         BestType = Context.LongTy;
15530       } else {
15531         BestWidth = Context.getTargetInfo().getLongLongWidth();
15532 
15533         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
15534           Diag(Enum->getLocation(), diag::ext_enum_too_large);
15535         BestType = Context.LongLongTy;
15536       }
15537     }
15538     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
15539   } else {
15540     // If there is no negative value, figure out the smallest type that fits
15541     // all of the enumerator values.
15542     // If it's packed, check also if it fits a char or a short.
15543     if (Packed && NumPositiveBits <= CharWidth) {
15544       BestType = Context.UnsignedCharTy;
15545       BestPromotionType = Context.IntTy;
15546       BestWidth = CharWidth;
15547     } else if (Packed && NumPositiveBits <= ShortWidth) {
15548       BestType = Context.UnsignedShortTy;
15549       BestPromotionType = Context.IntTy;
15550       BestWidth = ShortWidth;
15551     } else if (NumPositiveBits <= IntWidth) {
15552       BestType = Context.UnsignedIntTy;
15553       BestWidth = IntWidth;
15554       BestPromotionType
15555         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15556                            ? Context.UnsignedIntTy : Context.IntTy;
15557     } else if (NumPositiveBits <=
15558                (BestWidth = Context.getTargetInfo().getLongWidth())) {
15559       BestType = Context.UnsignedLongTy;
15560       BestPromotionType
15561         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15562                            ? Context.UnsignedLongTy : Context.LongTy;
15563     } else {
15564       BestWidth = Context.getTargetInfo().getLongLongWidth();
15565       assert(NumPositiveBits <= BestWidth &&
15566              "How could an initializer get larger than ULL?");
15567       BestType = Context.UnsignedLongLongTy;
15568       BestPromotionType
15569         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15570                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
15571     }
15572   }
15573 
15574   // Loop over all of the enumerator constants, changing their types to match
15575   // the type of the enum if needed.
15576   for (auto *D : Elements) {
15577     auto *ECD = cast_or_null<EnumConstantDecl>(D);
15578     if (!ECD) continue;  // Already issued a diagnostic.
15579 
15580     // Standard C says the enumerators have int type, but we allow, as an
15581     // extension, the enumerators to be larger than int size.  If each
15582     // enumerator value fits in an int, type it as an int, otherwise type it the
15583     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
15584     // that X has type 'int', not 'unsigned'.
15585 
15586     // Determine whether the value fits into an int.
15587     llvm::APSInt InitVal = ECD->getInitVal();
15588 
15589     // If it fits into an integer type, force it.  Otherwise force it to match
15590     // the enum decl type.
15591     QualType NewTy;
15592     unsigned NewWidth;
15593     bool NewSign;
15594     if (!getLangOpts().CPlusPlus &&
15595         !Enum->isFixed() &&
15596         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
15597       NewTy = Context.IntTy;
15598       NewWidth = IntWidth;
15599       NewSign = true;
15600     } else if (ECD->getType() == BestType) {
15601       // Already the right type!
15602       if (getLangOpts().CPlusPlus)
15603         // C++ [dcl.enum]p4: Following the closing brace of an
15604         // enum-specifier, each enumerator has the type of its
15605         // enumeration.
15606         ECD->setType(EnumType);
15607       continue;
15608     } else {
15609       NewTy = BestType;
15610       NewWidth = BestWidth;
15611       NewSign = BestType->isSignedIntegerOrEnumerationType();
15612     }
15613 
15614     // Adjust the APSInt value.
15615     InitVal = InitVal.extOrTrunc(NewWidth);
15616     InitVal.setIsSigned(NewSign);
15617     ECD->setInitVal(InitVal);
15618 
15619     // Adjust the Expr initializer and type.
15620     if (ECD->getInitExpr() &&
15621         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
15622       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
15623                                                 CK_IntegralCast,
15624                                                 ECD->getInitExpr(),
15625                                                 /*base paths*/ nullptr,
15626                                                 VK_RValue));
15627     if (getLangOpts().CPlusPlus)
15628       // C++ [dcl.enum]p4: Following the closing brace of an
15629       // enum-specifier, each enumerator has the type of its
15630       // enumeration.
15631       ECD->setType(EnumType);
15632     else
15633       ECD->setType(NewTy);
15634   }
15635 
15636   Enum->completeDefinition(BestType, BestPromotionType,
15637                            NumPositiveBits, NumNegativeBits);
15638 
15639   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
15640 
15641   if (Enum->isClosedFlag()) {
15642     for (Decl *D : Elements) {
15643       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
15644       if (!ECD) continue;  // Already issued a diagnostic.
15645 
15646       llvm::APSInt InitVal = ECD->getInitVal();
15647       if (InitVal != 0 && !InitVal.isPowerOf2() &&
15648           !IsValueInFlagEnum(Enum, InitVal, true))
15649         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
15650           << ECD << Enum;
15651     }
15652   }
15653 
15654   // Now that the enum type is defined, ensure it's not been underaligned.
15655   if (Enum->hasAttrs())
15656     CheckAlignasUnderalignment(Enum);
15657 }
15658 
15659 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
15660                                   SourceLocation StartLoc,
15661                                   SourceLocation EndLoc) {
15662   StringLiteral *AsmString = cast<StringLiteral>(expr);
15663 
15664   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
15665                                                    AsmString, StartLoc,
15666                                                    EndLoc);
15667   CurContext->addDecl(New);
15668   return New;
15669 }
15670 
15671 static void checkModuleImportContext(Sema &S, Module *M,
15672                                      SourceLocation ImportLoc, DeclContext *DC,
15673                                      bool FromInclude = false) {
15674   SourceLocation ExternCLoc;
15675 
15676   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
15677     switch (LSD->getLanguage()) {
15678     case LinkageSpecDecl::lang_c:
15679       if (ExternCLoc.isInvalid())
15680         ExternCLoc = LSD->getLocStart();
15681       break;
15682     case LinkageSpecDecl::lang_cxx:
15683       break;
15684     }
15685     DC = LSD->getParent();
15686   }
15687 
15688   while (isa<LinkageSpecDecl>(DC))
15689     DC = DC->getParent();
15690 
15691   if (!isa<TranslationUnitDecl>(DC)) {
15692     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
15693                           ? diag::ext_module_import_not_at_top_level_noop
15694                           : diag::err_module_import_not_at_top_level_fatal)
15695         << M->getFullModuleName() << DC;
15696     S.Diag(cast<Decl>(DC)->getLocStart(),
15697            diag::note_module_import_not_at_top_level) << DC;
15698   } else if (!M->IsExternC && ExternCLoc.isValid()) {
15699     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
15700       << M->getFullModuleName();
15701     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
15702   }
15703 }
15704 
15705 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
15706                                            SourceLocation ModuleLoc,
15707                                            ModuleDeclKind MDK,
15708                                            ModuleIdPath Path) {
15709   // A module implementation unit requires that we are not compiling a module
15710   // of any kind. A module interface unit requires that we are not compiling a
15711   // module map.
15712   switch (getLangOpts().getCompilingModule()) {
15713   case LangOptions::CMK_None:
15714     // It's OK to compile a module interface as a normal translation unit.
15715     break;
15716 
15717   case LangOptions::CMK_ModuleInterface:
15718     if (MDK != ModuleDeclKind::Implementation)
15719       break;
15720 
15721     // We were asked to compile a module interface unit but this is a module
15722     // implementation unit. That indicates the 'export' is missing.
15723     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
15724       << FixItHint::CreateInsertion(ModuleLoc, "export ");
15725     break;
15726 
15727   case LangOptions::CMK_ModuleMap:
15728     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
15729     return nullptr;
15730   }
15731 
15732   // FIXME: Create a ModuleDecl and return it.
15733 
15734   // FIXME: Most of this work should be done by the preprocessor rather than
15735   // here, in order to support macro import.
15736 
15737   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
15738   // modules, the dots here are just another character that can appear in a
15739   // module name.
15740   std::string ModuleName;
15741   for (auto &Piece : Path) {
15742     if (!ModuleName.empty())
15743       ModuleName += ".";
15744     ModuleName += Piece.first->getName();
15745   }
15746 
15747   // If a module name was explicitly specified on the command line, it must be
15748   // correct.
15749   if (!getLangOpts().CurrentModule.empty() &&
15750       getLangOpts().CurrentModule != ModuleName) {
15751     Diag(Path.front().second, diag::err_current_module_name_mismatch)
15752         << SourceRange(Path.front().second, Path.back().second)
15753         << getLangOpts().CurrentModule;
15754     return nullptr;
15755   }
15756   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
15757 
15758   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
15759 
15760   switch (MDK) {
15761   case ModuleDeclKind::Module: {
15762     // FIXME: Check we're not in a submodule.
15763 
15764     // We can't have parsed or imported a definition of this module or parsed a
15765     // module map defining it already.
15766     if (auto *M = Map.findModule(ModuleName)) {
15767       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
15768       if (M->DefinitionLoc.isValid())
15769         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
15770       else if (const auto *FE = M->getASTFile())
15771         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
15772             << FE->getName();
15773       return nullptr;
15774     }
15775 
15776     // Create a Module for the module that we're defining.
15777     Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
15778     assert(Mod && "module creation should not fail");
15779 
15780     // Enter the semantic scope of the module.
15781     ActOnModuleBegin(ModuleLoc, Mod);
15782     return nullptr;
15783   }
15784 
15785   case ModuleDeclKind::Partition:
15786     // FIXME: Check we are in a submodule of the named module.
15787     return nullptr;
15788 
15789   case ModuleDeclKind::Implementation:
15790     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
15791         PP.getIdentifierInfo(ModuleName), Path[0].second);
15792 
15793     DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc);
15794     if (Import.isInvalid())
15795       return nullptr;
15796     return ConvertDeclToDeclGroup(Import.get());
15797   }
15798 
15799   llvm_unreachable("unexpected module decl kind");
15800 }
15801 
15802 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
15803                                    SourceLocation ImportLoc,
15804                                    ModuleIdPath Path) {
15805   Module *Mod =
15806       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
15807                                    /*IsIncludeDirective=*/false);
15808   if (!Mod)
15809     return true;
15810 
15811   VisibleModules.setVisible(Mod, ImportLoc);
15812 
15813   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
15814 
15815   // FIXME: we should support importing a submodule within a different submodule
15816   // of the same top-level module. Until we do, make it an error rather than
15817   // silently ignoring the import.
15818   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
15819   // warn on a redundant import of the current module?
15820   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
15821       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
15822     Diag(ImportLoc, getLangOpts().isCompilingModule()
15823                         ? diag::err_module_self_import
15824                         : diag::err_module_import_in_implementation)
15825         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
15826 
15827   SmallVector<SourceLocation, 2> IdentifierLocs;
15828   Module *ModCheck = Mod;
15829   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
15830     // If we've run out of module parents, just drop the remaining identifiers.
15831     // We need the length to be consistent.
15832     if (!ModCheck)
15833       break;
15834     ModCheck = ModCheck->Parent;
15835 
15836     IdentifierLocs.push_back(Path[I].second);
15837   }
15838 
15839   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15840   ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
15841                                           Mod, IdentifierLocs);
15842   if (!ModuleScopes.empty())
15843     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
15844   TU->addDecl(Import);
15845   return Import;
15846 }
15847 
15848 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15849   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15850   BuildModuleInclude(DirectiveLoc, Mod);
15851 }
15852 
15853 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15854   // Determine whether we're in the #include buffer for a module. The #includes
15855   // in that buffer do not qualify as module imports; they're just an
15856   // implementation detail of us building the module.
15857   //
15858   // FIXME: Should we even get ActOnModuleInclude calls for those?
15859   bool IsInModuleIncludes =
15860       TUKind == TU_Module &&
15861       getSourceManager().isWrittenInMainFile(DirectiveLoc);
15862 
15863   bool ShouldAddImport = !IsInModuleIncludes;
15864 
15865   // If this module import was due to an inclusion directive, create an
15866   // implicit import declaration to capture it in the AST.
15867   if (ShouldAddImport) {
15868     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15869     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15870                                                      DirectiveLoc, Mod,
15871                                                      DirectiveLoc);
15872     if (!ModuleScopes.empty())
15873       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
15874     TU->addDecl(ImportD);
15875     Consumer.HandleImplicitImportDecl(ImportD);
15876   }
15877 
15878   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
15879   VisibleModules.setVisible(Mod, DirectiveLoc);
15880 }
15881 
15882 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
15883   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15884 
15885   ModuleScopes.push_back({});
15886   ModuleScopes.back().Module = Mod;
15887   if (getLangOpts().ModulesLocalVisibility)
15888     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
15889 
15890   VisibleModules.setVisible(Mod, DirectiveLoc);
15891 }
15892 
15893 void Sema::ActOnModuleEnd(SourceLocation EofLoc, Module *Mod) {
15894   if (getLangOpts().ModulesLocalVisibility) {
15895     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
15896     // Leaving a module hides namespace names, so our visible namespace cache
15897     // is now out of date.
15898     VisibleNamespaceCache.clear();
15899   }
15900 
15901   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
15902          "left the wrong module scope");
15903   ModuleScopes.pop_back();
15904 
15905   // We got to the end of processing a #include of a local module. Create an
15906   // ImportDecl as we would for an imported module.
15907   FileID File = getSourceManager().getFileID(EofLoc);
15908   assert(File != getSourceManager().getMainFileID() &&
15909          "end of submodule in main source file");
15910   SourceLocation DirectiveLoc = getSourceManager().getIncludeLoc(File);
15911   BuildModuleInclude(DirectiveLoc, Mod);
15912 }
15913 
15914 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
15915                                                       Module *Mod) {
15916   // Bail if we're not allowed to implicitly import a module here.
15917   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
15918     return;
15919 
15920   // Create the implicit import declaration.
15921   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15922   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15923                                                    Loc, Mod, Loc);
15924   TU->addDecl(ImportD);
15925   Consumer.HandleImplicitImportDecl(ImportD);
15926 
15927   // Make the module visible.
15928   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
15929   VisibleModules.setVisible(Mod, Loc);
15930 }
15931 
15932 /// We have parsed the start of an export declaration, including the '{'
15933 /// (if present).
15934 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
15935                                  SourceLocation LBraceLoc) {
15936   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
15937 
15938   // C++ Modules TS draft:
15939   //   An export-declaration shall appear in the purview of a module other than
15940   //   the global module.
15941   if (ModuleScopes.empty() || !ModuleScopes.back().Module ||
15942       ModuleScopes.back().Module->Kind != Module::ModuleInterfaceUnit)
15943     Diag(ExportLoc, diag::err_export_not_in_module_interface);
15944 
15945   //   An export-declaration [...] shall not contain more than one
15946   //   export keyword.
15947   //
15948   // The intent here is that an export-declaration cannot appear within another
15949   // export-declaration.
15950   if (D->isExported())
15951     Diag(ExportLoc, diag::err_export_within_export);
15952 
15953   CurContext->addDecl(D);
15954   PushDeclContext(S, D);
15955   return D;
15956 }
15957 
15958 /// Complete the definition of an export declaration.
15959 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
15960   auto *ED = cast<ExportDecl>(D);
15961   if (RBraceLoc.isValid())
15962     ED->setRBraceLoc(RBraceLoc);
15963 
15964   // FIXME: Diagnose export of internal-linkage declaration (including
15965   // anonymous namespace).
15966 
15967   PopDeclContext();
15968   return D;
15969 }
15970 
15971 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
15972                                       IdentifierInfo* AliasName,
15973                                       SourceLocation PragmaLoc,
15974                                       SourceLocation NameLoc,
15975                                       SourceLocation AliasNameLoc) {
15976   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
15977                                          LookupOrdinaryName);
15978   AsmLabelAttr *Attr =
15979       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
15980 
15981   // If a declaration that:
15982   // 1) declares a function or a variable
15983   // 2) has external linkage
15984   // already exists, add a label attribute to it.
15985   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15986     if (isDeclExternC(PrevDecl))
15987       PrevDecl->addAttr(Attr);
15988     else
15989       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
15990           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
15991   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
15992   } else
15993     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
15994 }
15995 
15996 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
15997                              SourceLocation PragmaLoc,
15998                              SourceLocation NameLoc) {
15999   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
16000 
16001   if (PrevDecl) {
16002     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
16003   } else {
16004     (void)WeakUndeclaredIdentifiers.insert(
16005       std::pair<IdentifierInfo*,WeakInfo>
16006         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
16007   }
16008 }
16009 
16010 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
16011                                 IdentifierInfo* AliasName,
16012                                 SourceLocation PragmaLoc,
16013                                 SourceLocation NameLoc,
16014                                 SourceLocation AliasNameLoc) {
16015   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
16016                                     LookupOrdinaryName);
16017   WeakInfo W = WeakInfo(Name, NameLoc);
16018 
16019   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16020     if (!PrevDecl->hasAttr<AliasAttr>())
16021       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
16022         DeclApplyPragmaWeak(TUScope, ND, W);
16023   } else {
16024     (void)WeakUndeclaredIdentifiers.insert(
16025       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
16026   }
16027 }
16028 
16029 Decl *Sema::getObjCDeclContext() const {
16030   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
16031 }
16032