1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/CommentDiagnostic.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaInternal.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50 
51 using namespace clang;
52 using namespace sema;
53 
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59 
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62 
63 namespace {
64 
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66  public:
67    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
68                         bool AllowTemplates = false,
69                         bool AllowNonTemplates = true)
70        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
71          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
72      WantExpressionKeywords = false;
73      WantCXXNamedCasts = false;
74      WantRemainingKeywords = false;
75   }
76 
77   bool ValidateCandidate(const TypoCorrection &candidate) override {
78     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
79       if (!AllowInvalidDecl && ND->isInvalidDecl())
80         return false;
81 
82       if (getAsTypeTemplateDecl(ND))
83         return AllowTemplates;
84 
85       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
86       if (!IsType)
87         return false;
88 
89       if (AllowNonTemplates)
90         return true;
91 
92       // An injected-class-name of a class template (specialization) is valid
93       // as a template or as a non-template.
94       if (AllowTemplates) {
95         auto *RD = dyn_cast<CXXRecordDecl>(ND);
96         if (!RD || !RD->isInjectedClassName())
97           return false;
98         RD = cast<CXXRecordDecl>(RD->getDeclContext());
99         return RD->getDescribedClassTemplate() ||
100                isa<ClassTemplateSpecializationDecl>(RD);
101       }
102 
103       return false;
104     }
105 
106     return !WantClassName && candidate.isKeyword();
107   }
108 
109  private:
110   bool AllowInvalidDecl;
111   bool WantClassName;
112   bool AllowTemplates;
113   bool AllowNonTemplates;
114 };
115 
116 } // end anonymous namespace
117 
118 /// \brief Determine whether the token kind starts a simple-type-specifier.
119 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
120   switch (Kind) {
121   // FIXME: Take into account the current language when deciding whether a
122   // token kind is a valid type specifier
123   case tok::kw_short:
124   case tok::kw_long:
125   case tok::kw___int64:
126   case tok::kw___int128:
127   case tok::kw_signed:
128   case tok::kw_unsigned:
129   case tok::kw_void:
130   case tok::kw_char:
131   case tok::kw_int:
132   case tok::kw_half:
133   case tok::kw_float:
134   case tok::kw_double:
135   case tok::kw___float128:
136   case tok::kw_wchar_t:
137   case tok::kw_bool:
138   case tok::kw___underlying_type:
139   case tok::kw___auto_type:
140     return true;
141 
142   case tok::annot_typename:
143   case tok::kw_char16_t:
144   case tok::kw_char32_t:
145   case tok::kw_typeof:
146   case tok::annot_decltype:
147   case tok::kw_decltype:
148     return getLangOpts().CPlusPlus;
149 
150   default:
151     break;
152   }
153 
154   return false;
155 }
156 
157 namespace {
158 enum class UnqualifiedTypeNameLookupResult {
159   NotFound,
160   FoundNonType,
161   FoundType
162 };
163 } // end anonymous namespace
164 
165 /// \brief Tries to perform unqualified lookup of the type decls in bases for
166 /// dependent class.
167 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
168 /// type decl, \a FoundType if only type decls are found.
169 static UnqualifiedTypeNameLookupResult
170 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
171                                 SourceLocation NameLoc,
172                                 const CXXRecordDecl *RD) {
173   if (!RD->hasDefinition())
174     return UnqualifiedTypeNameLookupResult::NotFound;
175   // Look for type decls in base classes.
176   UnqualifiedTypeNameLookupResult FoundTypeDecl =
177       UnqualifiedTypeNameLookupResult::NotFound;
178   for (const auto &Base : RD->bases()) {
179     const CXXRecordDecl *BaseRD = nullptr;
180     if (auto *BaseTT = Base.getType()->getAs<TagType>())
181       BaseRD = BaseTT->getAsCXXRecordDecl();
182     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
183       // Look for type decls in dependent base classes that have known primary
184       // templates.
185       if (!TST || !TST->isDependentType())
186         continue;
187       auto *TD = TST->getTemplateName().getAsTemplateDecl();
188       if (!TD)
189         continue;
190       if (auto *BasePrimaryTemplate =
191           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
192         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
193           BaseRD = BasePrimaryTemplate;
194         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
195           if (const ClassTemplatePartialSpecializationDecl *PS =
196                   CTD->findPartialSpecialization(Base.getType()))
197             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
198               BaseRD = PS;
199         }
200       }
201     }
202     if (BaseRD) {
203       for (NamedDecl *ND : BaseRD->lookup(&II)) {
204         if (!isa<TypeDecl>(ND))
205           return UnqualifiedTypeNameLookupResult::FoundNonType;
206         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
207       }
208       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
209         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
210         case UnqualifiedTypeNameLookupResult::FoundNonType:
211           return UnqualifiedTypeNameLookupResult::FoundNonType;
212         case UnqualifiedTypeNameLookupResult::FoundType:
213           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
214           break;
215         case UnqualifiedTypeNameLookupResult::NotFound:
216           break;
217         }
218       }
219     }
220   }
221 
222   return FoundTypeDecl;
223 }
224 
225 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
226                                                       const IdentifierInfo &II,
227                                                       SourceLocation NameLoc) {
228   // Lookup in the parent class template context, if any.
229   const CXXRecordDecl *RD = nullptr;
230   UnqualifiedTypeNameLookupResult FoundTypeDecl =
231       UnqualifiedTypeNameLookupResult::NotFound;
232   for (DeclContext *DC = S.CurContext;
233        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
234        DC = DC->getParent()) {
235     // Look for type decls in dependent base classes that have known primary
236     // templates.
237     RD = dyn_cast<CXXRecordDecl>(DC);
238     if (RD && RD->getDescribedClassTemplate())
239       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
240   }
241   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
242     return nullptr;
243 
244   // We found some types in dependent base classes.  Recover as if the user
245   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
246   // lookup during template instantiation.
247   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
248 
249   ASTContext &Context = S.Context;
250   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
251                                           cast<Type>(Context.getRecordType(RD)));
252   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
253 
254   CXXScopeSpec SS;
255   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
256 
257   TypeLocBuilder Builder;
258   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
259   DepTL.setNameLoc(NameLoc);
260   DepTL.setElaboratedKeywordLoc(SourceLocation());
261   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
262   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
263 }
264 
265 /// \brief If the identifier refers to a type name within this scope,
266 /// return the declaration of that type.
267 ///
268 /// This routine performs ordinary name lookup of the identifier II
269 /// within the given scope, with optional C++ scope specifier SS, to
270 /// determine whether the name refers to a type. If so, returns an
271 /// opaque pointer (actually a QualType) corresponding to that
272 /// type. Otherwise, returns NULL.
273 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
274                              Scope *S, CXXScopeSpec *SS,
275                              bool isClassName, bool HasTrailingDot,
276                              ParsedType ObjectTypePtr,
277                              bool IsCtorOrDtorName,
278                              bool WantNontrivialTypeSourceInfo,
279                              bool IsClassTemplateDeductionContext,
280                              IdentifierInfo **CorrectedII) {
281   // FIXME: Consider allowing this outside C++1z mode as an extension.
282   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
283                               getLangOpts().CPlusPlus1z && !IsCtorOrDtorName &&
284                               !isClassName && !HasTrailingDot;
285 
286   // Determine where we will perform name lookup.
287   DeclContext *LookupCtx = nullptr;
288   if (ObjectTypePtr) {
289     QualType ObjectType = ObjectTypePtr.get();
290     if (ObjectType->isRecordType())
291       LookupCtx = computeDeclContext(ObjectType);
292   } else if (SS && SS->isNotEmpty()) {
293     LookupCtx = computeDeclContext(*SS, false);
294 
295     if (!LookupCtx) {
296       if (isDependentScopeSpecifier(*SS)) {
297         // C++ [temp.res]p3:
298         //   A qualified-id that refers to a type and in which the
299         //   nested-name-specifier depends on a template-parameter (14.6.2)
300         //   shall be prefixed by the keyword typename to indicate that the
301         //   qualified-id denotes a type, forming an
302         //   elaborated-type-specifier (7.1.5.3).
303         //
304         // We therefore do not perform any name lookup if the result would
305         // refer to a member of an unknown specialization.
306         if (!isClassName && !IsCtorOrDtorName)
307           return nullptr;
308 
309         // We know from the grammar that this name refers to a type,
310         // so build a dependent node to describe the type.
311         if (WantNontrivialTypeSourceInfo)
312           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
313 
314         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
315         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
316                                        II, NameLoc);
317         return ParsedType::make(T);
318       }
319 
320       return nullptr;
321     }
322 
323     if (!LookupCtx->isDependentContext() &&
324         RequireCompleteDeclContext(*SS, LookupCtx))
325       return nullptr;
326   }
327 
328   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
329   // lookup for class-names.
330   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
331                                       LookupOrdinaryName;
332   LookupResult Result(*this, &II, NameLoc, Kind);
333   if (LookupCtx) {
334     // Perform "qualified" name lookup into the declaration context we
335     // computed, which is either the type of the base of a member access
336     // expression or the declaration context associated with a prior
337     // nested-name-specifier.
338     LookupQualifiedName(Result, LookupCtx);
339 
340     if (ObjectTypePtr && Result.empty()) {
341       // C++ [basic.lookup.classref]p3:
342       //   If the unqualified-id is ~type-name, the type-name is looked up
343       //   in the context of the entire postfix-expression. If the type T of
344       //   the object expression is of a class type C, the type-name is also
345       //   looked up in the scope of class C. At least one of the lookups shall
346       //   find a name that refers to (possibly cv-qualified) T.
347       LookupName(Result, S);
348     }
349   } else {
350     // Perform unqualified name lookup.
351     LookupName(Result, S);
352 
353     // For unqualified lookup in a class template in MSVC mode, look into
354     // dependent base classes where the primary class template is known.
355     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
356       if (ParsedType TypeInBase =
357               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
358         return TypeInBase;
359     }
360   }
361 
362   NamedDecl *IIDecl = nullptr;
363   switch (Result.getResultKind()) {
364   case LookupResult::NotFound:
365   case LookupResult::NotFoundInCurrentInstantiation:
366     if (CorrectedII) {
367       TypoCorrection Correction =
368           CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
369                       llvm::make_unique<TypeNameValidatorCCC>(
370                           true, isClassName, AllowDeducedTemplate),
371                       CTK_ErrorRecovery);
372       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
373       TemplateTy Template;
374       bool MemberOfUnknownSpecialization;
375       UnqualifiedId TemplateName;
376       TemplateName.setIdentifier(NewII, NameLoc);
377       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
378       CXXScopeSpec NewSS, *NewSSPtr = SS;
379       if (SS && NNS) {
380         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
381         NewSSPtr = &NewSS;
382       }
383       if (Correction && (NNS || NewII != &II) &&
384           // Ignore a correction to a template type as the to-be-corrected
385           // identifier is not a template (typo correction for template names
386           // is handled elsewhere).
387           !(getLangOpts().CPlusPlus && NewSSPtr &&
388             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
389                            Template, MemberOfUnknownSpecialization))) {
390         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
391                                     isClassName, HasTrailingDot, ObjectTypePtr,
392                                     IsCtorOrDtorName,
393                                     WantNontrivialTypeSourceInfo,
394                                     IsClassTemplateDeductionContext);
395         if (Ty) {
396           diagnoseTypo(Correction,
397                        PDiag(diag::err_unknown_type_or_class_name_suggest)
398                          << Result.getLookupName() << isClassName);
399           if (SS && NNS)
400             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
401           *CorrectedII = NewII;
402           return Ty;
403         }
404       }
405     }
406     // If typo correction failed or was not performed, fall through
407     LLVM_FALLTHROUGH;
408   case LookupResult::FoundOverloaded:
409   case LookupResult::FoundUnresolvedValue:
410     Result.suppressDiagnostics();
411     return nullptr;
412 
413   case LookupResult::Ambiguous:
414     // Recover from type-hiding ambiguities by hiding the type.  We'll
415     // do the lookup again when looking for an object, and we can
416     // diagnose the error then.  If we don't do this, then the error
417     // about hiding the type will be immediately followed by an error
418     // that only makes sense if the identifier was treated like a type.
419     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
420       Result.suppressDiagnostics();
421       return nullptr;
422     }
423 
424     // Look to see if we have a type anywhere in the list of results.
425     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
426          Res != ResEnd; ++Res) {
427       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
428           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
429         if (!IIDecl ||
430             (*Res)->getLocation().getRawEncoding() <
431               IIDecl->getLocation().getRawEncoding())
432           IIDecl = *Res;
433       }
434     }
435 
436     if (!IIDecl) {
437       // None of the entities we found is a type, so there is no way
438       // to even assume that the result is a type. In this case, don't
439       // complain about the ambiguity. The parser will either try to
440       // perform this lookup again (e.g., as an object name), which
441       // will produce the ambiguity, or will complain that it expected
442       // a type name.
443       Result.suppressDiagnostics();
444       return nullptr;
445     }
446 
447     // We found a type within the ambiguous lookup; diagnose the
448     // ambiguity and then return that type. This might be the right
449     // answer, or it might not be, but it suppresses any attempt to
450     // perform the name lookup again.
451     break;
452 
453   case LookupResult::Found:
454     IIDecl = Result.getFoundDecl();
455     break;
456   }
457 
458   assert(IIDecl && "Didn't find decl");
459 
460   QualType T;
461   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
462     // C++ [class.qual]p2: A lookup that would find the injected-class-name
463     // instead names the constructors of the class, except when naming a class.
464     // This is ill-formed when we're not actually forming a ctor or dtor name.
465     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
466     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
467     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
468         FoundRD->isInjectedClassName() &&
469         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
470       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
471           << &II << /*Type*/1;
472 
473     DiagnoseUseOfDecl(IIDecl, NameLoc);
474 
475     T = Context.getTypeDeclType(TD);
476     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
477   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
478     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
479     if (!HasTrailingDot)
480       T = Context.getObjCInterfaceType(IDecl);
481   } else if (AllowDeducedTemplate) {
482     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
483       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
484                                                        QualType(), false);
485   }
486 
487   if (T.isNull()) {
488     // If it's not plausibly a type, suppress diagnostics.
489     Result.suppressDiagnostics();
490     return nullptr;
491   }
492 
493   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
494   // constructor or destructor name (in such a case, the scope specifier
495   // will be attached to the enclosing Expr or Decl node).
496   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
497       !isa<ObjCInterfaceDecl>(IIDecl)) {
498     if (WantNontrivialTypeSourceInfo) {
499       // Construct a type with type-source information.
500       TypeLocBuilder Builder;
501       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
502 
503       T = getElaboratedType(ETK_None, *SS, T);
504       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
505       ElabTL.setElaboratedKeywordLoc(SourceLocation());
506       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
507       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
508     } else {
509       T = getElaboratedType(ETK_None, *SS, T);
510     }
511   }
512 
513   return ParsedType::make(T);
514 }
515 
516 // Builds a fake NNS for the given decl context.
517 static NestedNameSpecifier *
518 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
519   for (;; DC = DC->getLookupParent()) {
520     DC = DC->getPrimaryContext();
521     auto *ND = dyn_cast<NamespaceDecl>(DC);
522     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
523       return NestedNameSpecifier::Create(Context, nullptr, ND);
524     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
525       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
526                                          RD->getTypeForDecl());
527     else if (isa<TranslationUnitDecl>(DC))
528       return NestedNameSpecifier::GlobalSpecifier(Context);
529   }
530   llvm_unreachable("something isn't in TU scope?");
531 }
532 
533 /// Find the parent class with dependent bases of the innermost enclosing method
534 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
535 /// up allowing unqualified dependent type names at class-level, which MSVC
536 /// correctly rejects.
537 static const CXXRecordDecl *
538 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
539   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
540     DC = DC->getPrimaryContext();
541     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
542       if (MD->getParent()->hasAnyDependentBases())
543         return MD->getParent();
544   }
545   return nullptr;
546 }
547 
548 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
549                                           SourceLocation NameLoc,
550                                           bool IsTemplateTypeArg) {
551   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
552 
553   NestedNameSpecifier *NNS = nullptr;
554   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
555     // If we weren't able to parse a default template argument, delay lookup
556     // until instantiation time by making a non-dependent DependentTypeName. We
557     // pretend we saw a NestedNameSpecifier referring to the current scope, and
558     // lookup is retried.
559     // FIXME: This hurts our diagnostic quality, since we get errors like "no
560     // type named 'Foo' in 'current_namespace'" when the user didn't write any
561     // name specifiers.
562     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
563     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
564   } else if (const CXXRecordDecl *RD =
565                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
566     // Build a DependentNameType that will perform lookup into RD at
567     // instantiation time.
568     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
569                                       RD->getTypeForDecl());
570 
571     // Diagnose that this identifier was undeclared, and retry the lookup during
572     // template instantiation.
573     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
574                                                                       << RD;
575   } else {
576     // This is not a situation that we should recover from.
577     return ParsedType();
578   }
579 
580   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
581 
582   // Build type location information.  We synthesized the qualifier, so we have
583   // to build a fake NestedNameSpecifierLoc.
584   NestedNameSpecifierLocBuilder NNSLocBuilder;
585   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
586   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
587 
588   TypeLocBuilder Builder;
589   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
590   DepTL.setNameLoc(NameLoc);
591   DepTL.setElaboratedKeywordLoc(SourceLocation());
592   DepTL.setQualifierLoc(QualifierLoc);
593   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
594 }
595 
596 /// isTagName() - This method is called *for error recovery purposes only*
597 /// to determine if the specified name is a valid tag name ("struct foo").  If
598 /// so, this returns the TST for the tag corresponding to it (TST_enum,
599 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
600 /// cases in C where the user forgot to specify the tag.
601 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
602   // Do a tag name lookup in this scope.
603   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
604   LookupName(R, S, false);
605   R.suppressDiagnostics();
606   if (R.getResultKind() == LookupResult::Found)
607     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
608       switch (TD->getTagKind()) {
609       case TTK_Struct: return DeclSpec::TST_struct;
610       case TTK_Interface: return DeclSpec::TST_interface;
611       case TTK_Union:  return DeclSpec::TST_union;
612       case TTK_Class:  return DeclSpec::TST_class;
613       case TTK_Enum:   return DeclSpec::TST_enum;
614       }
615     }
616 
617   return DeclSpec::TST_unspecified;
618 }
619 
620 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
621 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
622 /// then downgrade the missing typename error to a warning.
623 /// This is needed for MSVC compatibility; Example:
624 /// @code
625 /// template<class T> class A {
626 /// public:
627 ///   typedef int TYPE;
628 /// };
629 /// template<class T> class B : public A<T> {
630 /// public:
631 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
632 /// };
633 /// @endcode
634 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
635   if (CurContext->isRecord()) {
636     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
637       return true;
638 
639     const Type *Ty = SS->getScopeRep()->getAsType();
640 
641     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
642     for (const auto &Base : RD->bases())
643       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
644         return true;
645     return S->isFunctionPrototypeScope();
646   }
647   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
648 }
649 
650 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
651                                    SourceLocation IILoc,
652                                    Scope *S,
653                                    CXXScopeSpec *SS,
654                                    ParsedType &SuggestedType,
655                                    bool IsTemplateName) {
656   // Don't report typename errors for editor placeholders.
657   if (II->isEditorPlaceholder())
658     return;
659   // We don't have anything to suggest (yet).
660   SuggestedType = nullptr;
661 
662   // There may have been a typo in the name of the type. Look up typo
663   // results, in case we have something that we can suggest.
664   if (TypoCorrection Corrected =
665           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
666                       llvm::make_unique<TypeNameValidatorCCC>(
667                           false, false, IsTemplateName, !IsTemplateName),
668                       CTK_ErrorRecovery)) {
669     // FIXME: Support error recovery for the template-name case.
670     bool CanRecover = !IsTemplateName;
671     if (Corrected.isKeyword()) {
672       // We corrected to a keyword.
673       diagnoseTypo(Corrected,
674                    PDiag(IsTemplateName ? diag::err_no_template_suggest
675                                         : diag::err_unknown_typename_suggest)
676                        << II);
677       II = Corrected.getCorrectionAsIdentifierInfo();
678     } else {
679       // We found a similarly-named type or interface; suggest that.
680       if (!SS || !SS->isSet()) {
681         diagnoseTypo(Corrected,
682                      PDiag(IsTemplateName ? diag::err_no_template_suggest
683                                           : diag::err_unknown_typename_suggest)
684                          << II, CanRecover);
685       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
686         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
687         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
688                                 II->getName().equals(CorrectedStr);
689         diagnoseTypo(Corrected,
690                      PDiag(IsTemplateName
691                                ? diag::err_no_member_template_suggest
692                                : diag::err_unknown_nested_typename_suggest)
693                          << II << DC << DroppedSpecifier << SS->getRange(),
694                      CanRecover);
695       } else {
696         llvm_unreachable("could not have corrected a typo here");
697       }
698 
699       if (!CanRecover)
700         return;
701 
702       CXXScopeSpec tmpSS;
703       if (Corrected.getCorrectionSpecifier())
704         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
705                           SourceRange(IILoc));
706       // FIXME: Support class template argument deduction here.
707       SuggestedType =
708           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
709                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
710                       /*IsCtorOrDtorName=*/false,
711                       /*NonTrivialTypeSourceInfo=*/true);
712     }
713     return;
714   }
715 
716   if (getLangOpts().CPlusPlus && !IsTemplateName) {
717     // See if II is a class template that the user forgot to pass arguments to.
718     UnqualifiedId Name;
719     Name.setIdentifier(II, IILoc);
720     CXXScopeSpec EmptySS;
721     TemplateTy TemplateResult;
722     bool MemberOfUnknownSpecialization;
723     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
724                        Name, nullptr, true, TemplateResult,
725                        MemberOfUnknownSpecialization) == TNK_Type_template) {
726       TemplateName TplName = TemplateResult.get();
727       Diag(IILoc, diag::err_template_missing_args)
728         << (int)getTemplateNameKindForDiagnostics(TplName) << TplName;
729       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
730         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
731           << TplDecl->getTemplateParameters()->getSourceRange();
732       }
733       return;
734     }
735   }
736 
737   // FIXME: Should we move the logic that tries to recover from a missing tag
738   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
739 
740   if (!SS || (!SS->isSet() && !SS->isInvalid()))
741     Diag(IILoc, IsTemplateName ? diag::err_no_template
742                                : diag::err_unknown_typename)
743         << II;
744   else if (DeclContext *DC = computeDeclContext(*SS, false))
745     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
746                                : diag::err_typename_nested_not_found)
747         << II << DC << SS->getRange();
748   else if (isDependentScopeSpecifier(*SS)) {
749     unsigned DiagID = diag::err_typename_missing;
750     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
751       DiagID = diag::ext_typename_missing;
752 
753     Diag(SS->getRange().getBegin(), DiagID)
754       << SS->getScopeRep() << II->getName()
755       << SourceRange(SS->getRange().getBegin(), IILoc)
756       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
757     SuggestedType = ActOnTypenameType(S, SourceLocation(),
758                                       *SS, *II, IILoc).get();
759   } else {
760     assert(SS && SS->isInvalid() &&
761            "Invalid scope specifier has already been diagnosed");
762   }
763 }
764 
765 /// \brief Determine whether the given result set contains either a type name
766 /// or
767 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
768   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
769                        NextToken.is(tok::less);
770 
771   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
772     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
773       return true;
774 
775     if (CheckTemplate && isa<TemplateDecl>(*I))
776       return true;
777   }
778 
779   return false;
780 }
781 
782 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
783                                     Scope *S, CXXScopeSpec &SS,
784                                     IdentifierInfo *&Name,
785                                     SourceLocation NameLoc) {
786   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
787   SemaRef.LookupParsedName(R, S, &SS);
788   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
789     StringRef FixItTagName;
790     switch (Tag->getTagKind()) {
791       case TTK_Class:
792         FixItTagName = "class ";
793         break;
794 
795       case TTK_Enum:
796         FixItTagName = "enum ";
797         break;
798 
799       case TTK_Struct:
800         FixItTagName = "struct ";
801         break;
802 
803       case TTK_Interface:
804         FixItTagName = "__interface ";
805         break;
806 
807       case TTK_Union:
808         FixItTagName = "union ";
809         break;
810     }
811 
812     StringRef TagName = FixItTagName.drop_back();
813     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
814       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
815       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
816 
817     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
818          I != IEnd; ++I)
819       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
820         << Name << TagName;
821 
822     // Replace lookup results with just the tag decl.
823     Result.clear(Sema::LookupTagName);
824     SemaRef.LookupParsedName(Result, S, &SS);
825     return true;
826   }
827 
828   return false;
829 }
830 
831 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
832 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
833                                   QualType T, SourceLocation NameLoc) {
834   ASTContext &Context = S.Context;
835 
836   TypeLocBuilder Builder;
837   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
838 
839   T = S.getElaboratedType(ETK_None, SS, T);
840   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
841   ElabTL.setElaboratedKeywordLoc(SourceLocation());
842   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
843   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
844 }
845 
846 Sema::NameClassification
847 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
848                    SourceLocation NameLoc, const Token &NextToken,
849                    bool IsAddressOfOperand,
850                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
851   DeclarationNameInfo NameInfo(Name, NameLoc);
852   ObjCMethodDecl *CurMethod = getCurMethodDecl();
853 
854   if (NextToken.is(tok::coloncolon)) {
855     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
856     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
857   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
858              isCurrentClassName(*Name, S, &SS)) {
859     // Per [class.qual]p2, this names the constructors of SS, not the
860     // injected-class-name. We don't have a classification for that.
861     // There's not much point caching this result, since the parser
862     // will reject it later.
863     return NameClassification::Unknown();
864   }
865 
866   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
867   LookupParsedName(Result, S, &SS, !CurMethod);
868 
869   // For unqualified lookup in a class template in MSVC mode, look into
870   // dependent base classes where the primary class template is known.
871   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
872     if (ParsedType TypeInBase =
873             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
874       return TypeInBase;
875   }
876 
877   // Perform lookup for Objective-C instance variables (including automatically
878   // synthesized instance variables), if we're in an Objective-C method.
879   // FIXME: This lookup really, really needs to be folded in to the normal
880   // unqualified lookup mechanism.
881   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
882     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
883     if (E.get() || E.isInvalid())
884       return E;
885   }
886 
887   bool SecondTry = false;
888   bool IsFilteredTemplateName = false;
889 
890 Corrected:
891   switch (Result.getResultKind()) {
892   case LookupResult::NotFound:
893     // If an unqualified-id is followed by a '(', then we have a function
894     // call.
895     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
896       // In C++, this is an ADL-only call.
897       // FIXME: Reference?
898       if (getLangOpts().CPlusPlus)
899         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
900 
901       // C90 6.3.2.2:
902       //   If the expression that precedes the parenthesized argument list in a
903       //   function call consists solely of an identifier, and if no
904       //   declaration is visible for this identifier, the identifier is
905       //   implicitly declared exactly as if, in the innermost block containing
906       //   the function call, the declaration
907       //
908       //     extern int identifier ();
909       //
910       //   appeared.
911       //
912       // We also allow this in C99 as an extension.
913       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
914         Result.addDecl(D);
915         Result.resolveKind();
916         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
917       }
918     }
919 
920     // In C, we first see whether there is a tag type by the same name, in
921     // which case it's likely that the user just forgot to write "enum",
922     // "struct", or "union".
923     if (!getLangOpts().CPlusPlus && !SecondTry &&
924         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
925       break;
926     }
927 
928     // Perform typo correction to determine if there is another name that is
929     // close to this name.
930     if (!SecondTry && CCC) {
931       SecondTry = true;
932       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
933                                                  Result.getLookupKind(), S,
934                                                  &SS, std::move(CCC),
935                                                  CTK_ErrorRecovery)) {
936         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
937         unsigned QualifiedDiag = diag::err_no_member_suggest;
938 
939         NamedDecl *FirstDecl = Corrected.getFoundDecl();
940         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
941         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
942             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
943           UnqualifiedDiag = diag::err_no_template_suggest;
944           QualifiedDiag = diag::err_no_member_template_suggest;
945         } else if (UnderlyingFirstDecl &&
946                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
947                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
948                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
949           UnqualifiedDiag = diag::err_unknown_typename_suggest;
950           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
951         }
952 
953         if (SS.isEmpty()) {
954           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
955         } else {// FIXME: is this even reachable? Test it.
956           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
957           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
958                                   Name->getName().equals(CorrectedStr);
959           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
960                                     << Name << computeDeclContext(SS, false)
961                                     << DroppedSpecifier << SS.getRange());
962         }
963 
964         // Update the name, so that the caller has the new name.
965         Name = Corrected.getCorrectionAsIdentifierInfo();
966 
967         // Typo correction corrected to a keyword.
968         if (Corrected.isKeyword())
969           return Name;
970 
971         // Also update the LookupResult...
972         // FIXME: This should probably go away at some point
973         Result.clear();
974         Result.setLookupName(Corrected.getCorrection());
975         if (FirstDecl)
976           Result.addDecl(FirstDecl);
977 
978         // If we found an Objective-C instance variable, let
979         // LookupInObjCMethod build the appropriate expression to
980         // reference the ivar.
981         // FIXME: This is a gross hack.
982         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
983           Result.clear();
984           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
985           return E;
986         }
987 
988         goto Corrected;
989       }
990     }
991 
992     // We failed to correct; just fall through and let the parser deal with it.
993     Result.suppressDiagnostics();
994     return NameClassification::Unknown();
995 
996   case LookupResult::NotFoundInCurrentInstantiation: {
997     // We performed name lookup into the current instantiation, and there were
998     // dependent bases, so we treat this result the same way as any other
999     // dependent nested-name-specifier.
1000 
1001     // C++ [temp.res]p2:
1002     //   A name used in a template declaration or definition and that is
1003     //   dependent on a template-parameter is assumed not to name a type
1004     //   unless the applicable name lookup finds a type name or the name is
1005     //   qualified by the keyword typename.
1006     //
1007     // FIXME: If the next token is '<', we might want to ask the parser to
1008     // perform some heroics to see if we actually have a
1009     // template-argument-list, which would indicate a missing 'template'
1010     // keyword here.
1011     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1012                                       NameInfo, IsAddressOfOperand,
1013                                       /*TemplateArgs=*/nullptr);
1014   }
1015 
1016   case LookupResult::Found:
1017   case LookupResult::FoundOverloaded:
1018   case LookupResult::FoundUnresolvedValue:
1019     break;
1020 
1021   case LookupResult::Ambiguous:
1022     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1023         hasAnyAcceptableTemplateNames(Result)) {
1024       // C++ [temp.local]p3:
1025       //   A lookup that finds an injected-class-name (10.2) can result in an
1026       //   ambiguity in certain cases (for example, if it is found in more than
1027       //   one base class). If all of the injected-class-names that are found
1028       //   refer to specializations of the same class template, and if the name
1029       //   is followed by a template-argument-list, the reference refers to the
1030       //   class template itself and not a specialization thereof, and is not
1031       //   ambiguous.
1032       //
1033       // This filtering can make an ambiguous result into an unambiguous one,
1034       // so try again after filtering out template names.
1035       FilterAcceptableTemplateNames(Result);
1036       if (!Result.isAmbiguous()) {
1037         IsFilteredTemplateName = true;
1038         break;
1039       }
1040     }
1041 
1042     // Diagnose the ambiguity and return an error.
1043     return NameClassification::Error();
1044   }
1045 
1046   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1047       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
1048     // C++ [temp.names]p3:
1049     //   After name lookup (3.4) finds that a name is a template-name or that
1050     //   an operator-function-id or a literal- operator-id refers to a set of
1051     //   overloaded functions any member of which is a function template if
1052     //   this is followed by a <, the < is always taken as the delimiter of a
1053     //   template-argument-list and never as the less-than operator.
1054     if (!IsFilteredTemplateName)
1055       FilterAcceptableTemplateNames(Result);
1056 
1057     if (!Result.empty()) {
1058       bool IsFunctionTemplate;
1059       bool IsVarTemplate;
1060       TemplateName Template;
1061       if (Result.end() - Result.begin() > 1) {
1062         IsFunctionTemplate = true;
1063         Template = Context.getOverloadedTemplateName(Result.begin(),
1064                                                      Result.end());
1065       } else {
1066         TemplateDecl *TD
1067           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1068         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1069         IsVarTemplate = isa<VarTemplateDecl>(TD);
1070 
1071         if (SS.isSet() && !SS.isInvalid())
1072           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1073                                                     /*TemplateKeyword=*/false,
1074                                                       TD);
1075         else
1076           Template = TemplateName(TD);
1077       }
1078 
1079       if (IsFunctionTemplate) {
1080         // Function templates always go through overload resolution, at which
1081         // point we'll perform the various checks (e.g., accessibility) we need
1082         // to based on which function we selected.
1083         Result.suppressDiagnostics();
1084 
1085         return NameClassification::FunctionTemplate(Template);
1086       }
1087 
1088       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1089                            : NameClassification::TypeTemplate(Template);
1090     }
1091   }
1092 
1093   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1094   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1095     DiagnoseUseOfDecl(Type, NameLoc);
1096     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1097     QualType T = Context.getTypeDeclType(Type);
1098     if (SS.isNotEmpty())
1099       return buildNestedType(*this, SS, T, NameLoc);
1100     return ParsedType::make(T);
1101   }
1102 
1103   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1104   if (!Class) {
1105     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1106     if (ObjCCompatibleAliasDecl *Alias =
1107             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1108       Class = Alias->getClassInterface();
1109   }
1110 
1111   if (Class) {
1112     DiagnoseUseOfDecl(Class, NameLoc);
1113 
1114     if (NextToken.is(tok::period)) {
1115       // Interface. <something> is parsed as a property reference expression.
1116       // Just return "unknown" as a fall-through for now.
1117       Result.suppressDiagnostics();
1118       return NameClassification::Unknown();
1119     }
1120 
1121     QualType T = Context.getObjCInterfaceType(Class);
1122     return ParsedType::make(T);
1123   }
1124 
1125   // We can have a type template here if we're classifying a template argument.
1126   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1127       !isa<VarTemplateDecl>(FirstDecl))
1128     return NameClassification::TypeTemplate(
1129         TemplateName(cast<TemplateDecl>(FirstDecl)));
1130 
1131   // Check for a tag type hidden by a non-type decl in a few cases where it
1132   // seems likely a type is wanted instead of the non-type that was found.
1133   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1134   if ((NextToken.is(tok::identifier) ||
1135        (NextIsOp &&
1136         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1137       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1138     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1139     DiagnoseUseOfDecl(Type, NameLoc);
1140     QualType T = Context.getTypeDeclType(Type);
1141     if (SS.isNotEmpty())
1142       return buildNestedType(*this, SS, T, NameLoc);
1143     return ParsedType::make(T);
1144   }
1145 
1146   if (FirstDecl->isCXXClassMember())
1147     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1148                                            nullptr, S);
1149 
1150   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1151   return BuildDeclarationNameExpr(SS, Result, ADL);
1152 }
1153 
1154 Sema::TemplateNameKindForDiagnostics
1155 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1156   auto *TD = Name.getAsTemplateDecl();
1157   if (!TD)
1158     return TemplateNameKindForDiagnostics::DependentTemplate;
1159   if (isa<ClassTemplateDecl>(TD))
1160     return TemplateNameKindForDiagnostics::ClassTemplate;
1161   if (isa<FunctionTemplateDecl>(TD))
1162     return TemplateNameKindForDiagnostics::FunctionTemplate;
1163   if (isa<VarTemplateDecl>(TD))
1164     return TemplateNameKindForDiagnostics::VarTemplate;
1165   if (isa<TypeAliasTemplateDecl>(TD))
1166     return TemplateNameKindForDiagnostics::AliasTemplate;
1167   if (isa<TemplateTemplateParmDecl>(TD))
1168     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1169   return TemplateNameKindForDiagnostics::DependentTemplate;
1170 }
1171 
1172 // Determines the context to return to after temporarily entering a
1173 // context.  This depends in an unnecessarily complicated way on the
1174 // exact ordering of callbacks from the parser.
1175 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1176 
1177   // Functions defined inline within classes aren't parsed until we've
1178   // finished parsing the top-level class, so the top-level class is
1179   // the context we'll need to return to.
1180   // A Lambda call operator whose parent is a class must not be treated
1181   // as an inline member function.  A Lambda can be used legally
1182   // either as an in-class member initializer or a default argument.  These
1183   // are parsed once the class has been marked complete and so the containing
1184   // context would be the nested class (when the lambda is defined in one);
1185   // If the class is not complete, then the lambda is being used in an
1186   // ill-formed fashion (such as to specify the width of a bit-field, or
1187   // in an array-bound) - in which case we still want to return the
1188   // lexically containing DC (which could be a nested class).
1189   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1190     DC = DC->getLexicalParent();
1191 
1192     // A function not defined within a class will always return to its
1193     // lexical context.
1194     if (!isa<CXXRecordDecl>(DC))
1195       return DC;
1196 
1197     // A C++ inline method/friend is parsed *after* the topmost class
1198     // it was declared in is fully parsed ("complete");  the topmost
1199     // class is the context we need to return to.
1200     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1201       DC = RD;
1202 
1203     // Return the declaration context of the topmost class the inline method is
1204     // declared in.
1205     return DC;
1206   }
1207 
1208   return DC->getLexicalParent();
1209 }
1210 
1211 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1212   assert(getContainingDC(DC) == CurContext &&
1213       "The next DeclContext should be lexically contained in the current one.");
1214   CurContext = DC;
1215   S->setEntity(DC);
1216 }
1217 
1218 void Sema::PopDeclContext() {
1219   assert(CurContext && "DeclContext imbalance!");
1220 
1221   CurContext = getContainingDC(CurContext);
1222   assert(CurContext && "Popped translation unit!");
1223 }
1224 
1225 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1226                                                                     Decl *D) {
1227   // Unlike PushDeclContext, the context to which we return is not necessarily
1228   // the containing DC of TD, because the new context will be some pre-existing
1229   // TagDecl definition instead of a fresh one.
1230   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1231   CurContext = cast<TagDecl>(D)->getDefinition();
1232   assert(CurContext && "skipping definition of undefined tag");
1233   // Start lookups from the parent of the current context; we don't want to look
1234   // into the pre-existing complete definition.
1235   S->setEntity(CurContext->getLookupParent());
1236   return Result;
1237 }
1238 
1239 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1240   CurContext = static_cast<decltype(CurContext)>(Context);
1241 }
1242 
1243 /// EnterDeclaratorContext - Used when we must lookup names in the context
1244 /// of a declarator's nested name specifier.
1245 ///
1246 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1247   // C++0x [basic.lookup.unqual]p13:
1248   //   A name used in the definition of a static data member of class
1249   //   X (after the qualified-id of the static member) is looked up as
1250   //   if the name was used in a member function of X.
1251   // C++0x [basic.lookup.unqual]p14:
1252   //   If a variable member of a namespace is defined outside of the
1253   //   scope of its namespace then any name used in the definition of
1254   //   the variable member (after the declarator-id) is looked up as
1255   //   if the definition of the variable member occurred in its
1256   //   namespace.
1257   // Both of these imply that we should push a scope whose context
1258   // is the semantic context of the declaration.  We can't use
1259   // PushDeclContext here because that context is not necessarily
1260   // lexically contained in the current context.  Fortunately,
1261   // the containing scope should have the appropriate information.
1262 
1263   assert(!S->getEntity() && "scope already has entity");
1264 
1265 #ifndef NDEBUG
1266   Scope *Ancestor = S->getParent();
1267   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1268   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1269 #endif
1270 
1271   CurContext = DC;
1272   S->setEntity(DC);
1273 }
1274 
1275 void Sema::ExitDeclaratorContext(Scope *S) {
1276   assert(S->getEntity() == CurContext && "Context imbalance!");
1277 
1278   // Switch back to the lexical context.  The safety of this is
1279   // enforced by an assert in EnterDeclaratorContext.
1280   Scope *Ancestor = S->getParent();
1281   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1282   CurContext = Ancestor->getEntity();
1283 
1284   // We don't need to do anything with the scope, which is going to
1285   // disappear.
1286 }
1287 
1288 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1289   // We assume that the caller has already called
1290   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1291   FunctionDecl *FD = D->getAsFunction();
1292   if (!FD)
1293     return;
1294 
1295   // Same implementation as PushDeclContext, but enters the context
1296   // from the lexical parent, rather than the top-level class.
1297   assert(CurContext == FD->getLexicalParent() &&
1298     "The next DeclContext should be lexically contained in the current one.");
1299   CurContext = FD;
1300   S->setEntity(CurContext);
1301 
1302   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1303     ParmVarDecl *Param = FD->getParamDecl(P);
1304     // If the parameter has an identifier, then add it to the scope
1305     if (Param->getIdentifier()) {
1306       S->AddDecl(Param);
1307       IdResolver.AddDecl(Param);
1308     }
1309   }
1310 }
1311 
1312 void Sema::ActOnExitFunctionContext() {
1313   // Same implementation as PopDeclContext, but returns to the lexical parent,
1314   // rather than the top-level class.
1315   assert(CurContext && "DeclContext imbalance!");
1316   CurContext = CurContext->getLexicalParent();
1317   assert(CurContext && "Popped translation unit!");
1318 }
1319 
1320 /// \brief Determine whether we allow overloading of the function
1321 /// PrevDecl with another declaration.
1322 ///
1323 /// This routine determines whether overloading is possible, not
1324 /// whether some new function is actually an overload. It will return
1325 /// true in C++ (where we can always provide overloads) or, as an
1326 /// extension, in C when the previous function is already an
1327 /// overloaded function declaration or has the "overloadable"
1328 /// attribute.
1329 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1330                                        ASTContext &Context) {
1331   if (Context.getLangOpts().CPlusPlus)
1332     return true;
1333 
1334   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1335     return true;
1336 
1337   return (Previous.getResultKind() == LookupResult::Found
1338           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1339 }
1340 
1341 /// Add this decl to the scope shadowed decl chains.
1342 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1343   // Move up the scope chain until we find the nearest enclosing
1344   // non-transparent context. The declaration will be introduced into this
1345   // scope.
1346   while (S->getEntity() && S->getEntity()->isTransparentContext())
1347     S = S->getParent();
1348 
1349   // Add scoped declarations into their context, so that they can be
1350   // found later. Declarations without a context won't be inserted
1351   // into any context.
1352   if (AddToContext)
1353     CurContext->addDecl(D);
1354 
1355   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1356   // are function-local declarations.
1357   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1358       !D->getDeclContext()->getRedeclContext()->Equals(
1359         D->getLexicalDeclContext()->getRedeclContext()) &&
1360       !D->getLexicalDeclContext()->isFunctionOrMethod())
1361     return;
1362 
1363   // Template instantiations should also not be pushed into scope.
1364   if (isa<FunctionDecl>(D) &&
1365       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1366     return;
1367 
1368   // If this replaces anything in the current scope,
1369   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1370                                IEnd = IdResolver.end();
1371   for (; I != IEnd; ++I) {
1372     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1373       S->RemoveDecl(*I);
1374       IdResolver.RemoveDecl(*I);
1375 
1376       // Should only need to replace one decl.
1377       break;
1378     }
1379   }
1380 
1381   S->AddDecl(D);
1382 
1383   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1384     // Implicitly-generated labels may end up getting generated in an order that
1385     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1386     // the label at the appropriate place in the identifier chain.
1387     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1388       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1389       if (IDC == CurContext) {
1390         if (!S->isDeclScope(*I))
1391           continue;
1392       } else if (IDC->Encloses(CurContext))
1393         break;
1394     }
1395 
1396     IdResolver.InsertDeclAfter(I, D);
1397   } else {
1398     IdResolver.AddDecl(D);
1399   }
1400 }
1401 
1402 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1403   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1404     TUScope->AddDecl(D);
1405 }
1406 
1407 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1408                          bool AllowInlineNamespace) {
1409   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1410 }
1411 
1412 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1413   DeclContext *TargetDC = DC->getPrimaryContext();
1414   do {
1415     if (DeclContext *ScopeDC = S->getEntity())
1416       if (ScopeDC->getPrimaryContext() == TargetDC)
1417         return S;
1418   } while ((S = S->getParent()));
1419 
1420   return nullptr;
1421 }
1422 
1423 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1424                                             DeclContext*,
1425                                             ASTContext&);
1426 
1427 /// Filters out lookup results that don't fall within the given scope
1428 /// as determined by isDeclInScope.
1429 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1430                                 bool ConsiderLinkage,
1431                                 bool AllowInlineNamespace) {
1432   LookupResult::Filter F = R.makeFilter();
1433   while (F.hasNext()) {
1434     NamedDecl *D = F.next();
1435 
1436     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1437       continue;
1438 
1439     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1440       continue;
1441 
1442     F.erase();
1443   }
1444 
1445   F.done();
1446 }
1447 
1448 static bool isUsingDecl(NamedDecl *D) {
1449   return isa<UsingShadowDecl>(D) ||
1450          isa<UnresolvedUsingTypenameDecl>(D) ||
1451          isa<UnresolvedUsingValueDecl>(D);
1452 }
1453 
1454 /// Removes using shadow declarations from the lookup results.
1455 static void RemoveUsingDecls(LookupResult &R) {
1456   LookupResult::Filter F = R.makeFilter();
1457   while (F.hasNext())
1458     if (isUsingDecl(F.next()))
1459       F.erase();
1460 
1461   F.done();
1462 }
1463 
1464 /// \brief Check for this common pattern:
1465 /// @code
1466 /// class S {
1467 ///   S(const S&); // DO NOT IMPLEMENT
1468 ///   void operator=(const S&); // DO NOT IMPLEMENT
1469 /// };
1470 /// @endcode
1471 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1472   // FIXME: Should check for private access too but access is set after we get
1473   // the decl here.
1474   if (D->doesThisDeclarationHaveABody())
1475     return false;
1476 
1477   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1478     return CD->isCopyConstructor();
1479   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1480     return Method->isCopyAssignmentOperator();
1481   return false;
1482 }
1483 
1484 // We need this to handle
1485 //
1486 // typedef struct {
1487 //   void *foo() { return 0; }
1488 // } A;
1489 //
1490 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1491 // for example. If 'A', foo will have external linkage. If we have '*A',
1492 // foo will have no linkage. Since we can't know until we get to the end
1493 // of the typedef, this function finds out if D might have non-external linkage.
1494 // Callers should verify at the end of the TU if it D has external linkage or
1495 // not.
1496 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1497   const DeclContext *DC = D->getDeclContext();
1498   while (!DC->isTranslationUnit()) {
1499     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1500       if (!RD->hasNameForLinkage())
1501         return true;
1502     }
1503     DC = DC->getParent();
1504   }
1505 
1506   return !D->isExternallyVisible();
1507 }
1508 
1509 // FIXME: This needs to be refactored; some other isInMainFile users want
1510 // these semantics.
1511 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1512   if (S.TUKind != TU_Complete)
1513     return false;
1514   return S.SourceMgr.isInMainFile(Loc);
1515 }
1516 
1517 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1518   assert(D);
1519 
1520   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1521     return false;
1522 
1523   // Ignore all entities declared within templates, and out-of-line definitions
1524   // of members of class templates.
1525   if (D->getDeclContext()->isDependentContext() ||
1526       D->getLexicalDeclContext()->isDependentContext())
1527     return false;
1528 
1529   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1530     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1531       return false;
1532     // A non-out-of-line declaration of a member specialization was implicitly
1533     // instantiated; it's the out-of-line declaration that we're interested in.
1534     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1535         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1536       return false;
1537 
1538     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1539       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1540         return false;
1541     } else {
1542       // 'static inline' functions are defined in headers; don't warn.
1543       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1544         return false;
1545     }
1546 
1547     if (FD->doesThisDeclarationHaveABody() &&
1548         Context.DeclMustBeEmitted(FD))
1549       return false;
1550   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1551     // Constants and utility variables are defined in headers with internal
1552     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1553     // like "inline".)
1554     if (!isMainFileLoc(*this, VD->getLocation()))
1555       return false;
1556 
1557     if (Context.DeclMustBeEmitted(VD))
1558       return false;
1559 
1560     if (VD->isStaticDataMember() &&
1561         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1562       return false;
1563     if (VD->isStaticDataMember() &&
1564         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1565         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1566       return false;
1567 
1568     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1569       return false;
1570   } else {
1571     return false;
1572   }
1573 
1574   // Only warn for unused decls internal to the translation unit.
1575   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1576   // for inline functions defined in the main source file, for instance.
1577   return mightHaveNonExternalLinkage(D);
1578 }
1579 
1580 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1581   if (!D)
1582     return;
1583 
1584   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1585     const FunctionDecl *First = FD->getFirstDecl();
1586     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1587       return; // First should already be in the vector.
1588   }
1589 
1590   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1591     const VarDecl *First = VD->getFirstDecl();
1592     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1593       return; // First should already be in the vector.
1594   }
1595 
1596   if (ShouldWarnIfUnusedFileScopedDecl(D))
1597     UnusedFileScopedDecls.push_back(D);
1598 }
1599 
1600 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1601   if (D->isInvalidDecl())
1602     return false;
1603 
1604   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1605       D->hasAttr<ObjCPreciseLifetimeAttr>())
1606     return false;
1607 
1608   if (isa<LabelDecl>(D))
1609     return true;
1610 
1611   // Except for labels, we only care about unused decls that are local to
1612   // functions.
1613   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1614   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1615     // For dependent types, the diagnostic is deferred.
1616     WithinFunction =
1617         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1618   if (!WithinFunction)
1619     return false;
1620 
1621   if (isa<TypedefNameDecl>(D))
1622     return true;
1623 
1624   // White-list anything that isn't a local variable.
1625   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1626     return false;
1627 
1628   // Types of valid local variables should be complete, so this should succeed.
1629   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1630 
1631     // White-list anything with an __attribute__((unused)) type.
1632     const auto *Ty = VD->getType().getTypePtr();
1633 
1634     // Only look at the outermost level of typedef.
1635     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1636       if (TT->getDecl()->hasAttr<UnusedAttr>())
1637         return false;
1638     }
1639 
1640     // If we failed to complete the type for some reason, or if the type is
1641     // dependent, don't diagnose the variable.
1642     if (Ty->isIncompleteType() || Ty->isDependentType())
1643       return false;
1644 
1645     // Look at the element type to ensure that the warning behaviour is
1646     // consistent for both scalars and arrays.
1647     Ty = Ty->getBaseElementTypeUnsafe();
1648 
1649     if (const TagType *TT = Ty->getAs<TagType>()) {
1650       const TagDecl *Tag = TT->getDecl();
1651       if (Tag->hasAttr<UnusedAttr>())
1652         return false;
1653 
1654       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1655         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1656           return false;
1657 
1658         if (const Expr *Init = VD->getInit()) {
1659           if (const ExprWithCleanups *Cleanups =
1660                   dyn_cast<ExprWithCleanups>(Init))
1661             Init = Cleanups->getSubExpr();
1662           const CXXConstructExpr *Construct =
1663             dyn_cast<CXXConstructExpr>(Init);
1664           if (Construct && !Construct->isElidable()) {
1665             CXXConstructorDecl *CD = Construct->getConstructor();
1666             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1667               return false;
1668           }
1669         }
1670       }
1671     }
1672 
1673     // TODO: __attribute__((unused)) templates?
1674   }
1675 
1676   return true;
1677 }
1678 
1679 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1680                                      FixItHint &Hint) {
1681   if (isa<LabelDecl>(D)) {
1682     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1683                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1684     if (AfterColon.isInvalid())
1685       return;
1686     Hint = FixItHint::CreateRemoval(CharSourceRange::
1687                                     getCharRange(D->getLocStart(), AfterColon));
1688   }
1689 }
1690 
1691 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1692   if (D->getTypeForDecl()->isDependentType())
1693     return;
1694 
1695   for (auto *TmpD : D->decls()) {
1696     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1697       DiagnoseUnusedDecl(T);
1698     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1699       DiagnoseUnusedNestedTypedefs(R);
1700   }
1701 }
1702 
1703 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1704 /// unless they are marked attr(unused).
1705 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1706   if (!ShouldDiagnoseUnusedDecl(D))
1707     return;
1708 
1709   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1710     // typedefs can be referenced later on, so the diagnostics are emitted
1711     // at end-of-translation-unit.
1712     UnusedLocalTypedefNameCandidates.insert(TD);
1713     return;
1714   }
1715 
1716   FixItHint Hint;
1717   GenerateFixForUnusedDecl(D, Context, Hint);
1718 
1719   unsigned DiagID;
1720   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1721     DiagID = diag::warn_unused_exception_param;
1722   else if (isa<LabelDecl>(D))
1723     DiagID = diag::warn_unused_label;
1724   else
1725     DiagID = diag::warn_unused_variable;
1726 
1727   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1728 }
1729 
1730 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1731   // Verify that we have no forward references left.  If so, there was a goto
1732   // or address of a label taken, but no definition of it.  Label fwd
1733   // definitions are indicated with a null substmt which is also not a resolved
1734   // MS inline assembly label name.
1735   bool Diagnose = false;
1736   if (L->isMSAsmLabel())
1737     Diagnose = !L->isResolvedMSAsmLabel();
1738   else
1739     Diagnose = L->getStmt() == nullptr;
1740   if (Diagnose)
1741     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1742 }
1743 
1744 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1745   S->mergeNRVOIntoParent();
1746 
1747   if (S->decl_empty()) return;
1748   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1749          "Scope shouldn't contain decls!");
1750 
1751   for (auto *TmpD : S->decls()) {
1752     assert(TmpD && "This decl didn't get pushed??");
1753 
1754     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1755     NamedDecl *D = cast<NamedDecl>(TmpD);
1756 
1757     if (!D->getDeclName()) continue;
1758 
1759     // Diagnose unused variables in this scope.
1760     if (!S->hasUnrecoverableErrorOccurred()) {
1761       DiagnoseUnusedDecl(D);
1762       if (const auto *RD = dyn_cast<RecordDecl>(D))
1763         DiagnoseUnusedNestedTypedefs(RD);
1764     }
1765 
1766     // If this was a forward reference to a label, verify it was defined.
1767     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1768       CheckPoppedLabel(LD, *this);
1769 
1770     // Remove this name from our lexical scope, and warn on it if we haven't
1771     // already.
1772     IdResolver.RemoveDecl(D);
1773     auto ShadowI = ShadowingDecls.find(D);
1774     if (ShadowI != ShadowingDecls.end()) {
1775       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1776         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1777             << D << FD << FD->getParent();
1778         Diag(FD->getLocation(), diag::note_previous_declaration);
1779       }
1780       ShadowingDecls.erase(ShadowI);
1781     }
1782   }
1783 }
1784 
1785 /// \brief Look for an Objective-C class in the translation unit.
1786 ///
1787 /// \param Id The name of the Objective-C class we're looking for. If
1788 /// typo-correction fixes this name, the Id will be updated
1789 /// to the fixed name.
1790 ///
1791 /// \param IdLoc The location of the name in the translation unit.
1792 ///
1793 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1794 /// if there is no class with the given name.
1795 ///
1796 /// \returns The declaration of the named Objective-C class, or NULL if the
1797 /// class could not be found.
1798 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1799                                               SourceLocation IdLoc,
1800                                               bool DoTypoCorrection) {
1801   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1802   // creation from this context.
1803   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1804 
1805   if (!IDecl && DoTypoCorrection) {
1806     // Perform typo correction at the given location, but only if we
1807     // find an Objective-C class name.
1808     if (TypoCorrection C = CorrectTypo(
1809             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1810             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1811             CTK_ErrorRecovery)) {
1812       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1813       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1814       Id = IDecl->getIdentifier();
1815     }
1816   }
1817   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1818   // This routine must always return a class definition, if any.
1819   if (Def && Def->getDefinition())
1820       Def = Def->getDefinition();
1821   return Def;
1822 }
1823 
1824 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1825 /// from S, where a non-field would be declared. This routine copes
1826 /// with the difference between C and C++ scoping rules in structs and
1827 /// unions. For example, the following code is well-formed in C but
1828 /// ill-formed in C++:
1829 /// @code
1830 /// struct S6 {
1831 ///   enum { BAR } e;
1832 /// };
1833 ///
1834 /// void test_S6() {
1835 ///   struct S6 a;
1836 ///   a.e = BAR;
1837 /// }
1838 /// @endcode
1839 /// For the declaration of BAR, this routine will return a different
1840 /// scope. The scope S will be the scope of the unnamed enumeration
1841 /// within S6. In C++, this routine will return the scope associated
1842 /// with S6, because the enumeration's scope is a transparent
1843 /// context but structures can contain non-field names. In C, this
1844 /// routine will return the translation unit scope, since the
1845 /// enumeration's scope is a transparent context and structures cannot
1846 /// contain non-field names.
1847 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1848   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1849          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1850          (S->isClassScope() && !getLangOpts().CPlusPlus))
1851     S = S->getParent();
1852   return S;
1853 }
1854 
1855 /// \brief Looks up the declaration of "struct objc_super" and
1856 /// saves it for later use in building builtin declaration of
1857 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1858 /// pre-existing declaration exists no action takes place.
1859 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1860                                         IdentifierInfo *II) {
1861   if (!II->isStr("objc_msgSendSuper"))
1862     return;
1863   ASTContext &Context = ThisSema.Context;
1864 
1865   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1866                       SourceLocation(), Sema::LookupTagName);
1867   ThisSema.LookupName(Result, S);
1868   if (Result.getResultKind() == LookupResult::Found)
1869     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1870       Context.setObjCSuperType(Context.getTagDeclType(TD));
1871 }
1872 
1873 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1874   switch (Error) {
1875   case ASTContext::GE_None:
1876     return "";
1877   case ASTContext::GE_Missing_stdio:
1878     return "stdio.h";
1879   case ASTContext::GE_Missing_setjmp:
1880     return "setjmp.h";
1881   case ASTContext::GE_Missing_ucontext:
1882     return "ucontext.h";
1883   }
1884   llvm_unreachable("unhandled error kind");
1885 }
1886 
1887 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1888 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1889 /// if we're creating this built-in in anticipation of redeclaring the
1890 /// built-in.
1891 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1892                                      Scope *S, bool ForRedeclaration,
1893                                      SourceLocation Loc) {
1894   LookupPredefedObjCSuperType(*this, S, II);
1895 
1896   ASTContext::GetBuiltinTypeError Error;
1897   QualType R = Context.GetBuiltinType(ID, Error);
1898   if (Error) {
1899     if (ForRedeclaration)
1900       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1901           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1902     return nullptr;
1903   }
1904 
1905   if (!ForRedeclaration &&
1906       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1907        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1908     Diag(Loc, diag::ext_implicit_lib_function_decl)
1909         << Context.BuiltinInfo.getName(ID) << R;
1910     if (Context.BuiltinInfo.getHeaderName(ID) &&
1911         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1912       Diag(Loc, diag::note_include_header_or_declare)
1913           << Context.BuiltinInfo.getHeaderName(ID)
1914           << Context.BuiltinInfo.getName(ID);
1915   }
1916 
1917   if (R.isNull())
1918     return nullptr;
1919 
1920   DeclContext *Parent = Context.getTranslationUnitDecl();
1921   if (getLangOpts().CPlusPlus) {
1922     LinkageSpecDecl *CLinkageDecl =
1923         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1924                                 LinkageSpecDecl::lang_c, false);
1925     CLinkageDecl->setImplicit();
1926     Parent->addDecl(CLinkageDecl);
1927     Parent = CLinkageDecl;
1928   }
1929 
1930   FunctionDecl *New = FunctionDecl::Create(Context,
1931                                            Parent,
1932                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1933                                            SC_Extern,
1934                                            false,
1935                                            R->isFunctionProtoType());
1936   New->setImplicit();
1937 
1938   // Create Decl objects for each parameter, adding them to the
1939   // FunctionDecl.
1940   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1941     SmallVector<ParmVarDecl*, 16> Params;
1942     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1943       ParmVarDecl *parm =
1944           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1945                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1946                               SC_None, nullptr);
1947       parm->setScopeInfo(0, i);
1948       Params.push_back(parm);
1949     }
1950     New->setParams(Params);
1951   }
1952 
1953   AddKnownFunctionAttributes(New);
1954   RegisterLocallyScopedExternCDecl(New, S);
1955 
1956   // TUScope is the translation-unit scope to insert this function into.
1957   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1958   // relate Scopes to DeclContexts, and probably eliminate CurContext
1959   // entirely, but we're not there yet.
1960   DeclContext *SavedContext = CurContext;
1961   CurContext = Parent;
1962   PushOnScopeChains(New, TUScope);
1963   CurContext = SavedContext;
1964   return New;
1965 }
1966 
1967 /// Typedef declarations don't have linkage, but they still denote the same
1968 /// entity if their types are the same.
1969 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1970 /// isSameEntity.
1971 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1972                                                      TypedefNameDecl *Decl,
1973                                                      LookupResult &Previous) {
1974   // This is only interesting when modules are enabled.
1975   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1976     return;
1977 
1978   // Empty sets are uninteresting.
1979   if (Previous.empty())
1980     return;
1981 
1982   LookupResult::Filter Filter = Previous.makeFilter();
1983   while (Filter.hasNext()) {
1984     NamedDecl *Old = Filter.next();
1985 
1986     // Non-hidden declarations are never ignored.
1987     if (S.isVisible(Old))
1988       continue;
1989 
1990     // Declarations of the same entity are not ignored, even if they have
1991     // different linkages.
1992     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1993       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1994                                 Decl->getUnderlyingType()))
1995         continue;
1996 
1997       // If both declarations give a tag declaration a typedef name for linkage
1998       // purposes, then they declare the same entity.
1999       if (S.getLangOpts().CPlusPlus &&
2000           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2001           Decl->getAnonDeclWithTypedefName())
2002         continue;
2003     }
2004 
2005     Filter.erase();
2006   }
2007 
2008   Filter.done();
2009 }
2010 
2011 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2012   QualType OldType;
2013   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2014     OldType = OldTypedef->getUnderlyingType();
2015   else
2016     OldType = Context.getTypeDeclType(Old);
2017   QualType NewType = New->getUnderlyingType();
2018 
2019   if (NewType->isVariablyModifiedType()) {
2020     // Must not redefine a typedef with a variably-modified type.
2021     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2022     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2023       << Kind << NewType;
2024     if (Old->getLocation().isValid())
2025       notePreviousDefinition(Old, New->getLocation());
2026     New->setInvalidDecl();
2027     return true;
2028   }
2029 
2030   if (OldType != NewType &&
2031       !OldType->isDependentType() &&
2032       !NewType->isDependentType() &&
2033       !Context.hasSameType(OldType, NewType)) {
2034     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2035     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2036       << Kind << NewType << OldType;
2037     if (Old->getLocation().isValid())
2038       notePreviousDefinition(Old, New->getLocation());
2039     New->setInvalidDecl();
2040     return true;
2041   }
2042   return false;
2043 }
2044 
2045 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2046 /// same name and scope as a previous declaration 'Old'.  Figure out
2047 /// how to resolve this situation, merging decls or emitting
2048 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2049 ///
2050 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2051                                 LookupResult &OldDecls) {
2052   // If the new decl is known invalid already, don't bother doing any
2053   // merging checks.
2054   if (New->isInvalidDecl()) return;
2055 
2056   // Allow multiple definitions for ObjC built-in typedefs.
2057   // FIXME: Verify the underlying types are equivalent!
2058   if (getLangOpts().ObjC1) {
2059     const IdentifierInfo *TypeID = New->getIdentifier();
2060     switch (TypeID->getLength()) {
2061     default: break;
2062     case 2:
2063       {
2064         if (!TypeID->isStr("id"))
2065           break;
2066         QualType T = New->getUnderlyingType();
2067         if (!T->isPointerType())
2068           break;
2069         if (!T->isVoidPointerType()) {
2070           QualType PT = T->getAs<PointerType>()->getPointeeType();
2071           if (!PT->isStructureType())
2072             break;
2073         }
2074         Context.setObjCIdRedefinitionType(T);
2075         // Install the built-in type for 'id', ignoring the current definition.
2076         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2077         return;
2078       }
2079     case 5:
2080       if (!TypeID->isStr("Class"))
2081         break;
2082       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2083       // Install the built-in type for 'Class', ignoring the current definition.
2084       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2085       return;
2086     case 3:
2087       if (!TypeID->isStr("SEL"))
2088         break;
2089       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2090       // Install the built-in type for 'SEL', ignoring the current definition.
2091       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2092       return;
2093     }
2094     // Fall through - the typedef name was not a builtin type.
2095   }
2096 
2097   // Verify the old decl was also a type.
2098   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2099   if (!Old) {
2100     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2101       << New->getDeclName();
2102 
2103     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2104     if (OldD->getLocation().isValid())
2105       notePreviousDefinition(OldD, New->getLocation());
2106 
2107     return New->setInvalidDecl();
2108   }
2109 
2110   // If the old declaration is invalid, just give up here.
2111   if (Old->isInvalidDecl())
2112     return New->setInvalidDecl();
2113 
2114   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2115     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2116     auto *NewTag = New->getAnonDeclWithTypedefName();
2117     NamedDecl *Hidden = nullptr;
2118     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
2119         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2120         !hasVisibleDefinition(OldTag, &Hidden)) {
2121       // There is a definition of this tag, but it is not visible. Use it
2122       // instead of our tag.
2123       New->setTypeForDecl(OldTD->getTypeForDecl());
2124       if (OldTD->isModed())
2125         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2126                                     OldTD->getUnderlyingType());
2127       else
2128         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2129 
2130       // Make the old tag definition visible.
2131       makeMergedDefinitionVisible(Hidden);
2132 
2133       // If this was an unscoped enumeration, yank all of its enumerators
2134       // out of the scope.
2135       if (isa<EnumDecl>(NewTag)) {
2136         Scope *EnumScope = getNonFieldDeclScope(S);
2137         for (auto *D : NewTag->decls()) {
2138           auto *ED = cast<EnumConstantDecl>(D);
2139           assert(EnumScope->isDeclScope(ED));
2140           EnumScope->RemoveDecl(ED);
2141           IdResolver.RemoveDecl(ED);
2142           ED->getLexicalDeclContext()->removeDecl(ED);
2143         }
2144       }
2145     }
2146   }
2147 
2148   // If the typedef types are not identical, reject them in all languages and
2149   // with any extensions enabled.
2150   if (isIncompatibleTypedef(Old, New))
2151     return;
2152 
2153   // The types match.  Link up the redeclaration chain and merge attributes if
2154   // the old declaration was a typedef.
2155   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2156     New->setPreviousDecl(Typedef);
2157     mergeDeclAttributes(New, Old);
2158   }
2159 
2160   if (getLangOpts().MicrosoftExt)
2161     return;
2162 
2163   if (getLangOpts().CPlusPlus) {
2164     // C++ [dcl.typedef]p2:
2165     //   In a given non-class scope, a typedef specifier can be used to
2166     //   redefine the name of any type declared in that scope to refer
2167     //   to the type to which it already refers.
2168     if (!isa<CXXRecordDecl>(CurContext))
2169       return;
2170 
2171     // C++0x [dcl.typedef]p4:
2172     //   In a given class scope, a typedef specifier can be used to redefine
2173     //   any class-name declared in that scope that is not also a typedef-name
2174     //   to refer to the type to which it already refers.
2175     //
2176     // This wording came in via DR424, which was a correction to the
2177     // wording in DR56, which accidentally banned code like:
2178     //
2179     //   struct S {
2180     //     typedef struct A { } A;
2181     //   };
2182     //
2183     // in the C++03 standard. We implement the C++0x semantics, which
2184     // allow the above but disallow
2185     //
2186     //   struct S {
2187     //     typedef int I;
2188     //     typedef int I;
2189     //   };
2190     //
2191     // since that was the intent of DR56.
2192     if (!isa<TypedefNameDecl>(Old))
2193       return;
2194 
2195     Diag(New->getLocation(), diag::err_redefinition)
2196       << New->getDeclName();
2197     notePreviousDefinition(Old, New->getLocation());
2198     return New->setInvalidDecl();
2199   }
2200 
2201   // Modules always permit redefinition of typedefs, as does C11.
2202   if (getLangOpts().Modules || getLangOpts().C11)
2203     return;
2204 
2205   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2206   // is normally mapped to an error, but can be controlled with
2207   // -Wtypedef-redefinition.  If either the original or the redefinition is
2208   // in a system header, don't emit this for compatibility with GCC.
2209   if (getDiagnostics().getSuppressSystemWarnings() &&
2210       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2211       (Old->isImplicit() ||
2212        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2213        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2214     return;
2215 
2216   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2217     << New->getDeclName();
2218   notePreviousDefinition(Old, New->getLocation());
2219 }
2220 
2221 /// DeclhasAttr - returns true if decl Declaration already has the target
2222 /// attribute.
2223 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2224   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2225   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2226   for (const auto *i : D->attrs())
2227     if (i->getKind() == A->getKind()) {
2228       if (Ann) {
2229         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2230           return true;
2231         continue;
2232       }
2233       // FIXME: Don't hardcode this check
2234       if (OA && isa<OwnershipAttr>(i))
2235         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2236       return true;
2237     }
2238 
2239   return false;
2240 }
2241 
2242 static bool isAttributeTargetADefinition(Decl *D) {
2243   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2244     return VD->isThisDeclarationADefinition();
2245   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2246     return TD->isCompleteDefinition() || TD->isBeingDefined();
2247   return true;
2248 }
2249 
2250 /// Merge alignment attributes from \p Old to \p New, taking into account the
2251 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2252 ///
2253 /// \return \c true if any attributes were added to \p New.
2254 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2255   // Look for alignas attributes on Old, and pick out whichever attribute
2256   // specifies the strictest alignment requirement.
2257   AlignedAttr *OldAlignasAttr = nullptr;
2258   AlignedAttr *OldStrictestAlignAttr = nullptr;
2259   unsigned OldAlign = 0;
2260   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2261     // FIXME: We have no way of representing inherited dependent alignments
2262     // in a case like:
2263     //   template<int A, int B> struct alignas(A) X;
2264     //   template<int A, int B> struct alignas(B) X {};
2265     // For now, we just ignore any alignas attributes which are not on the
2266     // definition in such a case.
2267     if (I->isAlignmentDependent())
2268       return false;
2269 
2270     if (I->isAlignas())
2271       OldAlignasAttr = I;
2272 
2273     unsigned Align = I->getAlignment(S.Context);
2274     if (Align > OldAlign) {
2275       OldAlign = Align;
2276       OldStrictestAlignAttr = I;
2277     }
2278   }
2279 
2280   // Look for alignas attributes on New.
2281   AlignedAttr *NewAlignasAttr = nullptr;
2282   unsigned NewAlign = 0;
2283   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2284     if (I->isAlignmentDependent())
2285       return false;
2286 
2287     if (I->isAlignas())
2288       NewAlignasAttr = I;
2289 
2290     unsigned Align = I->getAlignment(S.Context);
2291     if (Align > NewAlign)
2292       NewAlign = Align;
2293   }
2294 
2295   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2296     // Both declarations have 'alignas' attributes. We require them to match.
2297     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2298     // fall short. (If two declarations both have alignas, they must both match
2299     // every definition, and so must match each other if there is a definition.)
2300 
2301     // If either declaration only contains 'alignas(0)' specifiers, then it
2302     // specifies the natural alignment for the type.
2303     if (OldAlign == 0 || NewAlign == 0) {
2304       QualType Ty;
2305       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2306         Ty = VD->getType();
2307       else
2308         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2309 
2310       if (OldAlign == 0)
2311         OldAlign = S.Context.getTypeAlign(Ty);
2312       if (NewAlign == 0)
2313         NewAlign = S.Context.getTypeAlign(Ty);
2314     }
2315 
2316     if (OldAlign != NewAlign) {
2317       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2318         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2319         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2320       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2321     }
2322   }
2323 
2324   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2325     // C++11 [dcl.align]p6:
2326     //   if any declaration of an entity has an alignment-specifier,
2327     //   every defining declaration of that entity shall specify an
2328     //   equivalent alignment.
2329     // C11 6.7.5/7:
2330     //   If the definition of an object does not have an alignment
2331     //   specifier, any other declaration of that object shall also
2332     //   have no alignment specifier.
2333     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2334       << OldAlignasAttr;
2335     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2336       << OldAlignasAttr;
2337   }
2338 
2339   bool AnyAdded = false;
2340 
2341   // Ensure we have an attribute representing the strictest alignment.
2342   if (OldAlign > NewAlign) {
2343     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2344     Clone->setInherited(true);
2345     New->addAttr(Clone);
2346     AnyAdded = true;
2347   }
2348 
2349   // Ensure we have an alignas attribute if the old declaration had one.
2350   if (OldAlignasAttr && !NewAlignasAttr &&
2351       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2352     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2353     Clone->setInherited(true);
2354     New->addAttr(Clone);
2355     AnyAdded = true;
2356   }
2357 
2358   return AnyAdded;
2359 }
2360 
2361 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2362                                const InheritableAttr *Attr,
2363                                Sema::AvailabilityMergeKind AMK) {
2364   // This function copies an attribute Attr from a previous declaration to the
2365   // new declaration D if the new declaration doesn't itself have that attribute
2366   // yet or if that attribute allows duplicates.
2367   // If you're adding a new attribute that requires logic different from
2368   // "use explicit attribute on decl if present, else use attribute from
2369   // previous decl", for example if the attribute needs to be consistent
2370   // between redeclarations, you need to call a custom merge function here.
2371   InheritableAttr *NewAttr = nullptr;
2372   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2373   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2374     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2375                                       AA->isImplicit(), AA->getIntroduced(),
2376                                       AA->getDeprecated(),
2377                                       AA->getObsoleted(), AA->getUnavailable(),
2378                                       AA->getMessage(), AA->getStrict(),
2379                                       AA->getReplacement(), AMK,
2380                                       AttrSpellingListIndex);
2381   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2382     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2383                                     AttrSpellingListIndex);
2384   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2385     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2386                                         AttrSpellingListIndex);
2387   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2388     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2389                                    AttrSpellingListIndex);
2390   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2391     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2392                                    AttrSpellingListIndex);
2393   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2394     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2395                                 FA->getFormatIdx(), FA->getFirstArg(),
2396                                 AttrSpellingListIndex);
2397   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2398     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2399                                  AttrSpellingListIndex);
2400   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2401     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2402                                        AttrSpellingListIndex,
2403                                        IA->getSemanticSpelling());
2404   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2405     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2406                                       &S.Context.Idents.get(AA->getSpelling()),
2407                                       AttrSpellingListIndex);
2408   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2409            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2410             isa<CUDAGlobalAttr>(Attr))) {
2411     // CUDA target attributes are part of function signature for
2412     // overloading purposes and must not be merged.
2413     return false;
2414   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2415     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2416   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2417     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2418   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2419     NewAttr = S.mergeInternalLinkageAttr(
2420         D, InternalLinkageA->getRange(),
2421         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2422         AttrSpellingListIndex);
2423   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2424     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2425                                 &S.Context.Idents.get(CommonA->getSpelling()),
2426                                 AttrSpellingListIndex);
2427   else if (isa<AlignedAttr>(Attr))
2428     // AlignedAttrs are handled separately, because we need to handle all
2429     // such attributes on a declaration at the same time.
2430     NewAttr = nullptr;
2431   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2432            (AMK == Sema::AMK_Override ||
2433             AMK == Sema::AMK_ProtocolImplementation))
2434     NewAttr = nullptr;
2435   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2436     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2437                               UA->getGuid());
2438   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2439     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2440 
2441   if (NewAttr) {
2442     NewAttr->setInherited(true);
2443     D->addAttr(NewAttr);
2444     if (isa<MSInheritanceAttr>(NewAttr))
2445       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2446     return true;
2447   }
2448 
2449   return false;
2450 }
2451 
2452 static const NamedDecl *getDefinition(const Decl *D) {
2453   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2454     return TD->getDefinition();
2455   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2456     const VarDecl *Def = VD->getDefinition();
2457     if (Def)
2458       return Def;
2459     return VD->getActingDefinition();
2460   }
2461   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2462     return FD->getDefinition();
2463   return nullptr;
2464 }
2465 
2466 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2467   for (const auto *Attribute : D->attrs())
2468     if (Attribute->getKind() == Kind)
2469       return true;
2470   return false;
2471 }
2472 
2473 /// checkNewAttributesAfterDef - If we already have a definition, check that
2474 /// there are no new attributes in this declaration.
2475 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2476   if (!New->hasAttrs())
2477     return;
2478 
2479   const NamedDecl *Def = getDefinition(Old);
2480   if (!Def || Def == New)
2481     return;
2482 
2483   AttrVec &NewAttributes = New->getAttrs();
2484   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2485     const Attr *NewAttribute = NewAttributes[I];
2486 
2487     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2488       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2489         Sema::SkipBodyInfo SkipBody;
2490         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2491 
2492         // If we're skipping this definition, drop the "alias" attribute.
2493         if (SkipBody.ShouldSkip) {
2494           NewAttributes.erase(NewAttributes.begin() + I);
2495           --E;
2496           continue;
2497         }
2498       } else {
2499         VarDecl *VD = cast<VarDecl>(New);
2500         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2501                                 VarDecl::TentativeDefinition
2502                             ? diag::err_alias_after_tentative
2503                             : diag::err_redefinition;
2504         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2505         if (Diag == diag::err_redefinition)
2506           S.notePreviousDefinition(Def, VD->getLocation());
2507         else
2508           S.Diag(Def->getLocation(), diag::note_previous_definition);
2509         VD->setInvalidDecl();
2510       }
2511       ++I;
2512       continue;
2513     }
2514 
2515     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2516       // Tentative definitions are only interesting for the alias check above.
2517       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2518         ++I;
2519         continue;
2520       }
2521     }
2522 
2523     if (hasAttribute(Def, NewAttribute->getKind())) {
2524       ++I;
2525       continue; // regular attr merging will take care of validating this.
2526     }
2527 
2528     if (isa<C11NoReturnAttr>(NewAttribute)) {
2529       // C's _Noreturn is allowed to be added to a function after it is defined.
2530       ++I;
2531       continue;
2532     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2533       if (AA->isAlignas()) {
2534         // C++11 [dcl.align]p6:
2535         //   if any declaration of an entity has an alignment-specifier,
2536         //   every defining declaration of that entity shall specify an
2537         //   equivalent alignment.
2538         // C11 6.7.5/7:
2539         //   If the definition of an object does not have an alignment
2540         //   specifier, any other declaration of that object shall also
2541         //   have no alignment specifier.
2542         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2543           << AA;
2544         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2545           << AA;
2546         NewAttributes.erase(NewAttributes.begin() + I);
2547         --E;
2548         continue;
2549       }
2550     }
2551 
2552     S.Diag(NewAttribute->getLocation(),
2553            diag::warn_attribute_precede_definition);
2554     S.Diag(Def->getLocation(), diag::note_previous_definition);
2555     NewAttributes.erase(NewAttributes.begin() + I);
2556     --E;
2557   }
2558 }
2559 
2560 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2561 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2562                                AvailabilityMergeKind AMK) {
2563   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2564     UsedAttr *NewAttr = OldAttr->clone(Context);
2565     NewAttr->setInherited(true);
2566     New->addAttr(NewAttr);
2567   }
2568 
2569   if (!Old->hasAttrs() && !New->hasAttrs())
2570     return;
2571 
2572   // Attributes declared post-definition are currently ignored.
2573   checkNewAttributesAfterDef(*this, New, Old);
2574 
2575   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2576     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2577       if (OldA->getLabel() != NewA->getLabel()) {
2578         // This redeclaration changes __asm__ label.
2579         Diag(New->getLocation(), diag::err_different_asm_label);
2580         Diag(OldA->getLocation(), diag::note_previous_declaration);
2581       }
2582     } else if (Old->isUsed()) {
2583       // This redeclaration adds an __asm__ label to a declaration that has
2584       // already been ODR-used.
2585       Diag(New->getLocation(), diag::err_late_asm_label_name)
2586         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2587     }
2588   }
2589 
2590   // Re-declaration cannot add abi_tag's.
2591   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2592     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2593       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2594         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2595                       NewTag) == OldAbiTagAttr->tags_end()) {
2596           Diag(NewAbiTagAttr->getLocation(),
2597                diag::err_new_abi_tag_on_redeclaration)
2598               << NewTag;
2599           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2600         }
2601       }
2602     } else {
2603       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2604       Diag(Old->getLocation(), diag::note_previous_declaration);
2605     }
2606   }
2607 
2608   if (!Old->hasAttrs())
2609     return;
2610 
2611   bool foundAny = New->hasAttrs();
2612 
2613   // Ensure that any moving of objects within the allocated map is done before
2614   // we process them.
2615   if (!foundAny) New->setAttrs(AttrVec());
2616 
2617   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2618     // Ignore deprecated/unavailable/availability attributes if requested.
2619     AvailabilityMergeKind LocalAMK = AMK_None;
2620     if (isa<DeprecatedAttr>(I) ||
2621         isa<UnavailableAttr>(I) ||
2622         isa<AvailabilityAttr>(I)) {
2623       switch (AMK) {
2624       case AMK_None:
2625         continue;
2626 
2627       case AMK_Redeclaration:
2628       case AMK_Override:
2629       case AMK_ProtocolImplementation:
2630         LocalAMK = AMK;
2631         break;
2632       }
2633     }
2634 
2635     // Already handled.
2636     if (isa<UsedAttr>(I))
2637       continue;
2638 
2639     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2640       foundAny = true;
2641   }
2642 
2643   if (mergeAlignedAttrs(*this, New, Old))
2644     foundAny = true;
2645 
2646   if (!foundAny) New->dropAttrs();
2647 }
2648 
2649 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2650 /// to the new one.
2651 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2652                                      const ParmVarDecl *oldDecl,
2653                                      Sema &S) {
2654   // C++11 [dcl.attr.depend]p2:
2655   //   The first declaration of a function shall specify the
2656   //   carries_dependency attribute for its declarator-id if any declaration
2657   //   of the function specifies the carries_dependency attribute.
2658   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2659   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2660     S.Diag(CDA->getLocation(),
2661            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2662     // Find the first declaration of the parameter.
2663     // FIXME: Should we build redeclaration chains for function parameters?
2664     const FunctionDecl *FirstFD =
2665       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2666     const ParmVarDecl *FirstVD =
2667       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2668     S.Diag(FirstVD->getLocation(),
2669            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2670   }
2671 
2672   if (!oldDecl->hasAttrs())
2673     return;
2674 
2675   bool foundAny = newDecl->hasAttrs();
2676 
2677   // Ensure that any moving of objects within the allocated map is
2678   // done before we process them.
2679   if (!foundAny) newDecl->setAttrs(AttrVec());
2680 
2681   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2682     if (!DeclHasAttr(newDecl, I)) {
2683       InheritableAttr *newAttr =
2684         cast<InheritableParamAttr>(I->clone(S.Context));
2685       newAttr->setInherited(true);
2686       newDecl->addAttr(newAttr);
2687       foundAny = true;
2688     }
2689   }
2690 
2691   if (!foundAny) newDecl->dropAttrs();
2692 }
2693 
2694 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2695                                 const ParmVarDecl *OldParam,
2696                                 Sema &S) {
2697   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2698     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2699       if (*Oldnullability != *Newnullability) {
2700         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2701           << DiagNullabilityKind(
2702                *Newnullability,
2703                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2704                 != 0))
2705           << DiagNullabilityKind(
2706                *Oldnullability,
2707                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2708                 != 0));
2709         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2710       }
2711     } else {
2712       QualType NewT = NewParam->getType();
2713       NewT = S.Context.getAttributedType(
2714                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2715                          NewT, NewT);
2716       NewParam->setType(NewT);
2717     }
2718   }
2719 }
2720 
2721 namespace {
2722 
2723 /// Used in MergeFunctionDecl to keep track of function parameters in
2724 /// C.
2725 struct GNUCompatibleParamWarning {
2726   ParmVarDecl *OldParm;
2727   ParmVarDecl *NewParm;
2728   QualType PromotedType;
2729 };
2730 
2731 } // end anonymous namespace
2732 
2733 /// getSpecialMember - get the special member enum for a method.
2734 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2735   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2736     if (Ctor->isDefaultConstructor())
2737       return Sema::CXXDefaultConstructor;
2738 
2739     if (Ctor->isCopyConstructor())
2740       return Sema::CXXCopyConstructor;
2741 
2742     if (Ctor->isMoveConstructor())
2743       return Sema::CXXMoveConstructor;
2744   } else if (isa<CXXDestructorDecl>(MD)) {
2745     return Sema::CXXDestructor;
2746   } else if (MD->isCopyAssignmentOperator()) {
2747     return Sema::CXXCopyAssignment;
2748   } else if (MD->isMoveAssignmentOperator()) {
2749     return Sema::CXXMoveAssignment;
2750   }
2751 
2752   return Sema::CXXInvalid;
2753 }
2754 
2755 // Determine whether the previous declaration was a definition, implicit
2756 // declaration, or a declaration.
2757 template <typename T>
2758 static std::pair<diag::kind, SourceLocation>
2759 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2760   diag::kind PrevDiag;
2761   SourceLocation OldLocation = Old->getLocation();
2762   if (Old->isThisDeclarationADefinition())
2763     PrevDiag = diag::note_previous_definition;
2764   else if (Old->isImplicit()) {
2765     PrevDiag = diag::note_previous_implicit_declaration;
2766     if (OldLocation.isInvalid())
2767       OldLocation = New->getLocation();
2768   } else
2769     PrevDiag = diag::note_previous_declaration;
2770   return std::make_pair(PrevDiag, OldLocation);
2771 }
2772 
2773 /// canRedefineFunction - checks if a function can be redefined. Currently,
2774 /// only extern inline functions can be redefined, and even then only in
2775 /// GNU89 mode.
2776 static bool canRedefineFunction(const FunctionDecl *FD,
2777                                 const LangOptions& LangOpts) {
2778   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2779           !LangOpts.CPlusPlus &&
2780           FD->isInlineSpecified() &&
2781           FD->getStorageClass() == SC_Extern);
2782 }
2783 
2784 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2785   const AttributedType *AT = T->getAs<AttributedType>();
2786   while (AT && !AT->isCallingConv())
2787     AT = AT->getModifiedType()->getAs<AttributedType>();
2788   return AT;
2789 }
2790 
2791 template <typename T>
2792 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2793   const DeclContext *DC = Old->getDeclContext();
2794   if (DC->isRecord())
2795     return false;
2796 
2797   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2798   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2799     return true;
2800   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2801     return true;
2802   return false;
2803 }
2804 
2805 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2806 static bool isExternC(VarTemplateDecl *) { return false; }
2807 
2808 /// \brief Check whether a redeclaration of an entity introduced by a
2809 /// using-declaration is valid, given that we know it's not an overload
2810 /// (nor a hidden tag declaration).
2811 template<typename ExpectedDecl>
2812 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2813                                    ExpectedDecl *New) {
2814   // C++11 [basic.scope.declarative]p4:
2815   //   Given a set of declarations in a single declarative region, each of
2816   //   which specifies the same unqualified name,
2817   //   -- they shall all refer to the same entity, or all refer to functions
2818   //      and function templates; or
2819   //   -- exactly one declaration shall declare a class name or enumeration
2820   //      name that is not a typedef name and the other declarations shall all
2821   //      refer to the same variable or enumerator, or all refer to functions
2822   //      and function templates; in this case the class name or enumeration
2823   //      name is hidden (3.3.10).
2824 
2825   // C++11 [namespace.udecl]p14:
2826   //   If a function declaration in namespace scope or block scope has the
2827   //   same name and the same parameter-type-list as a function introduced
2828   //   by a using-declaration, and the declarations do not declare the same
2829   //   function, the program is ill-formed.
2830 
2831   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2832   if (Old &&
2833       !Old->getDeclContext()->getRedeclContext()->Equals(
2834           New->getDeclContext()->getRedeclContext()) &&
2835       !(isExternC(Old) && isExternC(New)))
2836     Old = nullptr;
2837 
2838   if (!Old) {
2839     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2840     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2841     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2842     return true;
2843   }
2844   return false;
2845 }
2846 
2847 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2848                                             const FunctionDecl *B) {
2849   assert(A->getNumParams() == B->getNumParams());
2850 
2851   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2852     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2853     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2854     if (AttrA == AttrB)
2855       return true;
2856     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2857   };
2858 
2859   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2860 }
2861 
2862 /// MergeFunctionDecl - We just parsed a function 'New' from
2863 /// declarator D which has the same name and scope as a previous
2864 /// declaration 'Old'.  Figure out how to resolve this situation,
2865 /// merging decls or emitting diagnostics as appropriate.
2866 ///
2867 /// In C++, New and Old must be declarations that are not
2868 /// overloaded. Use IsOverload to determine whether New and Old are
2869 /// overloaded, and to select the Old declaration that New should be
2870 /// merged with.
2871 ///
2872 /// Returns true if there was an error, false otherwise.
2873 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2874                              Scope *S, bool MergeTypeWithOld) {
2875   // Verify the old decl was also a function.
2876   FunctionDecl *Old = OldD->getAsFunction();
2877   if (!Old) {
2878     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2879       if (New->getFriendObjectKind()) {
2880         Diag(New->getLocation(), diag::err_using_decl_friend);
2881         Diag(Shadow->getTargetDecl()->getLocation(),
2882              diag::note_using_decl_target);
2883         Diag(Shadow->getUsingDecl()->getLocation(),
2884              diag::note_using_decl) << 0;
2885         return true;
2886       }
2887 
2888       // Check whether the two declarations might declare the same function.
2889       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2890         return true;
2891       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2892     } else {
2893       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2894         << New->getDeclName();
2895       notePreviousDefinition(OldD, New->getLocation());
2896       return true;
2897     }
2898   }
2899 
2900   // If the old declaration is invalid, just give up here.
2901   if (Old->isInvalidDecl())
2902     return true;
2903 
2904   diag::kind PrevDiag;
2905   SourceLocation OldLocation;
2906   std::tie(PrevDiag, OldLocation) =
2907       getNoteDiagForInvalidRedeclaration(Old, New);
2908 
2909   // Don't complain about this if we're in GNU89 mode and the old function
2910   // is an extern inline function.
2911   // Don't complain about specializations. They are not supposed to have
2912   // storage classes.
2913   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2914       New->getStorageClass() == SC_Static &&
2915       Old->hasExternalFormalLinkage() &&
2916       !New->getTemplateSpecializationInfo() &&
2917       !canRedefineFunction(Old, getLangOpts())) {
2918     if (getLangOpts().MicrosoftExt) {
2919       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2920       Diag(OldLocation, PrevDiag);
2921     } else {
2922       Diag(New->getLocation(), diag::err_static_non_static) << New;
2923       Diag(OldLocation, PrevDiag);
2924       return true;
2925     }
2926   }
2927 
2928   if (New->hasAttr<InternalLinkageAttr>() &&
2929       !Old->hasAttr<InternalLinkageAttr>()) {
2930     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2931         << New->getDeclName();
2932     notePreviousDefinition(Old, New->getLocation());
2933     New->dropAttr<InternalLinkageAttr>();
2934   }
2935 
2936   // If a function is first declared with a calling convention, but is later
2937   // declared or defined without one, all following decls assume the calling
2938   // convention of the first.
2939   //
2940   // It's OK if a function is first declared without a calling convention,
2941   // but is later declared or defined with the default calling convention.
2942   //
2943   // To test if either decl has an explicit calling convention, we look for
2944   // AttributedType sugar nodes on the type as written.  If they are missing or
2945   // were canonicalized away, we assume the calling convention was implicit.
2946   //
2947   // Note also that we DO NOT return at this point, because we still have
2948   // other tests to run.
2949   QualType OldQType = Context.getCanonicalType(Old->getType());
2950   QualType NewQType = Context.getCanonicalType(New->getType());
2951   const FunctionType *OldType = cast<FunctionType>(OldQType);
2952   const FunctionType *NewType = cast<FunctionType>(NewQType);
2953   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2954   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2955   bool RequiresAdjustment = false;
2956 
2957   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2958     FunctionDecl *First = Old->getFirstDecl();
2959     const FunctionType *FT =
2960         First->getType().getCanonicalType()->castAs<FunctionType>();
2961     FunctionType::ExtInfo FI = FT->getExtInfo();
2962     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2963     if (!NewCCExplicit) {
2964       // Inherit the CC from the previous declaration if it was specified
2965       // there but not here.
2966       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2967       RequiresAdjustment = true;
2968     } else {
2969       // Calling conventions aren't compatible, so complain.
2970       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2971       Diag(New->getLocation(), diag::err_cconv_change)
2972         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2973         << !FirstCCExplicit
2974         << (!FirstCCExplicit ? "" :
2975             FunctionType::getNameForCallConv(FI.getCC()));
2976 
2977       // Put the note on the first decl, since it is the one that matters.
2978       Diag(First->getLocation(), diag::note_previous_declaration);
2979       return true;
2980     }
2981   }
2982 
2983   // FIXME: diagnose the other way around?
2984   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2985     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2986     RequiresAdjustment = true;
2987   }
2988 
2989   // Merge regparm attribute.
2990   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2991       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2992     if (NewTypeInfo.getHasRegParm()) {
2993       Diag(New->getLocation(), diag::err_regparm_mismatch)
2994         << NewType->getRegParmType()
2995         << OldType->getRegParmType();
2996       Diag(OldLocation, diag::note_previous_declaration);
2997       return true;
2998     }
2999 
3000     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3001     RequiresAdjustment = true;
3002   }
3003 
3004   // Merge ns_returns_retained attribute.
3005   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3006     if (NewTypeInfo.getProducesResult()) {
3007       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3008           << "'ns_returns_retained'";
3009       Diag(OldLocation, diag::note_previous_declaration);
3010       return true;
3011     }
3012 
3013     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3014     RequiresAdjustment = true;
3015   }
3016 
3017   if (OldTypeInfo.getNoCallerSavedRegs() !=
3018       NewTypeInfo.getNoCallerSavedRegs()) {
3019     if (NewTypeInfo.getNoCallerSavedRegs()) {
3020       AnyX86NoCallerSavedRegistersAttr *Attr =
3021         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3022       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3023       Diag(OldLocation, diag::note_previous_declaration);
3024       return true;
3025     }
3026 
3027     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3028     RequiresAdjustment = true;
3029   }
3030 
3031   if (RequiresAdjustment) {
3032     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3033     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3034     New->setType(QualType(AdjustedType, 0));
3035     NewQType = Context.getCanonicalType(New->getType());
3036     NewType = cast<FunctionType>(NewQType);
3037   }
3038 
3039   // If this redeclaration makes the function inline, we may need to add it to
3040   // UndefinedButUsed.
3041   if (!Old->isInlined() && New->isInlined() &&
3042       !New->hasAttr<GNUInlineAttr>() &&
3043       !getLangOpts().GNUInline &&
3044       Old->isUsed(false) &&
3045       !Old->isDefined() && !New->isThisDeclarationADefinition())
3046     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3047                                            SourceLocation()));
3048 
3049   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3050   // about it.
3051   if (New->hasAttr<GNUInlineAttr>() &&
3052       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3053     UndefinedButUsed.erase(Old->getCanonicalDecl());
3054   }
3055 
3056   // If pass_object_size params don't match up perfectly, this isn't a valid
3057   // redeclaration.
3058   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3059       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3060     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3061         << New->getDeclName();
3062     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3063     return true;
3064   }
3065 
3066   if (getLangOpts().CPlusPlus) {
3067     // C++1z [over.load]p2
3068     //   Certain function declarations cannot be overloaded:
3069     //     -- Function declarations that differ only in the return type,
3070     //        the exception specification, or both cannot be overloaded.
3071 
3072     // Check the exception specifications match. This may recompute the type of
3073     // both Old and New if it resolved exception specifications, so grab the
3074     // types again after this. Because this updates the type, we do this before
3075     // any of the other checks below, which may update the "de facto" NewQType
3076     // but do not necessarily update the type of New.
3077     if (CheckEquivalentExceptionSpec(Old, New))
3078       return true;
3079     OldQType = Context.getCanonicalType(Old->getType());
3080     NewQType = Context.getCanonicalType(New->getType());
3081 
3082     // Go back to the type source info to compare the declared return types,
3083     // per C++1y [dcl.type.auto]p13:
3084     //   Redeclarations or specializations of a function or function template
3085     //   with a declared return type that uses a placeholder type shall also
3086     //   use that placeholder, not a deduced type.
3087     QualType OldDeclaredReturnType =
3088         (Old->getTypeSourceInfo()
3089              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3090              : OldType)->getReturnType();
3091     QualType NewDeclaredReturnType =
3092         (New->getTypeSourceInfo()
3093              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3094              : NewType)->getReturnType();
3095     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3096         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3097           New->isLocalExternDecl())) {
3098       QualType ResQT;
3099       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3100           OldDeclaredReturnType->isObjCObjectPointerType())
3101         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3102       if (ResQT.isNull()) {
3103         if (New->isCXXClassMember() && New->isOutOfLine())
3104           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3105               << New << New->getReturnTypeSourceRange();
3106         else
3107           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3108               << New->getReturnTypeSourceRange();
3109         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3110                                     << Old->getReturnTypeSourceRange();
3111         return true;
3112       }
3113       else
3114         NewQType = ResQT;
3115     }
3116 
3117     QualType OldReturnType = OldType->getReturnType();
3118     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3119     if (OldReturnType != NewReturnType) {
3120       // If this function has a deduced return type and has already been
3121       // defined, copy the deduced value from the old declaration.
3122       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3123       if (OldAT && OldAT->isDeduced()) {
3124         New->setType(
3125             SubstAutoType(New->getType(),
3126                           OldAT->isDependentType() ? Context.DependentTy
3127                                                    : OldAT->getDeducedType()));
3128         NewQType = Context.getCanonicalType(
3129             SubstAutoType(NewQType,
3130                           OldAT->isDependentType() ? Context.DependentTy
3131                                                    : OldAT->getDeducedType()));
3132       }
3133     }
3134 
3135     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3136     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3137     if (OldMethod && NewMethod) {
3138       // Preserve triviality.
3139       NewMethod->setTrivial(OldMethod->isTrivial());
3140 
3141       // MSVC allows explicit template specialization at class scope:
3142       // 2 CXXMethodDecls referring to the same function will be injected.
3143       // We don't want a redeclaration error.
3144       bool IsClassScopeExplicitSpecialization =
3145                               OldMethod->isFunctionTemplateSpecialization() &&
3146                               NewMethod->isFunctionTemplateSpecialization();
3147       bool isFriend = NewMethod->getFriendObjectKind();
3148 
3149       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3150           !IsClassScopeExplicitSpecialization) {
3151         //    -- Member function declarations with the same name and the
3152         //       same parameter types cannot be overloaded if any of them
3153         //       is a static member function declaration.
3154         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3155           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3156           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3157           return true;
3158         }
3159 
3160         // C++ [class.mem]p1:
3161         //   [...] A member shall not be declared twice in the
3162         //   member-specification, except that a nested class or member
3163         //   class template can be declared and then later defined.
3164         if (!inTemplateInstantiation()) {
3165           unsigned NewDiag;
3166           if (isa<CXXConstructorDecl>(OldMethod))
3167             NewDiag = diag::err_constructor_redeclared;
3168           else if (isa<CXXDestructorDecl>(NewMethod))
3169             NewDiag = diag::err_destructor_redeclared;
3170           else if (isa<CXXConversionDecl>(NewMethod))
3171             NewDiag = diag::err_conv_function_redeclared;
3172           else
3173             NewDiag = diag::err_member_redeclared;
3174 
3175           Diag(New->getLocation(), NewDiag);
3176         } else {
3177           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3178             << New << New->getType();
3179         }
3180         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3181         return true;
3182 
3183       // Complain if this is an explicit declaration of a special
3184       // member that was initially declared implicitly.
3185       //
3186       // As an exception, it's okay to befriend such methods in order
3187       // to permit the implicit constructor/destructor/operator calls.
3188       } else if (OldMethod->isImplicit()) {
3189         if (isFriend) {
3190           NewMethod->setImplicit();
3191         } else {
3192           Diag(NewMethod->getLocation(),
3193                diag::err_definition_of_implicitly_declared_member)
3194             << New << getSpecialMember(OldMethod);
3195           return true;
3196         }
3197       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3198         Diag(NewMethod->getLocation(),
3199              diag::err_definition_of_explicitly_defaulted_member)
3200           << getSpecialMember(OldMethod);
3201         return true;
3202       }
3203     }
3204 
3205     // C++11 [dcl.attr.noreturn]p1:
3206     //   The first declaration of a function shall specify the noreturn
3207     //   attribute if any declaration of that function specifies the noreturn
3208     //   attribute.
3209     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3210     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3211       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3212       Diag(Old->getFirstDecl()->getLocation(),
3213            diag::note_noreturn_missing_first_decl);
3214     }
3215 
3216     // C++11 [dcl.attr.depend]p2:
3217     //   The first declaration of a function shall specify the
3218     //   carries_dependency attribute for its declarator-id if any declaration
3219     //   of the function specifies the carries_dependency attribute.
3220     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3221     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3222       Diag(CDA->getLocation(),
3223            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3224       Diag(Old->getFirstDecl()->getLocation(),
3225            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3226     }
3227 
3228     // (C++98 8.3.5p3):
3229     //   All declarations for a function shall agree exactly in both the
3230     //   return type and the parameter-type-list.
3231     // We also want to respect all the extended bits except noreturn.
3232 
3233     // noreturn should now match unless the old type info didn't have it.
3234     QualType OldQTypeForComparison = OldQType;
3235     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3236       auto *OldType = OldQType->castAs<FunctionProtoType>();
3237       const FunctionType *OldTypeForComparison
3238         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3239       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3240       assert(OldQTypeForComparison.isCanonical());
3241     }
3242 
3243     if (haveIncompatibleLanguageLinkages(Old, New)) {
3244       // As a special case, retain the language linkage from previous
3245       // declarations of a friend function as an extension.
3246       //
3247       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3248       // and is useful because there's otherwise no way to specify language
3249       // linkage within class scope.
3250       //
3251       // Check cautiously as the friend object kind isn't yet complete.
3252       if (New->getFriendObjectKind() != Decl::FOK_None) {
3253         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3254         Diag(OldLocation, PrevDiag);
3255       } else {
3256         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3257         Diag(OldLocation, PrevDiag);
3258         return true;
3259       }
3260     }
3261 
3262     if (OldQTypeForComparison == NewQType)
3263       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3264 
3265     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3266         New->isLocalExternDecl()) {
3267       // It's OK if we couldn't merge types for a local function declaraton
3268       // if either the old or new type is dependent. We'll merge the types
3269       // when we instantiate the function.
3270       return false;
3271     }
3272 
3273     // Fall through for conflicting redeclarations and redefinitions.
3274   }
3275 
3276   // C: Function types need to be compatible, not identical. This handles
3277   // duplicate function decls like "void f(int); void f(enum X);" properly.
3278   if (!getLangOpts().CPlusPlus &&
3279       Context.typesAreCompatible(OldQType, NewQType)) {
3280     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3281     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3282     const FunctionProtoType *OldProto = nullptr;
3283     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3284         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3285       // The old declaration provided a function prototype, but the
3286       // new declaration does not. Merge in the prototype.
3287       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3288       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3289       NewQType =
3290           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3291                                   OldProto->getExtProtoInfo());
3292       New->setType(NewQType);
3293       New->setHasInheritedPrototype();
3294 
3295       // Synthesize parameters with the same types.
3296       SmallVector<ParmVarDecl*, 16> Params;
3297       for (const auto &ParamType : OldProto->param_types()) {
3298         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3299                                                  SourceLocation(), nullptr,
3300                                                  ParamType, /*TInfo=*/nullptr,
3301                                                  SC_None, nullptr);
3302         Param->setScopeInfo(0, Params.size());
3303         Param->setImplicit();
3304         Params.push_back(Param);
3305       }
3306 
3307       New->setParams(Params);
3308     }
3309 
3310     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3311   }
3312 
3313   // GNU C permits a K&R definition to follow a prototype declaration
3314   // if the declared types of the parameters in the K&R definition
3315   // match the types in the prototype declaration, even when the
3316   // promoted types of the parameters from the K&R definition differ
3317   // from the types in the prototype. GCC then keeps the types from
3318   // the prototype.
3319   //
3320   // If a variadic prototype is followed by a non-variadic K&R definition,
3321   // the K&R definition becomes variadic.  This is sort of an edge case, but
3322   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3323   // C99 6.9.1p8.
3324   if (!getLangOpts().CPlusPlus &&
3325       Old->hasPrototype() && !New->hasPrototype() &&
3326       New->getType()->getAs<FunctionProtoType>() &&
3327       Old->getNumParams() == New->getNumParams()) {
3328     SmallVector<QualType, 16> ArgTypes;
3329     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3330     const FunctionProtoType *OldProto
3331       = Old->getType()->getAs<FunctionProtoType>();
3332     const FunctionProtoType *NewProto
3333       = New->getType()->getAs<FunctionProtoType>();
3334 
3335     // Determine whether this is the GNU C extension.
3336     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3337                                                NewProto->getReturnType());
3338     bool LooseCompatible = !MergedReturn.isNull();
3339     for (unsigned Idx = 0, End = Old->getNumParams();
3340          LooseCompatible && Idx != End; ++Idx) {
3341       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3342       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3343       if (Context.typesAreCompatible(OldParm->getType(),
3344                                      NewProto->getParamType(Idx))) {
3345         ArgTypes.push_back(NewParm->getType());
3346       } else if (Context.typesAreCompatible(OldParm->getType(),
3347                                             NewParm->getType(),
3348                                             /*CompareUnqualified=*/true)) {
3349         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3350                                            NewProto->getParamType(Idx) };
3351         Warnings.push_back(Warn);
3352         ArgTypes.push_back(NewParm->getType());
3353       } else
3354         LooseCompatible = false;
3355     }
3356 
3357     if (LooseCompatible) {
3358       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3359         Diag(Warnings[Warn].NewParm->getLocation(),
3360              diag::ext_param_promoted_not_compatible_with_prototype)
3361           << Warnings[Warn].PromotedType
3362           << Warnings[Warn].OldParm->getType();
3363         if (Warnings[Warn].OldParm->getLocation().isValid())
3364           Diag(Warnings[Warn].OldParm->getLocation(),
3365                diag::note_previous_declaration);
3366       }
3367 
3368       if (MergeTypeWithOld)
3369         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3370                                              OldProto->getExtProtoInfo()));
3371       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3372     }
3373 
3374     // Fall through to diagnose conflicting types.
3375   }
3376 
3377   // A function that has already been declared has been redeclared or
3378   // defined with a different type; show an appropriate diagnostic.
3379 
3380   // If the previous declaration was an implicitly-generated builtin
3381   // declaration, then at the very least we should use a specialized note.
3382   unsigned BuiltinID;
3383   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3384     // If it's actually a library-defined builtin function like 'malloc'
3385     // or 'printf', just warn about the incompatible redeclaration.
3386     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3387       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3388       Diag(OldLocation, diag::note_previous_builtin_declaration)
3389         << Old << Old->getType();
3390 
3391       // If this is a global redeclaration, just forget hereafter
3392       // about the "builtin-ness" of the function.
3393       //
3394       // Doing this for local extern declarations is problematic.  If
3395       // the builtin declaration remains visible, a second invalid
3396       // local declaration will produce a hard error; if it doesn't
3397       // remain visible, a single bogus local redeclaration (which is
3398       // actually only a warning) could break all the downstream code.
3399       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3400         New->getIdentifier()->revertBuiltin();
3401 
3402       return false;
3403     }
3404 
3405     PrevDiag = diag::note_previous_builtin_declaration;
3406   }
3407 
3408   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3409   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3410   return true;
3411 }
3412 
3413 /// \brief Completes the merge of two function declarations that are
3414 /// known to be compatible.
3415 ///
3416 /// This routine handles the merging of attributes and other
3417 /// properties of function declarations from the old declaration to
3418 /// the new declaration, once we know that New is in fact a
3419 /// redeclaration of Old.
3420 ///
3421 /// \returns false
3422 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3423                                         Scope *S, bool MergeTypeWithOld) {
3424   // Merge the attributes
3425   mergeDeclAttributes(New, Old);
3426 
3427   // Merge "pure" flag.
3428   if (Old->isPure())
3429     New->setPure();
3430 
3431   // Merge "used" flag.
3432   if (Old->getMostRecentDecl()->isUsed(false))
3433     New->setIsUsed();
3434 
3435   // Merge attributes from the parameters.  These can mismatch with K&R
3436   // declarations.
3437   if (New->getNumParams() == Old->getNumParams())
3438       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3439         ParmVarDecl *NewParam = New->getParamDecl(i);
3440         ParmVarDecl *OldParam = Old->getParamDecl(i);
3441         mergeParamDeclAttributes(NewParam, OldParam, *this);
3442         mergeParamDeclTypes(NewParam, OldParam, *this);
3443       }
3444 
3445   if (getLangOpts().CPlusPlus)
3446     return MergeCXXFunctionDecl(New, Old, S);
3447 
3448   // Merge the function types so the we get the composite types for the return
3449   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3450   // was visible.
3451   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3452   if (!Merged.isNull() && MergeTypeWithOld)
3453     New->setType(Merged);
3454 
3455   return false;
3456 }
3457 
3458 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3459                                 ObjCMethodDecl *oldMethod) {
3460   // Merge the attributes, including deprecated/unavailable
3461   AvailabilityMergeKind MergeKind =
3462     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3463       ? AMK_ProtocolImplementation
3464       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3465                                                        : AMK_Override;
3466 
3467   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3468 
3469   // Merge attributes from the parameters.
3470   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3471                                        oe = oldMethod->param_end();
3472   for (ObjCMethodDecl::param_iterator
3473          ni = newMethod->param_begin(), ne = newMethod->param_end();
3474        ni != ne && oi != oe; ++ni, ++oi)
3475     mergeParamDeclAttributes(*ni, *oi, *this);
3476 
3477   CheckObjCMethodOverride(newMethod, oldMethod);
3478 }
3479 
3480 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3481   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3482 
3483   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3484          ? diag::err_redefinition_different_type
3485          : diag::err_redeclaration_different_type)
3486     << New->getDeclName() << New->getType() << Old->getType();
3487 
3488   diag::kind PrevDiag;
3489   SourceLocation OldLocation;
3490   std::tie(PrevDiag, OldLocation)
3491     = getNoteDiagForInvalidRedeclaration(Old, New);
3492   S.Diag(OldLocation, PrevDiag);
3493   New->setInvalidDecl();
3494 }
3495 
3496 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3497 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3498 /// emitting diagnostics as appropriate.
3499 ///
3500 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3501 /// to here in AddInitializerToDecl. We can't check them before the initializer
3502 /// is attached.
3503 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3504                              bool MergeTypeWithOld) {
3505   if (New->isInvalidDecl() || Old->isInvalidDecl())
3506     return;
3507 
3508   QualType MergedT;
3509   if (getLangOpts().CPlusPlus) {
3510     if (New->getType()->isUndeducedType()) {
3511       // We don't know what the new type is until the initializer is attached.
3512       return;
3513     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3514       // These could still be something that needs exception specs checked.
3515       return MergeVarDeclExceptionSpecs(New, Old);
3516     }
3517     // C++ [basic.link]p10:
3518     //   [...] the types specified by all declarations referring to a given
3519     //   object or function shall be identical, except that declarations for an
3520     //   array object can specify array types that differ by the presence or
3521     //   absence of a major array bound (8.3.4).
3522     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3523       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3524       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3525 
3526       // We are merging a variable declaration New into Old. If it has an array
3527       // bound, and that bound differs from Old's bound, we should diagnose the
3528       // mismatch.
3529       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3530         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3531              PrevVD = PrevVD->getPreviousDecl()) {
3532           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3533           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3534             continue;
3535 
3536           if (!Context.hasSameType(NewArray, PrevVDTy))
3537             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3538         }
3539       }
3540 
3541       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3542         if (Context.hasSameType(OldArray->getElementType(),
3543                                 NewArray->getElementType()))
3544           MergedT = New->getType();
3545       }
3546       // FIXME: Check visibility. New is hidden but has a complete type. If New
3547       // has no array bound, it should not inherit one from Old, if Old is not
3548       // visible.
3549       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3550         if (Context.hasSameType(OldArray->getElementType(),
3551                                 NewArray->getElementType()))
3552           MergedT = Old->getType();
3553       }
3554     }
3555     else if (New->getType()->isObjCObjectPointerType() &&
3556                Old->getType()->isObjCObjectPointerType()) {
3557       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3558                                               Old->getType());
3559     }
3560   } else {
3561     // C 6.2.7p2:
3562     //   All declarations that refer to the same object or function shall have
3563     //   compatible type.
3564     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3565   }
3566   if (MergedT.isNull()) {
3567     // It's OK if we couldn't merge types if either type is dependent, for a
3568     // block-scope variable. In other cases (static data members of class
3569     // templates, variable templates, ...), we require the types to be
3570     // equivalent.
3571     // FIXME: The C++ standard doesn't say anything about this.
3572     if ((New->getType()->isDependentType() ||
3573          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3574       // If the old type was dependent, we can't merge with it, so the new type
3575       // becomes dependent for now. We'll reproduce the original type when we
3576       // instantiate the TypeSourceInfo for the variable.
3577       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3578         New->setType(Context.DependentTy);
3579       return;
3580     }
3581     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3582   }
3583 
3584   // Don't actually update the type on the new declaration if the old
3585   // declaration was an extern declaration in a different scope.
3586   if (MergeTypeWithOld)
3587     New->setType(MergedT);
3588 }
3589 
3590 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3591                                   LookupResult &Previous) {
3592   // C11 6.2.7p4:
3593   //   For an identifier with internal or external linkage declared
3594   //   in a scope in which a prior declaration of that identifier is
3595   //   visible, if the prior declaration specifies internal or
3596   //   external linkage, the type of the identifier at the later
3597   //   declaration becomes the composite type.
3598   //
3599   // If the variable isn't visible, we do not merge with its type.
3600   if (Previous.isShadowed())
3601     return false;
3602 
3603   if (S.getLangOpts().CPlusPlus) {
3604     // C++11 [dcl.array]p3:
3605     //   If there is a preceding declaration of the entity in the same
3606     //   scope in which the bound was specified, an omitted array bound
3607     //   is taken to be the same as in that earlier declaration.
3608     return NewVD->isPreviousDeclInSameBlockScope() ||
3609            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3610             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3611   } else {
3612     // If the old declaration was function-local, don't merge with its
3613     // type unless we're in the same function.
3614     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3615            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3616   }
3617 }
3618 
3619 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3620 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3621 /// situation, merging decls or emitting diagnostics as appropriate.
3622 ///
3623 /// Tentative definition rules (C99 6.9.2p2) are checked by
3624 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3625 /// definitions here, since the initializer hasn't been attached.
3626 ///
3627 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3628   // If the new decl is already invalid, don't do any other checking.
3629   if (New->isInvalidDecl())
3630     return;
3631 
3632   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3633     return;
3634 
3635   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3636 
3637   // Verify the old decl was also a variable or variable template.
3638   VarDecl *Old = nullptr;
3639   VarTemplateDecl *OldTemplate = nullptr;
3640   if (Previous.isSingleResult()) {
3641     if (NewTemplate) {
3642       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3643       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3644 
3645       if (auto *Shadow =
3646               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3647         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3648           return New->setInvalidDecl();
3649     } else {
3650       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3651 
3652       if (auto *Shadow =
3653               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3654         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3655           return New->setInvalidDecl();
3656     }
3657   }
3658   if (!Old) {
3659     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3660         << New->getDeclName();
3661     notePreviousDefinition(Previous.getRepresentativeDecl(),
3662                            New->getLocation());
3663     return New->setInvalidDecl();
3664   }
3665 
3666   // Ensure the template parameters are compatible.
3667   if (NewTemplate &&
3668       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3669                                       OldTemplate->getTemplateParameters(),
3670                                       /*Complain=*/true, TPL_TemplateMatch))
3671     return New->setInvalidDecl();
3672 
3673   // C++ [class.mem]p1:
3674   //   A member shall not be declared twice in the member-specification [...]
3675   //
3676   // Here, we need only consider static data members.
3677   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3678     Diag(New->getLocation(), diag::err_duplicate_member)
3679       << New->getIdentifier();
3680     Diag(Old->getLocation(), diag::note_previous_declaration);
3681     New->setInvalidDecl();
3682   }
3683 
3684   mergeDeclAttributes(New, Old);
3685   // Warn if an already-declared variable is made a weak_import in a subsequent
3686   // declaration
3687   if (New->hasAttr<WeakImportAttr>() &&
3688       Old->getStorageClass() == SC_None &&
3689       !Old->hasAttr<WeakImportAttr>()) {
3690     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3691     notePreviousDefinition(Old, New->getLocation());
3692     // Remove weak_import attribute on new declaration.
3693     New->dropAttr<WeakImportAttr>();
3694   }
3695 
3696   if (New->hasAttr<InternalLinkageAttr>() &&
3697       !Old->hasAttr<InternalLinkageAttr>()) {
3698     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3699         << New->getDeclName();
3700     notePreviousDefinition(Old, New->getLocation());
3701     New->dropAttr<InternalLinkageAttr>();
3702   }
3703 
3704   // Merge the types.
3705   VarDecl *MostRecent = Old->getMostRecentDecl();
3706   if (MostRecent != Old) {
3707     MergeVarDeclTypes(New, MostRecent,
3708                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3709     if (New->isInvalidDecl())
3710       return;
3711   }
3712 
3713   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3714   if (New->isInvalidDecl())
3715     return;
3716 
3717   diag::kind PrevDiag;
3718   SourceLocation OldLocation;
3719   std::tie(PrevDiag, OldLocation) =
3720       getNoteDiagForInvalidRedeclaration(Old, New);
3721 
3722   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3723   if (New->getStorageClass() == SC_Static &&
3724       !New->isStaticDataMember() &&
3725       Old->hasExternalFormalLinkage()) {
3726     if (getLangOpts().MicrosoftExt) {
3727       Diag(New->getLocation(), diag::ext_static_non_static)
3728           << New->getDeclName();
3729       Diag(OldLocation, PrevDiag);
3730     } else {
3731       Diag(New->getLocation(), diag::err_static_non_static)
3732           << New->getDeclName();
3733       Diag(OldLocation, PrevDiag);
3734       return New->setInvalidDecl();
3735     }
3736   }
3737   // C99 6.2.2p4:
3738   //   For an identifier declared with the storage-class specifier
3739   //   extern in a scope in which a prior declaration of that
3740   //   identifier is visible,23) if the prior declaration specifies
3741   //   internal or external linkage, the linkage of the identifier at
3742   //   the later declaration is the same as the linkage specified at
3743   //   the prior declaration. If no prior declaration is visible, or
3744   //   if the prior declaration specifies no linkage, then the
3745   //   identifier has external linkage.
3746   if (New->hasExternalStorage() && Old->hasLinkage())
3747     /* Okay */;
3748   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3749            !New->isStaticDataMember() &&
3750            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3751     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3752     Diag(OldLocation, PrevDiag);
3753     return New->setInvalidDecl();
3754   }
3755 
3756   // Check if extern is followed by non-extern and vice-versa.
3757   if (New->hasExternalStorage() &&
3758       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3759     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3760     Diag(OldLocation, PrevDiag);
3761     return New->setInvalidDecl();
3762   }
3763   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3764       !New->hasExternalStorage()) {
3765     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3766     Diag(OldLocation, PrevDiag);
3767     return New->setInvalidDecl();
3768   }
3769 
3770   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3771 
3772   // FIXME: The test for external storage here seems wrong? We still
3773   // need to check for mismatches.
3774   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3775       // Don't complain about out-of-line definitions of static members.
3776       !(Old->getLexicalDeclContext()->isRecord() &&
3777         !New->getLexicalDeclContext()->isRecord())) {
3778     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3779     Diag(OldLocation, PrevDiag);
3780     return New->setInvalidDecl();
3781   }
3782 
3783   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3784     if (VarDecl *Def = Old->getDefinition()) {
3785       // C++1z [dcl.fcn.spec]p4:
3786       //   If the definition of a variable appears in a translation unit before
3787       //   its first declaration as inline, the program is ill-formed.
3788       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3789       Diag(Def->getLocation(), diag::note_previous_definition);
3790     }
3791   }
3792 
3793   // If this redeclaration makes the function inline, we may need to add it to
3794   // UndefinedButUsed.
3795   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3796       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3797     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3798                                            SourceLocation()));
3799 
3800   if (New->getTLSKind() != Old->getTLSKind()) {
3801     if (!Old->getTLSKind()) {
3802       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3803       Diag(OldLocation, PrevDiag);
3804     } else if (!New->getTLSKind()) {
3805       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3806       Diag(OldLocation, PrevDiag);
3807     } else {
3808       // Do not allow redeclaration to change the variable between requiring
3809       // static and dynamic initialization.
3810       // FIXME: GCC allows this, but uses the TLS keyword on the first
3811       // declaration to determine the kind. Do we need to be compatible here?
3812       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3813         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3814       Diag(OldLocation, PrevDiag);
3815     }
3816   }
3817 
3818   // C++ doesn't have tentative definitions, so go right ahead and check here.
3819   if (getLangOpts().CPlusPlus &&
3820       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3821     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3822         Old->getCanonicalDecl()->isConstexpr()) {
3823       // This definition won't be a definition any more once it's been merged.
3824       Diag(New->getLocation(),
3825            diag::warn_deprecated_redundant_constexpr_static_def);
3826     } else if (VarDecl *Def = Old->getDefinition()) {
3827       if (checkVarDeclRedefinition(Def, New))
3828         return;
3829     }
3830   }
3831 
3832   if (haveIncompatibleLanguageLinkages(Old, New)) {
3833     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3834     Diag(OldLocation, PrevDiag);
3835     New->setInvalidDecl();
3836     return;
3837   }
3838 
3839   // Merge "used" flag.
3840   if (Old->getMostRecentDecl()->isUsed(false))
3841     New->setIsUsed();
3842 
3843   // Keep a chain of previous declarations.
3844   New->setPreviousDecl(Old);
3845   if (NewTemplate)
3846     NewTemplate->setPreviousDecl(OldTemplate);
3847 
3848   // Inherit access appropriately.
3849   New->setAccess(Old->getAccess());
3850   if (NewTemplate)
3851     NewTemplate->setAccess(New->getAccess());
3852 
3853   if (Old->isInline())
3854     New->setImplicitlyInline();
3855 }
3856 
3857 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
3858   SourceManager &SrcMgr = getSourceManager();
3859   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
3860   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
3861   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
3862   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
3863   auto &HSI = PP.getHeaderSearchInfo();
3864   StringRef HdrFilename =
3865       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
3866 
3867   auto noteFromModuleOrInclude = [&](Module *Mod,
3868                                      SourceLocation IncLoc) -> bool {
3869     // Redefinition errors with modules are common with non modular mapped
3870     // headers, example: a non-modular header H in module A that also gets
3871     // included directly in a TU. Pointing twice to the same header/definition
3872     // is confusing, try to get better diagnostics when modules is on.
3873     if (IncLoc.isValid()) {
3874       if (Mod) {
3875         Diag(IncLoc, diag::note_redefinition_modules_same_file)
3876             << HdrFilename.str() << Mod->getFullModuleName();
3877         if (!Mod->DefinitionLoc.isInvalid())
3878           Diag(Mod->DefinitionLoc, diag::note_defined_here)
3879               << Mod->getFullModuleName();
3880       } else {
3881         Diag(IncLoc, diag::note_redefinition_include_same_file)
3882             << HdrFilename.str();
3883       }
3884       return true;
3885     }
3886 
3887     return false;
3888   };
3889 
3890   // Is it the same file and same offset? Provide more information on why
3891   // this leads to a redefinition error.
3892   bool EmittedDiag = false;
3893   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
3894     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
3895     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
3896     EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
3897     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
3898 
3899     // If the header has no guards, emit a note suggesting one.
3900     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
3901       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
3902 
3903     if (EmittedDiag)
3904       return;
3905   }
3906 
3907   // Redefinition coming from different files or couldn't do better above.
3908   Diag(Old->getLocation(), diag::note_previous_definition);
3909 }
3910 
3911 /// We've just determined that \p Old and \p New both appear to be definitions
3912 /// of the same variable. Either diagnose or fix the problem.
3913 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
3914   if (!hasVisibleDefinition(Old) &&
3915       (New->getFormalLinkage() == InternalLinkage ||
3916        New->isInline() ||
3917        New->getDescribedVarTemplate() ||
3918        New->getNumTemplateParameterLists() ||
3919        New->getDeclContext()->isDependentContext())) {
3920     // The previous definition is hidden, and multiple definitions are
3921     // permitted (in separate TUs). Demote this to a declaration.
3922     New->demoteThisDefinitionToDeclaration();
3923 
3924     // Make the canonical definition visible.
3925     if (auto *OldTD = Old->getDescribedVarTemplate())
3926       makeMergedDefinitionVisible(OldTD);
3927     makeMergedDefinitionVisible(Old);
3928     return false;
3929   } else {
3930     Diag(New->getLocation(), diag::err_redefinition) << New;
3931     notePreviousDefinition(Old, New->getLocation());
3932     New->setInvalidDecl();
3933     return true;
3934   }
3935 }
3936 
3937 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3938 /// no declarator (e.g. "struct foo;") is parsed.
3939 Decl *
3940 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3941                                  RecordDecl *&AnonRecord) {
3942   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3943                                     AnonRecord);
3944 }
3945 
3946 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3947 // disambiguate entities defined in different scopes.
3948 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3949 // compatibility.
3950 // We will pick our mangling number depending on which version of MSVC is being
3951 // targeted.
3952 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3953   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3954              ? S->getMSCurManglingNumber()
3955              : S->getMSLastManglingNumber();
3956 }
3957 
3958 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3959   if (!Context.getLangOpts().CPlusPlus)
3960     return;
3961 
3962   if (isa<CXXRecordDecl>(Tag->getParent())) {
3963     // If this tag is the direct child of a class, number it if
3964     // it is anonymous.
3965     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3966       return;
3967     MangleNumberingContext &MCtx =
3968         Context.getManglingNumberContext(Tag->getParent());
3969     Context.setManglingNumber(
3970         Tag, MCtx.getManglingNumber(
3971                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3972     return;
3973   }
3974 
3975   // If this tag isn't a direct child of a class, number it if it is local.
3976   Decl *ManglingContextDecl;
3977   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3978           Tag->getDeclContext(), ManglingContextDecl)) {
3979     Context.setManglingNumber(
3980         Tag, MCtx->getManglingNumber(
3981                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3982   }
3983 }
3984 
3985 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3986                                         TypedefNameDecl *NewTD) {
3987   if (TagFromDeclSpec->isInvalidDecl())
3988     return;
3989 
3990   // Do nothing if the tag already has a name for linkage purposes.
3991   if (TagFromDeclSpec->hasNameForLinkage())
3992     return;
3993 
3994   // A well-formed anonymous tag must always be a TUK_Definition.
3995   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3996 
3997   // The type must match the tag exactly;  no qualifiers allowed.
3998   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3999                            Context.getTagDeclType(TagFromDeclSpec))) {
4000     if (getLangOpts().CPlusPlus)
4001       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4002     return;
4003   }
4004 
4005   // If we've already computed linkage for the anonymous tag, then
4006   // adding a typedef name for the anonymous decl can change that
4007   // linkage, which might be a serious problem.  Diagnose this as
4008   // unsupported and ignore the typedef name.  TODO: we should
4009   // pursue this as a language defect and establish a formal rule
4010   // for how to handle it.
4011   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4012     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4013 
4014     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4015     tagLoc = getLocForEndOfToken(tagLoc);
4016 
4017     llvm::SmallString<40> textToInsert;
4018     textToInsert += ' ';
4019     textToInsert += NewTD->getIdentifier()->getName();
4020     Diag(tagLoc, diag::note_typedef_changes_linkage)
4021         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4022     return;
4023   }
4024 
4025   // Otherwise, set this is the anon-decl typedef for the tag.
4026   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4027 }
4028 
4029 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4030   switch (T) {
4031   case DeclSpec::TST_class:
4032     return 0;
4033   case DeclSpec::TST_struct:
4034     return 1;
4035   case DeclSpec::TST_interface:
4036     return 2;
4037   case DeclSpec::TST_union:
4038     return 3;
4039   case DeclSpec::TST_enum:
4040     return 4;
4041   default:
4042     llvm_unreachable("unexpected type specifier");
4043   }
4044 }
4045 
4046 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4047 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4048 /// parameters to cope with template friend declarations.
4049 Decl *
4050 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4051                                  MultiTemplateParamsArg TemplateParams,
4052                                  bool IsExplicitInstantiation,
4053                                  RecordDecl *&AnonRecord) {
4054   Decl *TagD = nullptr;
4055   TagDecl *Tag = nullptr;
4056   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4057       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4058       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4059       DS.getTypeSpecType() == DeclSpec::TST_union ||
4060       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4061     TagD = DS.getRepAsDecl();
4062 
4063     if (!TagD) // We probably had an error
4064       return nullptr;
4065 
4066     // Note that the above type specs guarantee that the
4067     // type rep is a Decl, whereas in many of the others
4068     // it's a Type.
4069     if (isa<TagDecl>(TagD))
4070       Tag = cast<TagDecl>(TagD);
4071     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4072       Tag = CTD->getTemplatedDecl();
4073   }
4074 
4075   if (Tag) {
4076     handleTagNumbering(Tag, S);
4077     Tag->setFreeStanding();
4078     if (Tag->isInvalidDecl())
4079       return Tag;
4080   }
4081 
4082   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4083     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4084     // or incomplete types shall not be restrict-qualified."
4085     if (TypeQuals & DeclSpec::TQ_restrict)
4086       Diag(DS.getRestrictSpecLoc(),
4087            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4088            << DS.getSourceRange();
4089   }
4090 
4091   if (DS.isInlineSpecified())
4092     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4093         << getLangOpts().CPlusPlus1z;
4094 
4095   if (DS.isConstexprSpecified()) {
4096     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4097     // and definitions of functions and variables.
4098     if (Tag)
4099       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4100           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4101     else
4102       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4103     // Don't emit warnings after this error.
4104     return TagD;
4105   }
4106 
4107   if (DS.isConceptSpecified()) {
4108     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
4109     // either a function concept and its definition or a variable concept and
4110     // its initializer.
4111     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
4112     return TagD;
4113   }
4114 
4115   DiagnoseFunctionSpecifiers(DS);
4116 
4117   if (DS.isFriendSpecified()) {
4118     // If we're dealing with a decl but not a TagDecl, assume that
4119     // whatever routines created it handled the friendship aspect.
4120     if (TagD && !Tag)
4121       return nullptr;
4122     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4123   }
4124 
4125   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4126   bool IsExplicitSpecialization =
4127     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4128   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4129       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4130       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4131     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4132     // nested-name-specifier unless it is an explicit instantiation
4133     // or an explicit specialization.
4134     //
4135     // FIXME: We allow class template partial specializations here too, per the
4136     // obvious intent of DR1819.
4137     //
4138     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4139     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4140         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4141     return nullptr;
4142   }
4143 
4144   // Track whether this decl-specifier declares anything.
4145   bool DeclaresAnything = true;
4146 
4147   // Handle anonymous struct definitions.
4148   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4149     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4150         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4151       if (getLangOpts().CPlusPlus ||
4152           Record->getDeclContext()->isRecord()) {
4153         // If CurContext is a DeclContext that can contain statements,
4154         // RecursiveASTVisitor won't visit the decls that
4155         // BuildAnonymousStructOrUnion() will put into CurContext.
4156         // Also store them here so that they can be part of the
4157         // DeclStmt that gets created in this case.
4158         // FIXME: Also return the IndirectFieldDecls created by
4159         // BuildAnonymousStructOr union, for the same reason?
4160         if (CurContext->isFunctionOrMethod())
4161           AnonRecord = Record;
4162         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4163                                            Context.getPrintingPolicy());
4164       }
4165 
4166       DeclaresAnything = false;
4167     }
4168   }
4169 
4170   // C11 6.7.2.1p2:
4171   //   A struct-declaration that does not declare an anonymous structure or
4172   //   anonymous union shall contain a struct-declarator-list.
4173   //
4174   // This rule also existed in C89 and C99; the grammar for struct-declaration
4175   // did not permit a struct-declaration without a struct-declarator-list.
4176   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4177       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4178     // Check for Microsoft C extension: anonymous struct/union member.
4179     // Handle 2 kinds of anonymous struct/union:
4180     //   struct STRUCT;
4181     //   union UNION;
4182     // and
4183     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4184     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4185     if ((Tag && Tag->getDeclName()) ||
4186         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4187       RecordDecl *Record = nullptr;
4188       if (Tag)
4189         Record = dyn_cast<RecordDecl>(Tag);
4190       else if (const RecordType *RT =
4191                    DS.getRepAsType().get()->getAsStructureType())
4192         Record = RT->getDecl();
4193       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4194         Record = UT->getDecl();
4195 
4196       if (Record && getLangOpts().MicrosoftExt) {
4197         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4198           << Record->isUnion() << DS.getSourceRange();
4199         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4200       }
4201 
4202       DeclaresAnything = false;
4203     }
4204   }
4205 
4206   // Skip all the checks below if we have a type error.
4207   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4208       (TagD && TagD->isInvalidDecl()))
4209     return TagD;
4210 
4211   if (getLangOpts().CPlusPlus &&
4212       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4213     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4214       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4215           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4216         DeclaresAnything = false;
4217 
4218   if (!DS.isMissingDeclaratorOk()) {
4219     // Customize diagnostic for a typedef missing a name.
4220     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4221       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4222         << DS.getSourceRange();
4223     else
4224       DeclaresAnything = false;
4225   }
4226 
4227   if (DS.isModulePrivateSpecified() &&
4228       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4229     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4230       << Tag->getTagKind()
4231       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4232 
4233   ActOnDocumentableDecl(TagD);
4234 
4235   // C 6.7/2:
4236   //   A declaration [...] shall declare at least a declarator [...], a tag,
4237   //   or the members of an enumeration.
4238   // C++ [dcl.dcl]p3:
4239   //   [If there are no declarators], and except for the declaration of an
4240   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4241   //   names into the program, or shall redeclare a name introduced by a
4242   //   previous declaration.
4243   if (!DeclaresAnything) {
4244     // In C, we allow this as a (popular) extension / bug. Don't bother
4245     // producing further diagnostics for redundant qualifiers after this.
4246     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4247     return TagD;
4248   }
4249 
4250   // C++ [dcl.stc]p1:
4251   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4252   //   init-declarator-list of the declaration shall not be empty.
4253   // C++ [dcl.fct.spec]p1:
4254   //   If a cv-qualifier appears in a decl-specifier-seq, the
4255   //   init-declarator-list of the declaration shall not be empty.
4256   //
4257   // Spurious qualifiers here appear to be valid in C.
4258   unsigned DiagID = diag::warn_standalone_specifier;
4259   if (getLangOpts().CPlusPlus)
4260     DiagID = diag::ext_standalone_specifier;
4261 
4262   // Note that a linkage-specification sets a storage class, but
4263   // 'extern "C" struct foo;' is actually valid and not theoretically
4264   // useless.
4265   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4266     if (SCS == DeclSpec::SCS_mutable)
4267       // Since mutable is not a viable storage class specifier in C, there is
4268       // no reason to treat it as an extension. Instead, diagnose as an error.
4269       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4270     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4271       Diag(DS.getStorageClassSpecLoc(), DiagID)
4272         << DeclSpec::getSpecifierName(SCS);
4273   }
4274 
4275   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4276     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4277       << DeclSpec::getSpecifierName(TSCS);
4278   if (DS.getTypeQualifiers()) {
4279     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4280       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4281     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4282       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4283     // Restrict is covered above.
4284     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4285       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4286     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4287       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4288   }
4289 
4290   // Warn about ignored type attributes, for example:
4291   // __attribute__((aligned)) struct A;
4292   // Attributes should be placed after tag to apply to type declaration.
4293   if (!DS.getAttributes().empty()) {
4294     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4295     if (TypeSpecType == DeclSpec::TST_class ||
4296         TypeSpecType == DeclSpec::TST_struct ||
4297         TypeSpecType == DeclSpec::TST_interface ||
4298         TypeSpecType == DeclSpec::TST_union ||
4299         TypeSpecType == DeclSpec::TST_enum) {
4300       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4301            attrs = attrs->getNext())
4302         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4303             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4304     }
4305   }
4306 
4307   return TagD;
4308 }
4309 
4310 /// We are trying to inject an anonymous member into the given scope;
4311 /// check if there's an existing declaration that can't be overloaded.
4312 ///
4313 /// \return true if this is a forbidden redeclaration
4314 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4315                                          Scope *S,
4316                                          DeclContext *Owner,
4317                                          DeclarationName Name,
4318                                          SourceLocation NameLoc,
4319                                          bool IsUnion) {
4320   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4321                  Sema::ForRedeclaration);
4322   if (!SemaRef.LookupName(R, S)) return false;
4323 
4324   // Pick a representative declaration.
4325   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4326   assert(PrevDecl && "Expected a non-null Decl");
4327 
4328   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4329     return false;
4330 
4331   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4332     << IsUnion << Name;
4333   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4334 
4335   return true;
4336 }
4337 
4338 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4339 /// anonymous struct or union AnonRecord into the owning context Owner
4340 /// and scope S. This routine will be invoked just after we realize
4341 /// that an unnamed union or struct is actually an anonymous union or
4342 /// struct, e.g.,
4343 ///
4344 /// @code
4345 /// union {
4346 ///   int i;
4347 ///   float f;
4348 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4349 ///    // f into the surrounding scope.x
4350 /// @endcode
4351 ///
4352 /// This routine is recursive, injecting the names of nested anonymous
4353 /// structs/unions into the owning context and scope as well.
4354 static bool
4355 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4356                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4357                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4358   bool Invalid = false;
4359 
4360   // Look every FieldDecl and IndirectFieldDecl with a name.
4361   for (auto *D : AnonRecord->decls()) {
4362     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4363         cast<NamedDecl>(D)->getDeclName()) {
4364       ValueDecl *VD = cast<ValueDecl>(D);
4365       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4366                                        VD->getLocation(),
4367                                        AnonRecord->isUnion())) {
4368         // C++ [class.union]p2:
4369         //   The names of the members of an anonymous union shall be
4370         //   distinct from the names of any other entity in the
4371         //   scope in which the anonymous union is declared.
4372         Invalid = true;
4373       } else {
4374         // C++ [class.union]p2:
4375         //   For the purpose of name lookup, after the anonymous union
4376         //   definition, the members of the anonymous union are
4377         //   considered to have been defined in the scope in which the
4378         //   anonymous union is declared.
4379         unsigned OldChainingSize = Chaining.size();
4380         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4381           Chaining.append(IF->chain_begin(), IF->chain_end());
4382         else
4383           Chaining.push_back(VD);
4384 
4385         assert(Chaining.size() >= 2);
4386         NamedDecl **NamedChain =
4387           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4388         for (unsigned i = 0; i < Chaining.size(); i++)
4389           NamedChain[i] = Chaining[i];
4390 
4391         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4392             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4393             VD->getType(), {NamedChain, Chaining.size()});
4394 
4395         for (const auto *Attr : VD->attrs())
4396           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4397 
4398         IndirectField->setAccess(AS);
4399         IndirectField->setImplicit();
4400         SemaRef.PushOnScopeChains(IndirectField, S);
4401 
4402         // That includes picking up the appropriate access specifier.
4403         if (AS != AS_none) IndirectField->setAccess(AS);
4404 
4405         Chaining.resize(OldChainingSize);
4406       }
4407     }
4408   }
4409 
4410   return Invalid;
4411 }
4412 
4413 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4414 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4415 /// illegal input values are mapped to SC_None.
4416 static StorageClass
4417 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4418   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4419   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4420          "Parser allowed 'typedef' as storage class VarDecl.");
4421   switch (StorageClassSpec) {
4422   case DeclSpec::SCS_unspecified:    return SC_None;
4423   case DeclSpec::SCS_extern:
4424     if (DS.isExternInLinkageSpec())
4425       return SC_None;
4426     return SC_Extern;
4427   case DeclSpec::SCS_static:         return SC_Static;
4428   case DeclSpec::SCS_auto:           return SC_Auto;
4429   case DeclSpec::SCS_register:       return SC_Register;
4430   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4431     // Illegal SCSs map to None: error reporting is up to the caller.
4432   case DeclSpec::SCS_mutable:        // Fall through.
4433   case DeclSpec::SCS_typedef:        return SC_None;
4434   }
4435   llvm_unreachable("unknown storage class specifier");
4436 }
4437 
4438 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4439   assert(Record->hasInClassInitializer());
4440 
4441   for (const auto *I : Record->decls()) {
4442     const auto *FD = dyn_cast<FieldDecl>(I);
4443     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4444       FD = IFD->getAnonField();
4445     if (FD && FD->hasInClassInitializer())
4446       return FD->getLocation();
4447   }
4448 
4449   llvm_unreachable("couldn't find in-class initializer");
4450 }
4451 
4452 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4453                                       SourceLocation DefaultInitLoc) {
4454   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4455     return;
4456 
4457   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4458   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4459 }
4460 
4461 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4462                                       CXXRecordDecl *AnonUnion) {
4463   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4464     return;
4465 
4466   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4467 }
4468 
4469 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4470 /// anonymous structure or union. Anonymous unions are a C++ feature
4471 /// (C++ [class.union]) and a C11 feature; anonymous structures
4472 /// are a C11 feature and GNU C++ extension.
4473 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4474                                         AccessSpecifier AS,
4475                                         RecordDecl *Record,
4476                                         const PrintingPolicy &Policy) {
4477   DeclContext *Owner = Record->getDeclContext();
4478 
4479   // Diagnose whether this anonymous struct/union is an extension.
4480   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4481     Diag(Record->getLocation(), diag::ext_anonymous_union);
4482   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4483     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4484   else if (!Record->isUnion() && !getLangOpts().C11)
4485     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4486 
4487   // C and C++ require different kinds of checks for anonymous
4488   // structs/unions.
4489   bool Invalid = false;
4490   if (getLangOpts().CPlusPlus) {
4491     const char *PrevSpec = nullptr;
4492     unsigned DiagID;
4493     if (Record->isUnion()) {
4494       // C++ [class.union]p6:
4495       //   Anonymous unions declared in a named namespace or in the
4496       //   global namespace shall be declared static.
4497       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4498           (isa<TranslationUnitDecl>(Owner) ||
4499            (isa<NamespaceDecl>(Owner) &&
4500             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4501         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4502           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4503 
4504         // Recover by adding 'static'.
4505         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4506                                PrevSpec, DiagID, Policy);
4507       }
4508       // C++ [class.union]p6:
4509       //   A storage class is not allowed in a declaration of an
4510       //   anonymous union in a class scope.
4511       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4512                isa<RecordDecl>(Owner)) {
4513         Diag(DS.getStorageClassSpecLoc(),
4514              diag::err_anonymous_union_with_storage_spec)
4515           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4516 
4517         // Recover by removing the storage specifier.
4518         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4519                                SourceLocation(),
4520                                PrevSpec, DiagID, Context.getPrintingPolicy());
4521       }
4522     }
4523 
4524     // Ignore const/volatile/restrict qualifiers.
4525     if (DS.getTypeQualifiers()) {
4526       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4527         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4528           << Record->isUnion() << "const"
4529           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4530       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4531         Diag(DS.getVolatileSpecLoc(),
4532              diag::ext_anonymous_struct_union_qualified)
4533           << Record->isUnion() << "volatile"
4534           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4535       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4536         Diag(DS.getRestrictSpecLoc(),
4537              diag::ext_anonymous_struct_union_qualified)
4538           << Record->isUnion() << "restrict"
4539           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4540       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4541         Diag(DS.getAtomicSpecLoc(),
4542              diag::ext_anonymous_struct_union_qualified)
4543           << Record->isUnion() << "_Atomic"
4544           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4545       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4546         Diag(DS.getUnalignedSpecLoc(),
4547              diag::ext_anonymous_struct_union_qualified)
4548           << Record->isUnion() << "__unaligned"
4549           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4550 
4551       DS.ClearTypeQualifiers();
4552     }
4553 
4554     // C++ [class.union]p2:
4555     //   The member-specification of an anonymous union shall only
4556     //   define non-static data members. [Note: nested types and
4557     //   functions cannot be declared within an anonymous union. ]
4558     for (auto *Mem : Record->decls()) {
4559       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4560         // C++ [class.union]p3:
4561         //   An anonymous union shall not have private or protected
4562         //   members (clause 11).
4563         assert(FD->getAccess() != AS_none);
4564         if (FD->getAccess() != AS_public) {
4565           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4566             << Record->isUnion() << (FD->getAccess() == AS_protected);
4567           Invalid = true;
4568         }
4569 
4570         // C++ [class.union]p1
4571         //   An object of a class with a non-trivial constructor, a non-trivial
4572         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4573         //   assignment operator cannot be a member of a union, nor can an
4574         //   array of such objects.
4575         if (CheckNontrivialField(FD))
4576           Invalid = true;
4577       } else if (Mem->isImplicit()) {
4578         // Any implicit members are fine.
4579       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4580         // This is a type that showed up in an
4581         // elaborated-type-specifier inside the anonymous struct or
4582         // union, but which actually declares a type outside of the
4583         // anonymous struct or union. It's okay.
4584       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4585         if (!MemRecord->isAnonymousStructOrUnion() &&
4586             MemRecord->getDeclName()) {
4587           // Visual C++ allows type definition in anonymous struct or union.
4588           if (getLangOpts().MicrosoftExt)
4589             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4590               << Record->isUnion();
4591           else {
4592             // This is a nested type declaration.
4593             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4594               << Record->isUnion();
4595             Invalid = true;
4596           }
4597         } else {
4598           // This is an anonymous type definition within another anonymous type.
4599           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4600           // not part of standard C++.
4601           Diag(MemRecord->getLocation(),
4602                diag::ext_anonymous_record_with_anonymous_type)
4603             << Record->isUnion();
4604         }
4605       } else if (isa<AccessSpecDecl>(Mem)) {
4606         // Any access specifier is fine.
4607       } else if (isa<StaticAssertDecl>(Mem)) {
4608         // In C++1z, static_assert declarations are also fine.
4609       } else {
4610         // We have something that isn't a non-static data
4611         // member. Complain about it.
4612         unsigned DK = diag::err_anonymous_record_bad_member;
4613         if (isa<TypeDecl>(Mem))
4614           DK = diag::err_anonymous_record_with_type;
4615         else if (isa<FunctionDecl>(Mem))
4616           DK = diag::err_anonymous_record_with_function;
4617         else if (isa<VarDecl>(Mem))
4618           DK = diag::err_anonymous_record_with_static;
4619 
4620         // Visual C++ allows type definition in anonymous struct or union.
4621         if (getLangOpts().MicrosoftExt &&
4622             DK == diag::err_anonymous_record_with_type)
4623           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4624             << Record->isUnion();
4625         else {
4626           Diag(Mem->getLocation(), DK) << Record->isUnion();
4627           Invalid = true;
4628         }
4629       }
4630     }
4631 
4632     // C++11 [class.union]p8 (DR1460):
4633     //   At most one variant member of a union may have a
4634     //   brace-or-equal-initializer.
4635     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4636         Owner->isRecord())
4637       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4638                                 cast<CXXRecordDecl>(Record));
4639   }
4640 
4641   if (!Record->isUnion() && !Owner->isRecord()) {
4642     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4643       << getLangOpts().CPlusPlus;
4644     Invalid = true;
4645   }
4646 
4647   // Mock up a declarator.
4648   Declarator Dc(DS, Declarator::MemberContext);
4649   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4650   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4651 
4652   // Create a declaration for this anonymous struct/union.
4653   NamedDecl *Anon = nullptr;
4654   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4655     Anon = FieldDecl::Create(Context, OwningClass,
4656                              DS.getLocStart(),
4657                              Record->getLocation(),
4658                              /*IdentifierInfo=*/nullptr,
4659                              Context.getTypeDeclType(Record),
4660                              TInfo,
4661                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4662                              /*InitStyle=*/ICIS_NoInit);
4663     Anon->setAccess(AS);
4664     if (getLangOpts().CPlusPlus)
4665       FieldCollector->Add(cast<FieldDecl>(Anon));
4666   } else {
4667     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4668     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4669     if (SCSpec == DeclSpec::SCS_mutable) {
4670       // mutable can only appear on non-static class members, so it's always
4671       // an error here
4672       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4673       Invalid = true;
4674       SC = SC_None;
4675     }
4676 
4677     Anon = VarDecl::Create(Context, Owner,
4678                            DS.getLocStart(),
4679                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4680                            Context.getTypeDeclType(Record),
4681                            TInfo, SC);
4682 
4683     // Default-initialize the implicit variable. This initialization will be
4684     // trivial in almost all cases, except if a union member has an in-class
4685     // initializer:
4686     //   union { int n = 0; };
4687     ActOnUninitializedDecl(Anon);
4688   }
4689   Anon->setImplicit();
4690 
4691   // Mark this as an anonymous struct/union type.
4692   Record->setAnonymousStructOrUnion(true);
4693 
4694   // Add the anonymous struct/union object to the current
4695   // context. We'll be referencing this object when we refer to one of
4696   // its members.
4697   Owner->addDecl(Anon);
4698 
4699   // Inject the members of the anonymous struct/union into the owning
4700   // context and into the identifier resolver chain for name lookup
4701   // purposes.
4702   SmallVector<NamedDecl*, 2> Chain;
4703   Chain.push_back(Anon);
4704 
4705   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4706     Invalid = true;
4707 
4708   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4709     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4710       Decl *ManglingContextDecl;
4711       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4712               NewVD->getDeclContext(), ManglingContextDecl)) {
4713         Context.setManglingNumber(
4714             NewVD, MCtx->getManglingNumber(
4715                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4716         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4717       }
4718     }
4719   }
4720 
4721   if (Invalid)
4722     Anon->setInvalidDecl();
4723 
4724   return Anon;
4725 }
4726 
4727 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4728 /// Microsoft C anonymous structure.
4729 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4730 /// Example:
4731 ///
4732 /// struct A { int a; };
4733 /// struct B { struct A; int b; };
4734 ///
4735 /// void foo() {
4736 ///   B var;
4737 ///   var.a = 3;
4738 /// }
4739 ///
4740 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4741                                            RecordDecl *Record) {
4742   assert(Record && "expected a record!");
4743 
4744   // Mock up a declarator.
4745   Declarator Dc(DS, Declarator::TypeNameContext);
4746   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4747   assert(TInfo && "couldn't build declarator info for anonymous struct");
4748 
4749   auto *ParentDecl = cast<RecordDecl>(CurContext);
4750   QualType RecTy = Context.getTypeDeclType(Record);
4751 
4752   // Create a declaration for this anonymous struct.
4753   NamedDecl *Anon = FieldDecl::Create(Context,
4754                              ParentDecl,
4755                              DS.getLocStart(),
4756                              DS.getLocStart(),
4757                              /*IdentifierInfo=*/nullptr,
4758                              RecTy,
4759                              TInfo,
4760                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4761                              /*InitStyle=*/ICIS_NoInit);
4762   Anon->setImplicit();
4763 
4764   // Add the anonymous struct object to the current context.
4765   CurContext->addDecl(Anon);
4766 
4767   // Inject the members of the anonymous struct into the current
4768   // context and into the identifier resolver chain for name lookup
4769   // purposes.
4770   SmallVector<NamedDecl*, 2> Chain;
4771   Chain.push_back(Anon);
4772 
4773   RecordDecl *RecordDef = Record->getDefinition();
4774   if (RequireCompleteType(Anon->getLocation(), RecTy,
4775                           diag::err_field_incomplete) ||
4776       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4777                                           AS_none, Chain)) {
4778     Anon->setInvalidDecl();
4779     ParentDecl->setInvalidDecl();
4780   }
4781 
4782   return Anon;
4783 }
4784 
4785 /// GetNameForDeclarator - Determine the full declaration name for the
4786 /// given Declarator.
4787 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4788   return GetNameFromUnqualifiedId(D.getName());
4789 }
4790 
4791 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4792 DeclarationNameInfo
4793 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4794   DeclarationNameInfo NameInfo;
4795   NameInfo.setLoc(Name.StartLocation);
4796 
4797   switch (Name.getKind()) {
4798 
4799   case UnqualifiedId::IK_ImplicitSelfParam:
4800   case UnqualifiedId::IK_Identifier:
4801     NameInfo.setName(Name.Identifier);
4802     NameInfo.setLoc(Name.StartLocation);
4803     return NameInfo;
4804 
4805   case UnqualifiedId::IK_DeductionGuideName: {
4806     // C++ [temp.deduct.guide]p3:
4807     //   The simple-template-id shall name a class template specialization.
4808     //   The template-name shall be the same identifier as the template-name
4809     //   of the simple-template-id.
4810     // These together intend to imply that the template-name shall name a
4811     // class template.
4812     // FIXME: template<typename T> struct X {};
4813     //        template<typename T> using Y = X<T>;
4814     //        Y(int) -> Y<int>;
4815     //   satisfies these rules but does not name a class template.
4816     TemplateName TN = Name.TemplateName.get().get();
4817     auto *Template = TN.getAsTemplateDecl();
4818     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4819       Diag(Name.StartLocation,
4820            diag::err_deduction_guide_name_not_class_template)
4821         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4822       if (Template)
4823         Diag(Template->getLocation(), diag::note_template_decl_here);
4824       return DeclarationNameInfo();
4825     }
4826 
4827     NameInfo.setName(
4828         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4829     NameInfo.setLoc(Name.StartLocation);
4830     return NameInfo;
4831   }
4832 
4833   case UnqualifiedId::IK_OperatorFunctionId:
4834     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4835                                            Name.OperatorFunctionId.Operator));
4836     NameInfo.setLoc(Name.StartLocation);
4837     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4838       = Name.OperatorFunctionId.SymbolLocations[0];
4839     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4840       = Name.EndLocation.getRawEncoding();
4841     return NameInfo;
4842 
4843   case UnqualifiedId::IK_LiteralOperatorId:
4844     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4845                                                            Name.Identifier));
4846     NameInfo.setLoc(Name.StartLocation);
4847     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4848     return NameInfo;
4849 
4850   case UnqualifiedId::IK_ConversionFunctionId: {
4851     TypeSourceInfo *TInfo;
4852     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4853     if (Ty.isNull())
4854       return DeclarationNameInfo();
4855     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4856                                                Context.getCanonicalType(Ty)));
4857     NameInfo.setLoc(Name.StartLocation);
4858     NameInfo.setNamedTypeInfo(TInfo);
4859     return NameInfo;
4860   }
4861 
4862   case UnqualifiedId::IK_ConstructorName: {
4863     TypeSourceInfo *TInfo;
4864     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4865     if (Ty.isNull())
4866       return DeclarationNameInfo();
4867     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4868                                               Context.getCanonicalType(Ty)));
4869     NameInfo.setLoc(Name.StartLocation);
4870     NameInfo.setNamedTypeInfo(TInfo);
4871     return NameInfo;
4872   }
4873 
4874   case UnqualifiedId::IK_ConstructorTemplateId: {
4875     // In well-formed code, we can only have a constructor
4876     // template-id that refers to the current context, so go there
4877     // to find the actual type being constructed.
4878     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4879     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4880       return DeclarationNameInfo();
4881 
4882     // Determine the type of the class being constructed.
4883     QualType CurClassType = Context.getTypeDeclType(CurClass);
4884 
4885     // FIXME: Check two things: that the template-id names the same type as
4886     // CurClassType, and that the template-id does not occur when the name
4887     // was qualified.
4888 
4889     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4890                                     Context.getCanonicalType(CurClassType)));
4891     NameInfo.setLoc(Name.StartLocation);
4892     // FIXME: should we retrieve TypeSourceInfo?
4893     NameInfo.setNamedTypeInfo(nullptr);
4894     return NameInfo;
4895   }
4896 
4897   case UnqualifiedId::IK_DestructorName: {
4898     TypeSourceInfo *TInfo;
4899     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4900     if (Ty.isNull())
4901       return DeclarationNameInfo();
4902     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4903                                               Context.getCanonicalType(Ty)));
4904     NameInfo.setLoc(Name.StartLocation);
4905     NameInfo.setNamedTypeInfo(TInfo);
4906     return NameInfo;
4907   }
4908 
4909   case UnqualifiedId::IK_TemplateId: {
4910     TemplateName TName = Name.TemplateId->Template.get();
4911     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4912     return Context.getNameForTemplate(TName, TNameLoc);
4913   }
4914 
4915   } // switch (Name.getKind())
4916 
4917   llvm_unreachable("Unknown name kind");
4918 }
4919 
4920 static QualType getCoreType(QualType Ty) {
4921   do {
4922     if (Ty->isPointerType() || Ty->isReferenceType())
4923       Ty = Ty->getPointeeType();
4924     else if (Ty->isArrayType())
4925       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4926     else
4927       return Ty.withoutLocalFastQualifiers();
4928   } while (true);
4929 }
4930 
4931 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4932 /// and Definition have "nearly" matching parameters. This heuristic is
4933 /// used to improve diagnostics in the case where an out-of-line function
4934 /// definition doesn't match any declaration within the class or namespace.
4935 /// Also sets Params to the list of indices to the parameters that differ
4936 /// between the declaration and the definition. If hasSimilarParameters
4937 /// returns true and Params is empty, then all of the parameters match.
4938 static bool hasSimilarParameters(ASTContext &Context,
4939                                      FunctionDecl *Declaration,
4940                                      FunctionDecl *Definition,
4941                                      SmallVectorImpl<unsigned> &Params) {
4942   Params.clear();
4943   if (Declaration->param_size() != Definition->param_size())
4944     return false;
4945   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4946     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4947     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4948 
4949     // The parameter types are identical
4950     if (Context.hasSameType(DefParamTy, DeclParamTy))
4951       continue;
4952 
4953     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4954     QualType DefParamBaseTy = getCoreType(DefParamTy);
4955     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4956     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4957 
4958     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4959         (DeclTyName && DeclTyName == DefTyName))
4960       Params.push_back(Idx);
4961     else  // The two parameters aren't even close
4962       return false;
4963   }
4964 
4965   return true;
4966 }
4967 
4968 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4969 /// declarator needs to be rebuilt in the current instantiation.
4970 /// Any bits of declarator which appear before the name are valid for
4971 /// consideration here.  That's specifically the type in the decl spec
4972 /// and the base type in any member-pointer chunks.
4973 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4974                                                     DeclarationName Name) {
4975   // The types we specifically need to rebuild are:
4976   //   - typenames, typeofs, and decltypes
4977   //   - types which will become injected class names
4978   // Of course, we also need to rebuild any type referencing such a
4979   // type.  It's safest to just say "dependent", but we call out a
4980   // few cases here.
4981 
4982   DeclSpec &DS = D.getMutableDeclSpec();
4983   switch (DS.getTypeSpecType()) {
4984   case DeclSpec::TST_typename:
4985   case DeclSpec::TST_typeofType:
4986   case DeclSpec::TST_underlyingType:
4987   case DeclSpec::TST_atomic: {
4988     // Grab the type from the parser.
4989     TypeSourceInfo *TSI = nullptr;
4990     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4991     if (T.isNull() || !T->isDependentType()) break;
4992 
4993     // Make sure there's a type source info.  This isn't really much
4994     // of a waste; most dependent types should have type source info
4995     // attached already.
4996     if (!TSI)
4997       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4998 
4999     // Rebuild the type in the current instantiation.
5000     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5001     if (!TSI) return true;
5002 
5003     // Store the new type back in the decl spec.
5004     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5005     DS.UpdateTypeRep(LocType);
5006     break;
5007   }
5008 
5009   case DeclSpec::TST_decltype:
5010   case DeclSpec::TST_typeofExpr: {
5011     Expr *E = DS.getRepAsExpr();
5012     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5013     if (Result.isInvalid()) return true;
5014     DS.UpdateExprRep(Result.get());
5015     break;
5016   }
5017 
5018   default:
5019     // Nothing to do for these decl specs.
5020     break;
5021   }
5022 
5023   // It doesn't matter what order we do this in.
5024   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5025     DeclaratorChunk &Chunk = D.getTypeObject(I);
5026 
5027     // The only type information in the declarator which can come
5028     // before the declaration name is the base type of a member
5029     // pointer.
5030     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5031       continue;
5032 
5033     // Rebuild the scope specifier in-place.
5034     CXXScopeSpec &SS = Chunk.Mem.Scope();
5035     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5036       return true;
5037   }
5038 
5039   return false;
5040 }
5041 
5042 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5043   D.setFunctionDefinitionKind(FDK_Declaration);
5044   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5045 
5046   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5047       Dcl && Dcl->getDeclContext()->isFileContext())
5048     Dcl->setTopLevelDeclInObjCContainer();
5049 
5050   if (getLangOpts().OpenCL)
5051     setCurrentOpenCLExtensionForDecl(Dcl);
5052 
5053   return Dcl;
5054 }
5055 
5056 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5057 ///   If T is the name of a class, then each of the following shall have a
5058 ///   name different from T:
5059 ///     - every static data member of class T;
5060 ///     - every member function of class T
5061 ///     - every member of class T that is itself a type;
5062 /// \returns true if the declaration name violates these rules.
5063 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5064                                    DeclarationNameInfo NameInfo) {
5065   DeclarationName Name = NameInfo.getName();
5066 
5067   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5068   while (Record && Record->isAnonymousStructOrUnion())
5069     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5070   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5071     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5072     return true;
5073   }
5074 
5075   return false;
5076 }
5077 
5078 /// \brief Diagnose a declaration whose declarator-id has the given
5079 /// nested-name-specifier.
5080 ///
5081 /// \param SS The nested-name-specifier of the declarator-id.
5082 ///
5083 /// \param DC The declaration context to which the nested-name-specifier
5084 /// resolves.
5085 ///
5086 /// \param Name The name of the entity being declared.
5087 ///
5088 /// \param Loc The location of the name of the entity being declared.
5089 ///
5090 /// \returns true if we cannot safely recover from this error, false otherwise.
5091 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5092                                         DeclarationName Name,
5093                                         SourceLocation Loc) {
5094   DeclContext *Cur = CurContext;
5095   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5096     Cur = Cur->getParent();
5097 
5098   // If the user provided a superfluous scope specifier that refers back to the
5099   // class in which the entity is already declared, diagnose and ignore it.
5100   //
5101   // class X {
5102   //   void X::f();
5103   // };
5104   //
5105   // Note, it was once ill-formed to give redundant qualification in all
5106   // contexts, but that rule was removed by DR482.
5107   if (Cur->Equals(DC)) {
5108     if (Cur->isRecord()) {
5109       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5110                                       : diag::err_member_extra_qualification)
5111         << Name << FixItHint::CreateRemoval(SS.getRange());
5112       SS.clear();
5113     } else {
5114       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5115     }
5116     return false;
5117   }
5118 
5119   // Check whether the qualifying scope encloses the scope of the original
5120   // declaration.
5121   if (!Cur->Encloses(DC)) {
5122     if (Cur->isRecord())
5123       Diag(Loc, diag::err_member_qualification)
5124         << Name << SS.getRange();
5125     else if (isa<TranslationUnitDecl>(DC))
5126       Diag(Loc, diag::err_invalid_declarator_global_scope)
5127         << Name << SS.getRange();
5128     else if (isa<FunctionDecl>(Cur))
5129       Diag(Loc, diag::err_invalid_declarator_in_function)
5130         << Name << SS.getRange();
5131     else if (isa<BlockDecl>(Cur))
5132       Diag(Loc, diag::err_invalid_declarator_in_block)
5133         << Name << SS.getRange();
5134     else
5135       Diag(Loc, diag::err_invalid_declarator_scope)
5136       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5137 
5138     return true;
5139   }
5140 
5141   if (Cur->isRecord()) {
5142     // Cannot qualify members within a class.
5143     Diag(Loc, diag::err_member_qualification)
5144       << Name << SS.getRange();
5145     SS.clear();
5146 
5147     // C++ constructors and destructors with incorrect scopes can break
5148     // our AST invariants by having the wrong underlying types. If
5149     // that's the case, then drop this declaration entirely.
5150     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5151          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5152         !Context.hasSameType(Name.getCXXNameType(),
5153                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5154       return true;
5155 
5156     return false;
5157   }
5158 
5159   // C++11 [dcl.meaning]p1:
5160   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5161   //   not begin with a decltype-specifer"
5162   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5163   while (SpecLoc.getPrefix())
5164     SpecLoc = SpecLoc.getPrefix();
5165   if (dyn_cast_or_null<DecltypeType>(
5166         SpecLoc.getNestedNameSpecifier()->getAsType()))
5167     Diag(Loc, diag::err_decltype_in_declarator)
5168       << SpecLoc.getTypeLoc().getSourceRange();
5169 
5170   return false;
5171 }
5172 
5173 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5174                                   MultiTemplateParamsArg TemplateParamLists) {
5175   // TODO: consider using NameInfo for diagnostic.
5176   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5177   DeclarationName Name = NameInfo.getName();
5178 
5179   // All of these full declarators require an identifier.  If it doesn't have
5180   // one, the ParsedFreeStandingDeclSpec action should be used.
5181   if (D.isDecompositionDeclarator()) {
5182     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5183   } else if (!Name) {
5184     if (!D.isInvalidType())  // Reject this if we think it is valid.
5185       Diag(D.getDeclSpec().getLocStart(),
5186            diag::err_declarator_need_ident)
5187         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5188     return nullptr;
5189   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5190     return nullptr;
5191 
5192   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5193   // we find one that is.
5194   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5195          (S->getFlags() & Scope::TemplateParamScope) != 0)
5196     S = S->getParent();
5197 
5198   DeclContext *DC = CurContext;
5199   if (D.getCXXScopeSpec().isInvalid())
5200     D.setInvalidType();
5201   else if (D.getCXXScopeSpec().isSet()) {
5202     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5203                                         UPPC_DeclarationQualifier))
5204       return nullptr;
5205 
5206     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5207     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5208     if (!DC || isa<EnumDecl>(DC)) {
5209       // If we could not compute the declaration context, it's because the
5210       // declaration context is dependent but does not refer to a class,
5211       // class template, or class template partial specialization. Complain
5212       // and return early, to avoid the coming semantic disaster.
5213       Diag(D.getIdentifierLoc(),
5214            diag::err_template_qualified_declarator_no_match)
5215         << D.getCXXScopeSpec().getScopeRep()
5216         << D.getCXXScopeSpec().getRange();
5217       return nullptr;
5218     }
5219     bool IsDependentContext = DC->isDependentContext();
5220 
5221     if (!IsDependentContext &&
5222         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5223       return nullptr;
5224 
5225     // If a class is incomplete, do not parse entities inside it.
5226     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5227       Diag(D.getIdentifierLoc(),
5228            diag::err_member_def_undefined_record)
5229         << Name << DC << D.getCXXScopeSpec().getRange();
5230       return nullptr;
5231     }
5232     if (!D.getDeclSpec().isFriendSpecified()) {
5233       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
5234                                       Name, D.getIdentifierLoc())) {
5235         if (DC->isRecord())
5236           return nullptr;
5237 
5238         D.setInvalidType();
5239       }
5240     }
5241 
5242     // Check whether we need to rebuild the type of the given
5243     // declaration in the current instantiation.
5244     if (EnteringContext && IsDependentContext &&
5245         TemplateParamLists.size() != 0) {
5246       ContextRAII SavedContext(*this, DC);
5247       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5248         D.setInvalidType();
5249     }
5250   }
5251 
5252   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5253   QualType R = TInfo->getType();
5254 
5255   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5256     // If this is a typedef, we'll end up spewing multiple diagnostics.
5257     // Just return early; it's safer. If this is a function, let the
5258     // "constructor cannot have a return type" diagnostic handle it.
5259     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5260       return nullptr;
5261 
5262   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5263                                       UPPC_DeclarationType))
5264     D.setInvalidType();
5265 
5266   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5267                         ForRedeclaration);
5268 
5269   // See if this is a redefinition of a variable in the same scope.
5270   if (!D.getCXXScopeSpec().isSet()) {
5271     bool IsLinkageLookup = false;
5272     bool CreateBuiltins = false;
5273 
5274     // If the declaration we're planning to build will be a function
5275     // or object with linkage, then look for another declaration with
5276     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5277     //
5278     // If the declaration we're planning to build will be declared with
5279     // external linkage in the translation unit, create any builtin with
5280     // the same name.
5281     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5282       /* Do nothing*/;
5283     else if (CurContext->isFunctionOrMethod() &&
5284              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5285               R->isFunctionType())) {
5286       IsLinkageLookup = true;
5287       CreateBuiltins =
5288           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5289     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5290                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5291       CreateBuiltins = true;
5292 
5293     if (IsLinkageLookup)
5294       Previous.clear(LookupRedeclarationWithLinkage);
5295 
5296     LookupName(Previous, S, CreateBuiltins);
5297   } else { // Something like "int foo::x;"
5298     LookupQualifiedName(Previous, DC);
5299 
5300     // C++ [dcl.meaning]p1:
5301     //   When the declarator-id is qualified, the declaration shall refer to a
5302     //  previously declared member of the class or namespace to which the
5303     //  qualifier refers (or, in the case of a namespace, of an element of the
5304     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5305     //  thereof; [...]
5306     //
5307     // Note that we already checked the context above, and that we do not have
5308     // enough information to make sure that Previous contains the declaration
5309     // we want to match. For example, given:
5310     //
5311     //   class X {
5312     //     void f();
5313     //     void f(float);
5314     //   };
5315     //
5316     //   void X::f(int) { } // ill-formed
5317     //
5318     // In this case, Previous will point to the overload set
5319     // containing the two f's declared in X, but neither of them
5320     // matches.
5321 
5322     // C++ [dcl.meaning]p1:
5323     //   [...] the member shall not merely have been introduced by a
5324     //   using-declaration in the scope of the class or namespace nominated by
5325     //   the nested-name-specifier of the declarator-id.
5326     RemoveUsingDecls(Previous);
5327   }
5328 
5329   if (Previous.isSingleResult() &&
5330       Previous.getFoundDecl()->isTemplateParameter()) {
5331     // Maybe we will complain about the shadowed template parameter.
5332     if (!D.isInvalidType())
5333       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5334                                       Previous.getFoundDecl());
5335 
5336     // Just pretend that we didn't see the previous declaration.
5337     Previous.clear();
5338   }
5339 
5340   // In C++, the previous declaration we find might be a tag type
5341   // (class or enum). In this case, the new declaration will hide the
5342   // tag type. Note that this does does not apply if we're declaring a
5343   // typedef (C++ [dcl.typedef]p4).
5344   if (Previous.isSingleTagDecl() &&
5345       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5346     Previous.clear();
5347 
5348   // Check that there are no default arguments other than in the parameters
5349   // of a function declaration (C++ only).
5350   if (getLangOpts().CPlusPlus)
5351     CheckExtraCXXDefaultArguments(D);
5352 
5353   if (D.getDeclSpec().isConceptSpecified()) {
5354     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5355     // applied only to the definition of a function template or variable
5356     // template, declared in namespace scope
5357     if (!TemplateParamLists.size()) {
5358       Diag(D.getDeclSpec().getConceptSpecLoc(),
5359            diag:: err_concept_wrong_decl_kind);
5360       return nullptr;
5361     }
5362 
5363     if (!DC->getRedeclContext()->isFileContext()) {
5364       Diag(D.getIdentifierLoc(),
5365            diag::err_concept_decls_may_only_appear_in_namespace_scope);
5366       return nullptr;
5367     }
5368   }
5369 
5370   NamedDecl *New;
5371 
5372   bool AddToScope = true;
5373   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5374     if (TemplateParamLists.size()) {
5375       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5376       return nullptr;
5377     }
5378 
5379     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5380   } else if (R->isFunctionType()) {
5381     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5382                                   TemplateParamLists,
5383                                   AddToScope);
5384   } else {
5385     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5386                                   AddToScope);
5387   }
5388 
5389   if (!New)
5390     return nullptr;
5391 
5392   // If this has an identifier and is not a function template specialization,
5393   // add it to the scope stack.
5394   if (New->getDeclName() && AddToScope) {
5395     // Only make a locally-scoped extern declaration visible if it is the first
5396     // declaration of this entity. Qualified lookup for such an entity should
5397     // only find this declaration if there is no visible declaration of it.
5398     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5399     PushOnScopeChains(New, S, AddToContext);
5400     if (!AddToContext)
5401       CurContext->addHiddenDecl(New);
5402   }
5403 
5404   if (isInOpenMPDeclareTargetContext())
5405     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5406 
5407   return New;
5408 }
5409 
5410 /// Helper method to turn variable array types into constant array
5411 /// types in certain situations which would otherwise be errors (for
5412 /// GCC compatibility).
5413 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5414                                                     ASTContext &Context,
5415                                                     bool &SizeIsNegative,
5416                                                     llvm::APSInt &Oversized) {
5417   // This method tries to turn a variable array into a constant
5418   // array even when the size isn't an ICE.  This is necessary
5419   // for compatibility with code that depends on gcc's buggy
5420   // constant expression folding, like struct {char x[(int)(char*)2];}
5421   SizeIsNegative = false;
5422   Oversized = 0;
5423 
5424   if (T->isDependentType())
5425     return QualType();
5426 
5427   QualifierCollector Qs;
5428   const Type *Ty = Qs.strip(T);
5429 
5430   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5431     QualType Pointee = PTy->getPointeeType();
5432     QualType FixedType =
5433         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5434                                             Oversized);
5435     if (FixedType.isNull()) return FixedType;
5436     FixedType = Context.getPointerType(FixedType);
5437     return Qs.apply(Context, FixedType);
5438   }
5439   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5440     QualType Inner = PTy->getInnerType();
5441     QualType FixedType =
5442         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5443                                             Oversized);
5444     if (FixedType.isNull()) return FixedType;
5445     FixedType = Context.getParenType(FixedType);
5446     return Qs.apply(Context, FixedType);
5447   }
5448 
5449   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5450   if (!VLATy)
5451     return QualType();
5452   // FIXME: We should probably handle this case
5453   if (VLATy->getElementType()->isVariablyModifiedType())
5454     return QualType();
5455 
5456   llvm::APSInt Res;
5457   if (!VLATy->getSizeExpr() ||
5458       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5459     return QualType();
5460 
5461   // Check whether the array size is negative.
5462   if (Res.isSigned() && Res.isNegative()) {
5463     SizeIsNegative = true;
5464     return QualType();
5465   }
5466 
5467   // Check whether the array is too large to be addressed.
5468   unsigned ActiveSizeBits
5469     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5470                                               Res);
5471   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5472     Oversized = Res;
5473     return QualType();
5474   }
5475 
5476   return Context.getConstantArrayType(VLATy->getElementType(),
5477                                       Res, ArrayType::Normal, 0);
5478 }
5479 
5480 static void
5481 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5482   SrcTL = SrcTL.getUnqualifiedLoc();
5483   DstTL = DstTL.getUnqualifiedLoc();
5484   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5485     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5486     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5487                                       DstPTL.getPointeeLoc());
5488     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5489     return;
5490   }
5491   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5492     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5493     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5494                                       DstPTL.getInnerLoc());
5495     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5496     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5497     return;
5498   }
5499   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5500   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5501   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5502   TypeLoc DstElemTL = DstATL.getElementLoc();
5503   DstElemTL.initializeFullCopy(SrcElemTL);
5504   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5505   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5506   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5507 }
5508 
5509 /// Helper method to turn variable array types into constant array
5510 /// types in certain situations which would otherwise be errors (for
5511 /// GCC compatibility).
5512 static TypeSourceInfo*
5513 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5514                                               ASTContext &Context,
5515                                               bool &SizeIsNegative,
5516                                               llvm::APSInt &Oversized) {
5517   QualType FixedTy
5518     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5519                                           SizeIsNegative, Oversized);
5520   if (FixedTy.isNull())
5521     return nullptr;
5522   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5523   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5524                                     FixedTInfo->getTypeLoc());
5525   return FixedTInfo;
5526 }
5527 
5528 /// \brief Register the given locally-scoped extern "C" declaration so
5529 /// that it can be found later for redeclarations. We include any extern "C"
5530 /// declaration that is not visible in the translation unit here, not just
5531 /// function-scope declarations.
5532 void
5533 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5534   if (!getLangOpts().CPlusPlus &&
5535       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5536     // Don't need to track declarations in the TU in C.
5537     return;
5538 
5539   // Note that we have a locally-scoped external with this name.
5540   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5541 }
5542 
5543 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5544   // FIXME: We can have multiple results via __attribute__((overloadable)).
5545   auto Result = Context.getExternCContextDecl()->lookup(Name);
5546   return Result.empty() ? nullptr : *Result.begin();
5547 }
5548 
5549 /// \brief Diagnose function specifiers on a declaration of an identifier that
5550 /// does not identify a function.
5551 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5552   // FIXME: We should probably indicate the identifier in question to avoid
5553   // confusion for constructs like "virtual int a(), b;"
5554   if (DS.isVirtualSpecified())
5555     Diag(DS.getVirtualSpecLoc(),
5556          diag::err_virtual_non_function);
5557 
5558   if (DS.isExplicitSpecified())
5559     Diag(DS.getExplicitSpecLoc(),
5560          diag::err_explicit_non_function);
5561 
5562   if (DS.isNoreturnSpecified())
5563     Diag(DS.getNoreturnSpecLoc(),
5564          diag::err_noreturn_non_function);
5565 }
5566 
5567 NamedDecl*
5568 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5569                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5570   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5571   if (D.getCXXScopeSpec().isSet()) {
5572     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5573       << D.getCXXScopeSpec().getRange();
5574     D.setInvalidType();
5575     // Pretend we didn't see the scope specifier.
5576     DC = CurContext;
5577     Previous.clear();
5578   }
5579 
5580   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5581 
5582   if (D.getDeclSpec().isInlineSpecified())
5583     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5584         << getLangOpts().CPlusPlus1z;
5585   if (D.getDeclSpec().isConstexprSpecified())
5586     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5587       << 1;
5588   if (D.getDeclSpec().isConceptSpecified())
5589     Diag(D.getDeclSpec().getConceptSpecLoc(),
5590          diag::err_concept_wrong_decl_kind);
5591 
5592   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5593     if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName)
5594       Diag(D.getName().StartLocation,
5595            diag::err_deduction_guide_invalid_specifier)
5596           << "typedef";
5597     else
5598       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5599           << D.getName().getSourceRange();
5600     return nullptr;
5601   }
5602 
5603   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5604   if (!NewTD) return nullptr;
5605 
5606   // Handle attributes prior to checking for duplicates in MergeVarDecl
5607   ProcessDeclAttributes(S, NewTD, D);
5608 
5609   CheckTypedefForVariablyModifiedType(S, NewTD);
5610 
5611   bool Redeclaration = D.isRedeclaration();
5612   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5613   D.setRedeclaration(Redeclaration);
5614   return ND;
5615 }
5616 
5617 void
5618 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5619   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5620   // then it shall have block scope.
5621   // Note that variably modified types must be fixed before merging the decl so
5622   // that redeclarations will match.
5623   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5624   QualType T = TInfo->getType();
5625   if (T->isVariablyModifiedType()) {
5626     getCurFunction()->setHasBranchProtectedScope();
5627 
5628     if (S->getFnParent() == nullptr) {
5629       bool SizeIsNegative;
5630       llvm::APSInt Oversized;
5631       TypeSourceInfo *FixedTInfo =
5632         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5633                                                       SizeIsNegative,
5634                                                       Oversized);
5635       if (FixedTInfo) {
5636         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5637         NewTD->setTypeSourceInfo(FixedTInfo);
5638       } else {
5639         if (SizeIsNegative)
5640           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5641         else if (T->isVariableArrayType())
5642           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5643         else if (Oversized.getBoolValue())
5644           Diag(NewTD->getLocation(), diag::err_array_too_large)
5645             << Oversized.toString(10);
5646         else
5647           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5648         NewTD->setInvalidDecl();
5649       }
5650     }
5651   }
5652 }
5653 
5654 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5655 /// declares a typedef-name, either using the 'typedef' type specifier or via
5656 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5657 NamedDecl*
5658 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5659                            LookupResult &Previous, bool &Redeclaration) {
5660 
5661   // Find the shadowed declaration before filtering for scope.
5662   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5663 
5664   // Merge the decl with the existing one if appropriate. If the decl is
5665   // in an outer scope, it isn't the same thing.
5666   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5667                        /*AllowInlineNamespace*/false);
5668   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5669   if (!Previous.empty()) {
5670     Redeclaration = true;
5671     MergeTypedefNameDecl(S, NewTD, Previous);
5672   }
5673 
5674   if (ShadowedDecl && !Redeclaration)
5675     CheckShadow(NewTD, ShadowedDecl, Previous);
5676 
5677   // If this is the C FILE type, notify the AST context.
5678   if (IdentifierInfo *II = NewTD->getIdentifier())
5679     if (!NewTD->isInvalidDecl() &&
5680         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5681       if (II->isStr("FILE"))
5682         Context.setFILEDecl(NewTD);
5683       else if (II->isStr("jmp_buf"))
5684         Context.setjmp_bufDecl(NewTD);
5685       else if (II->isStr("sigjmp_buf"))
5686         Context.setsigjmp_bufDecl(NewTD);
5687       else if (II->isStr("ucontext_t"))
5688         Context.setucontext_tDecl(NewTD);
5689     }
5690 
5691   return NewTD;
5692 }
5693 
5694 /// \brief Determines whether the given declaration is an out-of-scope
5695 /// previous declaration.
5696 ///
5697 /// This routine should be invoked when name lookup has found a
5698 /// previous declaration (PrevDecl) that is not in the scope where a
5699 /// new declaration by the same name is being introduced. If the new
5700 /// declaration occurs in a local scope, previous declarations with
5701 /// linkage may still be considered previous declarations (C99
5702 /// 6.2.2p4-5, C++ [basic.link]p6).
5703 ///
5704 /// \param PrevDecl the previous declaration found by name
5705 /// lookup
5706 ///
5707 /// \param DC the context in which the new declaration is being
5708 /// declared.
5709 ///
5710 /// \returns true if PrevDecl is an out-of-scope previous declaration
5711 /// for a new delcaration with the same name.
5712 static bool
5713 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5714                                 ASTContext &Context) {
5715   if (!PrevDecl)
5716     return false;
5717 
5718   if (!PrevDecl->hasLinkage())
5719     return false;
5720 
5721   if (Context.getLangOpts().CPlusPlus) {
5722     // C++ [basic.link]p6:
5723     //   If there is a visible declaration of an entity with linkage
5724     //   having the same name and type, ignoring entities declared
5725     //   outside the innermost enclosing namespace scope, the block
5726     //   scope declaration declares that same entity and receives the
5727     //   linkage of the previous declaration.
5728     DeclContext *OuterContext = DC->getRedeclContext();
5729     if (!OuterContext->isFunctionOrMethod())
5730       // This rule only applies to block-scope declarations.
5731       return false;
5732 
5733     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5734     if (PrevOuterContext->isRecord())
5735       // We found a member function: ignore it.
5736       return false;
5737 
5738     // Find the innermost enclosing namespace for the new and
5739     // previous declarations.
5740     OuterContext = OuterContext->getEnclosingNamespaceContext();
5741     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5742 
5743     // The previous declaration is in a different namespace, so it
5744     // isn't the same function.
5745     if (!OuterContext->Equals(PrevOuterContext))
5746       return false;
5747   }
5748 
5749   return true;
5750 }
5751 
5752 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5753   CXXScopeSpec &SS = D.getCXXScopeSpec();
5754   if (!SS.isSet()) return;
5755   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5756 }
5757 
5758 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5759   QualType type = decl->getType();
5760   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5761   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5762     // Various kinds of declaration aren't allowed to be __autoreleasing.
5763     unsigned kind = -1U;
5764     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5765       if (var->hasAttr<BlocksAttr>())
5766         kind = 0; // __block
5767       else if (!var->hasLocalStorage())
5768         kind = 1; // global
5769     } else if (isa<ObjCIvarDecl>(decl)) {
5770       kind = 3; // ivar
5771     } else if (isa<FieldDecl>(decl)) {
5772       kind = 2; // field
5773     }
5774 
5775     if (kind != -1U) {
5776       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5777         << kind;
5778     }
5779   } else if (lifetime == Qualifiers::OCL_None) {
5780     // Try to infer lifetime.
5781     if (!type->isObjCLifetimeType())
5782       return false;
5783 
5784     lifetime = type->getObjCARCImplicitLifetime();
5785     type = Context.getLifetimeQualifiedType(type, lifetime);
5786     decl->setType(type);
5787   }
5788 
5789   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5790     // Thread-local variables cannot have lifetime.
5791     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5792         var->getTLSKind()) {
5793       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5794         << var->getType();
5795       return true;
5796     }
5797   }
5798 
5799   return false;
5800 }
5801 
5802 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5803   // Ensure that an auto decl is deduced otherwise the checks below might cache
5804   // the wrong linkage.
5805   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5806 
5807   // 'weak' only applies to declarations with external linkage.
5808   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5809     if (!ND.isExternallyVisible()) {
5810       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5811       ND.dropAttr<WeakAttr>();
5812     }
5813   }
5814   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5815     if (ND.isExternallyVisible()) {
5816       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5817       ND.dropAttr<WeakRefAttr>();
5818       ND.dropAttr<AliasAttr>();
5819     }
5820   }
5821 
5822   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5823     if (VD->hasInit()) {
5824       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5825         assert(VD->isThisDeclarationADefinition() &&
5826                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5827         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5828         VD->dropAttr<AliasAttr>();
5829       }
5830     }
5831   }
5832 
5833   // 'selectany' only applies to externally visible variable declarations.
5834   // It does not apply to functions.
5835   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5836     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5837       S.Diag(Attr->getLocation(),
5838              diag::err_attribute_selectany_non_extern_data);
5839       ND.dropAttr<SelectAnyAttr>();
5840     }
5841   }
5842 
5843   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5844     // dll attributes require external linkage. Static locals may have external
5845     // linkage but still cannot be explicitly imported or exported.
5846     auto *VD = dyn_cast<VarDecl>(&ND);
5847     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5848       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5849         << &ND << Attr;
5850       ND.setInvalidDecl();
5851     }
5852   }
5853 
5854   // Virtual functions cannot be marked as 'notail'.
5855   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5856     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5857       if (MD->isVirtual()) {
5858         S.Diag(ND.getLocation(),
5859                diag::err_invalid_attribute_on_virtual_function)
5860             << Attr;
5861         ND.dropAttr<NotTailCalledAttr>();
5862       }
5863 }
5864 
5865 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5866                                            NamedDecl *NewDecl,
5867                                            bool IsSpecialization,
5868                                            bool IsDefinition) {
5869   if (OldDecl->isInvalidDecl())
5870     return;
5871 
5872   bool IsTemplate = false;
5873   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5874     OldDecl = OldTD->getTemplatedDecl();
5875     IsTemplate = true;
5876     if (!IsSpecialization)
5877       IsDefinition = false;
5878   }
5879   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
5880     NewDecl = NewTD->getTemplatedDecl();
5881     IsTemplate = true;
5882   }
5883 
5884   if (!OldDecl || !NewDecl)
5885     return;
5886 
5887   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5888   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5889   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5890   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5891 
5892   // dllimport and dllexport are inheritable attributes so we have to exclude
5893   // inherited attribute instances.
5894   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5895                     (NewExportAttr && !NewExportAttr->isInherited());
5896 
5897   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5898   // the only exception being explicit specializations.
5899   // Implicitly generated declarations are also excluded for now because there
5900   // is no other way to switch these to use dllimport or dllexport.
5901   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5902 
5903   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5904     // Allow with a warning for free functions and global variables.
5905     bool JustWarn = false;
5906     if (!OldDecl->isCXXClassMember()) {
5907       auto *VD = dyn_cast<VarDecl>(OldDecl);
5908       if (VD && !VD->getDescribedVarTemplate())
5909         JustWarn = true;
5910       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5911       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5912         JustWarn = true;
5913     }
5914 
5915     // We cannot change a declaration that's been used because IR has already
5916     // been emitted. Dllimported functions will still work though (modulo
5917     // address equality) as they can use the thunk.
5918     if (OldDecl->isUsed())
5919       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5920         JustWarn = false;
5921 
5922     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5923                                : diag::err_attribute_dll_redeclaration;
5924     S.Diag(NewDecl->getLocation(), DiagID)
5925         << NewDecl
5926         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5927     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5928     if (!JustWarn) {
5929       NewDecl->setInvalidDecl();
5930       return;
5931     }
5932   }
5933 
5934   // A redeclaration is not allowed to drop a dllimport attribute, the only
5935   // exceptions being inline function definitions (except for function
5936   // templates), local extern declarations, qualified friend declarations or
5937   // special MSVC extension: in the last case, the declaration is treated as if
5938   // it were marked dllexport.
5939   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5940   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5941   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5942     // Ignore static data because out-of-line definitions are diagnosed
5943     // separately.
5944     IsStaticDataMember = VD->isStaticDataMember();
5945     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5946                    VarDecl::DeclarationOnly;
5947   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5948     IsInline = FD->isInlined();
5949     IsQualifiedFriend = FD->getQualifier() &&
5950                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5951   }
5952 
5953   if (OldImportAttr && !HasNewAttr &&
5954       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
5955       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5956     if (IsMicrosoft && IsDefinition) {
5957       S.Diag(NewDecl->getLocation(),
5958              diag::warn_redeclaration_without_import_attribute)
5959           << NewDecl;
5960       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5961       NewDecl->dropAttr<DLLImportAttr>();
5962       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
5963           NewImportAttr->getRange(), S.Context,
5964           NewImportAttr->getSpellingListIndex()));
5965     } else {
5966       S.Diag(NewDecl->getLocation(),
5967              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5968           << NewDecl << OldImportAttr;
5969       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5970       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5971       OldDecl->dropAttr<DLLImportAttr>();
5972       NewDecl->dropAttr<DLLImportAttr>();
5973     }
5974   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
5975     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5976     OldDecl->dropAttr<DLLImportAttr>();
5977     NewDecl->dropAttr<DLLImportAttr>();
5978     S.Diag(NewDecl->getLocation(),
5979            diag::warn_dllimport_dropped_from_inline_function)
5980         << NewDecl << OldImportAttr;
5981   }
5982 }
5983 
5984 /// Given that we are within the definition of the given function,
5985 /// will that definition behave like C99's 'inline', where the
5986 /// definition is discarded except for optimization purposes?
5987 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5988   // Try to avoid calling GetGVALinkageForFunction.
5989 
5990   // All cases of this require the 'inline' keyword.
5991   if (!FD->isInlined()) return false;
5992 
5993   // This is only possible in C++ with the gnu_inline attribute.
5994   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5995     return false;
5996 
5997   // Okay, go ahead and call the relatively-more-expensive function.
5998   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5999 }
6000 
6001 /// Determine whether a variable is extern "C" prior to attaching
6002 /// an initializer. We can't just call isExternC() here, because that
6003 /// will also compute and cache whether the declaration is externally
6004 /// visible, which might change when we attach the initializer.
6005 ///
6006 /// This can only be used if the declaration is known to not be a
6007 /// redeclaration of an internal linkage declaration.
6008 ///
6009 /// For instance:
6010 ///
6011 ///   auto x = []{};
6012 ///
6013 /// Attaching the initializer here makes this declaration not externally
6014 /// visible, because its type has internal linkage.
6015 ///
6016 /// FIXME: This is a hack.
6017 template<typename T>
6018 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6019   if (S.getLangOpts().CPlusPlus) {
6020     // In C++, the overloadable attribute negates the effects of extern "C".
6021     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6022       return false;
6023 
6024     // So do CUDA's host/device attributes.
6025     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6026                                  D->template hasAttr<CUDAHostAttr>()))
6027       return false;
6028   }
6029   return D->isExternC();
6030 }
6031 
6032 static bool shouldConsiderLinkage(const VarDecl *VD) {
6033   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6034   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
6035     return VD->hasExternalStorage();
6036   if (DC->isFileContext())
6037     return true;
6038   if (DC->isRecord())
6039     return false;
6040   llvm_unreachable("Unexpected context");
6041 }
6042 
6043 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6044   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6045   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6046       isa<OMPDeclareReductionDecl>(DC))
6047     return true;
6048   if (DC->isRecord())
6049     return false;
6050   llvm_unreachable("Unexpected context");
6051 }
6052 
6053 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
6054                           AttributeList::Kind Kind) {
6055   for (const AttributeList *L = AttrList; L; L = L->getNext())
6056     if (L->getKind() == Kind)
6057       return true;
6058   return false;
6059 }
6060 
6061 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6062                           AttributeList::Kind Kind) {
6063   // Check decl attributes on the DeclSpec.
6064   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
6065     return true;
6066 
6067   // Walk the declarator structure, checking decl attributes that were in a type
6068   // position to the decl itself.
6069   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6070     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
6071       return true;
6072   }
6073 
6074   // Finally, check attributes on the decl itself.
6075   return hasParsedAttr(S, PD.getAttributes(), Kind);
6076 }
6077 
6078 /// Adjust the \c DeclContext for a function or variable that might be a
6079 /// function-local external declaration.
6080 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6081   if (!DC->isFunctionOrMethod())
6082     return false;
6083 
6084   // If this is a local extern function or variable declared within a function
6085   // template, don't add it into the enclosing namespace scope until it is
6086   // instantiated; it might have a dependent type right now.
6087   if (DC->isDependentContext())
6088     return true;
6089 
6090   // C++11 [basic.link]p7:
6091   //   When a block scope declaration of an entity with linkage is not found to
6092   //   refer to some other declaration, then that entity is a member of the
6093   //   innermost enclosing namespace.
6094   //
6095   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6096   // semantically-enclosing namespace, not a lexically-enclosing one.
6097   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6098     DC = DC->getParent();
6099   return true;
6100 }
6101 
6102 /// \brief Returns true if given declaration has external C language linkage.
6103 static bool isDeclExternC(const Decl *D) {
6104   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6105     return FD->isExternC();
6106   if (const auto *VD = dyn_cast<VarDecl>(D))
6107     return VD->isExternC();
6108 
6109   llvm_unreachable("Unknown type of decl!");
6110 }
6111 
6112 NamedDecl *Sema::ActOnVariableDeclarator(
6113     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6114     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6115     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6116   QualType R = TInfo->getType();
6117   DeclarationName Name = GetNameForDeclarator(D).getName();
6118 
6119   IdentifierInfo *II = Name.getAsIdentifierInfo();
6120 
6121   if (D.isDecompositionDeclarator()) {
6122     AddToScope = false;
6123     // Take the name of the first declarator as our name for diagnostic
6124     // purposes.
6125     auto &Decomp = D.getDecompositionDeclarator();
6126     if (!Decomp.bindings().empty()) {
6127       II = Decomp.bindings()[0].Name;
6128       Name = II;
6129     }
6130   } else if (!II) {
6131     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6132     return nullptr;
6133   }
6134 
6135   if (getLangOpts().OpenCL) {
6136     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6137     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6138     // argument.
6139     if (R->isImageType() || R->isPipeType()) {
6140       Diag(D.getIdentifierLoc(),
6141            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6142           << R;
6143       D.setInvalidType();
6144       return nullptr;
6145     }
6146 
6147     // OpenCL v1.2 s6.9.r:
6148     // The event type cannot be used to declare a program scope variable.
6149     // OpenCL v2.0 s6.9.q:
6150     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6151     if (NULL == S->getParent()) {
6152       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6153         Diag(D.getIdentifierLoc(),
6154              diag::err_invalid_type_for_program_scope_var) << R;
6155         D.setInvalidType();
6156         return nullptr;
6157       }
6158     }
6159 
6160     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6161     QualType NR = R;
6162     while (NR->isPointerType()) {
6163       if (NR->isFunctionPointerType()) {
6164         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6165         D.setInvalidType();
6166         break;
6167       }
6168       NR = NR->getPointeeType();
6169     }
6170 
6171     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6172       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6173       // half array type (unless the cl_khr_fp16 extension is enabled).
6174       if (Context.getBaseElementType(R)->isHalfType()) {
6175         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6176         D.setInvalidType();
6177       }
6178     }
6179 
6180     if (R->isSamplerT()) {
6181       // OpenCL v1.2 s6.9.b p4:
6182       // The sampler type cannot be used with the __local and __global address
6183       // space qualifiers.
6184       if (R.getAddressSpace() == LangAS::opencl_local ||
6185           R.getAddressSpace() == LangAS::opencl_global) {
6186         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6187       }
6188 
6189       // OpenCL v1.2 s6.12.14.1:
6190       // A global sampler must be declared with either the constant address
6191       // space qualifier or with the const qualifier.
6192       if (DC->isTranslationUnit() &&
6193           !(R.getAddressSpace() == LangAS::opencl_constant ||
6194           R.isConstQualified())) {
6195         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6196         D.setInvalidType();
6197       }
6198     }
6199 
6200     // OpenCL v1.2 s6.9.r:
6201     // The event type cannot be used with the __local, __constant and __global
6202     // address space qualifiers.
6203     if (R->isEventT()) {
6204       if (R.getAddressSpace()) {
6205         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6206         D.setInvalidType();
6207       }
6208     }
6209   }
6210 
6211   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6212   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6213 
6214   // dllimport globals without explicit storage class are treated as extern. We
6215   // have to change the storage class this early to get the right DeclContext.
6216   if (SC == SC_None && !DC->isRecord() &&
6217       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
6218       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
6219     SC = SC_Extern;
6220 
6221   DeclContext *OriginalDC = DC;
6222   bool IsLocalExternDecl = SC == SC_Extern &&
6223                            adjustContextForLocalExternDecl(DC);
6224 
6225   if (SCSpec == DeclSpec::SCS_mutable) {
6226     // mutable can only appear on non-static class members, so it's always
6227     // an error here
6228     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6229     D.setInvalidType();
6230     SC = SC_None;
6231   }
6232 
6233   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6234       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6235                               D.getDeclSpec().getStorageClassSpecLoc())) {
6236     // In C++11, the 'register' storage class specifier is deprecated.
6237     // Suppress the warning in system macros, it's used in macros in some
6238     // popular C system headers, such as in glibc's htonl() macro.
6239     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6240          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
6241                                    : diag::warn_deprecated_register)
6242       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6243   }
6244 
6245   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6246 
6247   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6248     // C99 6.9p2: The storage-class specifiers auto and register shall not
6249     // appear in the declaration specifiers in an external declaration.
6250     // Global Register+Asm is a GNU extension we support.
6251     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6252       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6253       D.setInvalidType();
6254     }
6255   }
6256 
6257   bool IsMemberSpecialization = false;
6258   bool IsVariableTemplateSpecialization = false;
6259   bool IsPartialSpecialization = false;
6260   bool IsVariableTemplate = false;
6261   VarDecl *NewVD = nullptr;
6262   VarTemplateDecl *NewTemplate = nullptr;
6263   TemplateParameterList *TemplateParams = nullptr;
6264   if (!getLangOpts().CPlusPlus) {
6265     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6266                             D.getIdentifierLoc(), II,
6267                             R, TInfo, SC);
6268 
6269     if (R->getContainedDeducedType())
6270       ParsingInitForAutoVars.insert(NewVD);
6271 
6272     if (D.isInvalidType())
6273       NewVD->setInvalidDecl();
6274   } else {
6275     bool Invalid = false;
6276 
6277     if (DC->isRecord() && !CurContext->isRecord()) {
6278       // This is an out-of-line definition of a static data member.
6279       switch (SC) {
6280       case SC_None:
6281         break;
6282       case SC_Static:
6283         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6284              diag::err_static_out_of_line)
6285           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6286         break;
6287       case SC_Auto:
6288       case SC_Register:
6289       case SC_Extern:
6290         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6291         // to names of variables declared in a block or to function parameters.
6292         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6293         // of class members
6294 
6295         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6296              diag::err_storage_class_for_static_member)
6297           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6298         break;
6299       case SC_PrivateExtern:
6300         llvm_unreachable("C storage class in c++!");
6301       }
6302     }
6303 
6304     if (SC == SC_Static && CurContext->isRecord()) {
6305       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6306         if (RD->isLocalClass())
6307           Diag(D.getIdentifierLoc(),
6308                diag::err_static_data_member_not_allowed_in_local_class)
6309             << Name << RD->getDeclName();
6310 
6311         // C++98 [class.union]p1: If a union contains a static data member,
6312         // the program is ill-formed. C++11 drops this restriction.
6313         if (RD->isUnion())
6314           Diag(D.getIdentifierLoc(),
6315                getLangOpts().CPlusPlus11
6316                  ? diag::warn_cxx98_compat_static_data_member_in_union
6317                  : diag::ext_static_data_member_in_union) << Name;
6318         // We conservatively disallow static data members in anonymous structs.
6319         else if (!RD->getDeclName())
6320           Diag(D.getIdentifierLoc(),
6321                diag::err_static_data_member_not_allowed_in_anon_struct)
6322             << Name << RD->isUnion();
6323       }
6324     }
6325 
6326     // Match up the template parameter lists with the scope specifier, then
6327     // determine whether we have a template or a template specialization.
6328     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6329         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6330         D.getCXXScopeSpec(),
6331         D.getName().getKind() == UnqualifiedId::IK_TemplateId
6332             ? D.getName().TemplateId
6333             : nullptr,
6334         TemplateParamLists,
6335         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6336 
6337     if (TemplateParams) {
6338       if (!TemplateParams->size() &&
6339           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6340         // There is an extraneous 'template<>' for this variable. Complain
6341         // about it, but allow the declaration of the variable.
6342         Diag(TemplateParams->getTemplateLoc(),
6343              diag::err_template_variable_noparams)
6344           << II
6345           << SourceRange(TemplateParams->getTemplateLoc(),
6346                          TemplateParams->getRAngleLoc());
6347         TemplateParams = nullptr;
6348       } else {
6349         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6350           // This is an explicit specialization or a partial specialization.
6351           // FIXME: Check that we can declare a specialization here.
6352           IsVariableTemplateSpecialization = true;
6353           IsPartialSpecialization = TemplateParams->size() > 0;
6354         } else { // if (TemplateParams->size() > 0)
6355           // This is a template declaration.
6356           IsVariableTemplate = true;
6357 
6358           // Check that we can declare a template here.
6359           if (CheckTemplateDeclScope(S, TemplateParams))
6360             return nullptr;
6361 
6362           // Only C++1y supports variable templates (N3651).
6363           Diag(D.getIdentifierLoc(),
6364                getLangOpts().CPlusPlus14
6365                    ? diag::warn_cxx11_compat_variable_template
6366                    : diag::ext_variable_template);
6367         }
6368       }
6369     } else {
6370       assert(
6371           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6372           "should have a 'template<>' for this decl");
6373     }
6374 
6375     if (IsVariableTemplateSpecialization) {
6376       SourceLocation TemplateKWLoc =
6377           TemplateParamLists.size() > 0
6378               ? TemplateParamLists[0]->getTemplateLoc()
6379               : SourceLocation();
6380       DeclResult Res = ActOnVarTemplateSpecialization(
6381           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6382           IsPartialSpecialization);
6383       if (Res.isInvalid())
6384         return nullptr;
6385       NewVD = cast<VarDecl>(Res.get());
6386       AddToScope = false;
6387     } else if (D.isDecompositionDeclarator()) {
6388       NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6389                                         D.getIdentifierLoc(), R, TInfo, SC,
6390                                         Bindings);
6391     } else
6392       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6393                               D.getIdentifierLoc(), II, R, TInfo, SC);
6394 
6395     // If this is supposed to be a variable template, create it as such.
6396     if (IsVariableTemplate) {
6397       NewTemplate =
6398           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6399                                   TemplateParams, NewVD);
6400       NewVD->setDescribedVarTemplate(NewTemplate);
6401     }
6402 
6403     // If this decl has an auto type in need of deduction, make a note of the
6404     // Decl so we can diagnose uses of it in its own initializer.
6405     if (R->getContainedDeducedType())
6406       ParsingInitForAutoVars.insert(NewVD);
6407 
6408     if (D.isInvalidType() || Invalid) {
6409       NewVD->setInvalidDecl();
6410       if (NewTemplate)
6411         NewTemplate->setInvalidDecl();
6412     }
6413 
6414     SetNestedNameSpecifier(NewVD, D);
6415 
6416     // If we have any template parameter lists that don't directly belong to
6417     // the variable (matching the scope specifier), store them.
6418     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6419     if (TemplateParamLists.size() > VDTemplateParamLists)
6420       NewVD->setTemplateParameterListsInfo(
6421           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6422 
6423     if (D.getDeclSpec().isConstexprSpecified()) {
6424       NewVD->setConstexpr(true);
6425       // C++1z [dcl.spec.constexpr]p1:
6426       //   A static data member declared with the constexpr specifier is
6427       //   implicitly an inline variable.
6428       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6429         NewVD->setImplicitlyInline();
6430     }
6431 
6432     if (D.getDeclSpec().isConceptSpecified()) {
6433       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6434         VTD->setConcept();
6435 
6436       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6437       // be declared with the thread_local, inline, friend, or constexpr
6438       // specifiers, [...]
6439       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6440         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6441              diag::err_concept_decl_invalid_specifiers)
6442             << 0 << 0;
6443         NewVD->setInvalidDecl(true);
6444       }
6445 
6446       if (D.getDeclSpec().isConstexprSpecified()) {
6447         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6448              diag::err_concept_decl_invalid_specifiers)
6449             << 0 << 3;
6450         NewVD->setInvalidDecl(true);
6451       }
6452 
6453       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6454       // applied only to the definition of a function template or variable
6455       // template, declared in namespace scope.
6456       if (IsVariableTemplateSpecialization) {
6457         Diag(D.getDeclSpec().getConceptSpecLoc(),
6458              diag::err_concept_specified_specialization)
6459             << (IsPartialSpecialization ? 2 : 1);
6460       }
6461 
6462       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6463       // following restrictions:
6464       // - The declared type shall have the type bool.
6465       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6466           !NewVD->isInvalidDecl()) {
6467         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6468         NewVD->setInvalidDecl(true);
6469       }
6470     }
6471   }
6472 
6473   if (D.getDeclSpec().isInlineSpecified()) {
6474     if (!getLangOpts().CPlusPlus) {
6475       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6476           << 0;
6477     } else if (CurContext->isFunctionOrMethod()) {
6478       // 'inline' is not allowed on block scope variable declaration.
6479       Diag(D.getDeclSpec().getInlineSpecLoc(),
6480            diag::err_inline_declaration_block_scope) << Name
6481         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6482     } else {
6483       Diag(D.getDeclSpec().getInlineSpecLoc(),
6484            getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6485                                      : diag::ext_inline_variable);
6486       NewVD->setInlineSpecified();
6487     }
6488   }
6489 
6490   // Set the lexical context. If the declarator has a C++ scope specifier, the
6491   // lexical context will be different from the semantic context.
6492   NewVD->setLexicalDeclContext(CurContext);
6493   if (NewTemplate)
6494     NewTemplate->setLexicalDeclContext(CurContext);
6495 
6496   if (IsLocalExternDecl) {
6497     if (D.isDecompositionDeclarator())
6498       for (auto *B : Bindings)
6499         B->setLocalExternDecl();
6500     else
6501       NewVD->setLocalExternDecl();
6502   }
6503 
6504   bool EmitTLSUnsupportedError = false;
6505   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6506     // C++11 [dcl.stc]p4:
6507     //   When thread_local is applied to a variable of block scope the
6508     //   storage-class-specifier static is implied if it does not appear
6509     //   explicitly.
6510     // Core issue: 'static' is not implied if the variable is declared
6511     //   'extern'.
6512     if (NewVD->hasLocalStorage() &&
6513         (SCSpec != DeclSpec::SCS_unspecified ||
6514          TSCS != DeclSpec::TSCS_thread_local ||
6515          !DC->isFunctionOrMethod()))
6516       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6517            diag::err_thread_non_global)
6518         << DeclSpec::getSpecifierName(TSCS);
6519     else if (!Context.getTargetInfo().isTLSSupported()) {
6520       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6521         // Postpone error emission until we've collected attributes required to
6522         // figure out whether it's a host or device variable and whether the
6523         // error should be ignored.
6524         EmitTLSUnsupportedError = true;
6525         // We still need to mark the variable as TLS so it shows up in AST with
6526         // proper storage class for other tools to use even if we're not going
6527         // to emit any code for it.
6528         NewVD->setTSCSpec(TSCS);
6529       } else
6530         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6531              diag::err_thread_unsupported);
6532     } else
6533       NewVD->setTSCSpec(TSCS);
6534   }
6535 
6536   // C99 6.7.4p3
6537   //   An inline definition of a function with external linkage shall
6538   //   not contain a definition of a modifiable object with static or
6539   //   thread storage duration...
6540   // We only apply this when the function is required to be defined
6541   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6542   // that a local variable with thread storage duration still has to
6543   // be marked 'static'.  Also note that it's possible to get these
6544   // semantics in C++ using __attribute__((gnu_inline)).
6545   if (SC == SC_Static && S->getFnParent() != nullptr &&
6546       !NewVD->getType().isConstQualified()) {
6547     FunctionDecl *CurFD = getCurFunctionDecl();
6548     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6549       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6550            diag::warn_static_local_in_extern_inline);
6551       MaybeSuggestAddingStaticToDecl(CurFD);
6552     }
6553   }
6554 
6555   if (D.getDeclSpec().isModulePrivateSpecified()) {
6556     if (IsVariableTemplateSpecialization)
6557       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6558           << (IsPartialSpecialization ? 1 : 0)
6559           << FixItHint::CreateRemoval(
6560                  D.getDeclSpec().getModulePrivateSpecLoc());
6561     else if (IsMemberSpecialization)
6562       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6563         << 2
6564         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6565     else if (NewVD->hasLocalStorage())
6566       Diag(NewVD->getLocation(), diag::err_module_private_local)
6567         << 0 << NewVD->getDeclName()
6568         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6569         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6570     else {
6571       NewVD->setModulePrivate();
6572       if (NewTemplate)
6573         NewTemplate->setModulePrivate();
6574       for (auto *B : Bindings)
6575         B->setModulePrivate();
6576     }
6577   }
6578 
6579   // Handle attributes prior to checking for duplicates in MergeVarDecl
6580   ProcessDeclAttributes(S, NewVD, D);
6581 
6582   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6583     if (EmitTLSUnsupportedError &&
6584         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6585          (getLangOpts().OpenMPIsDevice &&
6586           NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6587       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6588            diag::err_thread_unsupported);
6589     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6590     // storage [duration]."
6591     if (SC == SC_None && S->getFnParent() != nullptr &&
6592         (NewVD->hasAttr<CUDASharedAttr>() ||
6593          NewVD->hasAttr<CUDAConstantAttr>())) {
6594       NewVD->setStorageClass(SC_Static);
6595     }
6596   }
6597 
6598   // Ensure that dllimport globals without explicit storage class are treated as
6599   // extern. The storage class is set above using parsed attributes. Now we can
6600   // check the VarDecl itself.
6601   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6602          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6603          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6604 
6605   // In auto-retain/release, infer strong retension for variables of
6606   // retainable type.
6607   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6608     NewVD->setInvalidDecl();
6609 
6610   // Handle GNU asm-label extension (encoded as an attribute).
6611   if (Expr *E = (Expr*)D.getAsmLabel()) {
6612     // The parser guarantees this is a string.
6613     StringLiteral *SE = cast<StringLiteral>(E);
6614     StringRef Label = SE->getString();
6615     if (S->getFnParent() != nullptr) {
6616       switch (SC) {
6617       case SC_None:
6618       case SC_Auto:
6619         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6620         break;
6621       case SC_Register:
6622         // Local Named register
6623         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6624             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6625           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6626         break;
6627       case SC_Static:
6628       case SC_Extern:
6629       case SC_PrivateExtern:
6630         break;
6631       }
6632     } else if (SC == SC_Register) {
6633       // Global Named register
6634       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6635         const auto &TI = Context.getTargetInfo();
6636         bool HasSizeMismatch;
6637 
6638         if (!TI.isValidGCCRegisterName(Label))
6639           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6640         else if (!TI.validateGlobalRegisterVariable(Label,
6641                                                     Context.getTypeSize(R),
6642                                                     HasSizeMismatch))
6643           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6644         else if (HasSizeMismatch)
6645           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6646       }
6647 
6648       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6649         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6650         NewVD->setInvalidDecl(true);
6651       }
6652     }
6653 
6654     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6655                                                 Context, Label, 0));
6656   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6657     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6658       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6659     if (I != ExtnameUndeclaredIdentifiers.end()) {
6660       if (isDeclExternC(NewVD)) {
6661         NewVD->addAttr(I->second);
6662         ExtnameUndeclaredIdentifiers.erase(I);
6663       } else
6664         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6665             << /*Variable*/1 << NewVD;
6666     }
6667   }
6668 
6669   // Find the shadowed declaration before filtering for scope.
6670   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6671                                 ? getShadowedDeclaration(NewVD, Previous)
6672                                 : nullptr;
6673 
6674   // Don't consider existing declarations that are in a different
6675   // scope and are out-of-semantic-context declarations (if the new
6676   // declaration has linkage).
6677   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6678                        D.getCXXScopeSpec().isNotEmpty() ||
6679                        IsMemberSpecialization ||
6680                        IsVariableTemplateSpecialization);
6681 
6682   // Check whether the previous declaration is in the same block scope. This
6683   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6684   if (getLangOpts().CPlusPlus &&
6685       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6686     NewVD->setPreviousDeclInSameBlockScope(
6687         Previous.isSingleResult() && !Previous.isShadowed() &&
6688         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6689 
6690   if (!getLangOpts().CPlusPlus) {
6691     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6692   } else {
6693     // If this is an explicit specialization of a static data member, check it.
6694     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6695         CheckMemberSpecialization(NewVD, Previous))
6696       NewVD->setInvalidDecl();
6697 
6698     // Merge the decl with the existing one if appropriate.
6699     if (!Previous.empty()) {
6700       if (Previous.isSingleResult() &&
6701           isa<FieldDecl>(Previous.getFoundDecl()) &&
6702           D.getCXXScopeSpec().isSet()) {
6703         // The user tried to define a non-static data member
6704         // out-of-line (C++ [dcl.meaning]p1).
6705         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6706           << D.getCXXScopeSpec().getRange();
6707         Previous.clear();
6708         NewVD->setInvalidDecl();
6709       }
6710     } else if (D.getCXXScopeSpec().isSet()) {
6711       // No previous declaration in the qualifying scope.
6712       Diag(D.getIdentifierLoc(), diag::err_no_member)
6713         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6714         << D.getCXXScopeSpec().getRange();
6715       NewVD->setInvalidDecl();
6716     }
6717 
6718     if (!IsVariableTemplateSpecialization)
6719       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6720 
6721     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6722     // an explicit specialization (14.8.3) or a partial specialization of a
6723     // concept definition.
6724     if (IsVariableTemplateSpecialization &&
6725         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6726         Previous.isSingleResult()) {
6727       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6728       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6729         if (VarTmpl->isConcept()) {
6730           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6731               << 1                            /*variable*/
6732               << (IsPartialSpecialization ? 2 /*partially specialized*/
6733                                           : 1 /*explicitly specialized*/);
6734           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6735           NewVD->setInvalidDecl();
6736         }
6737       }
6738     }
6739 
6740     if (NewTemplate) {
6741       VarTemplateDecl *PrevVarTemplate =
6742           NewVD->getPreviousDecl()
6743               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6744               : nullptr;
6745 
6746       // Check the template parameter list of this declaration, possibly
6747       // merging in the template parameter list from the previous variable
6748       // template declaration.
6749       if (CheckTemplateParameterList(
6750               TemplateParams,
6751               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6752                               : nullptr,
6753               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6754                DC->isDependentContext())
6755                   ? TPC_ClassTemplateMember
6756                   : TPC_VarTemplate))
6757         NewVD->setInvalidDecl();
6758 
6759       // If we are providing an explicit specialization of a static variable
6760       // template, make a note of that.
6761       if (PrevVarTemplate &&
6762           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6763         PrevVarTemplate->setMemberSpecialization();
6764     }
6765   }
6766 
6767   // Diagnose shadowed variables iff this isn't a redeclaration.
6768   if (ShadowedDecl && !D.isRedeclaration())
6769     CheckShadow(NewVD, ShadowedDecl, Previous);
6770 
6771   ProcessPragmaWeak(S, NewVD);
6772 
6773   // If this is the first declaration of an extern C variable, update
6774   // the map of such variables.
6775   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6776       isIncompleteDeclExternC(*this, NewVD))
6777     RegisterLocallyScopedExternCDecl(NewVD, S);
6778 
6779   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6780     Decl *ManglingContextDecl;
6781     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6782             NewVD->getDeclContext(), ManglingContextDecl)) {
6783       Context.setManglingNumber(
6784           NewVD, MCtx->getManglingNumber(
6785                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6786       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6787     }
6788   }
6789 
6790   // Special handling of variable named 'main'.
6791   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6792       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6793       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6794 
6795     // C++ [basic.start.main]p3
6796     // A program that declares a variable main at global scope is ill-formed.
6797     if (getLangOpts().CPlusPlus)
6798       Diag(D.getLocStart(), diag::err_main_global_variable);
6799 
6800     // In C, and external-linkage variable named main results in undefined
6801     // behavior.
6802     else if (NewVD->hasExternalFormalLinkage())
6803       Diag(D.getLocStart(), diag::warn_main_redefined);
6804   }
6805 
6806   if (D.isRedeclaration() && !Previous.empty()) {
6807     checkDLLAttributeRedeclaration(
6808         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6809         IsMemberSpecialization, D.isFunctionDefinition());
6810   }
6811 
6812   if (NewTemplate) {
6813     if (NewVD->isInvalidDecl())
6814       NewTemplate->setInvalidDecl();
6815     ActOnDocumentableDecl(NewTemplate);
6816     return NewTemplate;
6817   }
6818 
6819   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6820     CompleteMemberSpecialization(NewVD, Previous);
6821 
6822   return NewVD;
6823 }
6824 
6825 /// Enum describing the %select options in diag::warn_decl_shadow.
6826 enum ShadowedDeclKind {
6827   SDK_Local,
6828   SDK_Global,
6829   SDK_StaticMember,
6830   SDK_Field,
6831   SDK_Typedef,
6832   SDK_Using
6833 };
6834 
6835 /// Determine what kind of declaration we're shadowing.
6836 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6837                                                 const DeclContext *OldDC) {
6838   if (isa<TypeAliasDecl>(ShadowedDecl))
6839     return SDK_Using;
6840   else if (isa<TypedefDecl>(ShadowedDecl))
6841     return SDK_Typedef;
6842   else if (isa<RecordDecl>(OldDC))
6843     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6844 
6845   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6846 }
6847 
6848 /// Return the location of the capture if the given lambda captures the given
6849 /// variable \p VD, or an invalid source location otherwise.
6850 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6851                                          const VarDecl *VD) {
6852   for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
6853     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6854       return Capture.getLocation();
6855   }
6856   return SourceLocation();
6857 }
6858 
6859 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6860                                      const LookupResult &R) {
6861   // Only diagnose if we're shadowing an unambiguous field or variable.
6862   if (R.getResultKind() != LookupResult::Found)
6863     return false;
6864 
6865   // Return false if warning is ignored.
6866   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6867 }
6868 
6869 /// \brief Return the declaration shadowed by the given variable \p D, or null
6870 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6871 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6872                                         const LookupResult &R) {
6873   if (!shouldWarnIfShadowedDecl(Diags, R))
6874     return nullptr;
6875 
6876   // Don't diagnose declarations at file scope.
6877   if (D->hasGlobalStorage())
6878     return nullptr;
6879 
6880   NamedDecl *ShadowedDecl = R.getFoundDecl();
6881   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6882              ? ShadowedDecl
6883              : nullptr;
6884 }
6885 
6886 /// \brief Return the declaration shadowed by the given typedef \p D, or null
6887 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6888 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
6889                                         const LookupResult &R) {
6890   // Don't warn if typedef declaration is part of a class
6891   if (D->getDeclContext()->isRecord())
6892     return nullptr;
6893 
6894   if (!shouldWarnIfShadowedDecl(Diags, R))
6895     return nullptr;
6896 
6897   NamedDecl *ShadowedDecl = R.getFoundDecl();
6898   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
6899 }
6900 
6901 /// \brief Diagnose variable or built-in function shadowing.  Implements
6902 /// -Wshadow.
6903 ///
6904 /// This method is called whenever a VarDecl is added to a "useful"
6905 /// scope.
6906 ///
6907 /// \param ShadowedDecl the declaration that is shadowed by the given variable
6908 /// \param R the lookup of the name
6909 ///
6910 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
6911                        const LookupResult &R) {
6912   DeclContext *NewDC = D->getDeclContext();
6913 
6914   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6915     // Fields are not shadowed by variables in C++ static methods.
6916     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6917       if (MD->isStatic())
6918         return;
6919 
6920     // Fields shadowed by constructor parameters are a special case. Usually
6921     // the constructor initializes the field with the parameter.
6922     if (isa<CXXConstructorDecl>(NewDC))
6923       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
6924         // Remember that this was shadowed so we can either warn about its
6925         // modification or its existence depending on warning settings.
6926         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
6927         return;
6928       }
6929   }
6930 
6931   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6932     if (shadowedVar->isExternC()) {
6933       // For shadowing external vars, make sure that we point to the global
6934       // declaration, not a locally scoped extern declaration.
6935       for (auto I : shadowedVar->redecls())
6936         if (I->isFileVarDecl()) {
6937           ShadowedDecl = I;
6938           break;
6939         }
6940     }
6941 
6942   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
6943 
6944   unsigned WarningDiag = diag::warn_decl_shadow;
6945   SourceLocation CaptureLoc;
6946   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
6947       isa<CXXMethodDecl>(NewDC)) {
6948     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
6949       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
6950         if (RD->getLambdaCaptureDefault() == LCD_None) {
6951           // Try to avoid warnings for lambdas with an explicit capture list.
6952           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
6953           // Warn only when the lambda captures the shadowed decl explicitly.
6954           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
6955           if (CaptureLoc.isInvalid())
6956             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
6957         } else {
6958           // Remember that this was shadowed so we can avoid the warning if the
6959           // shadowed decl isn't captured and the warning settings allow it.
6960           cast<LambdaScopeInfo>(getCurFunction())
6961               ->ShadowingDecls.push_back(
6962                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
6963           return;
6964         }
6965       }
6966     }
6967   }
6968 
6969   // Only warn about certain kinds of shadowing for class members.
6970   if (NewDC && NewDC->isRecord()) {
6971     // In particular, don't warn about shadowing non-class members.
6972     if (!OldDC->isRecord())
6973       return;
6974 
6975     // TODO: should we warn about static data members shadowing
6976     // static data members from base classes?
6977 
6978     // TODO: don't diagnose for inaccessible shadowed members.
6979     // This is hard to do perfectly because we might friend the
6980     // shadowing context, but that's just a false negative.
6981   }
6982 
6983 
6984   DeclarationName Name = R.getLookupName();
6985 
6986   // Emit warning and note.
6987   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6988     return;
6989   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
6990   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
6991   if (!CaptureLoc.isInvalid())
6992     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
6993         << Name << /*explicitly*/ 1;
6994   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6995 }
6996 
6997 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
6998 /// when these variables are captured by the lambda.
6999 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7000   for (const auto &Shadow : LSI->ShadowingDecls) {
7001     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7002     // Try to avoid the warning when the shadowed decl isn't captured.
7003     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7004     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7005     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7006                                        ? diag::warn_decl_shadow_uncaptured_local
7007                                        : diag::warn_decl_shadow)
7008         << Shadow.VD->getDeclName()
7009         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7010     if (!CaptureLoc.isInvalid())
7011       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7012           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7013     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7014   }
7015 }
7016 
7017 /// \brief Check -Wshadow without the advantage of a previous lookup.
7018 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7019   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7020     return;
7021 
7022   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7023                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
7024   LookupName(R, S);
7025   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7026     CheckShadow(D, ShadowedDecl, R);
7027 }
7028 
7029 /// Check if 'E', which is an expression that is about to be modified, refers
7030 /// to a constructor parameter that shadows a field.
7031 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7032   // Quickly ignore expressions that can't be shadowing ctor parameters.
7033   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7034     return;
7035   E = E->IgnoreParenImpCasts();
7036   auto *DRE = dyn_cast<DeclRefExpr>(E);
7037   if (!DRE)
7038     return;
7039   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7040   auto I = ShadowingDecls.find(D);
7041   if (I == ShadowingDecls.end())
7042     return;
7043   const NamedDecl *ShadowedDecl = I->second;
7044   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7045   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7046   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7047   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7048 
7049   // Avoid issuing multiple warnings about the same decl.
7050   ShadowingDecls.erase(I);
7051 }
7052 
7053 /// Check for conflict between this global or extern "C" declaration and
7054 /// previous global or extern "C" declarations. This is only used in C++.
7055 template<typename T>
7056 static bool checkGlobalOrExternCConflict(
7057     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7058   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7059   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7060 
7061   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7062     // The common case: this global doesn't conflict with any extern "C"
7063     // declaration.
7064     return false;
7065   }
7066 
7067   if (Prev) {
7068     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7069       // Both the old and new declarations have C language linkage. This is a
7070       // redeclaration.
7071       Previous.clear();
7072       Previous.addDecl(Prev);
7073       return true;
7074     }
7075 
7076     // This is a global, non-extern "C" declaration, and there is a previous
7077     // non-global extern "C" declaration. Diagnose if this is a variable
7078     // declaration.
7079     if (!isa<VarDecl>(ND))
7080       return false;
7081   } else {
7082     // The declaration is extern "C". Check for any declaration in the
7083     // translation unit which might conflict.
7084     if (IsGlobal) {
7085       // We have already performed the lookup into the translation unit.
7086       IsGlobal = false;
7087       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7088            I != E; ++I) {
7089         if (isa<VarDecl>(*I)) {
7090           Prev = *I;
7091           break;
7092         }
7093       }
7094     } else {
7095       DeclContext::lookup_result R =
7096           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7097       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7098            I != E; ++I) {
7099         if (isa<VarDecl>(*I)) {
7100           Prev = *I;
7101           break;
7102         }
7103         // FIXME: If we have any other entity with this name in global scope,
7104         // the declaration is ill-formed, but that is a defect: it breaks the
7105         // 'stat' hack, for instance. Only variables can have mangled name
7106         // clashes with extern "C" declarations, so only they deserve a
7107         // diagnostic.
7108       }
7109     }
7110 
7111     if (!Prev)
7112       return false;
7113   }
7114 
7115   // Use the first declaration's location to ensure we point at something which
7116   // is lexically inside an extern "C" linkage-spec.
7117   assert(Prev && "should have found a previous declaration to diagnose");
7118   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7119     Prev = FD->getFirstDecl();
7120   else
7121     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7122 
7123   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7124     << IsGlobal << ND;
7125   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7126     << IsGlobal;
7127   return false;
7128 }
7129 
7130 /// Apply special rules for handling extern "C" declarations. Returns \c true
7131 /// if we have found that this is a redeclaration of some prior entity.
7132 ///
7133 /// Per C++ [dcl.link]p6:
7134 ///   Two declarations [for a function or variable] with C language linkage
7135 ///   with the same name that appear in different scopes refer to the same
7136 ///   [entity]. An entity with C language linkage shall not be declared with
7137 ///   the same name as an entity in global scope.
7138 template<typename T>
7139 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7140                                                   LookupResult &Previous) {
7141   if (!S.getLangOpts().CPlusPlus) {
7142     // In C, when declaring a global variable, look for a corresponding 'extern'
7143     // variable declared in function scope. We don't need this in C++, because
7144     // we find local extern decls in the surrounding file-scope DeclContext.
7145     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7146       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7147         Previous.clear();
7148         Previous.addDecl(Prev);
7149         return true;
7150       }
7151     }
7152     return false;
7153   }
7154 
7155   // A declaration in the translation unit can conflict with an extern "C"
7156   // declaration.
7157   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7158     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7159 
7160   // An extern "C" declaration can conflict with a declaration in the
7161   // translation unit or can be a redeclaration of an extern "C" declaration
7162   // in another scope.
7163   if (isIncompleteDeclExternC(S,ND))
7164     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7165 
7166   // Neither global nor extern "C": nothing to do.
7167   return false;
7168 }
7169 
7170 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7171   // If the decl is already known invalid, don't check it.
7172   if (NewVD->isInvalidDecl())
7173     return;
7174 
7175   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
7176   QualType T = TInfo->getType();
7177 
7178   // Defer checking an 'auto' type until its initializer is attached.
7179   if (T->isUndeducedType())
7180     return;
7181 
7182   if (NewVD->hasAttrs())
7183     CheckAlignasUnderalignment(NewVD);
7184 
7185   if (T->isObjCObjectType()) {
7186     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7187       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7188     T = Context.getObjCObjectPointerType(T);
7189     NewVD->setType(T);
7190   }
7191 
7192   // Emit an error if an address space was applied to decl with local storage.
7193   // This includes arrays of objects with address space qualifiers, but not
7194   // automatic variables that point to other address spaces.
7195   // ISO/IEC TR 18037 S5.1.2
7196   if (!getLangOpts().OpenCL
7197       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
7198     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7199     NewVD->setInvalidDecl();
7200     return;
7201   }
7202 
7203   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7204   // scope.
7205   if (getLangOpts().OpenCLVersion == 120 &&
7206       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7207       NewVD->isStaticLocal()) {
7208     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7209     NewVD->setInvalidDecl();
7210     return;
7211   }
7212 
7213   if (getLangOpts().OpenCL) {
7214     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7215     if (NewVD->hasAttr<BlocksAttr>()) {
7216       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7217       return;
7218     }
7219 
7220     if (T->isBlockPointerType()) {
7221       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7222       // can't use 'extern' storage class.
7223       if (!T.isConstQualified()) {
7224         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7225             << 0 /*const*/;
7226         NewVD->setInvalidDecl();
7227         return;
7228       }
7229       if (NewVD->hasExternalStorage()) {
7230         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7231         NewVD->setInvalidDecl();
7232         return;
7233       }
7234     }
7235     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7236     // __constant address space.
7237     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7238     // variables inside a function can also be declared in the global
7239     // address space.
7240     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7241         NewVD->hasExternalStorage()) {
7242       if (!T->isSamplerT() &&
7243           !(T.getAddressSpace() == LangAS::opencl_constant ||
7244             (T.getAddressSpace() == LangAS::opencl_global &&
7245              getLangOpts().OpenCLVersion == 200))) {
7246         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7247         if (getLangOpts().OpenCLVersion == 200)
7248           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7249               << Scope << "global or constant";
7250         else
7251           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7252               << Scope << "constant";
7253         NewVD->setInvalidDecl();
7254         return;
7255       }
7256     } else {
7257       if (T.getAddressSpace() == LangAS::opencl_global) {
7258         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7259             << 1 /*is any function*/ << "global";
7260         NewVD->setInvalidDecl();
7261         return;
7262       }
7263       if (T.getAddressSpace() == LangAS::opencl_constant ||
7264           T.getAddressSpace() == LangAS::opencl_local) {
7265         FunctionDecl *FD = getCurFunctionDecl();
7266         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7267         // in functions.
7268         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7269           if (T.getAddressSpace() == LangAS::opencl_constant)
7270             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7271                 << 0 /*non-kernel only*/ << "constant";
7272           else
7273             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7274                 << 0 /*non-kernel only*/ << "local";
7275           NewVD->setInvalidDecl();
7276           return;
7277         }
7278         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7279         // in the outermost scope of a kernel function.
7280         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7281           if (!getCurScope()->isFunctionScope()) {
7282             if (T.getAddressSpace() == LangAS::opencl_constant)
7283               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7284                   << "constant";
7285             else
7286               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7287                   << "local";
7288             NewVD->setInvalidDecl();
7289             return;
7290           }
7291         }
7292       } else if (T.getAddressSpace() != LangAS::Default) {
7293         // Do not allow other address spaces on automatic variable.
7294         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7295         NewVD->setInvalidDecl();
7296         return;
7297       }
7298     }
7299   }
7300 
7301   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7302       && !NewVD->hasAttr<BlocksAttr>()) {
7303     if (getLangOpts().getGC() != LangOptions::NonGC)
7304       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7305     else {
7306       assert(!getLangOpts().ObjCAutoRefCount);
7307       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7308     }
7309   }
7310 
7311   bool isVM = T->isVariablyModifiedType();
7312   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7313       NewVD->hasAttr<BlocksAttr>())
7314     getCurFunction()->setHasBranchProtectedScope();
7315 
7316   if ((isVM && NewVD->hasLinkage()) ||
7317       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7318     bool SizeIsNegative;
7319     llvm::APSInt Oversized;
7320     TypeSourceInfo *FixedTInfo =
7321       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7322                                                     SizeIsNegative, Oversized);
7323     if (!FixedTInfo && T->isVariableArrayType()) {
7324       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7325       // FIXME: This won't give the correct result for
7326       // int a[10][n];
7327       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7328 
7329       if (NewVD->isFileVarDecl())
7330         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7331         << SizeRange;
7332       else if (NewVD->isStaticLocal())
7333         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7334         << SizeRange;
7335       else
7336         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7337         << SizeRange;
7338       NewVD->setInvalidDecl();
7339       return;
7340     }
7341 
7342     if (!FixedTInfo) {
7343       if (NewVD->isFileVarDecl())
7344         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7345       else
7346         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7347       NewVD->setInvalidDecl();
7348       return;
7349     }
7350 
7351     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7352     NewVD->setType(FixedTInfo->getType());
7353     NewVD->setTypeSourceInfo(FixedTInfo);
7354   }
7355 
7356   if (T->isVoidType()) {
7357     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7358     //                    of objects and functions.
7359     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7360       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7361         << T;
7362       NewVD->setInvalidDecl();
7363       return;
7364     }
7365   }
7366 
7367   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7368     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7369     NewVD->setInvalidDecl();
7370     return;
7371   }
7372 
7373   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7374     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7375     NewVD->setInvalidDecl();
7376     return;
7377   }
7378 
7379   if (NewVD->isConstexpr() && !T->isDependentType() &&
7380       RequireLiteralType(NewVD->getLocation(), T,
7381                          diag::err_constexpr_var_non_literal)) {
7382     NewVD->setInvalidDecl();
7383     return;
7384   }
7385 }
7386 
7387 /// \brief Perform semantic checking on a newly-created variable
7388 /// declaration.
7389 ///
7390 /// This routine performs all of the type-checking required for a
7391 /// variable declaration once it has been built. It is used both to
7392 /// check variables after they have been parsed and their declarators
7393 /// have been translated into a declaration, and to check variables
7394 /// that have been instantiated from a template.
7395 ///
7396 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7397 ///
7398 /// Returns true if the variable declaration is a redeclaration.
7399 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7400   CheckVariableDeclarationType(NewVD);
7401 
7402   // If the decl is already known invalid, don't check it.
7403   if (NewVD->isInvalidDecl())
7404     return false;
7405 
7406   // If we did not find anything by this name, look for a non-visible
7407   // extern "C" declaration with the same name.
7408   if (Previous.empty() &&
7409       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7410     Previous.setShadowed();
7411 
7412   if (!Previous.empty()) {
7413     MergeVarDecl(NewVD, Previous);
7414     return true;
7415   }
7416   return false;
7417 }
7418 
7419 namespace {
7420 struct FindOverriddenMethod {
7421   Sema *S;
7422   CXXMethodDecl *Method;
7423 
7424   /// Member lookup function that determines whether a given C++
7425   /// method overrides a method in a base class, to be used with
7426   /// CXXRecordDecl::lookupInBases().
7427   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7428     RecordDecl *BaseRecord =
7429         Specifier->getType()->getAs<RecordType>()->getDecl();
7430 
7431     DeclarationName Name = Method->getDeclName();
7432 
7433     // FIXME: Do we care about other names here too?
7434     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7435       // We really want to find the base class destructor here.
7436       QualType T = S->Context.getTypeDeclType(BaseRecord);
7437       CanQualType CT = S->Context.getCanonicalType(T);
7438 
7439       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7440     }
7441 
7442     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7443          Path.Decls = Path.Decls.slice(1)) {
7444       NamedDecl *D = Path.Decls.front();
7445       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7446         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7447           return true;
7448       }
7449     }
7450 
7451     return false;
7452   }
7453 };
7454 
7455 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7456 } // end anonymous namespace
7457 
7458 /// \brief Report an error regarding overriding, along with any relevant
7459 /// overriden methods.
7460 ///
7461 /// \param DiagID the primary error to report.
7462 /// \param MD the overriding method.
7463 /// \param OEK which overrides to include as notes.
7464 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7465                             OverrideErrorKind OEK = OEK_All) {
7466   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7467   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7468                                       E = MD->end_overridden_methods();
7469        I != E; ++I) {
7470     // This check (& the OEK parameter) could be replaced by a predicate, but
7471     // without lambdas that would be overkill. This is still nicer than writing
7472     // out the diag loop 3 times.
7473     if ((OEK == OEK_All) ||
7474         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7475         (OEK == OEK_Deleted && (*I)->isDeleted()))
7476       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7477   }
7478 }
7479 
7480 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7481 /// and if so, check that it's a valid override and remember it.
7482 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7483   // Look for methods in base classes that this method might override.
7484   CXXBasePaths Paths;
7485   FindOverriddenMethod FOM;
7486   FOM.Method = MD;
7487   FOM.S = this;
7488   bool hasDeletedOverridenMethods = false;
7489   bool hasNonDeletedOverridenMethods = false;
7490   bool AddedAny = false;
7491   if (DC->lookupInBases(FOM, Paths)) {
7492     for (auto *I : Paths.found_decls()) {
7493       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7494         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7495         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7496             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7497             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7498             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7499           hasDeletedOverridenMethods |= OldMD->isDeleted();
7500           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7501           AddedAny = true;
7502         }
7503       }
7504     }
7505   }
7506 
7507   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7508     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7509   }
7510   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7511     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7512   }
7513 
7514   return AddedAny;
7515 }
7516 
7517 namespace {
7518   // Struct for holding all of the extra arguments needed by
7519   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7520   struct ActOnFDArgs {
7521     Scope *S;
7522     Declarator &D;
7523     MultiTemplateParamsArg TemplateParamLists;
7524     bool AddToScope;
7525   };
7526 } // end anonymous namespace
7527 
7528 namespace {
7529 
7530 // Callback to only accept typo corrections that have a non-zero edit distance.
7531 // Also only accept corrections that have the same parent decl.
7532 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7533  public:
7534   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7535                             CXXRecordDecl *Parent)
7536       : Context(Context), OriginalFD(TypoFD),
7537         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7538 
7539   bool ValidateCandidate(const TypoCorrection &candidate) override {
7540     if (candidate.getEditDistance() == 0)
7541       return false;
7542 
7543     SmallVector<unsigned, 1> MismatchedParams;
7544     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7545                                           CDeclEnd = candidate.end();
7546          CDecl != CDeclEnd; ++CDecl) {
7547       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7548 
7549       if (FD && !FD->hasBody() &&
7550           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7551         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7552           CXXRecordDecl *Parent = MD->getParent();
7553           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7554             return true;
7555         } else if (!ExpectedParent) {
7556           return true;
7557         }
7558       }
7559     }
7560 
7561     return false;
7562   }
7563 
7564  private:
7565   ASTContext &Context;
7566   FunctionDecl *OriginalFD;
7567   CXXRecordDecl *ExpectedParent;
7568 };
7569 
7570 } // end anonymous namespace
7571 
7572 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7573   TypoCorrectedFunctionDefinitions.insert(F);
7574 }
7575 
7576 /// \brief Generate diagnostics for an invalid function redeclaration.
7577 ///
7578 /// This routine handles generating the diagnostic messages for an invalid
7579 /// function redeclaration, including finding possible similar declarations
7580 /// or performing typo correction if there are no previous declarations with
7581 /// the same name.
7582 ///
7583 /// Returns a NamedDecl iff typo correction was performed and substituting in
7584 /// the new declaration name does not cause new errors.
7585 static NamedDecl *DiagnoseInvalidRedeclaration(
7586     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7587     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7588   DeclarationName Name = NewFD->getDeclName();
7589   DeclContext *NewDC = NewFD->getDeclContext();
7590   SmallVector<unsigned, 1> MismatchedParams;
7591   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7592   TypoCorrection Correction;
7593   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7594   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7595                                    : diag::err_member_decl_does_not_match;
7596   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7597                     IsLocalFriend ? Sema::LookupLocalFriendName
7598                                   : Sema::LookupOrdinaryName,
7599                     Sema::ForRedeclaration);
7600 
7601   NewFD->setInvalidDecl();
7602   if (IsLocalFriend)
7603     SemaRef.LookupName(Prev, S);
7604   else
7605     SemaRef.LookupQualifiedName(Prev, NewDC);
7606   assert(!Prev.isAmbiguous() &&
7607          "Cannot have an ambiguity in previous-declaration lookup");
7608   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7609   if (!Prev.empty()) {
7610     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7611          Func != FuncEnd; ++Func) {
7612       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7613       if (FD &&
7614           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7615         // Add 1 to the index so that 0 can mean the mismatch didn't
7616         // involve a parameter
7617         unsigned ParamNum =
7618             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7619         NearMatches.push_back(std::make_pair(FD, ParamNum));
7620       }
7621     }
7622   // If the qualified name lookup yielded nothing, try typo correction
7623   } else if ((Correction = SemaRef.CorrectTypo(
7624                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7625                   &ExtraArgs.D.getCXXScopeSpec(),
7626                   llvm::make_unique<DifferentNameValidatorCCC>(
7627                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7628                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7629     // Set up everything for the call to ActOnFunctionDeclarator
7630     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7631                               ExtraArgs.D.getIdentifierLoc());
7632     Previous.clear();
7633     Previous.setLookupName(Correction.getCorrection());
7634     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7635                                     CDeclEnd = Correction.end();
7636          CDecl != CDeclEnd; ++CDecl) {
7637       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7638       if (FD && !FD->hasBody() &&
7639           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7640         Previous.addDecl(FD);
7641       }
7642     }
7643     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7644 
7645     NamedDecl *Result;
7646     // Retry building the function declaration with the new previous
7647     // declarations, and with errors suppressed.
7648     {
7649       // Trap errors.
7650       Sema::SFINAETrap Trap(SemaRef);
7651 
7652       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7653       // pieces need to verify the typo-corrected C++ declaration and hopefully
7654       // eliminate the need for the parameter pack ExtraArgs.
7655       Result = SemaRef.ActOnFunctionDeclarator(
7656           ExtraArgs.S, ExtraArgs.D,
7657           Correction.getCorrectionDecl()->getDeclContext(),
7658           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7659           ExtraArgs.AddToScope);
7660 
7661       if (Trap.hasErrorOccurred())
7662         Result = nullptr;
7663     }
7664 
7665     if (Result) {
7666       // Determine which correction we picked.
7667       Decl *Canonical = Result->getCanonicalDecl();
7668       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7669            I != E; ++I)
7670         if ((*I)->getCanonicalDecl() == Canonical)
7671           Correction.setCorrectionDecl(*I);
7672 
7673       // Let Sema know about the correction.
7674       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7675       SemaRef.diagnoseTypo(
7676           Correction,
7677           SemaRef.PDiag(IsLocalFriend
7678                           ? diag::err_no_matching_local_friend_suggest
7679                           : diag::err_member_decl_does_not_match_suggest)
7680             << Name << NewDC << IsDefinition);
7681       return Result;
7682     }
7683 
7684     // Pretend the typo correction never occurred
7685     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7686                               ExtraArgs.D.getIdentifierLoc());
7687     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7688     Previous.clear();
7689     Previous.setLookupName(Name);
7690   }
7691 
7692   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7693       << Name << NewDC << IsDefinition << NewFD->getLocation();
7694 
7695   bool NewFDisConst = false;
7696   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7697     NewFDisConst = NewMD->isConst();
7698 
7699   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7700        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7701        NearMatch != NearMatchEnd; ++NearMatch) {
7702     FunctionDecl *FD = NearMatch->first;
7703     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7704     bool FDisConst = MD && MD->isConst();
7705     bool IsMember = MD || !IsLocalFriend;
7706 
7707     // FIXME: These notes are poorly worded for the local friend case.
7708     if (unsigned Idx = NearMatch->second) {
7709       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7710       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7711       if (Loc.isInvalid()) Loc = FD->getLocation();
7712       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7713                                  : diag::note_local_decl_close_param_match)
7714         << Idx << FDParam->getType()
7715         << NewFD->getParamDecl(Idx - 1)->getType();
7716     } else if (FDisConst != NewFDisConst) {
7717       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7718           << NewFDisConst << FD->getSourceRange().getEnd();
7719     } else
7720       SemaRef.Diag(FD->getLocation(),
7721                    IsMember ? diag::note_member_def_close_match
7722                             : diag::note_local_decl_close_match);
7723   }
7724   return nullptr;
7725 }
7726 
7727 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7728   switch (D.getDeclSpec().getStorageClassSpec()) {
7729   default: llvm_unreachable("Unknown storage class!");
7730   case DeclSpec::SCS_auto:
7731   case DeclSpec::SCS_register:
7732   case DeclSpec::SCS_mutable:
7733     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7734                  diag::err_typecheck_sclass_func);
7735     D.getMutableDeclSpec().ClearStorageClassSpecs();
7736     D.setInvalidType();
7737     break;
7738   case DeclSpec::SCS_unspecified: break;
7739   case DeclSpec::SCS_extern:
7740     if (D.getDeclSpec().isExternInLinkageSpec())
7741       return SC_None;
7742     return SC_Extern;
7743   case DeclSpec::SCS_static: {
7744     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7745       // C99 6.7.1p5:
7746       //   The declaration of an identifier for a function that has
7747       //   block scope shall have no explicit storage-class specifier
7748       //   other than extern
7749       // See also (C++ [dcl.stc]p4).
7750       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7751                    diag::err_static_block_func);
7752       break;
7753     } else
7754       return SC_Static;
7755   }
7756   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7757   }
7758 
7759   // No explicit storage class has already been returned
7760   return SC_None;
7761 }
7762 
7763 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7764                                            DeclContext *DC, QualType &R,
7765                                            TypeSourceInfo *TInfo,
7766                                            StorageClass SC,
7767                                            bool &IsVirtualOkay) {
7768   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7769   DeclarationName Name = NameInfo.getName();
7770 
7771   FunctionDecl *NewFD = nullptr;
7772   bool isInline = D.getDeclSpec().isInlineSpecified();
7773 
7774   if (!SemaRef.getLangOpts().CPlusPlus) {
7775     // Determine whether the function was written with a
7776     // prototype. This true when:
7777     //   - there is a prototype in the declarator, or
7778     //   - the type R of the function is some kind of typedef or other non-
7779     //     attributed reference to a type name (which eventually refers to a
7780     //     function type).
7781     bool HasPrototype =
7782       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7783       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7784 
7785     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7786                                  D.getLocStart(), NameInfo, R,
7787                                  TInfo, SC, isInline,
7788                                  HasPrototype, false);
7789     if (D.isInvalidType())
7790       NewFD->setInvalidDecl();
7791 
7792     return NewFD;
7793   }
7794 
7795   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7796   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7797 
7798   // Check that the return type is not an abstract class type.
7799   // For record types, this is done by the AbstractClassUsageDiagnoser once
7800   // the class has been completely parsed.
7801   if (!DC->isRecord() &&
7802       SemaRef.RequireNonAbstractType(
7803           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7804           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7805     D.setInvalidType();
7806 
7807   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7808     // This is a C++ constructor declaration.
7809     assert(DC->isRecord() &&
7810            "Constructors can only be declared in a member context");
7811 
7812     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7813     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7814                                       D.getLocStart(), NameInfo,
7815                                       R, TInfo, isExplicit, isInline,
7816                                       /*isImplicitlyDeclared=*/false,
7817                                       isConstexpr);
7818 
7819   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7820     // This is a C++ destructor declaration.
7821     if (DC->isRecord()) {
7822       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7823       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7824       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7825                                         SemaRef.Context, Record,
7826                                         D.getLocStart(),
7827                                         NameInfo, R, TInfo, isInline,
7828                                         /*isImplicitlyDeclared=*/false);
7829 
7830       // If the class is complete, then we now create the implicit exception
7831       // specification. If the class is incomplete or dependent, we can't do
7832       // it yet.
7833       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7834           Record->getDefinition() && !Record->isBeingDefined() &&
7835           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7836         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7837       }
7838 
7839       IsVirtualOkay = true;
7840       return NewDD;
7841 
7842     } else {
7843       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7844       D.setInvalidType();
7845 
7846       // Create a FunctionDecl to satisfy the function definition parsing
7847       // code path.
7848       return FunctionDecl::Create(SemaRef.Context, DC,
7849                                   D.getLocStart(),
7850                                   D.getIdentifierLoc(), Name, R, TInfo,
7851                                   SC, isInline,
7852                                   /*hasPrototype=*/true, isConstexpr);
7853     }
7854 
7855   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7856     if (!DC->isRecord()) {
7857       SemaRef.Diag(D.getIdentifierLoc(),
7858            diag::err_conv_function_not_member);
7859       return nullptr;
7860     }
7861 
7862     SemaRef.CheckConversionDeclarator(D, R, SC);
7863     IsVirtualOkay = true;
7864     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7865                                      D.getLocStart(), NameInfo,
7866                                      R, TInfo, isInline, isExplicit,
7867                                      isConstexpr, SourceLocation());
7868 
7869   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7870     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7871 
7872     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
7873                                          isExplicit, NameInfo, R, TInfo,
7874                                          D.getLocEnd());
7875   } else if (DC->isRecord()) {
7876     // If the name of the function is the same as the name of the record,
7877     // then this must be an invalid constructor that has a return type.
7878     // (The parser checks for a return type and makes the declarator a
7879     // constructor if it has no return type).
7880     if (Name.getAsIdentifierInfo() &&
7881         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7882       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7883         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7884         << SourceRange(D.getIdentifierLoc());
7885       return nullptr;
7886     }
7887 
7888     // This is a C++ method declaration.
7889     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7890                                                cast<CXXRecordDecl>(DC),
7891                                                D.getLocStart(), NameInfo, R,
7892                                                TInfo, SC, isInline,
7893                                                isConstexpr, SourceLocation());
7894     IsVirtualOkay = !Ret->isStatic();
7895     return Ret;
7896   } else {
7897     bool isFriend =
7898         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7899     if (!isFriend && SemaRef.CurContext->isRecord())
7900       return nullptr;
7901 
7902     // Determine whether the function was written with a
7903     // prototype. This true when:
7904     //   - we're in C++ (where every function has a prototype),
7905     return FunctionDecl::Create(SemaRef.Context, DC,
7906                                 D.getLocStart(),
7907                                 NameInfo, R, TInfo, SC, isInline,
7908                                 true/*HasPrototype*/, isConstexpr);
7909   }
7910 }
7911 
7912 enum OpenCLParamType {
7913   ValidKernelParam,
7914   PtrPtrKernelParam,
7915   PtrKernelParam,
7916   InvalidAddrSpacePtrKernelParam,
7917   InvalidKernelParam,
7918   RecordKernelParam
7919 };
7920 
7921 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
7922   if (PT->isPointerType()) {
7923     QualType PointeeType = PT->getPointeeType();
7924     if (PointeeType->isPointerType())
7925       return PtrPtrKernelParam;
7926     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
7927         PointeeType.getAddressSpace() == 0)
7928       return InvalidAddrSpacePtrKernelParam;
7929     return PtrKernelParam;
7930   }
7931 
7932   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7933   // be used as builtin types.
7934 
7935   if (PT->isImageType())
7936     return PtrKernelParam;
7937 
7938   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
7939     return InvalidKernelParam;
7940 
7941   // OpenCL extension spec v1.2 s9.5:
7942   // This extension adds support for half scalar and vector types as built-in
7943   // types that can be used for arithmetic operations, conversions etc.
7944   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
7945     return InvalidKernelParam;
7946 
7947   if (PT->isRecordType())
7948     return RecordKernelParam;
7949 
7950   return ValidKernelParam;
7951 }
7952 
7953 static void checkIsValidOpenCLKernelParameter(
7954   Sema &S,
7955   Declarator &D,
7956   ParmVarDecl *Param,
7957   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7958   QualType PT = Param->getType();
7959 
7960   // Cache the valid types we encounter to avoid rechecking structs that are
7961   // used again
7962   if (ValidTypes.count(PT.getTypePtr()))
7963     return;
7964 
7965   switch (getOpenCLKernelParameterType(S, PT)) {
7966   case PtrPtrKernelParam:
7967     // OpenCL v1.2 s6.9.a:
7968     // A kernel function argument cannot be declared as a
7969     // pointer to a pointer type.
7970     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7971     D.setInvalidType();
7972     return;
7973 
7974   case InvalidAddrSpacePtrKernelParam:
7975     // OpenCL v1.0 s6.5:
7976     // __kernel function arguments declared to be a pointer of a type can point
7977     // to one of the following address spaces only : __global, __local or
7978     // __constant.
7979     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
7980     D.setInvalidType();
7981     return;
7982 
7983     // OpenCL v1.2 s6.9.k:
7984     // Arguments to kernel functions in a program cannot be declared with the
7985     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7986     // uintptr_t or a struct and/or union that contain fields declared to be
7987     // one of these built-in scalar types.
7988 
7989   case InvalidKernelParam:
7990     // OpenCL v1.2 s6.8 n:
7991     // A kernel function argument cannot be declared
7992     // of event_t type.
7993     // Do not diagnose half type since it is diagnosed as invalid argument
7994     // type for any function elsewhere.
7995     if (!PT->isHalfType())
7996       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7997     D.setInvalidType();
7998     return;
7999 
8000   case PtrKernelParam:
8001   case ValidKernelParam:
8002     ValidTypes.insert(PT.getTypePtr());
8003     return;
8004 
8005   case RecordKernelParam:
8006     break;
8007   }
8008 
8009   // Track nested structs we will inspect
8010   SmallVector<const Decl *, 4> VisitStack;
8011 
8012   // Track where we are in the nested structs. Items will migrate from
8013   // VisitStack to HistoryStack as we do the DFS for bad field.
8014   SmallVector<const FieldDecl *, 4> HistoryStack;
8015   HistoryStack.push_back(nullptr);
8016 
8017   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
8018   VisitStack.push_back(PD);
8019 
8020   assert(VisitStack.back() && "First decl null?");
8021 
8022   do {
8023     const Decl *Next = VisitStack.pop_back_val();
8024     if (!Next) {
8025       assert(!HistoryStack.empty());
8026       // Found a marker, we have gone up a level
8027       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8028         ValidTypes.insert(Hist->getType().getTypePtr());
8029 
8030       continue;
8031     }
8032 
8033     // Adds everything except the original parameter declaration (which is not a
8034     // field itself) to the history stack.
8035     const RecordDecl *RD;
8036     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8037       HistoryStack.push_back(Field);
8038       RD = Field->getType()->castAs<RecordType>()->getDecl();
8039     } else {
8040       RD = cast<RecordDecl>(Next);
8041     }
8042 
8043     // Add a null marker so we know when we've gone back up a level
8044     VisitStack.push_back(nullptr);
8045 
8046     for (const auto *FD : RD->fields()) {
8047       QualType QT = FD->getType();
8048 
8049       if (ValidTypes.count(QT.getTypePtr()))
8050         continue;
8051 
8052       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8053       if (ParamType == ValidKernelParam)
8054         continue;
8055 
8056       if (ParamType == RecordKernelParam) {
8057         VisitStack.push_back(FD);
8058         continue;
8059       }
8060 
8061       // OpenCL v1.2 s6.9.p:
8062       // Arguments to kernel functions that are declared to be a struct or union
8063       // do not allow OpenCL objects to be passed as elements of the struct or
8064       // union.
8065       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8066           ParamType == InvalidAddrSpacePtrKernelParam) {
8067         S.Diag(Param->getLocation(),
8068                diag::err_record_with_pointers_kernel_param)
8069           << PT->isUnionType()
8070           << PT;
8071       } else {
8072         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8073       }
8074 
8075       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
8076         << PD->getDeclName();
8077 
8078       // We have an error, now let's go back up through history and show where
8079       // the offending field came from
8080       for (ArrayRef<const FieldDecl *>::const_iterator
8081                I = HistoryStack.begin() + 1,
8082                E = HistoryStack.end();
8083            I != E; ++I) {
8084         const FieldDecl *OuterField = *I;
8085         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8086           << OuterField->getType();
8087       }
8088 
8089       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8090         << QT->isPointerType()
8091         << QT;
8092       D.setInvalidType();
8093       return;
8094     }
8095   } while (!VisitStack.empty());
8096 }
8097 
8098 /// Find the DeclContext in which a tag is implicitly declared if we see an
8099 /// elaborated type specifier in the specified context, and lookup finds
8100 /// nothing.
8101 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8102   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8103     DC = DC->getParent();
8104   return DC;
8105 }
8106 
8107 /// Find the Scope in which a tag is implicitly declared if we see an
8108 /// elaborated type specifier in the specified context, and lookup finds
8109 /// nothing.
8110 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8111   while (S->isClassScope() ||
8112          (LangOpts.CPlusPlus &&
8113           S->isFunctionPrototypeScope()) ||
8114          ((S->getFlags() & Scope::DeclScope) == 0) ||
8115          (S->getEntity() && S->getEntity()->isTransparentContext()))
8116     S = S->getParent();
8117   return S;
8118 }
8119 
8120 NamedDecl*
8121 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8122                               TypeSourceInfo *TInfo, LookupResult &Previous,
8123                               MultiTemplateParamsArg TemplateParamLists,
8124                               bool &AddToScope) {
8125   QualType R = TInfo->getType();
8126 
8127   assert(R.getTypePtr()->isFunctionType());
8128 
8129   // TODO: consider using NameInfo for diagnostic.
8130   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8131   DeclarationName Name = NameInfo.getName();
8132   StorageClass SC = getFunctionStorageClass(*this, D);
8133 
8134   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8135     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8136          diag::err_invalid_thread)
8137       << DeclSpec::getSpecifierName(TSCS);
8138 
8139   if (D.isFirstDeclarationOfMember())
8140     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8141                            D.getIdentifierLoc());
8142 
8143   bool isFriend = false;
8144   FunctionTemplateDecl *FunctionTemplate = nullptr;
8145   bool isMemberSpecialization = false;
8146   bool isFunctionTemplateSpecialization = false;
8147 
8148   bool isDependentClassScopeExplicitSpecialization = false;
8149   bool HasExplicitTemplateArgs = false;
8150   TemplateArgumentListInfo TemplateArgs;
8151 
8152   bool isVirtualOkay = false;
8153 
8154   DeclContext *OriginalDC = DC;
8155   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8156 
8157   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8158                                               isVirtualOkay);
8159   if (!NewFD) return nullptr;
8160 
8161   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8162     NewFD->setTopLevelDeclInObjCContainer();
8163 
8164   // Set the lexical context. If this is a function-scope declaration, or has a
8165   // C++ scope specifier, or is the object of a friend declaration, the lexical
8166   // context will be different from the semantic context.
8167   NewFD->setLexicalDeclContext(CurContext);
8168 
8169   if (IsLocalExternDecl)
8170     NewFD->setLocalExternDecl();
8171 
8172   if (getLangOpts().CPlusPlus) {
8173     bool isInline = D.getDeclSpec().isInlineSpecified();
8174     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8175     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8176     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8177     bool isConcept = D.getDeclSpec().isConceptSpecified();
8178     isFriend = D.getDeclSpec().isFriendSpecified();
8179     if (isFriend && !isInline && D.isFunctionDefinition()) {
8180       // C++ [class.friend]p5
8181       //   A function can be defined in a friend declaration of a
8182       //   class . . . . Such a function is implicitly inline.
8183       NewFD->setImplicitlyInline();
8184     }
8185 
8186     // If this is a method defined in an __interface, and is not a constructor
8187     // or an overloaded operator, then set the pure flag (isVirtual will already
8188     // return true).
8189     if (const CXXRecordDecl *Parent =
8190           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8191       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8192         NewFD->setPure(true);
8193 
8194       // C++ [class.union]p2
8195       //   A union can have member functions, but not virtual functions.
8196       if (isVirtual && Parent->isUnion())
8197         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8198     }
8199 
8200     SetNestedNameSpecifier(NewFD, D);
8201     isMemberSpecialization = false;
8202     isFunctionTemplateSpecialization = false;
8203     if (D.isInvalidType())
8204       NewFD->setInvalidDecl();
8205 
8206     // Match up the template parameter lists with the scope specifier, then
8207     // determine whether we have a template or a template specialization.
8208     bool Invalid = false;
8209     if (TemplateParameterList *TemplateParams =
8210             MatchTemplateParametersToScopeSpecifier(
8211                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
8212                 D.getCXXScopeSpec(),
8213                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
8214                     ? D.getName().TemplateId
8215                     : nullptr,
8216                 TemplateParamLists, isFriend, isMemberSpecialization,
8217                 Invalid)) {
8218       if (TemplateParams->size() > 0) {
8219         // This is a function template
8220 
8221         // Check that we can declare a template here.
8222         if (CheckTemplateDeclScope(S, TemplateParams))
8223           NewFD->setInvalidDecl();
8224 
8225         // A destructor cannot be a template.
8226         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8227           Diag(NewFD->getLocation(), diag::err_destructor_template);
8228           NewFD->setInvalidDecl();
8229         }
8230 
8231         // If we're adding a template to a dependent context, we may need to
8232         // rebuilding some of the types used within the template parameter list,
8233         // now that we know what the current instantiation is.
8234         if (DC->isDependentContext()) {
8235           ContextRAII SavedContext(*this, DC);
8236           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8237             Invalid = true;
8238         }
8239 
8240         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8241                                                         NewFD->getLocation(),
8242                                                         Name, TemplateParams,
8243                                                         NewFD);
8244         FunctionTemplate->setLexicalDeclContext(CurContext);
8245         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8246 
8247         // For source fidelity, store the other template param lists.
8248         if (TemplateParamLists.size() > 1) {
8249           NewFD->setTemplateParameterListsInfo(Context,
8250                                                TemplateParamLists.drop_back(1));
8251         }
8252       } else {
8253         // This is a function template specialization.
8254         isFunctionTemplateSpecialization = true;
8255         // For source fidelity, store all the template param lists.
8256         if (TemplateParamLists.size() > 0)
8257           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8258 
8259         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8260         if (isFriend) {
8261           // We want to remove the "template<>", found here.
8262           SourceRange RemoveRange = TemplateParams->getSourceRange();
8263 
8264           // If we remove the template<> and the name is not a
8265           // template-id, we're actually silently creating a problem:
8266           // the friend declaration will refer to an untemplated decl,
8267           // and clearly the user wants a template specialization.  So
8268           // we need to insert '<>' after the name.
8269           SourceLocation InsertLoc;
8270           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8271             InsertLoc = D.getName().getSourceRange().getEnd();
8272             InsertLoc = getLocForEndOfToken(InsertLoc);
8273           }
8274 
8275           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8276             << Name << RemoveRange
8277             << FixItHint::CreateRemoval(RemoveRange)
8278             << FixItHint::CreateInsertion(InsertLoc, "<>");
8279         }
8280       }
8281     }
8282     else {
8283       // All template param lists were matched against the scope specifier:
8284       // this is NOT (an explicit specialization of) a template.
8285       if (TemplateParamLists.size() > 0)
8286         // For source fidelity, store all the template param lists.
8287         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8288     }
8289 
8290     if (Invalid) {
8291       NewFD->setInvalidDecl();
8292       if (FunctionTemplate)
8293         FunctionTemplate->setInvalidDecl();
8294     }
8295 
8296     // C++ [dcl.fct.spec]p5:
8297     //   The virtual specifier shall only be used in declarations of
8298     //   nonstatic class member functions that appear within a
8299     //   member-specification of a class declaration; see 10.3.
8300     //
8301     if (isVirtual && !NewFD->isInvalidDecl()) {
8302       if (!isVirtualOkay) {
8303         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8304              diag::err_virtual_non_function);
8305       } else if (!CurContext->isRecord()) {
8306         // 'virtual' was specified outside of the class.
8307         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8308              diag::err_virtual_out_of_class)
8309           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8310       } else if (NewFD->getDescribedFunctionTemplate()) {
8311         // C++ [temp.mem]p3:
8312         //  A member function template shall not be virtual.
8313         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8314              diag::err_virtual_member_function_template)
8315           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8316       } else {
8317         // Okay: Add virtual to the method.
8318         NewFD->setVirtualAsWritten(true);
8319       }
8320 
8321       if (getLangOpts().CPlusPlus14 &&
8322           NewFD->getReturnType()->isUndeducedType())
8323         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8324     }
8325 
8326     if (getLangOpts().CPlusPlus14 &&
8327         (NewFD->isDependentContext() ||
8328          (isFriend && CurContext->isDependentContext())) &&
8329         NewFD->getReturnType()->isUndeducedType()) {
8330       // If the function template is referenced directly (for instance, as a
8331       // member of the current instantiation), pretend it has a dependent type.
8332       // This is not really justified by the standard, but is the only sane
8333       // thing to do.
8334       // FIXME: For a friend function, we have not marked the function as being
8335       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8336       const FunctionProtoType *FPT =
8337           NewFD->getType()->castAs<FunctionProtoType>();
8338       QualType Result =
8339           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8340       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8341                                              FPT->getExtProtoInfo()));
8342     }
8343 
8344     // C++ [dcl.fct.spec]p3:
8345     //  The inline specifier shall not appear on a block scope function
8346     //  declaration.
8347     if (isInline && !NewFD->isInvalidDecl()) {
8348       if (CurContext->isFunctionOrMethod()) {
8349         // 'inline' is not allowed on block scope function declaration.
8350         Diag(D.getDeclSpec().getInlineSpecLoc(),
8351              diag::err_inline_declaration_block_scope) << Name
8352           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8353       }
8354     }
8355 
8356     // C++ [dcl.fct.spec]p6:
8357     //  The explicit specifier shall be used only in the declaration of a
8358     //  constructor or conversion function within its class definition;
8359     //  see 12.3.1 and 12.3.2.
8360     if (isExplicit && !NewFD->isInvalidDecl() &&
8361         !isa<CXXDeductionGuideDecl>(NewFD)) {
8362       if (!CurContext->isRecord()) {
8363         // 'explicit' was specified outside of the class.
8364         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8365              diag::err_explicit_out_of_class)
8366           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8367       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8368                  !isa<CXXConversionDecl>(NewFD)) {
8369         // 'explicit' was specified on a function that wasn't a constructor
8370         // or conversion function.
8371         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8372              diag::err_explicit_non_ctor_or_conv_function)
8373           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8374       }
8375     }
8376 
8377     if (isConstexpr) {
8378       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8379       // are implicitly inline.
8380       NewFD->setImplicitlyInline();
8381 
8382       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8383       // be either constructors or to return a literal type. Therefore,
8384       // destructors cannot be declared constexpr.
8385       if (isa<CXXDestructorDecl>(NewFD))
8386         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8387     }
8388 
8389     if (isConcept) {
8390       // This is a function concept.
8391       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
8392         FTD->setConcept();
8393 
8394       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8395       // applied only to the definition of a function template [...]
8396       if (!D.isFunctionDefinition()) {
8397         Diag(D.getDeclSpec().getConceptSpecLoc(),
8398              diag::err_function_concept_not_defined);
8399         NewFD->setInvalidDecl();
8400       }
8401 
8402       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
8403       // have no exception-specification and is treated as if it were specified
8404       // with noexcept(true) (15.4). [...]
8405       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
8406         if (FPT->hasExceptionSpec()) {
8407           SourceRange Range;
8408           if (D.isFunctionDeclarator())
8409             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
8410           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
8411               << FixItHint::CreateRemoval(Range);
8412           NewFD->setInvalidDecl();
8413         } else {
8414           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
8415         }
8416 
8417         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8418         // following restrictions:
8419         // - The declared return type shall have the type bool.
8420         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
8421           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
8422           NewFD->setInvalidDecl();
8423         }
8424 
8425         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8426         // following restrictions:
8427         // - The declaration's parameter list shall be equivalent to an empty
8428         //   parameter list.
8429         if (FPT->getNumParams() > 0 || FPT->isVariadic())
8430           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
8431       }
8432 
8433       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
8434       // implicity defined to be a constexpr declaration (implicitly inline)
8435       NewFD->setImplicitlyInline();
8436 
8437       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
8438       // be declared with the thread_local, inline, friend, or constexpr
8439       // specifiers, [...]
8440       if (isInline) {
8441         Diag(D.getDeclSpec().getInlineSpecLoc(),
8442              diag::err_concept_decl_invalid_specifiers)
8443             << 1 << 1;
8444         NewFD->setInvalidDecl(true);
8445       }
8446 
8447       if (isFriend) {
8448         Diag(D.getDeclSpec().getFriendSpecLoc(),
8449              diag::err_concept_decl_invalid_specifiers)
8450             << 1 << 2;
8451         NewFD->setInvalidDecl(true);
8452       }
8453 
8454       if (isConstexpr) {
8455         Diag(D.getDeclSpec().getConstexprSpecLoc(),
8456              diag::err_concept_decl_invalid_specifiers)
8457             << 1 << 3;
8458         NewFD->setInvalidDecl(true);
8459       }
8460 
8461       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8462       // applied only to the definition of a function template or variable
8463       // template, declared in namespace scope.
8464       if (isFunctionTemplateSpecialization) {
8465         Diag(D.getDeclSpec().getConceptSpecLoc(),
8466              diag::err_concept_specified_specialization) << 1;
8467         NewFD->setInvalidDecl(true);
8468         return NewFD;
8469       }
8470     }
8471 
8472     // If __module_private__ was specified, mark the function accordingly.
8473     if (D.getDeclSpec().isModulePrivateSpecified()) {
8474       if (isFunctionTemplateSpecialization) {
8475         SourceLocation ModulePrivateLoc
8476           = D.getDeclSpec().getModulePrivateSpecLoc();
8477         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8478           << 0
8479           << FixItHint::CreateRemoval(ModulePrivateLoc);
8480       } else {
8481         NewFD->setModulePrivate();
8482         if (FunctionTemplate)
8483           FunctionTemplate->setModulePrivate();
8484       }
8485     }
8486 
8487     if (isFriend) {
8488       if (FunctionTemplate) {
8489         FunctionTemplate->setObjectOfFriendDecl();
8490         FunctionTemplate->setAccess(AS_public);
8491       }
8492       NewFD->setObjectOfFriendDecl();
8493       NewFD->setAccess(AS_public);
8494     }
8495 
8496     // If a function is defined as defaulted or deleted, mark it as such now.
8497     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8498     // definition kind to FDK_Definition.
8499     switch (D.getFunctionDefinitionKind()) {
8500       case FDK_Declaration:
8501       case FDK_Definition:
8502         break;
8503 
8504       case FDK_Defaulted:
8505         NewFD->setDefaulted();
8506         break;
8507 
8508       case FDK_Deleted:
8509         NewFD->setDeletedAsWritten();
8510         break;
8511     }
8512 
8513     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8514         D.isFunctionDefinition()) {
8515       // C++ [class.mfct]p2:
8516       //   A member function may be defined (8.4) in its class definition, in
8517       //   which case it is an inline member function (7.1.2)
8518       NewFD->setImplicitlyInline();
8519     }
8520 
8521     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8522         !CurContext->isRecord()) {
8523       // C++ [class.static]p1:
8524       //   A data or function member of a class may be declared static
8525       //   in a class definition, in which case it is a static member of
8526       //   the class.
8527 
8528       // Complain about the 'static' specifier if it's on an out-of-line
8529       // member function definition.
8530       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8531            diag::err_static_out_of_line)
8532         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8533     }
8534 
8535     // C++11 [except.spec]p15:
8536     //   A deallocation function with no exception-specification is treated
8537     //   as if it were specified with noexcept(true).
8538     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8539     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8540          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8541         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8542       NewFD->setType(Context.getFunctionType(
8543           FPT->getReturnType(), FPT->getParamTypes(),
8544           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8545   }
8546 
8547   // Filter out previous declarations that don't match the scope.
8548   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8549                        D.getCXXScopeSpec().isNotEmpty() ||
8550                        isMemberSpecialization ||
8551                        isFunctionTemplateSpecialization);
8552 
8553   // Handle GNU asm-label extension (encoded as an attribute).
8554   if (Expr *E = (Expr*) D.getAsmLabel()) {
8555     // The parser guarantees this is a string.
8556     StringLiteral *SE = cast<StringLiteral>(E);
8557     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8558                                                 SE->getString(), 0));
8559   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8560     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8561       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8562     if (I != ExtnameUndeclaredIdentifiers.end()) {
8563       if (isDeclExternC(NewFD)) {
8564         NewFD->addAttr(I->second);
8565         ExtnameUndeclaredIdentifiers.erase(I);
8566       } else
8567         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8568             << /*Variable*/0 << NewFD;
8569     }
8570   }
8571 
8572   // Copy the parameter declarations from the declarator D to the function
8573   // declaration NewFD, if they are available.  First scavenge them into Params.
8574   SmallVector<ParmVarDecl*, 16> Params;
8575   unsigned FTIIdx;
8576   if (D.isFunctionDeclarator(FTIIdx)) {
8577     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8578 
8579     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8580     // function that takes no arguments, not a function that takes a
8581     // single void argument.
8582     // We let through "const void" here because Sema::GetTypeForDeclarator
8583     // already checks for that case.
8584     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8585       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8586         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8587         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8588         Param->setDeclContext(NewFD);
8589         Params.push_back(Param);
8590 
8591         if (Param->isInvalidDecl())
8592           NewFD->setInvalidDecl();
8593       }
8594     }
8595 
8596     if (!getLangOpts().CPlusPlus) {
8597       // In C, find all the tag declarations from the prototype and move them
8598       // into the function DeclContext. Remove them from the surrounding tag
8599       // injection context of the function, which is typically but not always
8600       // the TU.
8601       DeclContext *PrototypeTagContext =
8602           getTagInjectionContext(NewFD->getLexicalDeclContext());
8603       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8604         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8605 
8606         // We don't want to reparent enumerators. Look at their parent enum
8607         // instead.
8608         if (!TD) {
8609           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8610             TD = cast<EnumDecl>(ECD->getDeclContext());
8611         }
8612         if (!TD)
8613           continue;
8614         DeclContext *TagDC = TD->getLexicalDeclContext();
8615         if (!TagDC->containsDecl(TD))
8616           continue;
8617         TagDC->removeDecl(TD);
8618         TD->setDeclContext(NewFD);
8619         NewFD->addDecl(TD);
8620 
8621         // Preserve the lexical DeclContext if it is not the surrounding tag
8622         // injection context of the FD. In this example, the semantic context of
8623         // E will be f and the lexical context will be S, while both the
8624         // semantic and lexical contexts of S will be f:
8625         //   void f(struct S { enum E { a } f; } s);
8626         if (TagDC != PrototypeTagContext)
8627           TD->setLexicalDeclContext(TagDC);
8628       }
8629     }
8630   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8631     // When we're declaring a function with a typedef, typeof, etc as in the
8632     // following example, we'll need to synthesize (unnamed)
8633     // parameters for use in the declaration.
8634     //
8635     // @code
8636     // typedef void fn(int);
8637     // fn f;
8638     // @endcode
8639 
8640     // Synthesize a parameter for each argument type.
8641     for (const auto &AI : FT->param_types()) {
8642       ParmVarDecl *Param =
8643           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8644       Param->setScopeInfo(0, Params.size());
8645       Params.push_back(Param);
8646     }
8647   } else {
8648     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8649            "Should not need args for typedef of non-prototype fn");
8650   }
8651 
8652   // Finally, we know we have the right number of parameters, install them.
8653   NewFD->setParams(Params);
8654 
8655   if (D.getDeclSpec().isNoreturnSpecified())
8656     NewFD->addAttr(
8657         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8658                                        Context, 0));
8659 
8660   // Functions returning a variably modified type violate C99 6.7.5.2p2
8661   // because all functions have linkage.
8662   if (!NewFD->isInvalidDecl() &&
8663       NewFD->getReturnType()->isVariablyModifiedType()) {
8664     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8665     NewFD->setInvalidDecl();
8666   }
8667 
8668   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8669   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8670       !NewFD->hasAttr<SectionAttr>()) {
8671     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8672                                                  PragmaClangTextSection.SectionName,
8673                                                  PragmaClangTextSection.PragmaLocation));
8674   }
8675 
8676   // Apply an implicit SectionAttr if #pragma code_seg is active.
8677   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8678       !NewFD->hasAttr<SectionAttr>()) {
8679     NewFD->addAttr(
8680         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8681                                     CodeSegStack.CurrentValue->getString(),
8682                                     CodeSegStack.CurrentPragmaLocation));
8683     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8684                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8685                          ASTContext::PSF_Read,
8686                      NewFD))
8687       NewFD->dropAttr<SectionAttr>();
8688   }
8689 
8690   // Handle attributes.
8691   ProcessDeclAttributes(S, NewFD, D);
8692 
8693   if (getLangOpts().OpenCL) {
8694     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8695     // type declaration will generate a compilation error.
8696     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8697     if (AddressSpace == LangAS::opencl_local ||
8698         AddressSpace == LangAS::opencl_global ||
8699         AddressSpace == LangAS::opencl_constant) {
8700       Diag(NewFD->getLocation(),
8701            diag::err_opencl_return_value_with_address_space);
8702       NewFD->setInvalidDecl();
8703     }
8704   }
8705 
8706   if (!getLangOpts().CPlusPlus) {
8707     // Perform semantic checking on the function declaration.
8708     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8709       CheckMain(NewFD, D.getDeclSpec());
8710 
8711     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8712       CheckMSVCRTEntryPoint(NewFD);
8713 
8714     if (!NewFD->isInvalidDecl())
8715       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8716                                                   isMemberSpecialization));
8717     else if (!Previous.empty())
8718       // Recover gracefully from an invalid redeclaration.
8719       D.setRedeclaration(true);
8720     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8721             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8722            "previous declaration set still overloaded");
8723 
8724     // Diagnose no-prototype function declarations with calling conventions that
8725     // don't support variadic calls. Only do this in C and do it after merging
8726     // possibly prototyped redeclarations.
8727     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8728     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8729       CallingConv CC = FT->getExtInfo().getCC();
8730       if (!supportsVariadicCall(CC)) {
8731         // Windows system headers sometimes accidentally use stdcall without
8732         // (void) parameters, so we relax this to a warning.
8733         int DiagID =
8734             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8735         Diag(NewFD->getLocation(), DiagID)
8736             << FunctionType::getNameForCallConv(CC);
8737       }
8738     }
8739   } else {
8740     // C++11 [replacement.functions]p3:
8741     //  The program's definitions shall not be specified as inline.
8742     //
8743     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8744     //
8745     // Suppress the diagnostic if the function is __attribute__((used)), since
8746     // that forces an external definition to be emitted.
8747     if (D.getDeclSpec().isInlineSpecified() &&
8748         NewFD->isReplaceableGlobalAllocationFunction() &&
8749         !NewFD->hasAttr<UsedAttr>())
8750       Diag(D.getDeclSpec().getInlineSpecLoc(),
8751            diag::ext_operator_new_delete_declared_inline)
8752         << NewFD->getDeclName();
8753 
8754     // If the declarator is a template-id, translate the parser's template
8755     // argument list into our AST format.
8756     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8757       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8758       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8759       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8760       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8761                                          TemplateId->NumArgs);
8762       translateTemplateArguments(TemplateArgsPtr,
8763                                  TemplateArgs);
8764 
8765       HasExplicitTemplateArgs = true;
8766 
8767       if (NewFD->isInvalidDecl()) {
8768         HasExplicitTemplateArgs = false;
8769       } else if (FunctionTemplate) {
8770         // Function template with explicit template arguments.
8771         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8772           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8773 
8774         HasExplicitTemplateArgs = false;
8775       } else {
8776         assert((isFunctionTemplateSpecialization ||
8777                 D.getDeclSpec().isFriendSpecified()) &&
8778                "should have a 'template<>' for this decl");
8779         // "friend void foo<>(int);" is an implicit specialization decl.
8780         isFunctionTemplateSpecialization = true;
8781       }
8782     } else if (isFriend && isFunctionTemplateSpecialization) {
8783       // This combination is only possible in a recovery case;  the user
8784       // wrote something like:
8785       //   template <> friend void foo(int);
8786       // which we're recovering from as if the user had written:
8787       //   friend void foo<>(int);
8788       // Go ahead and fake up a template id.
8789       HasExplicitTemplateArgs = true;
8790       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8791       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8792     }
8793 
8794     // We do not add HD attributes to specializations here because
8795     // they may have different constexpr-ness compared to their
8796     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8797     // may end up with different effective targets. Instead, a
8798     // specialization inherits its target attributes from its template
8799     // in the CheckFunctionTemplateSpecialization() call below.
8800     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8801       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8802 
8803     // If it's a friend (and only if it's a friend), it's possible
8804     // that either the specialized function type or the specialized
8805     // template is dependent, and therefore matching will fail.  In
8806     // this case, don't check the specialization yet.
8807     bool InstantiationDependent = false;
8808     if (isFunctionTemplateSpecialization && isFriend &&
8809         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8810          TemplateSpecializationType::anyDependentTemplateArguments(
8811             TemplateArgs,
8812             InstantiationDependent))) {
8813       assert(HasExplicitTemplateArgs &&
8814              "friend function specialization without template args");
8815       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8816                                                        Previous))
8817         NewFD->setInvalidDecl();
8818     } else if (isFunctionTemplateSpecialization) {
8819       if (CurContext->isDependentContext() && CurContext->isRecord()
8820           && !isFriend) {
8821         isDependentClassScopeExplicitSpecialization = true;
8822         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8823           diag::ext_function_specialization_in_class :
8824           diag::err_function_specialization_in_class)
8825           << NewFD->getDeclName();
8826       } else if (CheckFunctionTemplateSpecialization(NewFD,
8827                                   (HasExplicitTemplateArgs ? &TemplateArgs
8828                                                            : nullptr),
8829                                                      Previous))
8830         NewFD->setInvalidDecl();
8831 
8832       // C++ [dcl.stc]p1:
8833       //   A storage-class-specifier shall not be specified in an explicit
8834       //   specialization (14.7.3)
8835       FunctionTemplateSpecializationInfo *Info =
8836           NewFD->getTemplateSpecializationInfo();
8837       if (Info && SC != SC_None) {
8838         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8839           Diag(NewFD->getLocation(),
8840                diag::err_explicit_specialization_inconsistent_storage_class)
8841             << SC
8842             << FixItHint::CreateRemoval(
8843                                       D.getDeclSpec().getStorageClassSpecLoc());
8844 
8845         else
8846           Diag(NewFD->getLocation(),
8847                diag::ext_explicit_specialization_storage_class)
8848             << FixItHint::CreateRemoval(
8849                                       D.getDeclSpec().getStorageClassSpecLoc());
8850       }
8851     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8852       if (CheckMemberSpecialization(NewFD, Previous))
8853           NewFD->setInvalidDecl();
8854     }
8855 
8856     // Perform semantic checking on the function declaration.
8857     if (!isDependentClassScopeExplicitSpecialization) {
8858       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8859         CheckMain(NewFD, D.getDeclSpec());
8860 
8861       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8862         CheckMSVCRTEntryPoint(NewFD);
8863 
8864       if (!NewFD->isInvalidDecl())
8865         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8866                                                     isMemberSpecialization));
8867       else if (!Previous.empty())
8868         // Recover gracefully from an invalid redeclaration.
8869         D.setRedeclaration(true);
8870     }
8871 
8872     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8873             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8874            "previous declaration set still overloaded");
8875 
8876     NamedDecl *PrincipalDecl = (FunctionTemplate
8877                                 ? cast<NamedDecl>(FunctionTemplate)
8878                                 : NewFD);
8879 
8880     if (isFriend && NewFD->getPreviousDecl()) {
8881       AccessSpecifier Access = AS_public;
8882       if (!NewFD->isInvalidDecl())
8883         Access = NewFD->getPreviousDecl()->getAccess();
8884 
8885       NewFD->setAccess(Access);
8886       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8887     }
8888 
8889     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8890         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8891       PrincipalDecl->setNonMemberOperator();
8892 
8893     // If we have a function template, check the template parameter
8894     // list. This will check and merge default template arguments.
8895     if (FunctionTemplate) {
8896       FunctionTemplateDecl *PrevTemplate =
8897                                      FunctionTemplate->getPreviousDecl();
8898       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8899                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8900                                     : nullptr,
8901                             D.getDeclSpec().isFriendSpecified()
8902                               ? (D.isFunctionDefinition()
8903                                    ? TPC_FriendFunctionTemplateDefinition
8904                                    : TPC_FriendFunctionTemplate)
8905                               : (D.getCXXScopeSpec().isSet() &&
8906                                  DC && DC->isRecord() &&
8907                                  DC->isDependentContext())
8908                                   ? TPC_ClassTemplateMember
8909                                   : TPC_FunctionTemplate);
8910     }
8911 
8912     if (NewFD->isInvalidDecl()) {
8913       // Ignore all the rest of this.
8914     } else if (!D.isRedeclaration()) {
8915       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8916                                        AddToScope };
8917       // Fake up an access specifier if it's supposed to be a class member.
8918       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8919         NewFD->setAccess(AS_public);
8920 
8921       // Qualified decls generally require a previous declaration.
8922       if (D.getCXXScopeSpec().isSet()) {
8923         // ...with the major exception of templated-scope or
8924         // dependent-scope friend declarations.
8925 
8926         // TODO: we currently also suppress this check in dependent
8927         // contexts because (1) the parameter depth will be off when
8928         // matching friend templates and (2) we might actually be
8929         // selecting a friend based on a dependent factor.  But there
8930         // are situations where these conditions don't apply and we
8931         // can actually do this check immediately.
8932         if (isFriend &&
8933             (TemplateParamLists.size() ||
8934              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8935              CurContext->isDependentContext())) {
8936           // ignore these
8937         } else {
8938           // The user tried to provide an out-of-line definition for a
8939           // function that is a member of a class or namespace, but there
8940           // was no such member function declared (C++ [class.mfct]p2,
8941           // C++ [namespace.memdef]p2). For example:
8942           //
8943           // class X {
8944           //   void f() const;
8945           // };
8946           //
8947           // void X::f() { } // ill-formed
8948           //
8949           // Complain about this problem, and attempt to suggest close
8950           // matches (e.g., those that differ only in cv-qualifiers and
8951           // whether the parameter types are references).
8952 
8953           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8954                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8955             AddToScope = ExtraArgs.AddToScope;
8956             return Result;
8957           }
8958         }
8959 
8960         // Unqualified local friend declarations are required to resolve
8961         // to something.
8962       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8963         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8964                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8965           AddToScope = ExtraArgs.AddToScope;
8966           return Result;
8967         }
8968       }
8969     } else if (!D.isFunctionDefinition() &&
8970                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8971                !isFriend && !isFunctionTemplateSpecialization &&
8972                !isMemberSpecialization) {
8973       // An out-of-line member function declaration must also be a
8974       // definition (C++ [class.mfct]p2).
8975       // Note that this is not the case for explicit specializations of
8976       // function templates or member functions of class templates, per
8977       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8978       // extension for compatibility with old SWIG code which likes to
8979       // generate them.
8980       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8981         << D.getCXXScopeSpec().getRange();
8982     }
8983   }
8984 
8985   ProcessPragmaWeak(S, NewFD);
8986   checkAttributesAfterMerging(*this, *NewFD);
8987 
8988   AddKnownFunctionAttributes(NewFD);
8989 
8990   if (NewFD->hasAttr<OverloadableAttr>() &&
8991       !NewFD->getType()->getAs<FunctionProtoType>()) {
8992     Diag(NewFD->getLocation(),
8993          diag::err_attribute_overloadable_no_prototype)
8994       << NewFD;
8995 
8996     // Turn this into a variadic function with no parameters.
8997     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8998     FunctionProtoType::ExtProtoInfo EPI(
8999         Context.getDefaultCallingConvention(true, false));
9000     EPI.Variadic = true;
9001     EPI.ExtInfo = FT->getExtInfo();
9002 
9003     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9004     NewFD->setType(R);
9005   }
9006 
9007   // If there's a #pragma GCC visibility in scope, and this isn't a class
9008   // member, set the visibility of this function.
9009   if (!DC->isRecord() && NewFD->isExternallyVisible())
9010     AddPushedVisibilityAttribute(NewFD);
9011 
9012   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9013   // marking the function.
9014   AddCFAuditedAttribute(NewFD);
9015 
9016   // If this is a function definition, check if we have to apply optnone due to
9017   // a pragma.
9018   if(D.isFunctionDefinition())
9019     AddRangeBasedOptnone(NewFD);
9020 
9021   // If this is the first declaration of an extern C variable, update
9022   // the map of such variables.
9023   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9024       isIncompleteDeclExternC(*this, NewFD))
9025     RegisterLocallyScopedExternCDecl(NewFD, S);
9026 
9027   // Set this FunctionDecl's range up to the right paren.
9028   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9029 
9030   if (D.isRedeclaration() && !Previous.empty()) {
9031     checkDLLAttributeRedeclaration(
9032         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
9033         isMemberSpecialization || isFunctionTemplateSpecialization,
9034         D.isFunctionDefinition());
9035   }
9036 
9037   if (getLangOpts().CUDA) {
9038     IdentifierInfo *II = NewFD->getIdentifier();
9039     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
9040         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9041       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9042         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
9043 
9044       Context.setcudaConfigureCallDecl(NewFD);
9045     }
9046 
9047     // Variadic functions, other than a *declaration* of printf, are not allowed
9048     // in device-side CUDA code, unless someone passed
9049     // -fcuda-allow-variadic-functions.
9050     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9051         (NewFD->hasAttr<CUDADeviceAttr>() ||
9052          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9053         !(II && II->isStr("printf") && NewFD->isExternC() &&
9054           !D.isFunctionDefinition())) {
9055       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9056     }
9057   }
9058 
9059   MarkUnusedFileScopedDecl(NewFD);
9060 
9061   if (getLangOpts().CPlusPlus) {
9062     if (FunctionTemplate) {
9063       if (NewFD->isInvalidDecl())
9064         FunctionTemplate->setInvalidDecl();
9065       return FunctionTemplate;
9066     }
9067 
9068     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9069       CompleteMemberSpecialization(NewFD, Previous);
9070   }
9071 
9072   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9073     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9074     if ((getLangOpts().OpenCLVersion >= 120)
9075         && (SC == SC_Static)) {
9076       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9077       D.setInvalidType();
9078     }
9079 
9080     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9081     if (!NewFD->getReturnType()->isVoidType()) {
9082       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9083       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9084           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9085                                 : FixItHint());
9086       D.setInvalidType();
9087     }
9088 
9089     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9090     for (auto Param : NewFD->parameters())
9091       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9092   }
9093   for (const ParmVarDecl *Param : NewFD->parameters()) {
9094     QualType PT = Param->getType();
9095 
9096     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9097     // types.
9098     if (getLangOpts().OpenCLVersion >= 200) {
9099       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9100         QualType ElemTy = PipeTy->getElementType();
9101           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9102             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9103             D.setInvalidType();
9104           }
9105       }
9106     }
9107   }
9108 
9109   // Here we have an function template explicit specialization at class scope.
9110   // The actually specialization will be postponed to template instatiation
9111   // time via the ClassScopeFunctionSpecializationDecl node.
9112   if (isDependentClassScopeExplicitSpecialization) {
9113     ClassScopeFunctionSpecializationDecl *NewSpec =
9114                          ClassScopeFunctionSpecializationDecl::Create(
9115                                 Context, CurContext, SourceLocation(),
9116                                 cast<CXXMethodDecl>(NewFD),
9117                                 HasExplicitTemplateArgs, TemplateArgs);
9118     CurContext->addDecl(NewSpec);
9119     AddToScope = false;
9120   }
9121 
9122   return NewFD;
9123 }
9124 
9125 /// \brief Checks if the new declaration declared in dependent context must be
9126 /// put in the same redeclaration chain as the specified declaration.
9127 ///
9128 /// \param D Declaration that is checked.
9129 /// \param PrevDecl Previous declaration found with proper lookup method for the
9130 ///                 same declaration name.
9131 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9132 ///          belongs to.
9133 ///
9134 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9135   // Any declarations should be put into redeclaration chains except for
9136   // friend declaration in a dependent context that names a function in
9137   // namespace scope.
9138   //
9139   // This allows to compile code like:
9140   //
9141   //       void func();
9142   //       template<typename T> class C1 { friend void func() { } };
9143   //       template<typename T> class C2 { friend void func() { } };
9144   //
9145   // This code snippet is a valid code unless both templates are instantiated.
9146   return !(D->getLexicalDeclContext()->isDependentContext() &&
9147            D->getDeclContext()->isFileContext() &&
9148            D->getFriendObjectKind() != Decl::FOK_None);
9149 }
9150 
9151 /// \brief Perform semantic checking of a new function declaration.
9152 ///
9153 /// Performs semantic analysis of the new function declaration
9154 /// NewFD. This routine performs all semantic checking that does not
9155 /// require the actual declarator involved in the declaration, and is
9156 /// used both for the declaration of functions as they are parsed
9157 /// (called via ActOnDeclarator) and for the declaration of functions
9158 /// that have been instantiated via C++ template instantiation (called
9159 /// via InstantiateDecl).
9160 ///
9161 /// \param IsMemberSpecialization whether this new function declaration is
9162 /// a member specialization (that replaces any definition provided by the
9163 /// previous declaration).
9164 ///
9165 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9166 ///
9167 /// \returns true if the function declaration is a redeclaration.
9168 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9169                                     LookupResult &Previous,
9170                                     bool IsMemberSpecialization) {
9171   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9172          "Variably modified return types are not handled here");
9173 
9174   // Determine whether the type of this function should be merged with
9175   // a previous visible declaration. This never happens for functions in C++,
9176   // and always happens in C if the previous declaration was visible.
9177   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9178                                !Previous.isShadowed();
9179 
9180   bool Redeclaration = false;
9181   NamedDecl *OldDecl = nullptr;
9182 
9183   // Merge or overload the declaration with an existing declaration of
9184   // the same name, if appropriate.
9185   if (!Previous.empty()) {
9186     // Determine whether NewFD is an overload of PrevDecl or
9187     // a declaration that requires merging. If it's an overload,
9188     // there's no more work to do here; we'll just add the new
9189     // function to the scope.
9190     if (!AllowOverloadingOfFunction(Previous, Context)) {
9191       NamedDecl *Candidate = Previous.getRepresentativeDecl();
9192       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9193         Redeclaration = true;
9194         OldDecl = Candidate;
9195       }
9196     } else {
9197       switch (CheckOverload(S, NewFD, Previous, OldDecl,
9198                             /*NewIsUsingDecl*/ false)) {
9199       case Ovl_Match:
9200         Redeclaration = true;
9201         break;
9202 
9203       case Ovl_NonFunction:
9204         Redeclaration = true;
9205         break;
9206 
9207       case Ovl_Overload:
9208         Redeclaration = false;
9209         break;
9210       }
9211 
9212       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
9213         // If a function name is overloadable in C, then every function
9214         // with that name must be marked "overloadable".
9215         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
9216           << Redeclaration << NewFD;
9217         NamedDecl *OverloadedDecl =
9218             Redeclaration ? OldDecl : Previous.getRepresentativeDecl();
9219         Diag(OverloadedDecl->getLocation(),
9220              diag::note_attribute_overloadable_prev_overload);
9221         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9222       }
9223     }
9224   }
9225 
9226   // Check for a previous extern "C" declaration with this name.
9227   if (!Redeclaration &&
9228       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9229     if (!Previous.empty()) {
9230       // This is an extern "C" declaration with the same name as a previous
9231       // declaration, and thus redeclares that entity...
9232       Redeclaration = true;
9233       OldDecl = Previous.getFoundDecl();
9234       MergeTypeWithPrevious = false;
9235 
9236       // ... except in the presence of __attribute__((overloadable)).
9237       if (OldDecl->hasAttr<OverloadableAttr>()) {
9238         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
9239           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
9240             << Redeclaration << NewFD;
9241           Diag(Previous.getFoundDecl()->getLocation(),
9242                diag::note_attribute_overloadable_prev_overload);
9243           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9244         }
9245         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9246           Redeclaration = false;
9247           OldDecl = nullptr;
9248         }
9249       }
9250     }
9251   }
9252 
9253   // C++11 [dcl.constexpr]p8:
9254   //   A constexpr specifier for a non-static member function that is not
9255   //   a constructor declares that member function to be const.
9256   //
9257   // This needs to be delayed until we know whether this is an out-of-line
9258   // definition of a static member function.
9259   //
9260   // This rule is not present in C++1y, so we produce a backwards
9261   // compatibility warning whenever it happens in C++11.
9262   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9263   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9264       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9265       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9266     CXXMethodDecl *OldMD = nullptr;
9267     if (OldDecl)
9268       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9269     if (!OldMD || !OldMD->isStatic()) {
9270       const FunctionProtoType *FPT =
9271         MD->getType()->castAs<FunctionProtoType>();
9272       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9273       EPI.TypeQuals |= Qualifiers::Const;
9274       MD->setType(Context.getFunctionType(FPT->getReturnType(),
9275                                           FPT->getParamTypes(), EPI));
9276 
9277       // Warn that we did this, if we're not performing template instantiation.
9278       // In that case, we'll have warned already when the template was defined.
9279       if (!inTemplateInstantiation()) {
9280         SourceLocation AddConstLoc;
9281         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
9282                 .IgnoreParens().getAs<FunctionTypeLoc>())
9283           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
9284 
9285         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
9286           << FixItHint::CreateInsertion(AddConstLoc, " const");
9287       }
9288     }
9289   }
9290 
9291   if (Redeclaration) {
9292     // NewFD and OldDecl represent declarations that need to be
9293     // merged.
9294     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
9295       NewFD->setInvalidDecl();
9296       return Redeclaration;
9297     }
9298 
9299     Previous.clear();
9300     Previous.addDecl(OldDecl);
9301 
9302     if (FunctionTemplateDecl *OldTemplateDecl
9303                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
9304       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
9305       FunctionTemplateDecl *NewTemplateDecl
9306         = NewFD->getDescribedFunctionTemplate();
9307       assert(NewTemplateDecl && "Template/non-template mismatch");
9308       if (CXXMethodDecl *Method
9309             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
9310         Method->setAccess(OldTemplateDecl->getAccess());
9311         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
9312       }
9313 
9314       // If this is an explicit specialization of a member that is a function
9315       // template, mark it as a member specialization.
9316       if (IsMemberSpecialization &&
9317           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
9318         NewTemplateDecl->setMemberSpecialization();
9319         assert(OldTemplateDecl->isMemberSpecialization());
9320         // Explicit specializations of a member template do not inherit deleted
9321         // status from the parent member template that they are specializing.
9322         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
9323           FunctionDecl *const OldTemplatedDecl =
9324               OldTemplateDecl->getTemplatedDecl();
9325           // FIXME: This assert will not hold in the presence of modules.
9326           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
9327           // FIXME: We need an update record for this AST mutation.
9328           OldTemplatedDecl->setDeletedAsWritten(false);
9329         }
9330       }
9331 
9332     } else {
9333       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9334         // This needs to happen first so that 'inline' propagates.
9335         NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
9336         if (isa<CXXMethodDecl>(NewFD))
9337           NewFD->setAccess(OldDecl->getAccess());
9338       }
9339     }
9340   }
9341 
9342   // Semantic checking for this function declaration (in isolation).
9343 
9344   if (getLangOpts().CPlusPlus) {
9345     // C++-specific checks.
9346     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9347       CheckConstructor(Constructor);
9348     } else if (CXXDestructorDecl *Destructor =
9349                 dyn_cast<CXXDestructorDecl>(NewFD)) {
9350       CXXRecordDecl *Record = Destructor->getParent();
9351       QualType ClassType = Context.getTypeDeclType(Record);
9352 
9353       // FIXME: Shouldn't we be able to perform this check even when the class
9354       // type is dependent? Both gcc and edg can handle that.
9355       if (!ClassType->isDependentType()) {
9356         DeclarationName Name
9357           = Context.DeclarationNames.getCXXDestructorName(
9358                                         Context.getCanonicalType(ClassType));
9359         if (NewFD->getDeclName() != Name) {
9360           Diag(NewFD->getLocation(), diag::err_destructor_name);
9361           NewFD->setInvalidDecl();
9362           return Redeclaration;
9363         }
9364       }
9365     } else if (CXXConversionDecl *Conversion
9366                = dyn_cast<CXXConversionDecl>(NewFD)) {
9367       ActOnConversionDeclarator(Conversion);
9368     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
9369       if (auto *TD = Guide->getDescribedFunctionTemplate())
9370         CheckDeductionGuideTemplate(TD);
9371 
9372       // A deduction guide is not on the list of entities that can be
9373       // explicitly specialized.
9374       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
9375         Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
9376             << /*explicit specialization*/ 1;
9377     }
9378 
9379     // Find any virtual functions that this function overrides.
9380     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9381       if (!Method->isFunctionTemplateSpecialization() &&
9382           !Method->getDescribedFunctionTemplate() &&
9383           Method->isCanonicalDecl()) {
9384         if (AddOverriddenMethods(Method->getParent(), Method)) {
9385           // If the function was marked as "static", we have a problem.
9386           if (NewFD->getStorageClass() == SC_Static) {
9387             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
9388           }
9389         }
9390       }
9391 
9392       if (Method->isStatic())
9393         checkThisInStaticMemberFunctionType(Method);
9394     }
9395 
9396     // Extra checking for C++ overloaded operators (C++ [over.oper]).
9397     if (NewFD->isOverloadedOperator() &&
9398         CheckOverloadedOperatorDeclaration(NewFD)) {
9399       NewFD->setInvalidDecl();
9400       return Redeclaration;
9401     }
9402 
9403     // Extra checking for C++0x literal operators (C++0x [over.literal]).
9404     if (NewFD->getLiteralIdentifier() &&
9405         CheckLiteralOperatorDeclaration(NewFD)) {
9406       NewFD->setInvalidDecl();
9407       return Redeclaration;
9408     }
9409 
9410     // In C++, check default arguments now that we have merged decls. Unless
9411     // the lexical context is the class, because in this case this is done
9412     // during delayed parsing anyway.
9413     if (!CurContext->isRecord())
9414       CheckCXXDefaultArguments(NewFD);
9415 
9416     // If this function declares a builtin function, check the type of this
9417     // declaration against the expected type for the builtin.
9418     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9419       ASTContext::GetBuiltinTypeError Error;
9420       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9421       QualType T = Context.GetBuiltinType(BuiltinID, Error);
9422       // If the type of the builtin differs only in its exception
9423       // specification, that's OK.
9424       // FIXME: If the types do differ in this way, it would be better to
9425       // retain the 'noexcept' form of the type.
9426       if (!T.isNull() &&
9427           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
9428                                                             NewFD->getType()))
9429         // The type of this function differs from the type of the builtin,
9430         // so forget about the builtin entirely.
9431         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9432     }
9433 
9434     // If this function is declared as being extern "C", then check to see if
9435     // the function returns a UDT (class, struct, or union type) that is not C
9436     // compatible, and if it does, warn the user.
9437     // But, issue any diagnostic on the first declaration only.
9438     if (Previous.empty() && NewFD->isExternC()) {
9439       QualType R = NewFD->getReturnType();
9440       if (R->isIncompleteType() && !R->isVoidType())
9441         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9442             << NewFD << R;
9443       else if (!R.isPODType(Context) && !R->isVoidType() &&
9444                !R->isObjCObjectPointerType())
9445         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9446     }
9447 
9448     // C++1z [dcl.fct]p6:
9449     //   [...] whether the function has a non-throwing exception-specification
9450     //   [is] part of the function type
9451     //
9452     // This results in an ABI break between C++14 and C++17 for functions whose
9453     // declared type includes an exception-specification in a parameter or
9454     // return type. (Exception specifications on the function itself are OK in
9455     // most cases, and exception specifications are not permitted in most other
9456     // contexts where they could make it into a mangling.)
9457     if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) {
9458       auto HasNoexcept = [&](QualType T) -> bool {
9459         // Strip off declarator chunks that could be between us and a function
9460         // type. We don't need to look far, exception specifications are very
9461         // restricted prior to C++17.
9462         if (auto *RT = T->getAs<ReferenceType>())
9463           T = RT->getPointeeType();
9464         else if (T->isAnyPointerType())
9465           T = T->getPointeeType();
9466         else if (auto *MPT = T->getAs<MemberPointerType>())
9467           T = MPT->getPointeeType();
9468         if (auto *FPT = T->getAs<FunctionProtoType>())
9469           if (FPT->isNothrow(Context))
9470             return true;
9471         return false;
9472       };
9473 
9474       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9475       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9476       for (QualType T : FPT->param_types())
9477         AnyNoexcept |= HasNoexcept(T);
9478       if (AnyNoexcept)
9479         Diag(NewFD->getLocation(),
9480              diag::warn_cxx1z_compat_exception_spec_in_signature)
9481             << NewFD;
9482     }
9483 
9484     if (!Redeclaration && LangOpts.CUDA)
9485       checkCUDATargetOverload(NewFD, Previous);
9486   }
9487   return Redeclaration;
9488 }
9489 
9490 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9491   // C++11 [basic.start.main]p3:
9492   //   A program that [...] declares main to be inline, static or
9493   //   constexpr is ill-formed.
9494   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
9495   //   appear in a declaration of main.
9496   // static main is not an error under C99, but we should warn about it.
9497   // We accept _Noreturn main as an extension.
9498   if (FD->getStorageClass() == SC_Static)
9499     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9500          ? diag::err_static_main : diag::warn_static_main)
9501       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9502   if (FD->isInlineSpecified())
9503     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9504       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9505   if (DS.isNoreturnSpecified()) {
9506     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9507     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9508     Diag(NoreturnLoc, diag::ext_noreturn_main);
9509     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9510       << FixItHint::CreateRemoval(NoreturnRange);
9511   }
9512   if (FD->isConstexpr()) {
9513     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9514       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9515     FD->setConstexpr(false);
9516   }
9517 
9518   if (getLangOpts().OpenCL) {
9519     Diag(FD->getLocation(), diag::err_opencl_no_main)
9520         << FD->hasAttr<OpenCLKernelAttr>();
9521     FD->setInvalidDecl();
9522     return;
9523   }
9524 
9525   QualType T = FD->getType();
9526   assert(T->isFunctionType() && "function decl is not of function type");
9527   const FunctionType* FT = T->castAs<FunctionType>();
9528 
9529   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9530     // In C with GNU extensions we allow main() to have non-integer return
9531     // type, but we should warn about the extension, and we disable the
9532     // implicit-return-zero rule.
9533 
9534     // GCC in C mode accepts qualified 'int'.
9535     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9536       FD->setHasImplicitReturnZero(true);
9537     else {
9538       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9539       SourceRange RTRange = FD->getReturnTypeSourceRange();
9540       if (RTRange.isValid())
9541         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9542             << FixItHint::CreateReplacement(RTRange, "int");
9543     }
9544   } else {
9545     // In C and C++, main magically returns 0 if you fall off the end;
9546     // set the flag which tells us that.
9547     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9548 
9549     // All the standards say that main() should return 'int'.
9550     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9551       FD->setHasImplicitReturnZero(true);
9552     else {
9553       // Otherwise, this is just a flat-out error.
9554       SourceRange RTRange = FD->getReturnTypeSourceRange();
9555       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9556           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9557                                 : FixItHint());
9558       FD->setInvalidDecl(true);
9559     }
9560   }
9561 
9562   // Treat protoless main() as nullary.
9563   if (isa<FunctionNoProtoType>(FT)) return;
9564 
9565   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9566   unsigned nparams = FTP->getNumParams();
9567   assert(FD->getNumParams() == nparams);
9568 
9569   bool HasExtraParameters = (nparams > 3);
9570 
9571   if (FTP->isVariadic()) {
9572     Diag(FD->getLocation(), diag::ext_variadic_main);
9573     // FIXME: if we had information about the location of the ellipsis, we
9574     // could add a FixIt hint to remove it as a parameter.
9575   }
9576 
9577   // Darwin passes an undocumented fourth argument of type char**.  If
9578   // other platforms start sprouting these, the logic below will start
9579   // getting shifty.
9580   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9581     HasExtraParameters = false;
9582 
9583   if (HasExtraParameters) {
9584     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9585     FD->setInvalidDecl(true);
9586     nparams = 3;
9587   }
9588 
9589   // FIXME: a lot of the following diagnostics would be improved
9590   // if we had some location information about types.
9591 
9592   QualType CharPP =
9593     Context.getPointerType(Context.getPointerType(Context.CharTy));
9594   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9595 
9596   for (unsigned i = 0; i < nparams; ++i) {
9597     QualType AT = FTP->getParamType(i);
9598 
9599     bool mismatch = true;
9600 
9601     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9602       mismatch = false;
9603     else if (Expected[i] == CharPP) {
9604       // As an extension, the following forms are okay:
9605       //   char const **
9606       //   char const * const *
9607       //   char * const *
9608 
9609       QualifierCollector qs;
9610       const PointerType* PT;
9611       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9612           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9613           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9614                               Context.CharTy)) {
9615         qs.removeConst();
9616         mismatch = !qs.empty();
9617       }
9618     }
9619 
9620     if (mismatch) {
9621       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9622       // TODO: suggest replacing given type with expected type
9623       FD->setInvalidDecl(true);
9624     }
9625   }
9626 
9627   if (nparams == 1 && !FD->isInvalidDecl()) {
9628     Diag(FD->getLocation(), diag::warn_main_one_arg);
9629   }
9630 
9631   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9632     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9633     FD->setInvalidDecl();
9634   }
9635 }
9636 
9637 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9638   QualType T = FD->getType();
9639   assert(T->isFunctionType() && "function decl is not of function type");
9640   const FunctionType *FT = T->castAs<FunctionType>();
9641 
9642   // Set an implicit return of 'zero' if the function can return some integral,
9643   // enumeration, pointer or nullptr type.
9644   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9645       FT->getReturnType()->isAnyPointerType() ||
9646       FT->getReturnType()->isNullPtrType())
9647     // DllMain is exempt because a return value of zero means it failed.
9648     if (FD->getName() != "DllMain")
9649       FD->setHasImplicitReturnZero(true);
9650 
9651   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9652     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9653     FD->setInvalidDecl();
9654   }
9655 }
9656 
9657 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9658   // FIXME: Need strict checking.  In C89, we need to check for
9659   // any assignment, increment, decrement, function-calls, or
9660   // commas outside of a sizeof.  In C99, it's the same list,
9661   // except that the aforementioned are allowed in unevaluated
9662   // expressions.  Everything else falls under the
9663   // "may accept other forms of constant expressions" exception.
9664   // (We never end up here for C++, so the constant expression
9665   // rules there don't matter.)
9666   const Expr *Culprit;
9667   if (Init->isConstantInitializer(Context, false, &Culprit))
9668     return false;
9669   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9670     << Culprit->getSourceRange();
9671   return true;
9672 }
9673 
9674 namespace {
9675   // Visits an initialization expression to see if OrigDecl is evaluated in
9676   // its own initialization and throws a warning if it does.
9677   class SelfReferenceChecker
9678       : public EvaluatedExprVisitor<SelfReferenceChecker> {
9679     Sema &S;
9680     Decl *OrigDecl;
9681     bool isRecordType;
9682     bool isPODType;
9683     bool isReferenceType;
9684 
9685     bool isInitList;
9686     llvm::SmallVector<unsigned, 4> InitFieldIndex;
9687 
9688   public:
9689     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9690 
9691     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9692                                                     S(S), OrigDecl(OrigDecl) {
9693       isPODType = false;
9694       isRecordType = false;
9695       isReferenceType = false;
9696       isInitList = false;
9697       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9698         isPODType = VD->getType().isPODType(S.Context);
9699         isRecordType = VD->getType()->isRecordType();
9700         isReferenceType = VD->getType()->isReferenceType();
9701       }
9702     }
9703 
9704     // For most expressions, just call the visitor.  For initializer lists,
9705     // track the index of the field being initialized since fields are
9706     // initialized in order allowing use of previously initialized fields.
9707     void CheckExpr(Expr *E) {
9708       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9709       if (!InitList) {
9710         Visit(E);
9711         return;
9712       }
9713 
9714       // Track and increment the index here.
9715       isInitList = true;
9716       InitFieldIndex.push_back(0);
9717       for (auto Child : InitList->children()) {
9718         CheckExpr(cast<Expr>(Child));
9719         ++InitFieldIndex.back();
9720       }
9721       InitFieldIndex.pop_back();
9722     }
9723 
9724     // Returns true if MemberExpr is checked and no further checking is needed.
9725     // Returns false if additional checking is required.
9726     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9727       llvm::SmallVector<FieldDecl*, 4> Fields;
9728       Expr *Base = E;
9729       bool ReferenceField = false;
9730 
9731       // Get the field memebers used.
9732       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9733         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9734         if (!FD)
9735           return false;
9736         Fields.push_back(FD);
9737         if (FD->getType()->isReferenceType())
9738           ReferenceField = true;
9739         Base = ME->getBase()->IgnoreParenImpCasts();
9740       }
9741 
9742       // Keep checking only if the base Decl is the same.
9743       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9744       if (!DRE || DRE->getDecl() != OrigDecl)
9745         return false;
9746 
9747       // A reference field can be bound to an unininitialized field.
9748       if (CheckReference && !ReferenceField)
9749         return true;
9750 
9751       // Convert FieldDecls to their index number.
9752       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9753       for (const FieldDecl *I : llvm::reverse(Fields))
9754         UsedFieldIndex.push_back(I->getFieldIndex());
9755 
9756       // See if a warning is needed by checking the first difference in index
9757       // numbers.  If field being used has index less than the field being
9758       // initialized, then the use is safe.
9759       for (auto UsedIter = UsedFieldIndex.begin(),
9760                 UsedEnd = UsedFieldIndex.end(),
9761                 OrigIter = InitFieldIndex.begin(),
9762                 OrigEnd = InitFieldIndex.end();
9763            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9764         if (*UsedIter < *OrigIter)
9765           return true;
9766         if (*UsedIter > *OrigIter)
9767           break;
9768       }
9769 
9770       // TODO: Add a different warning which will print the field names.
9771       HandleDeclRefExpr(DRE);
9772       return true;
9773     }
9774 
9775     // For most expressions, the cast is directly above the DeclRefExpr.
9776     // For conditional operators, the cast can be outside the conditional
9777     // operator if both expressions are DeclRefExpr's.
9778     void HandleValue(Expr *E) {
9779       E = E->IgnoreParens();
9780       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9781         HandleDeclRefExpr(DRE);
9782         return;
9783       }
9784 
9785       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9786         Visit(CO->getCond());
9787         HandleValue(CO->getTrueExpr());
9788         HandleValue(CO->getFalseExpr());
9789         return;
9790       }
9791 
9792       if (BinaryConditionalOperator *BCO =
9793               dyn_cast<BinaryConditionalOperator>(E)) {
9794         Visit(BCO->getCond());
9795         HandleValue(BCO->getFalseExpr());
9796         return;
9797       }
9798 
9799       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9800         HandleValue(OVE->getSourceExpr());
9801         return;
9802       }
9803 
9804       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9805         if (BO->getOpcode() == BO_Comma) {
9806           Visit(BO->getLHS());
9807           HandleValue(BO->getRHS());
9808           return;
9809         }
9810       }
9811 
9812       if (isa<MemberExpr>(E)) {
9813         if (isInitList) {
9814           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9815                                       false /*CheckReference*/))
9816             return;
9817         }
9818 
9819         Expr *Base = E->IgnoreParenImpCasts();
9820         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9821           // Check for static member variables and don't warn on them.
9822           if (!isa<FieldDecl>(ME->getMemberDecl()))
9823             return;
9824           Base = ME->getBase()->IgnoreParenImpCasts();
9825         }
9826         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9827           HandleDeclRefExpr(DRE);
9828         return;
9829       }
9830 
9831       Visit(E);
9832     }
9833 
9834     // Reference types not handled in HandleValue are handled here since all
9835     // uses of references are bad, not just r-value uses.
9836     void VisitDeclRefExpr(DeclRefExpr *E) {
9837       if (isReferenceType)
9838         HandleDeclRefExpr(E);
9839     }
9840 
9841     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9842       if (E->getCastKind() == CK_LValueToRValue) {
9843         HandleValue(E->getSubExpr());
9844         return;
9845       }
9846 
9847       Inherited::VisitImplicitCastExpr(E);
9848     }
9849 
9850     void VisitMemberExpr(MemberExpr *E) {
9851       if (isInitList) {
9852         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9853           return;
9854       }
9855 
9856       // Don't warn on arrays since they can be treated as pointers.
9857       if (E->getType()->canDecayToPointerType()) return;
9858 
9859       // Warn when a non-static method call is followed by non-static member
9860       // field accesses, which is followed by a DeclRefExpr.
9861       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9862       bool Warn = (MD && !MD->isStatic());
9863       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9864       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9865         if (!isa<FieldDecl>(ME->getMemberDecl()))
9866           Warn = false;
9867         Base = ME->getBase()->IgnoreParenImpCasts();
9868       }
9869 
9870       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9871         if (Warn)
9872           HandleDeclRefExpr(DRE);
9873         return;
9874       }
9875 
9876       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9877       // Visit that expression.
9878       Visit(Base);
9879     }
9880 
9881     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9882       Expr *Callee = E->getCallee();
9883 
9884       if (isa<UnresolvedLookupExpr>(Callee))
9885         return Inherited::VisitCXXOperatorCallExpr(E);
9886 
9887       Visit(Callee);
9888       for (auto Arg: E->arguments())
9889         HandleValue(Arg->IgnoreParenImpCasts());
9890     }
9891 
9892     void VisitUnaryOperator(UnaryOperator *E) {
9893       // For POD record types, addresses of its own members are well-defined.
9894       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9895           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9896         if (!isPODType)
9897           HandleValue(E->getSubExpr());
9898         return;
9899       }
9900 
9901       if (E->isIncrementDecrementOp()) {
9902         HandleValue(E->getSubExpr());
9903         return;
9904       }
9905 
9906       Inherited::VisitUnaryOperator(E);
9907     }
9908 
9909     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9910 
9911     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9912       if (E->getConstructor()->isCopyConstructor()) {
9913         Expr *ArgExpr = E->getArg(0);
9914         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9915           if (ILE->getNumInits() == 1)
9916             ArgExpr = ILE->getInit(0);
9917         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9918           if (ICE->getCastKind() == CK_NoOp)
9919             ArgExpr = ICE->getSubExpr();
9920         HandleValue(ArgExpr);
9921         return;
9922       }
9923       Inherited::VisitCXXConstructExpr(E);
9924     }
9925 
9926     void VisitCallExpr(CallExpr *E) {
9927       // Treat std::move as a use.
9928       if (E->getNumArgs() == 1) {
9929         if (FunctionDecl *FD = E->getDirectCallee()) {
9930           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9931               FD->getIdentifier()->isStr("move")) {
9932             HandleValue(E->getArg(0));
9933             return;
9934           }
9935         }
9936       }
9937 
9938       Inherited::VisitCallExpr(E);
9939     }
9940 
9941     void VisitBinaryOperator(BinaryOperator *E) {
9942       if (E->isCompoundAssignmentOp()) {
9943         HandleValue(E->getLHS());
9944         Visit(E->getRHS());
9945         return;
9946       }
9947 
9948       Inherited::VisitBinaryOperator(E);
9949     }
9950 
9951     // A custom visitor for BinaryConditionalOperator is needed because the
9952     // regular visitor would check the condition and true expression separately
9953     // but both point to the same place giving duplicate diagnostics.
9954     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9955       Visit(E->getCond());
9956       Visit(E->getFalseExpr());
9957     }
9958 
9959     void HandleDeclRefExpr(DeclRefExpr *DRE) {
9960       Decl* ReferenceDecl = DRE->getDecl();
9961       if (OrigDecl != ReferenceDecl) return;
9962       unsigned diag;
9963       if (isReferenceType) {
9964         diag = diag::warn_uninit_self_reference_in_reference_init;
9965       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9966         diag = diag::warn_static_self_reference_in_init;
9967       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9968                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9969                  DRE->getDecl()->getType()->isRecordType()) {
9970         diag = diag::warn_uninit_self_reference_in_init;
9971       } else {
9972         // Local variables will be handled by the CFG analysis.
9973         return;
9974       }
9975 
9976       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9977                             S.PDiag(diag)
9978                               << DRE->getNameInfo().getName()
9979                               << OrigDecl->getLocation()
9980                               << DRE->getSourceRange());
9981     }
9982   };
9983 
9984   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9985   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9986                                  bool DirectInit) {
9987     // Parameters arguments are occassionially constructed with itself,
9988     // for instance, in recursive functions.  Skip them.
9989     if (isa<ParmVarDecl>(OrigDecl))
9990       return;
9991 
9992     E = E->IgnoreParens();
9993 
9994     // Skip checking T a = a where T is not a record or reference type.
9995     // Doing so is a way to silence uninitialized warnings.
9996     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9997       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9998         if (ICE->getCastKind() == CK_LValueToRValue)
9999           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10000             if (DRE->getDecl() == OrigDecl)
10001               return;
10002 
10003     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10004   }
10005 } // end anonymous namespace
10006 
10007 namespace {
10008   // Simple wrapper to add the name of a variable or (if no variable is
10009   // available) a DeclarationName into a diagnostic.
10010   struct VarDeclOrName {
10011     VarDecl *VDecl;
10012     DeclarationName Name;
10013 
10014     friend const Sema::SemaDiagnosticBuilder &
10015     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10016       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10017     }
10018   };
10019 } // end anonymous namespace
10020 
10021 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10022                                             DeclarationName Name, QualType Type,
10023                                             TypeSourceInfo *TSI,
10024                                             SourceRange Range, bool DirectInit,
10025                                             Expr *Init) {
10026   bool IsInitCapture = !VDecl;
10027   assert((!VDecl || !VDecl->isInitCapture()) &&
10028          "init captures are expected to be deduced prior to initialization");
10029 
10030   VarDeclOrName VN{VDecl, Name};
10031 
10032   DeducedType *Deduced = Type->getContainedDeducedType();
10033   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10034 
10035   // C++11 [dcl.spec.auto]p3
10036   if (!Init) {
10037     assert(VDecl && "no init for init capture deduction?");
10038     Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10039       << VDecl->getDeclName() << Type;
10040     return QualType();
10041   }
10042 
10043   ArrayRef<Expr*> DeduceInits = Init;
10044   if (DirectInit) {
10045     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10046       DeduceInits = PL->exprs();
10047   }
10048 
10049   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10050     assert(VDecl && "non-auto type for init capture deduction?");
10051     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10052     InitializationKind Kind = InitializationKind::CreateForInit(
10053         VDecl->getLocation(), DirectInit, Init);
10054     // FIXME: Initialization should not be taking a mutable list of inits.
10055     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10056     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10057                                                        InitsCopy);
10058   }
10059 
10060   if (DirectInit) {
10061     if (auto *IL = dyn_cast<InitListExpr>(Init))
10062       DeduceInits = IL->inits();
10063   }
10064 
10065   // Deduction only works if we have exactly one source expression.
10066   if (DeduceInits.empty()) {
10067     // It isn't possible to write this directly, but it is possible to
10068     // end up in this situation with "auto x(some_pack...);"
10069     Diag(Init->getLocStart(), IsInitCapture
10070                                   ? diag::err_init_capture_no_expression
10071                                   : diag::err_auto_var_init_no_expression)
10072         << VN << Type << Range;
10073     return QualType();
10074   }
10075 
10076   if (DeduceInits.size() > 1) {
10077     Diag(DeduceInits[1]->getLocStart(),
10078          IsInitCapture ? diag::err_init_capture_multiple_expressions
10079                        : diag::err_auto_var_init_multiple_expressions)
10080         << VN << Type << Range;
10081     return QualType();
10082   }
10083 
10084   Expr *DeduceInit = DeduceInits[0];
10085   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10086     Diag(Init->getLocStart(), IsInitCapture
10087                                   ? diag::err_init_capture_paren_braces
10088                                   : diag::err_auto_var_init_paren_braces)
10089         << isa<InitListExpr>(Init) << VN << Type << Range;
10090     return QualType();
10091   }
10092 
10093   // Expressions default to 'id' when we're in a debugger.
10094   bool DefaultedAnyToId = false;
10095   if (getLangOpts().DebuggerCastResultToId &&
10096       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10097     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10098     if (Result.isInvalid()) {
10099       return QualType();
10100     }
10101     Init = Result.get();
10102     DefaultedAnyToId = true;
10103   }
10104 
10105   // C++ [dcl.decomp]p1:
10106   //   If the assignment-expression [...] has array type A and no ref-qualifier
10107   //   is present, e has type cv A
10108   if (VDecl && isa<DecompositionDecl>(VDecl) &&
10109       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10110       DeduceInit->getType()->isConstantArrayType())
10111     return Context.getQualifiedType(DeduceInit->getType(),
10112                                     Type.getQualifiers());
10113 
10114   QualType DeducedType;
10115   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
10116     if (!IsInitCapture)
10117       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
10118     else if (isa<InitListExpr>(Init))
10119       Diag(Range.getBegin(),
10120            diag::err_init_capture_deduction_failure_from_init_list)
10121           << VN
10122           << (DeduceInit->getType().isNull() ? TSI->getType()
10123                                              : DeduceInit->getType())
10124           << DeduceInit->getSourceRange();
10125     else
10126       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10127           << VN << TSI->getType()
10128           << (DeduceInit->getType().isNull() ? TSI->getType()
10129                                              : DeduceInit->getType())
10130           << DeduceInit->getSourceRange();
10131   }
10132 
10133   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10134   // 'id' instead of a specific object type prevents most of our usual
10135   // checks.
10136   // We only want to warn outside of template instantiations, though:
10137   // inside a template, the 'id' could have come from a parameter.
10138   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10139       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10140     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10141     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10142   }
10143 
10144   return DeducedType;
10145 }
10146 
10147 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
10148                                          Expr *Init) {
10149   QualType DeducedType = deduceVarTypeFromInitializer(
10150       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10151       VDecl->getSourceRange(), DirectInit, Init);
10152   if (DeducedType.isNull()) {
10153     VDecl->setInvalidDecl();
10154     return true;
10155   }
10156 
10157   VDecl->setType(DeducedType);
10158   assert(VDecl->isLinkageValid());
10159 
10160   // In ARC, infer lifetime.
10161   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10162     VDecl->setInvalidDecl();
10163 
10164   // If this is a redeclaration, check that the type we just deduced matches
10165   // the previously declared type.
10166   if (VarDecl *Old = VDecl->getPreviousDecl()) {
10167     // We never need to merge the type, because we cannot form an incomplete
10168     // array of auto, nor deduce such a type.
10169     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
10170   }
10171 
10172   // Check the deduced type is valid for a variable declaration.
10173   CheckVariableDeclarationType(VDecl);
10174   return VDecl->isInvalidDecl();
10175 }
10176 
10177 /// AddInitializerToDecl - Adds the initializer Init to the
10178 /// declaration dcl. If DirectInit is true, this is C++ direct
10179 /// initialization rather than copy initialization.
10180 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10181   // If there is no declaration, there was an error parsing it.  Just ignore
10182   // the initializer.
10183   if (!RealDecl || RealDecl->isInvalidDecl()) {
10184     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10185     return;
10186   }
10187 
10188   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10189     // Pure-specifiers are handled in ActOnPureSpecifier.
10190     Diag(Method->getLocation(), diag::err_member_function_initialization)
10191       << Method->getDeclName() << Init->getSourceRange();
10192     Method->setInvalidDecl();
10193     return;
10194   }
10195 
10196   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
10197   if (!VDecl) {
10198     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
10199     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
10200     RealDecl->setInvalidDecl();
10201     return;
10202   }
10203 
10204   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
10205   if (VDecl->getType()->isUndeducedType()) {
10206     // Attempt typo correction early so that the type of the init expression can
10207     // be deduced based on the chosen correction if the original init contains a
10208     // TypoExpr.
10209     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
10210     if (!Res.isUsable()) {
10211       RealDecl->setInvalidDecl();
10212       return;
10213     }
10214     Init = Res.get();
10215 
10216     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
10217       return;
10218   }
10219 
10220   // dllimport cannot be used on variable definitions.
10221   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
10222     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
10223     VDecl->setInvalidDecl();
10224     return;
10225   }
10226 
10227   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
10228     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
10229     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
10230     VDecl->setInvalidDecl();
10231     return;
10232   }
10233 
10234   if (!VDecl->getType()->isDependentType()) {
10235     // A definition must end up with a complete type, which means it must be
10236     // complete with the restriction that an array type might be completed by
10237     // the initializer; note that later code assumes this restriction.
10238     QualType BaseDeclType = VDecl->getType();
10239     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
10240       BaseDeclType = Array->getElementType();
10241     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
10242                             diag::err_typecheck_decl_incomplete_type)) {
10243       RealDecl->setInvalidDecl();
10244       return;
10245     }
10246 
10247     // The variable can not have an abstract class type.
10248     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
10249                                diag::err_abstract_type_in_decl,
10250                                AbstractVariableType))
10251       VDecl->setInvalidDecl();
10252   }
10253 
10254   // If adding the initializer will turn this declaration into a definition,
10255   // and we already have a definition for this variable, diagnose or otherwise
10256   // handle the situation.
10257   VarDecl *Def;
10258   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
10259       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
10260       !VDecl->isThisDeclarationADemotedDefinition() &&
10261       checkVarDeclRedefinition(Def, VDecl))
10262     return;
10263 
10264   if (getLangOpts().CPlusPlus) {
10265     // C++ [class.static.data]p4
10266     //   If a static data member is of const integral or const
10267     //   enumeration type, its declaration in the class definition can
10268     //   specify a constant-initializer which shall be an integral
10269     //   constant expression (5.19). In that case, the member can appear
10270     //   in integral constant expressions. The member shall still be
10271     //   defined in a namespace scope if it is used in the program and the
10272     //   namespace scope definition shall not contain an initializer.
10273     //
10274     // We already performed a redefinition check above, but for static
10275     // data members we also need to check whether there was an in-class
10276     // declaration with an initializer.
10277     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
10278       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
10279           << VDecl->getDeclName();
10280       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
10281            diag::note_previous_initializer)
10282           << 0;
10283       return;
10284     }
10285 
10286     if (VDecl->hasLocalStorage())
10287       getCurFunction()->setHasBranchProtectedScope();
10288 
10289     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
10290       VDecl->setInvalidDecl();
10291       return;
10292     }
10293   }
10294 
10295   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
10296   // a kernel function cannot be initialized."
10297   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
10298     Diag(VDecl->getLocation(), diag::err_local_cant_init);
10299     VDecl->setInvalidDecl();
10300     return;
10301   }
10302 
10303   // Get the decls type and save a reference for later, since
10304   // CheckInitializerTypes may change it.
10305   QualType DclT = VDecl->getType(), SavT = DclT;
10306 
10307   // Expressions default to 'id' when we're in a debugger
10308   // and we are assigning it to a variable of Objective-C pointer type.
10309   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
10310       Init->getType() == Context.UnknownAnyTy) {
10311     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10312     if (Result.isInvalid()) {
10313       VDecl->setInvalidDecl();
10314       return;
10315     }
10316     Init = Result.get();
10317   }
10318 
10319   // Perform the initialization.
10320   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
10321   if (!VDecl->isInvalidDecl()) {
10322     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10323     InitializationKind Kind = InitializationKind::CreateForInit(
10324         VDecl->getLocation(), DirectInit, Init);
10325 
10326     MultiExprArg Args = Init;
10327     if (CXXDirectInit)
10328       Args = MultiExprArg(CXXDirectInit->getExprs(),
10329                           CXXDirectInit->getNumExprs());
10330 
10331     // Try to correct any TypoExprs in the initialization arguments.
10332     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
10333       ExprResult Res = CorrectDelayedTyposInExpr(
10334           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
10335             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
10336             return Init.Failed() ? ExprError() : E;
10337           });
10338       if (Res.isInvalid()) {
10339         VDecl->setInvalidDecl();
10340       } else if (Res.get() != Args[Idx]) {
10341         Args[Idx] = Res.get();
10342       }
10343     }
10344     if (VDecl->isInvalidDecl())
10345       return;
10346 
10347     InitializationSequence InitSeq(*this, Entity, Kind, Args,
10348                                    /*TopLevelOfInitList=*/false,
10349                                    /*TreatUnavailableAsInvalid=*/false);
10350     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
10351     if (Result.isInvalid()) {
10352       VDecl->setInvalidDecl();
10353       return;
10354     }
10355 
10356     Init = Result.getAs<Expr>();
10357   }
10358 
10359   // Check for self-references within variable initializers.
10360   // Variables declared within a function/method body (except for references)
10361   // are handled by a dataflow analysis.
10362   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
10363       VDecl->getType()->isReferenceType()) {
10364     CheckSelfReference(*this, RealDecl, Init, DirectInit);
10365   }
10366 
10367   // If the type changed, it means we had an incomplete type that was
10368   // completed by the initializer. For example:
10369   //   int ary[] = { 1, 3, 5 };
10370   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
10371   if (!VDecl->isInvalidDecl() && (DclT != SavT))
10372     VDecl->setType(DclT);
10373 
10374   if (!VDecl->isInvalidDecl()) {
10375     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
10376 
10377     if (VDecl->hasAttr<BlocksAttr>())
10378       checkRetainCycles(VDecl, Init);
10379 
10380     // It is safe to assign a weak reference into a strong variable.
10381     // Although this code can still have problems:
10382     //   id x = self.weakProp;
10383     //   id y = self.weakProp;
10384     // we do not warn to warn spuriously when 'x' and 'y' are on separate
10385     // paths through the function. This should be revisited if
10386     // -Wrepeated-use-of-weak is made flow-sensitive.
10387     if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
10388          VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
10389         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10390                          Init->getLocStart()))
10391       getCurFunction()->markSafeWeakUse(Init);
10392   }
10393 
10394   // The initialization is usually a full-expression.
10395   //
10396   // FIXME: If this is a braced initialization of an aggregate, it is not
10397   // an expression, and each individual field initializer is a separate
10398   // full-expression. For instance, in:
10399   //
10400   //   struct Temp { ~Temp(); };
10401   //   struct S { S(Temp); };
10402   //   struct T { S a, b; } t = { Temp(), Temp() }
10403   //
10404   // we should destroy the first Temp before constructing the second.
10405   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10406                                           false,
10407                                           VDecl->isConstexpr());
10408   if (Result.isInvalid()) {
10409     VDecl->setInvalidDecl();
10410     return;
10411   }
10412   Init = Result.get();
10413 
10414   // Attach the initializer to the decl.
10415   VDecl->setInit(Init);
10416 
10417   if (VDecl->isLocalVarDecl()) {
10418     // Don't check the initializer if the declaration is malformed.
10419     if (VDecl->isInvalidDecl()) {
10420       // do nothing
10421 
10422     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
10423     // This is true even in OpenCL C++.
10424     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
10425       CheckForConstantInitializer(Init, DclT);
10426 
10427     // Otherwise, C++ does not restrict the initializer.
10428     } else if (getLangOpts().CPlusPlus) {
10429       // do nothing
10430 
10431     // C99 6.7.8p4: All the expressions in an initializer for an object that has
10432     // static storage duration shall be constant expressions or string literals.
10433     } else if (VDecl->getStorageClass() == SC_Static) {
10434       CheckForConstantInitializer(Init, DclT);
10435 
10436     // C89 is stricter than C99 for aggregate initializers.
10437     // C89 6.5.7p3: All the expressions [...] in an initializer list
10438     // for an object that has aggregate or union type shall be
10439     // constant expressions.
10440     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10441                isa<InitListExpr>(Init)) {
10442       const Expr *Culprit;
10443       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
10444         Diag(Culprit->getExprLoc(),
10445              diag::ext_aggregate_init_not_constant)
10446           << Culprit->getSourceRange();
10447       }
10448     }
10449   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10450              VDecl->getLexicalDeclContext()->isRecord()) {
10451     // This is an in-class initialization for a static data member, e.g.,
10452     //
10453     // struct S {
10454     //   static const int value = 17;
10455     // };
10456 
10457     // C++ [class.mem]p4:
10458     //   A member-declarator can contain a constant-initializer only
10459     //   if it declares a static member (9.4) of const integral or
10460     //   const enumeration type, see 9.4.2.
10461     //
10462     // C++11 [class.static.data]p3:
10463     //   If a non-volatile non-inline const static data member is of integral
10464     //   or enumeration type, its declaration in the class definition can
10465     //   specify a brace-or-equal-initializer in which every initializer-clause
10466     //   that is an assignment-expression is a constant expression. A static
10467     //   data member of literal type can be declared in the class definition
10468     //   with the constexpr specifier; if so, its declaration shall specify a
10469     //   brace-or-equal-initializer in which every initializer-clause that is
10470     //   an assignment-expression is a constant expression.
10471 
10472     // Do nothing on dependent types.
10473     if (DclT->isDependentType()) {
10474 
10475     // Allow any 'static constexpr' members, whether or not they are of literal
10476     // type. We separately check that every constexpr variable is of literal
10477     // type.
10478     } else if (VDecl->isConstexpr()) {
10479 
10480     // Require constness.
10481     } else if (!DclT.isConstQualified()) {
10482       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10483         << Init->getSourceRange();
10484       VDecl->setInvalidDecl();
10485 
10486     // We allow integer constant expressions in all cases.
10487     } else if (DclT->isIntegralOrEnumerationType()) {
10488       // Check whether the expression is a constant expression.
10489       SourceLocation Loc;
10490       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10491         // In C++11, a non-constexpr const static data member with an
10492         // in-class initializer cannot be volatile.
10493         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10494       else if (Init->isValueDependent())
10495         ; // Nothing to check.
10496       else if (Init->isIntegerConstantExpr(Context, &Loc))
10497         ; // Ok, it's an ICE!
10498       else if (Init->isEvaluatable(Context)) {
10499         // If we can constant fold the initializer through heroics, accept it,
10500         // but report this as a use of an extension for -pedantic.
10501         Diag(Loc, diag::ext_in_class_initializer_non_constant)
10502           << Init->getSourceRange();
10503       } else {
10504         // Otherwise, this is some crazy unknown case.  Report the issue at the
10505         // location provided by the isIntegerConstantExpr failed check.
10506         Diag(Loc, diag::err_in_class_initializer_non_constant)
10507           << Init->getSourceRange();
10508         VDecl->setInvalidDecl();
10509       }
10510 
10511     // We allow foldable floating-point constants as an extension.
10512     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10513       // In C++98, this is a GNU extension. In C++11, it is not, but we support
10514       // it anyway and provide a fixit to add the 'constexpr'.
10515       if (getLangOpts().CPlusPlus11) {
10516         Diag(VDecl->getLocation(),
10517              diag::ext_in_class_initializer_float_type_cxx11)
10518             << DclT << Init->getSourceRange();
10519         Diag(VDecl->getLocStart(),
10520              diag::note_in_class_initializer_float_type_cxx11)
10521             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10522       } else {
10523         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10524           << DclT << Init->getSourceRange();
10525 
10526         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10527           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10528             << Init->getSourceRange();
10529           VDecl->setInvalidDecl();
10530         }
10531       }
10532 
10533     // Suggest adding 'constexpr' in C++11 for literal types.
10534     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10535       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10536         << DclT << Init->getSourceRange()
10537         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10538       VDecl->setConstexpr(true);
10539 
10540     } else {
10541       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10542         << DclT << Init->getSourceRange();
10543       VDecl->setInvalidDecl();
10544     }
10545   } else if (VDecl->isFileVarDecl()) {
10546     // In C, extern is typically used to avoid tentative definitions when
10547     // declaring variables in headers, but adding an intializer makes it a
10548     // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
10549     // In C++, extern is often used to give implictly static const variables
10550     // external linkage, so don't warn in that case. If selectany is present,
10551     // this might be header code intended for C and C++ inclusion, so apply the
10552     // C++ rules.
10553     if (VDecl->getStorageClass() == SC_Extern &&
10554         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10555          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10556         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10557         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10558       Diag(VDecl->getLocation(), diag::warn_extern_init);
10559 
10560     // C99 6.7.8p4. All file scoped initializers need to be constant.
10561     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10562       CheckForConstantInitializer(Init, DclT);
10563   }
10564 
10565   // We will represent direct-initialization similarly to copy-initialization:
10566   //    int x(1);  -as-> int x = 1;
10567   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10568   //
10569   // Clients that want to distinguish between the two forms, can check for
10570   // direct initializer using VarDecl::getInitStyle().
10571   // A major benefit is that clients that don't particularly care about which
10572   // exactly form was it (like the CodeGen) can handle both cases without
10573   // special case code.
10574 
10575   // C++ 8.5p11:
10576   // The form of initialization (using parentheses or '=') is generally
10577   // insignificant, but does matter when the entity being initialized has a
10578   // class type.
10579   if (CXXDirectInit) {
10580     assert(DirectInit && "Call-style initializer must be direct init.");
10581     VDecl->setInitStyle(VarDecl::CallInit);
10582   } else if (DirectInit) {
10583     // This must be list-initialization. No other way is direct-initialization.
10584     VDecl->setInitStyle(VarDecl::ListInit);
10585   }
10586 
10587   CheckCompleteVariableDeclaration(VDecl);
10588 }
10589 
10590 /// ActOnInitializerError - Given that there was an error parsing an
10591 /// initializer for the given declaration, try to return to some form
10592 /// of sanity.
10593 void Sema::ActOnInitializerError(Decl *D) {
10594   // Our main concern here is re-establishing invariants like "a
10595   // variable's type is either dependent or complete".
10596   if (!D || D->isInvalidDecl()) return;
10597 
10598   VarDecl *VD = dyn_cast<VarDecl>(D);
10599   if (!VD) return;
10600 
10601   // Bindings are not usable if we can't make sense of the initializer.
10602   if (auto *DD = dyn_cast<DecompositionDecl>(D))
10603     for (auto *BD : DD->bindings())
10604       BD->setInvalidDecl();
10605 
10606   // Auto types are meaningless if we can't make sense of the initializer.
10607   if (ParsingInitForAutoVars.count(D)) {
10608     D->setInvalidDecl();
10609     return;
10610   }
10611 
10612   QualType Ty = VD->getType();
10613   if (Ty->isDependentType()) return;
10614 
10615   // Require a complete type.
10616   if (RequireCompleteType(VD->getLocation(),
10617                           Context.getBaseElementType(Ty),
10618                           diag::err_typecheck_decl_incomplete_type)) {
10619     VD->setInvalidDecl();
10620     return;
10621   }
10622 
10623   // Require a non-abstract type.
10624   if (RequireNonAbstractType(VD->getLocation(), Ty,
10625                              diag::err_abstract_type_in_decl,
10626                              AbstractVariableType)) {
10627     VD->setInvalidDecl();
10628     return;
10629   }
10630 
10631   // Don't bother complaining about constructors or destructors,
10632   // though.
10633 }
10634 
10635 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
10636   // If there is no declaration, there was an error parsing it. Just ignore it.
10637   if (!RealDecl)
10638     return;
10639 
10640   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
10641     QualType Type = Var->getType();
10642 
10643     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
10644     if (isa<DecompositionDecl>(RealDecl)) {
10645       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
10646       Var->setInvalidDecl();
10647       return;
10648     }
10649 
10650     if (Type->isUndeducedType() &&
10651         DeduceVariableDeclarationType(Var, false, nullptr))
10652       return;
10653 
10654     // C++11 [class.static.data]p3: A static data member can be declared with
10655     // the constexpr specifier; if so, its declaration shall specify
10656     // a brace-or-equal-initializer.
10657     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10658     // the definition of a variable [...] or the declaration of a static data
10659     // member.
10660     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
10661         !Var->isThisDeclarationADemotedDefinition()) {
10662       if (Var->isStaticDataMember()) {
10663         // C++1z removes the relevant rule; the in-class declaration is always
10664         // a definition there.
10665         if (!getLangOpts().CPlusPlus1z) {
10666           Diag(Var->getLocation(),
10667                diag::err_constexpr_static_mem_var_requires_init)
10668             << Var->getDeclName();
10669           Var->setInvalidDecl();
10670           return;
10671         }
10672       } else {
10673         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10674         Var->setInvalidDecl();
10675         return;
10676       }
10677     }
10678 
10679     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
10680     // definition having the concept specifier is called a variable concept. A
10681     // concept definition refers to [...] a variable concept and its initializer.
10682     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10683       if (VTD->isConcept()) {
10684         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10685         Var->setInvalidDecl();
10686         return;
10687       }
10688     }
10689 
10690     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10691     // be initialized.
10692     if (!Var->isInvalidDecl() &&
10693         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10694         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10695       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10696       Var->setInvalidDecl();
10697       return;
10698     }
10699 
10700     switch (Var->isThisDeclarationADefinition()) {
10701     case VarDecl::Definition:
10702       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10703         break;
10704 
10705       // We have an out-of-line definition of a static data member
10706       // that has an in-class initializer, so we type-check this like
10707       // a declaration.
10708       //
10709       // Fall through
10710 
10711     case VarDecl::DeclarationOnly:
10712       // It's only a declaration.
10713 
10714       // Block scope. C99 6.7p7: If an identifier for an object is
10715       // declared with no linkage (C99 6.2.2p6), the type for the
10716       // object shall be complete.
10717       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10718           !Var->hasLinkage() && !Var->isInvalidDecl() &&
10719           RequireCompleteType(Var->getLocation(), Type,
10720                               diag::err_typecheck_decl_incomplete_type))
10721         Var->setInvalidDecl();
10722 
10723       // Make sure that the type is not abstract.
10724       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10725           RequireNonAbstractType(Var->getLocation(), Type,
10726                                  diag::err_abstract_type_in_decl,
10727                                  AbstractVariableType))
10728         Var->setInvalidDecl();
10729       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10730           Var->getStorageClass() == SC_PrivateExtern) {
10731         Diag(Var->getLocation(), diag::warn_private_extern);
10732         Diag(Var->getLocation(), diag::note_private_extern);
10733       }
10734 
10735       return;
10736 
10737     case VarDecl::TentativeDefinition:
10738       // File scope. C99 6.9.2p2: A declaration of an identifier for an
10739       // object that has file scope without an initializer, and without a
10740       // storage-class specifier or with the storage-class specifier "static",
10741       // constitutes a tentative definition. Note: A tentative definition with
10742       // external linkage is valid (C99 6.2.2p5).
10743       if (!Var->isInvalidDecl()) {
10744         if (const IncompleteArrayType *ArrayT
10745                                     = Context.getAsIncompleteArrayType(Type)) {
10746           if (RequireCompleteType(Var->getLocation(),
10747                                   ArrayT->getElementType(),
10748                                   diag::err_illegal_decl_array_incomplete_type))
10749             Var->setInvalidDecl();
10750         } else if (Var->getStorageClass() == SC_Static) {
10751           // C99 6.9.2p3: If the declaration of an identifier for an object is
10752           // a tentative definition and has internal linkage (C99 6.2.2p3), the
10753           // declared type shall not be an incomplete type.
10754           // NOTE: code such as the following
10755           //     static struct s;
10756           //     struct s { int a; };
10757           // is accepted by gcc. Hence here we issue a warning instead of
10758           // an error and we do not invalidate the static declaration.
10759           // NOTE: to avoid multiple warnings, only check the first declaration.
10760           if (Var->isFirstDecl())
10761             RequireCompleteType(Var->getLocation(), Type,
10762                                 diag::ext_typecheck_decl_incomplete_type);
10763         }
10764       }
10765 
10766       // Record the tentative definition; we're done.
10767       if (!Var->isInvalidDecl())
10768         TentativeDefinitions.push_back(Var);
10769       return;
10770     }
10771 
10772     // Provide a specific diagnostic for uninitialized variable
10773     // definitions with incomplete array type.
10774     if (Type->isIncompleteArrayType()) {
10775       Diag(Var->getLocation(),
10776            diag::err_typecheck_incomplete_array_needs_initializer);
10777       Var->setInvalidDecl();
10778       return;
10779     }
10780 
10781     // Provide a specific diagnostic for uninitialized variable
10782     // definitions with reference type.
10783     if (Type->isReferenceType()) {
10784       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10785         << Var->getDeclName()
10786         << SourceRange(Var->getLocation(), Var->getLocation());
10787       Var->setInvalidDecl();
10788       return;
10789     }
10790 
10791     // Do not attempt to type-check the default initializer for a
10792     // variable with dependent type.
10793     if (Type->isDependentType())
10794       return;
10795 
10796     if (Var->isInvalidDecl())
10797       return;
10798 
10799     if (!Var->hasAttr<AliasAttr>()) {
10800       if (RequireCompleteType(Var->getLocation(),
10801                               Context.getBaseElementType(Type),
10802                               diag::err_typecheck_decl_incomplete_type)) {
10803         Var->setInvalidDecl();
10804         return;
10805       }
10806     } else {
10807       return;
10808     }
10809 
10810     // The variable can not have an abstract class type.
10811     if (RequireNonAbstractType(Var->getLocation(), Type,
10812                                diag::err_abstract_type_in_decl,
10813                                AbstractVariableType)) {
10814       Var->setInvalidDecl();
10815       return;
10816     }
10817 
10818     // Check for jumps past the implicit initializer.  C++0x
10819     // clarifies that this applies to a "variable with automatic
10820     // storage duration", not a "local variable".
10821     // C++11 [stmt.dcl]p3
10822     //   A program that jumps from a point where a variable with automatic
10823     //   storage duration is not in scope to a point where it is in scope is
10824     //   ill-formed unless the variable has scalar type, class type with a
10825     //   trivial default constructor and a trivial destructor, a cv-qualified
10826     //   version of one of these types, or an array of one of the preceding
10827     //   types and is declared without an initializer.
10828     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10829       if (const RecordType *Record
10830             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10831         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10832         // Mark the function for further checking even if the looser rules of
10833         // C++11 do not require such checks, so that we can diagnose
10834         // incompatibilities with C++98.
10835         if (!CXXRecord->isPOD())
10836           getCurFunction()->setHasBranchProtectedScope();
10837       }
10838     }
10839 
10840     // C++03 [dcl.init]p9:
10841     //   If no initializer is specified for an object, and the
10842     //   object is of (possibly cv-qualified) non-POD class type (or
10843     //   array thereof), the object shall be default-initialized; if
10844     //   the object is of const-qualified type, the underlying class
10845     //   type shall have a user-declared default
10846     //   constructor. Otherwise, if no initializer is specified for
10847     //   a non- static object, the object and its subobjects, if
10848     //   any, have an indeterminate initial value); if the object
10849     //   or any of its subobjects are of const-qualified type, the
10850     //   program is ill-formed.
10851     // C++0x [dcl.init]p11:
10852     //   If no initializer is specified for an object, the object is
10853     //   default-initialized; [...].
10854     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10855     InitializationKind Kind
10856       = InitializationKind::CreateDefault(Var->getLocation());
10857 
10858     InitializationSequence InitSeq(*this, Entity, Kind, None);
10859     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10860     if (Init.isInvalid())
10861       Var->setInvalidDecl();
10862     else if (Init.get()) {
10863       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10864       // This is important for template substitution.
10865       Var->setInitStyle(VarDecl::CallInit);
10866     }
10867 
10868     CheckCompleteVariableDeclaration(Var);
10869   }
10870 }
10871 
10872 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10873   // If there is no declaration, there was an error parsing it. Ignore it.
10874   if (!D)
10875     return;
10876 
10877   VarDecl *VD = dyn_cast<VarDecl>(D);
10878   if (!VD) {
10879     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10880     D->setInvalidDecl();
10881     return;
10882   }
10883 
10884   VD->setCXXForRangeDecl(true);
10885 
10886   // for-range-declaration cannot be given a storage class specifier.
10887   int Error = -1;
10888   switch (VD->getStorageClass()) {
10889   case SC_None:
10890     break;
10891   case SC_Extern:
10892     Error = 0;
10893     break;
10894   case SC_Static:
10895     Error = 1;
10896     break;
10897   case SC_PrivateExtern:
10898     Error = 2;
10899     break;
10900   case SC_Auto:
10901     Error = 3;
10902     break;
10903   case SC_Register:
10904     Error = 4;
10905     break;
10906   }
10907   if (Error != -1) {
10908     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10909       << VD->getDeclName() << Error;
10910     D->setInvalidDecl();
10911   }
10912 }
10913 
10914 StmtResult
10915 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10916                                  IdentifierInfo *Ident,
10917                                  ParsedAttributes &Attrs,
10918                                  SourceLocation AttrEnd) {
10919   // C++1y [stmt.iter]p1:
10920   //   A range-based for statement of the form
10921   //      for ( for-range-identifier : for-range-initializer ) statement
10922   //   is equivalent to
10923   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
10924   DeclSpec DS(Attrs.getPool().getFactory());
10925 
10926   const char *PrevSpec;
10927   unsigned DiagID;
10928   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10929                      getPrintingPolicy());
10930 
10931   Declarator D(DS, Declarator::ForContext);
10932   D.SetIdentifier(Ident, IdentLoc);
10933   D.takeAttributes(Attrs, AttrEnd);
10934 
10935   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10936   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10937                 EmptyAttrs, IdentLoc);
10938   Decl *Var = ActOnDeclarator(S, D);
10939   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10940   FinalizeDeclaration(Var);
10941   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10942                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
10943 }
10944 
10945 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10946   if (var->isInvalidDecl()) return;
10947 
10948   if (getLangOpts().OpenCL) {
10949     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10950     // initialiser
10951     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10952         !var->hasInit()) {
10953       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10954           << 1 /*Init*/;
10955       var->setInvalidDecl();
10956       return;
10957     }
10958   }
10959 
10960   // In Objective-C, don't allow jumps past the implicit initialization of a
10961   // local retaining variable.
10962   if (getLangOpts().ObjC1 &&
10963       var->hasLocalStorage()) {
10964     switch (var->getType().getObjCLifetime()) {
10965     case Qualifiers::OCL_None:
10966     case Qualifiers::OCL_ExplicitNone:
10967     case Qualifiers::OCL_Autoreleasing:
10968       break;
10969 
10970     case Qualifiers::OCL_Weak:
10971     case Qualifiers::OCL_Strong:
10972       getCurFunction()->setHasBranchProtectedScope();
10973       break;
10974     }
10975   }
10976 
10977   // Warn about externally-visible variables being defined without a
10978   // prior declaration.  We only want to do this for global
10979   // declarations, but we also specifically need to avoid doing it for
10980   // class members because the linkage of an anonymous class can
10981   // change if it's later given a typedef name.
10982   if (var->isThisDeclarationADefinition() &&
10983       var->getDeclContext()->getRedeclContext()->isFileContext() &&
10984       var->isExternallyVisible() && var->hasLinkage() &&
10985       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10986                                   var->getLocation())) {
10987     // Find a previous declaration that's not a definition.
10988     VarDecl *prev = var->getPreviousDecl();
10989     while (prev && prev->isThisDeclarationADefinition())
10990       prev = prev->getPreviousDecl();
10991 
10992     if (!prev)
10993       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10994   }
10995 
10996   // Cache the result of checking for constant initialization.
10997   Optional<bool> CacheHasConstInit;
10998   const Expr *CacheCulprit;
10999   auto checkConstInit = [&]() mutable {
11000     if (!CacheHasConstInit)
11001       CacheHasConstInit = var->getInit()->isConstantInitializer(
11002             Context, var->getType()->isReferenceType(), &CacheCulprit);
11003     return *CacheHasConstInit;
11004   };
11005 
11006   if (var->getTLSKind() == VarDecl::TLS_Static) {
11007     if (var->getType().isDestructedType()) {
11008       // GNU C++98 edits for __thread, [basic.start.term]p3:
11009       //   The type of an object with thread storage duration shall not
11010       //   have a non-trivial destructor.
11011       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11012       if (getLangOpts().CPlusPlus11)
11013         Diag(var->getLocation(), diag::note_use_thread_local);
11014     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11015       if (!checkConstInit()) {
11016         // GNU C++98 edits for __thread, [basic.start.init]p4:
11017         //   An object of thread storage duration shall not require dynamic
11018         //   initialization.
11019         // FIXME: Need strict checking here.
11020         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11021           << CacheCulprit->getSourceRange();
11022         if (getLangOpts().CPlusPlus11)
11023           Diag(var->getLocation(), diag::note_use_thread_local);
11024       }
11025     }
11026   }
11027 
11028   // Apply section attributes and pragmas to global variables.
11029   bool GlobalStorage = var->hasGlobalStorage();
11030   if (GlobalStorage && var->isThisDeclarationADefinition() &&
11031       !inTemplateInstantiation()) {
11032     PragmaStack<StringLiteral *> *Stack = nullptr;
11033     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11034     if (var->getType().isConstQualified())
11035       Stack = &ConstSegStack;
11036     else if (!var->getInit()) {
11037       Stack = &BSSSegStack;
11038       SectionFlags |= ASTContext::PSF_Write;
11039     } else {
11040       Stack = &DataSegStack;
11041       SectionFlags |= ASTContext::PSF_Write;
11042     }
11043     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11044       var->addAttr(SectionAttr::CreateImplicit(
11045           Context, SectionAttr::Declspec_allocate,
11046           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11047     }
11048     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11049       if (UnifySection(SA->getName(), SectionFlags, var))
11050         var->dropAttr<SectionAttr>();
11051 
11052     // Apply the init_seg attribute if this has an initializer.  If the
11053     // initializer turns out to not be dynamic, we'll end up ignoring this
11054     // attribute.
11055     if (CurInitSeg && var->getInit())
11056       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11057                                                CurInitSegLoc));
11058   }
11059 
11060   // All the following checks are C++ only.
11061   if (!getLangOpts().CPlusPlus) {
11062       // If this variable must be emitted, add it as an initializer for the
11063       // current module.
11064      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11065        Context.addModuleInitializer(ModuleScopes.back().Module, var);
11066      return;
11067   }
11068 
11069   if (auto *DD = dyn_cast<DecompositionDecl>(var))
11070     CheckCompleteDecompositionDeclaration(DD);
11071 
11072   QualType type = var->getType();
11073   if (type->isDependentType()) return;
11074 
11075   // __block variables might require us to capture a copy-initializer.
11076   if (var->hasAttr<BlocksAttr>()) {
11077     // It's currently invalid to ever have a __block variable with an
11078     // array type; should we diagnose that here?
11079 
11080     // Regardless, we don't want to ignore array nesting when
11081     // constructing this copy.
11082     if (type->isStructureOrClassType()) {
11083       EnterExpressionEvaluationContext scope(
11084           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
11085       SourceLocation poi = var->getLocation();
11086       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
11087       ExprResult result
11088         = PerformMoveOrCopyInitialization(
11089             InitializedEntity::InitializeBlock(poi, type, false),
11090             var, var->getType(), varRef, /*AllowNRVO=*/true);
11091       if (!result.isInvalid()) {
11092         result = MaybeCreateExprWithCleanups(result);
11093         Expr *init = result.getAs<Expr>();
11094         Context.setBlockVarCopyInits(var, init);
11095       }
11096     }
11097   }
11098 
11099   Expr *Init = var->getInit();
11100   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11101   QualType baseType = Context.getBaseElementType(type);
11102 
11103   if (Init && !Init->isValueDependent()) {
11104     if (var->isConstexpr()) {
11105       SmallVector<PartialDiagnosticAt, 8> Notes;
11106       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11107         SourceLocation DiagLoc = var->getLocation();
11108         // If the note doesn't add any useful information other than a source
11109         // location, fold it into the primary diagnostic.
11110         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11111               diag::note_invalid_subexpr_in_const_expr) {
11112           DiagLoc = Notes[0].first;
11113           Notes.clear();
11114         }
11115         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11116           << var << Init->getSourceRange();
11117         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11118           Diag(Notes[I].first, Notes[I].second);
11119       }
11120     } else if (var->isUsableInConstantExpressions(Context)) {
11121       // Check whether the initializer of a const variable of integral or
11122       // enumeration type is an ICE now, since we can't tell whether it was
11123       // initialized by a constant expression if we check later.
11124       var->checkInitIsICE();
11125     }
11126 
11127     // Don't emit further diagnostics about constexpr globals since they
11128     // were just diagnosed.
11129     if (!var->isConstexpr() && GlobalStorage &&
11130             var->hasAttr<RequireConstantInitAttr>()) {
11131       // FIXME: Need strict checking in C++03 here.
11132       bool DiagErr = getLangOpts().CPlusPlus11
11133           ? !var->checkInitIsICE() : !checkConstInit();
11134       if (DiagErr) {
11135         auto attr = var->getAttr<RequireConstantInitAttr>();
11136         Diag(var->getLocation(), diag::err_require_constant_init_failed)
11137           << Init->getSourceRange();
11138         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11139           << attr->getRange();
11140         if (getLangOpts().CPlusPlus11) {
11141           APValue Value;
11142           SmallVector<PartialDiagnosticAt, 8> Notes;
11143           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11144           for (auto &it : Notes)
11145             Diag(it.first, it.second);
11146         } else {
11147           Diag(CacheCulprit->getExprLoc(),
11148                diag::note_invalid_subexpr_in_const_expr)
11149               << CacheCulprit->getSourceRange();
11150         }
11151       }
11152     }
11153     else if (!var->isConstexpr() && IsGlobal &&
11154              !getDiagnostics().isIgnored(diag::warn_global_constructor,
11155                                     var->getLocation())) {
11156       // Warn about globals which don't have a constant initializer.  Don't
11157       // warn about globals with a non-trivial destructor because we already
11158       // warned about them.
11159       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11160       if (!(RD && !RD->hasTrivialDestructor())) {
11161         if (!checkConstInit())
11162           Diag(var->getLocation(), diag::warn_global_constructor)
11163             << Init->getSourceRange();
11164       }
11165     }
11166   }
11167 
11168   // Require the destructor.
11169   if (const RecordType *recordType = baseType->getAs<RecordType>())
11170     FinalizeVarWithDestructor(var, recordType);
11171 
11172   // If this variable must be emitted, add it as an initializer for the current
11173   // module.
11174   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11175     Context.addModuleInitializer(ModuleScopes.back().Module, var);
11176 }
11177 
11178 /// \brief Determines if a variable's alignment is dependent.
11179 static bool hasDependentAlignment(VarDecl *VD) {
11180   if (VD->getType()->isDependentType())
11181     return true;
11182   for (auto *I : VD->specific_attrs<AlignedAttr>())
11183     if (I->isAlignmentDependent())
11184       return true;
11185   return false;
11186 }
11187 
11188 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
11189 /// any semantic actions necessary after any initializer has been attached.
11190 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
11191   // Note that we are no longer parsing the initializer for this declaration.
11192   ParsingInitForAutoVars.erase(ThisDecl);
11193 
11194   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
11195   if (!VD)
11196     return;
11197 
11198   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
11199   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
11200       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
11201     if (PragmaClangBSSSection.Valid)
11202       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
11203                                                             PragmaClangBSSSection.SectionName,
11204                                                             PragmaClangBSSSection.PragmaLocation));
11205     if (PragmaClangDataSection.Valid)
11206       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
11207                                                              PragmaClangDataSection.SectionName,
11208                                                              PragmaClangDataSection.PragmaLocation));
11209     if (PragmaClangRodataSection.Valid)
11210       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
11211                                                                PragmaClangRodataSection.SectionName,
11212                                                                PragmaClangRodataSection.PragmaLocation));
11213   }
11214 
11215   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
11216     for (auto *BD : DD->bindings()) {
11217       FinalizeDeclaration(BD);
11218     }
11219   }
11220 
11221   checkAttributesAfterMerging(*this, *VD);
11222 
11223   // Perform TLS alignment check here after attributes attached to the variable
11224   // which may affect the alignment have been processed. Only perform the check
11225   // if the target has a maximum TLS alignment (zero means no constraints).
11226   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
11227     // Protect the check so that it's not performed on dependent types and
11228     // dependent alignments (we can't determine the alignment in that case).
11229     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
11230         !VD->isInvalidDecl()) {
11231       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
11232       if (Context.getDeclAlign(VD) > MaxAlignChars) {
11233         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
11234           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
11235           << (unsigned)MaxAlignChars.getQuantity();
11236       }
11237     }
11238   }
11239 
11240   if (VD->isStaticLocal()) {
11241     if (FunctionDecl *FD =
11242             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
11243       // Static locals inherit dll attributes from their function.
11244       if (Attr *A = getDLLAttr(FD)) {
11245         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11246         NewAttr->setInherited(true);
11247         VD->addAttr(NewAttr);
11248       }
11249       // CUDA E.2.9.4: Within the body of a __device__ or __global__
11250       // function, only __shared__ variables may be declared with
11251       // static storage class.
11252       if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
11253           CUDADiagIfDeviceCode(VD->getLocation(),
11254                                diag::err_device_static_local_var)
11255               << CurrentCUDATarget())
11256         VD->setInvalidDecl();
11257     }
11258   }
11259 
11260   // Perform check for initializers of device-side global variables.
11261   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
11262   // 7.5). We must also apply the same checks to all __shared__
11263   // variables whether they are local or not. CUDA also allows
11264   // constant initializers for __constant__ and __device__ variables.
11265   if (getLangOpts().CUDA) {
11266     const Expr *Init = VD->getInit();
11267     if (Init && VD->hasGlobalStorage()) {
11268       if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
11269           VD->hasAttr<CUDASharedAttr>()) {
11270         assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
11271         bool AllowedInit = false;
11272         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
11273           AllowedInit =
11274               isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
11275         // We'll allow constant initializers even if it's a non-empty
11276         // constructor according to CUDA rules. This deviates from NVCC,
11277         // but allows us to handle things like constexpr constructors.
11278         if (!AllowedInit &&
11279             (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
11280           AllowedInit = VD->getInit()->isConstantInitializer(
11281               Context, VD->getType()->isReferenceType());
11282 
11283         // Also make sure that destructor, if there is one, is empty.
11284         if (AllowedInit)
11285           if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
11286             AllowedInit =
11287                 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
11288 
11289         if (!AllowedInit) {
11290           Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
11291                                       ? diag::err_shared_var_init
11292                                       : diag::err_dynamic_var_init)
11293               << Init->getSourceRange();
11294           VD->setInvalidDecl();
11295         }
11296       } else {
11297         // This is a host-side global variable.  Check that the initializer is
11298         // callable from the host side.
11299         const FunctionDecl *InitFn = nullptr;
11300         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
11301           InitFn = CE->getConstructor();
11302         } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
11303           InitFn = CE->getDirectCallee();
11304         }
11305         if (InitFn) {
11306           CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
11307           if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
11308             Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
11309                 << InitFnTarget << InitFn;
11310             Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
11311             VD->setInvalidDecl();
11312           }
11313         }
11314       }
11315     }
11316   }
11317 
11318   // Grab the dllimport or dllexport attribute off of the VarDecl.
11319   const InheritableAttr *DLLAttr = getDLLAttr(VD);
11320 
11321   // Imported static data members cannot be defined out-of-line.
11322   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
11323     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
11324         VD->isThisDeclarationADefinition()) {
11325       // We allow definitions of dllimport class template static data members
11326       // with a warning.
11327       CXXRecordDecl *Context =
11328         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
11329       bool IsClassTemplateMember =
11330           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
11331           Context->getDescribedClassTemplate();
11332 
11333       Diag(VD->getLocation(),
11334            IsClassTemplateMember
11335                ? diag::warn_attribute_dllimport_static_field_definition
11336                : diag::err_attribute_dllimport_static_field_definition);
11337       Diag(IA->getLocation(), diag::note_attribute);
11338       if (!IsClassTemplateMember)
11339         VD->setInvalidDecl();
11340     }
11341   }
11342 
11343   // dllimport/dllexport variables cannot be thread local, their TLS index
11344   // isn't exported with the variable.
11345   if (DLLAttr && VD->getTLSKind()) {
11346     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11347     if (F && getDLLAttr(F)) {
11348       assert(VD->isStaticLocal());
11349       // But if this is a static local in a dlimport/dllexport function, the
11350       // function will never be inlined, which means the var would never be
11351       // imported, so having it marked import/export is safe.
11352     } else {
11353       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
11354                                                                     << DLLAttr;
11355       VD->setInvalidDecl();
11356     }
11357   }
11358 
11359   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
11360     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
11361       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11362       VD->dropAttr<UsedAttr>();
11363     }
11364   }
11365 
11366   const DeclContext *DC = VD->getDeclContext();
11367   // If there's a #pragma GCC visibility in scope, and this isn't a class
11368   // member, set the visibility of this variable.
11369   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11370     AddPushedVisibilityAttribute(VD);
11371 
11372   // FIXME: Warn on unused var template partial specializations.
11373   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
11374     MarkUnusedFileScopedDecl(VD);
11375 
11376   // Now we have parsed the initializer and can update the table of magic
11377   // tag values.
11378   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11379       !VD->getType()->isIntegralOrEnumerationType())
11380     return;
11381 
11382   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11383     const Expr *MagicValueExpr = VD->getInit();
11384     if (!MagicValueExpr) {
11385       continue;
11386     }
11387     llvm::APSInt MagicValueInt;
11388     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11389       Diag(I->getRange().getBegin(),
11390            diag::err_type_tag_for_datatype_not_ice)
11391         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11392       continue;
11393     }
11394     if (MagicValueInt.getActiveBits() > 64) {
11395       Diag(I->getRange().getBegin(),
11396            diag::err_type_tag_for_datatype_too_large)
11397         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11398       continue;
11399     }
11400     uint64_t MagicValue = MagicValueInt.getZExtValue();
11401     RegisterTypeTagForDatatype(I->getArgumentKind(),
11402                                MagicValue,
11403                                I->getMatchingCType(),
11404                                I->getLayoutCompatible(),
11405                                I->getMustBeNull());
11406   }
11407 }
11408 
11409 static bool hasDeducedAuto(DeclaratorDecl *DD) {
11410   auto *VD = dyn_cast<VarDecl>(DD);
11411   return VD && !VD->getType()->hasAutoForTrailingReturnType();
11412 }
11413 
11414 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
11415                                                    ArrayRef<Decl *> Group) {
11416   SmallVector<Decl*, 8> Decls;
11417 
11418   if (DS.isTypeSpecOwned())
11419     Decls.push_back(DS.getRepAsDecl());
11420 
11421   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11422   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11423   bool DiagnosedMultipleDecomps = false;
11424   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
11425   bool DiagnosedNonDeducedAuto = false;
11426 
11427   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11428     if (Decl *D = Group[i]) {
11429       // For declarators, there are some additional syntactic-ish checks we need
11430       // to perform.
11431       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11432         if (!FirstDeclaratorInGroup)
11433           FirstDeclaratorInGroup = DD;
11434         if (!FirstDecompDeclaratorInGroup)
11435           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
11436         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
11437             !hasDeducedAuto(DD))
11438           FirstNonDeducedAutoInGroup = DD;
11439 
11440         if (FirstDeclaratorInGroup != DD) {
11441           // A decomposition declaration cannot be combined with any other
11442           // declaration in the same group.
11443           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
11444             Diag(FirstDecompDeclaratorInGroup->getLocation(),
11445                  diag::err_decomp_decl_not_alone)
11446                 << FirstDeclaratorInGroup->getSourceRange()
11447                 << DD->getSourceRange();
11448             DiagnosedMultipleDecomps = true;
11449           }
11450 
11451           // A declarator that uses 'auto' in any way other than to declare a
11452           // variable with a deduced type cannot be combined with any other
11453           // declarator in the same group.
11454           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
11455             Diag(FirstNonDeducedAutoInGroup->getLocation(),
11456                  diag::err_auto_non_deduced_not_alone)
11457                 << FirstNonDeducedAutoInGroup->getType()
11458                        ->hasAutoForTrailingReturnType()
11459                 << FirstDeclaratorInGroup->getSourceRange()
11460                 << DD->getSourceRange();
11461             DiagnosedNonDeducedAuto = true;
11462           }
11463         }
11464       }
11465 
11466       Decls.push_back(D);
11467     }
11468   }
11469 
11470   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11471     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11472       handleTagNumbering(Tag, S);
11473       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11474           getLangOpts().CPlusPlus)
11475         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11476     }
11477   }
11478 
11479   return BuildDeclaratorGroup(Decls);
11480 }
11481 
11482 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11483 /// group, performing any necessary semantic checking.
11484 Sema::DeclGroupPtrTy
11485 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
11486   // C++14 [dcl.spec.auto]p7: (DR1347)
11487   //   If the type that replaces the placeholder type is not the same in each
11488   //   deduction, the program is ill-formed.
11489   if (Group.size() > 1) {
11490     QualType Deduced;
11491     VarDecl *DeducedDecl = nullptr;
11492     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11493       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
11494       if (!D || D->isInvalidDecl())
11495         break;
11496       DeducedType *DT = D->getType()->getContainedDeducedType();
11497       if (!DT || DT->getDeducedType().isNull())
11498         continue;
11499       if (Deduced.isNull()) {
11500         Deduced = DT->getDeducedType();
11501         DeducedDecl = D;
11502       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
11503         auto *AT = dyn_cast<AutoType>(DT);
11504         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11505              diag::err_auto_different_deductions)
11506           << (AT ? (unsigned)AT->getKeyword() : 3)
11507           << Deduced << DeducedDecl->getDeclName()
11508           << DT->getDeducedType() << D->getDeclName()
11509           << DeducedDecl->getInit()->getSourceRange()
11510           << D->getInit()->getSourceRange();
11511         D->setInvalidDecl();
11512         break;
11513       }
11514     }
11515   }
11516 
11517   ActOnDocumentableDecls(Group);
11518 
11519   return DeclGroupPtrTy::make(
11520       DeclGroupRef::Create(Context, Group.data(), Group.size()));
11521 }
11522 
11523 void Sema::ActOnDocumentableDecl(Decl *D) {
11524   ActOnDocumentableDecls(D);
11525 }
11526 
11527 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11528   // Don't parse the comment if Doxygen diagnostics are ignored.
11529   if (Group.empty() || !Group[0])
11530     return;
11531 
11532   if (Diags.isIgnored(diag::warn_doc_param_not_found,
11533                       Group[0]->getLocation()) &&
11534       Diags.isIgnored(diag::warn_unknown_comment_command_name,
11535                       Group[0]->getLocation()))
11536     return;
11537 
11538   if (Group.size() >= 2) {
11539     // This is a decl group.  Normally it will contain only declarations
11540     // produced from declarator list.  But in case we have any definitions or
11541     // additional declaration references:
11542     //   'typedef struct S {} S;'
11543     //   'typedef struct S *S;'
11544     //   'struct S *pS;'
11545     // FinalizeDeclaratorGroup adds these as separate declarations.
11546     Decl *MaybeTagDecl = Group[0];
11547     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11548       Group = Group.slice(1);
11549     }
11550   }
11551 
11552   // See if there are any new comments that are not attached to a decl.
11553   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11554   if (!Comments.empty() &&
11555       !Comments.back()->isAttached()) {
11556     // There is at least one comment that not attached to a decl.
11557     // Maybe it should be attached to one of these decls?
11558     //
11559     // Note that this way we pick up not only comments that precede the
11560     // declaration, but also comments that *follow* the declaration -- thanks to
11561     // the lookahead in the lexer: we've consumed the semicolon and looked
11562     // ahead through comments.
11563     for (unsigned i = 0, e = Group.size(); i != e; ++i)
11564       Context.getCommentForDecl(Group[i], &PP);
11565   }
11566 }
11567 
11568 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11569 /// to introduce parameters into function prototype scope.
11570 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11571   const DeclSpec &DS = D.getDeclSpec();
11572 
11573   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11574 
11575   // C++03 [dcl.stc]p2 also permits 'auto'.
11576   StorageClass SC = SC_None;
11577   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11578     SC = SC_Register;
11579   } else if (getLangOpts().CPlusPlus &&
11580              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11581     SC = SC_Auto;
11582   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11583     Diag(DS.getStorageClassSpecLoc(),
11584          diag::err_invalid_storage_class_in_func_decl);
11585     D.getMutableDeclSpec().ClearStorageClassSpecs();
11586   }
11587 
11588   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11589     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11590       << DeclSpec::getSpecifierName(TSCS);
11591   if (DS.isInlineSpecified())
11592     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11593         << getLangOpts().CPlusPlus1z;
11594   if (DS.isConstexprSpecified())
11595     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11596       << 0;
11597   if (DS.isConceptSpecified())
11598     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
11599 
11600   DiagnoseFunctionSpecifiers(DS);
11601 
11602   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11603   QualType parmDeclType = TInfo->getType();
11604 
11605   if (getLangOpts().CPlusPlus) {
11606     // Check that there are no default arguments inside the type of this
11607     // parameter.
11608     CheckExtraCXXDefaultArguments(D);
11609 
11610     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11611     if (D.getCXXScopeSpec().isSet()) {
11612       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11613         << D.getCXXScopeSpec().getRange();
11614       D.getCXXScopeSpec().clear();
11615     }
11616   }
11617 
11618   // Ensure we have a valid name
11619   IdentifierInfo *II = nullptr;
11620   if (D.hasName()) {
11621     II = D.getIdentifier();
11622     if (!II) {
11623       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11624         << GetNameForDeclarator(D).getName();
11625       D.setInvalidType(true);
11626     }
11627   }
11628 
11629   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11630   if (II) {
11631     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
11632                    ForRedeclaration);
11633     LookupName(R, S);
11634     if (R.isSingleResult()) {
11635       NamedDecl *PrevDecl = R.getFoundDecl();
11636       if (PrevDecl->isTemplateParameter()) {
11637         // Maybe we will complain about the shadowed template parameter.
11638         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11639         // Just pretend that we didn't see the previous declaration.
11640         PrevDecl = nullptr;
11641       } else if (S->isDeclScope(PrevDecl)) {
11642         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
11643         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11644 
11645         // Recover by removing the name
11646         II = nullptr;
11647         D.SetIdentifier(nullptr, D.getIdentifierLoc());
11648         D.setInvalidType(true);
11649       }
11650     }
11651   }
11652 
11653   // Temporarily put parameter variables in the translation unit, not
11654   // the enclosing context.  This prevents them from accidentally
11655   // looking like class members in C++.
11656   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
11657                                     D.getLocStart(),
11658                                     D.getIdentifierLoc(), II,
11659                                     parmDeclType, TInfo,
11660                                     SC);
11661 
11662   if (D.isInvalidType())
11663     New->setInvalidDecl();
11664 
11665   assert(S->isFunctionPrototypeScope());
11666   assert(S->getFunctionPrototypeDepth() >= 1);
11667   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
11668                     S->getNextFunctionPrototypeIndex());
11669 
11670   // Add the parameter declaration into this scope.
11671   S->AddDecl(New);
11672   if (II)
11673     IdResolver.AddDecl(New);
11674 
11675   ProcessDeclAttributes(S, New, D);
11676 
11677   if (D.getDeclSpec().isModulePrivateSpecified())
11678     Diag(New->getLocation(), diag::err_module_private_local)
11679       << 1 << New->getDeclName()
11680       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11681       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11682 
11683   if (New->hasAttr<BlocksAttr>()) {
11684     Diag(New->getLocation(), diag::err_block_on_nonlocal);
11685   }
11686   return New;
11687 }
11688 
11689 /// \brief Synthesizes a variable for a parameter arising from a
11690 /// typedef.
11691 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
11692                                               SourceLocation Loc,
11693                                               QualType T) {
11694   /* FIXME: setting StartLoc == Loc.
11695      Would it be worth to modify callers so as to provide proper source
11696      location for the unnamed parameters, embedding the parameter's type? */
11697   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
11698                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
11699                                            SC_None, nullptr);
11700   Param->setImplicit();
11701   return Param;
11702 }
11703 
11704 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
11705   // Don't diagnose unused-parameter errors in template instantiations; we
11706   // will already have done so in the template itself.
11707   if (inTemplateInstantiation())
11708     return;
11709 
11710   for (const ParmVarDecl *Parameter : Parameters) {
11711     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
11712         !Parameter->hasAttr<UnusedAttr>()) {
11713       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
11714         << Parameter->getDeclName();
11715     }
11716   }
11717 }
11718 
11719 void Sema::DiagnoseSizeOfParametersAndReturnValue(
11720     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
11721   if (LangOpts.NumLargeByValueCopy == 0) // No check.
11722     return;
11723 
11724   // Warn if the return value is pass-by-value and larger than the specified
11725   // threshold.
11726   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
11727     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
11728     if (Size > LangOpts.NumLargeByValueCopy)
11729       Diag(D->getLocation(), diag::warn_return_value_size)
11730           << D->getDeclName() << Size;
11731   }
11732 
11733   // Warn if any parameter is pass-by-value and larger than the specified
11734   // threshold.
11735   for (const ParmVarDecl *Parameter : Parameters) {
11736     QualType T = Parameter->getType();
11737     if (T->isDependentType() || !T.isPODType(Context))
11738       continue;
11739     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
11740     if (Size > LangOpts.NumLargeByValueCopy)
11741       Diag(Parameter->getLocation(), diag::warn_parameter_size)
11742           << Parameter->getDeclName() << Size;
11743   }
11744 }
11745 
11746 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
11747                                   SourceLocation NameLoc, IdentifierInfo *Name,
11748                                   QualType T, TypeSourceInfo *TSInfo,
11749                                   StorageClass SC) {
11750   // In ARC, infer a lifetime qualifier for appropriate parameter types.
11751   if (getLangOpts().ObjCAutoRefCount &&
11752       T.getObjCLifetime() == Qualifiers::OCL_None &&
11753       T->isObjCLifetimeType()) {
11754 
11755     Qualifiers::ObjCLifetime lifetime;
11756 
11757     // Special cases for arrays:
11758     //   - if it's const, use __unsafe_unretained
11759     //   - otherwise, it's an error
11760     if (T->isArrayType()) {
11761       if (!T.isConstQualified()) {
11762         DelayedDiagnostics.add(
11763             sema::DelayedDiagnostic::makeForbiddenType(
11764             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
11765       }
11766       lifetime = Qualifiers::OCL_ExplicitNone;
11767     } else {
11768       lifetime = T->getObjCARCImplicitLifetime();
11769     }
11770     T = Context.getLifetimeQualifiedType(T, lifetime);
11771   }
11772 
11773   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
11774                                          Context.getAdjustedParameterType(T),
11775                                          TSInfo, SC, nullptr);
11776 
11777   // Parameters can not be abstract class types.
11778   // For record types, this is done by the AbstractClassUsageDiagnoser once
11779   // the class has been completely parsed.
11780   if (!CurContext->isRecord() &&
11781       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11782                              AbstractParamType))
11783     New->setInvalidDecl();
11784 
11785   // Parameter declarators cannot be interface types. All ObjC objects are
11786   // passed by reference.
11787   if (T->isObjCObjectType()) {
11788     SourceLocation TypeEndLoc =
11789         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11790     Diag(NameLoc,
11791          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11792       << FixItHint::CreateInsertion(TypeEndLoc, "*");
11793     T = Context.getObjCObjectPointerType(T);
11794     New->setType(T);
11795   }
11796 
11797   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11798   // duration shall not be qualified by an address-space qualifier."
11799   // Since all parameters have automatic store duration, they can not have
11800   // an address space.
11801   if (T.getAddressSpace() != 0) {
11802     // OpenCL allows function arguments declared to be an array of a type
11803     // to be qualified with an address space.
11804     if (!(getLangOpts().OpenCL && T->isArrayType())) {
11805       Diag(NameLoc, diag::err_arg_with_address_space);
11806       New->setInvalidDecl();
11807     }
11808   }
11809 
11810   return New;
11811 }
11812 
11813 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11814                                            SourceLocation LocAfterDecls) {
11815   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11816 
11817   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11818   // for a K&R function.
11819   if (!FTI.hasPrototype) {
11820     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11821       --i;
11822       if (FTI.Params[i].Param == nullptr) {
11823         SmallString<256> Code;
11824         llvm::raw_svector_ostream(Code)
11825             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
11826         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11827             << FTI.Params[i].Ident
11828             << FixItHint::CreateInsertion(LocAfterDecls, Code);
11829 
11830         // Implicitly declare the argument as type 'int' for lack of a better
11831         // type.
11832         AttributeFactory attrs;
11833         DeclSpec DS(attrs);
11834         const char* PrevSpec; // unused
11835         unsigned DiagID; // unused
11836         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11837                            DiagID, Context.getPrintingPolicy());
11838         // Use the identifier location for the type source range.
11839         DS.SetRangeStart(FTI.Params[i].IdentLoc);
11840         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11841         Declarator ParamD(DS, Declarator::KNRTypeListContext);
11842         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11843         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11844       }
11845     }
11846   }
11847 }
11848 
11849 Decl *
11850 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11851                               MultiTemplateParamsArg TemplateParameterLists,
11852                               SkipBodyInfo *SkipBody) {
11853   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11854   assert(D.isFunctionDeclarator() && "Not a function declarator!");
11855   Scope *ParentScope = FnBodyScope->getParent();
11856 
11857   D.setFunctionDefinitionKind(FDK_Definition);
11858   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11859   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11860 }
11861 
11862 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11863   Consumer.HandleInlineFunctionDefinition(D);
11864 }
11865 
11866 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11867                              const FunctionDecl*& PossibleZeroParamPrototype) {
11868   // Don't warn about invalid declarations.
11869   if (FD->isInvalidDecl())
11870     return false;
11871 
11872   // Or declarations that aren't global.
11873   if (!FD->isGlobal())
11874     return false;
11875 
11876   // Don't warn about C++ member functions.
11877   if (isa<CXXMethodDecl>(FD))
11878     return false;
11879 
11880   // Don't warn about 'main'.
11881   if (FD->isMain())
11882     return false;
11883 
11884   // Don't warn about inline functions.
11885   if (FD->isInlined())
11886     return false;
11887 
11888   // Don't warn about function templates.
11889   if (FD->getDescribedFunctionTemplate())
11890     return false;
11891 
11892   // Don't warn about function template specializations.
11893   if (FD->isFunctionTemplateSpecialization())
11894     return false;
11895 
11896   // Don't warn for OpenCL kernels.
11897   if (FD->hasAttr<OpenCLKernelAttr>())
11898     return false;
11899 
11900   // Don't warn on explicitly deleted functions.
11901   if (FD->isDeleted())
11902     return false;
11903 
11904   bool MissingPrototype = true;
11905   for (const FunctionDecl *Prev = FD->getPreviousDecl();
11906        Prev; Prev = Prev->getPreviousDecl()) {
11907     // Ignore any declarations that occur in function or method
11908     // scope, because they aren't visible from the header.
11909     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11910       continue;
11911 
11912     MissingPrototype = !Prev->getType()->isFunctionProtoType();
11913     if (FD->getNumParams() == 0)
11914       PossibleZeroParamPrototype = Prev;
11915     break;
11916   }
11917 
11918   return MissingPrototype;
11919 }
11920 
11921 void
11922 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11923                                    const FunctionDecl *EffectiveDefinition,
11924                                    SkipBodyInfo *SkipBody) {
11925   const FunctionDecl *Definition = EffectiveDefinition;
11926   if (!Definition)
11927     if (!FD->isDefined(Definition))
11928       return;
11929 
11930   if (canRedefineFunction(Definition, getLangOpts()))
11931     return;
11932 
11933   // Don't emit an error when this is redifinition of a typo-corrected
11934   // definition.
11935   if (TypoCorrectedFunctionDefinitions.count(Definition))
11936     return;
11937 
11938   // If we don't have a visible definition of the function, and it's inline or
11939   // a template, skip the new definition.
11940   if (SkipBody && !hasVisibleDefinition(Definition) &&
11941       (Definition->getFormalLinkage() == InternalLinkage ||
11942        Definition->isInlined() ||
11943        Definition->getDescribedFunctionTemplate() ||
11944        Definition->getNumTemplateParameterLists())) {
11945     SkipBody->ShouldSkip = true;
11946     if (auto *TD = Definition->getDescribedFunctionTemplate())
11947       makeMergedDefinitionVisible(TD);
11948     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
11949     return;
11950   }
11951 
11952   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11953       Definition->getStorageClass() == SC_Extern)
11954     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11955         << FD->getDeclName() << getLangOpts().CPlusPlus;
11956   else
11957     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11958 
11959   Diag(Definition->getLocation(), diag::note_previous_definition);
11960   FD->setInvalidDecl();
11961 }
11962 
11963 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11964                                    Sema &S) {
11965   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11966 
11967   LambdaScopeInfo *LSI = S.PushLambdaScope();
11968   LSI->CallOperator = CallOperator;
11969   LSI->Lambda = LambdaClass;
11970   LSI->ReturnType = CallOperator->getReturnType();
11971   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11972 
11973   if (LCD == LCD_None)
11974     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
11975   else if (LCD == LCD_ByCopy)
11976     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
11977   else if (LCD == LCD_ByRef)
11978     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
11979   DeclarationNameInfo DNI = CallOperator->getNameInfo();
11980 
11981   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
11982   LSI->Mutable = !CallOperator->isConst();
11983 
11984   // Add the captures to the LSI so they can be noted as already
11985   // captured within tryCaptureVar.
11986   auto I = LambdaClass->field_begin();
11987   for (const auto &C : LambdaClass->captures()) {
11988     if (C.capturesVariable()) {
11989       VarDecl *VD = C.getCapturedVar();
11990       if (VD->isInitCapture())
11991         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11992       QualType CaptureType = VD->getType();
11993       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11994       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11995           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11996           /*EllipsisLoc*/C.isPackExpansion()
11997                          ? C.getEllipsisLoc() : SourceLocation(),
11998           CaptureType, /*Expr*/ nullptr);
11999 
12000     } else if (C.capturesThis()) {
12001       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
12002                               /*Expr*/ nullptr,
12003                               C.getCaptureKind() == LCK_StarThis);
12004     } else {
12005       LSI->addVLATypeCapture(C.getLocation(), I->getType());
12006     }
12007     ++I;
12008   }
12009 }
12010 
12011 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12012                                     SkipBodyInfo *SkipBody) {
12013   if (!D)
12014     return D;
12015   FunctionDecl *FD = nullptr;
12016 
12017   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
12018     FD = FunTmpl->getTemplatedDecl();
12019   else
12020     FD = cast<FunctionDecl>(D);
12021 
12022   // Check for defining attributes before the check for redefinition.
12023   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
12024     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
12025     FD->dropAttr<AliasAttr>();
12026     FD->setInvalidDecl();
12027   }
12028   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12029     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12030     FD->dropAttr<IFuncAttr>();
12031     FD->setInvalidDecl();
12032   }
12033 
12034   // See if this is a redefinition.
12035   if (!FD->isLateTemplateParsed()) {
12036     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
12037 
12038     // If we're skipping the body, we're done. Don't enter the scope.
12039     if (SkipBody && SkipBody->ShouldSkip)
12040       return D;
12041   }
12042 
12043   // Mark this function as "will have a body eventually".  This lets users to
12044   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12045   // this function.
12046   FD->setWillHaveBody();
12047 
12048   // If we are instantiating a generic lambda call operator, push
12049   // a LambdaScopeInfo onto the function stack.  But use the information
12050   // that's already been calculated (ActOnLambdaExpr) to prime the current
12051   // LambdaScopeInfo.
12052   // When the template operator is being specialized, the LambdaScopeInfo,
12053   // has to be properly restored so that tryCaptureVariable doesn't try
12054   // and capture any new variables. In addition when calculating potential
12055   // captures during transformation of nested lambdas, it is necessary to
12056   // have the LSI properly restored.
12057   if (isGenericLambdaCallOperatorSpecialization(FD)) {
12058     assert(inTemplateInstantiation() &&
12059            "There should be an active template instantiation on the stack "
12060            "when instantiating a generic lambda!");
12061     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12062   } else {
12063     // Enter a new function scope
12064     PushFunctionScope();
12065   }
12066 
12067   // Builtin functions cannot be defined.
12068   if (unsigned BuiltinID = FD->getBuiltinID()) {
12069     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12070         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12071       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12072       FD->setInvalidDecl();
12073     }
12074   }
12075 
12076   // The return type of a function definition must be complete
12077   // (C99 6.9.1p3, C++ [dcl.fct]p6).
12078   QualType ResultType = FD->getReturnType();
12079   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12080       !FD->isInvalidDecl() &&
12081       RequireCompleteType(FD->getLocation(), ResultType,
12082                           diag::err_func_def_incomplete_result))
12083     FD->setInvalidDecl();
12084 
12085   if (FnBodyScope)
12086     PushDeclContext(FnBodyScope, FD);
12087 
12088   // Check the validity of our function parameters
12089   CheckParmsForFunctionDef(FD->parameters(),
12090                            /*CheckParameterNames=*/true);
12091 
12092   // Add non-parameter declarations already in the function to the current
12093   // scope.
12094   if (FnBodyScope) {
12095     for (Decl *NPD : FD->decls()) {
12096       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
12097       if (!NonParmDecl)
12098         continue;
12099       assert(!isa<ParmVarDecl>(NonParmDecl) &&
12100              "parameters should not be in newly created FD yet");
12101 
12102       // If the decl has a name, make it accessible in the current scope.
12103       if (NonParmDecl->getDeclName())
12104         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
12105 
12106       // Similarly, dive into enums and fish their constants out, making them
12107       // accessible in this scope.
12108       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
12109         for (auto *EI : ED->enumerators())
12110           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
12111       }
12112     }
12113   }
12114 
12115   // Introduce our parameters into the function scope
12116   for (auto Param : FD->parameters()) {
12117     Param->setOwningFunction(FD);
12118 
12119     // If this has an identifier, add it to the scope stack.
12120     if (Param->getIdentifier() && FnBodyScope) {
12121       CheckShadow(FnBodyScope, Param);
12122 
12123       PushOnScopeChains(Param, FnBodyScope);
12124     }
12125   }
12126 
12127   // Ensure that the function's exception specification is instantiated.
12128   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
12129     ResolveExceptionSpec(D->getLocation(), FPT);
12130 
12131   // dllimport cannot be applied to non-inline function definitions.
12132   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
12133       !FD->isTemplateInstantiation()) {
12134     assert(!FD->hasAttr<DLLExportAttr>());
12135     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
12136     FD->setInvalidDecl();
12137     return D;
12138   }
12139   // We want to attach documentation to original Decl (which might be
12140   // a function template).
12141   ActOnDocumentableDecl(D);
12142   if (getCurLexicalContext()->isObjCContainer() &&
12143       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
12144       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
12145     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
12146 
12147   return D;
12148 }
12149 
12150 /// \brief Given the set of return statements within a function body,
12151 /// compute the variables that are subject to the named return value
12152 /// optimization.
12153 ///
12154 /// Each of the variables that is subject to the named return value
12155 /// optimization will be marked as NRVO variables in the AST, and any
12156 /// return statement that has a marked NRVO variable as its NRVO candidate can
12157 /// use the named return value optimization.
12158 ///
12159 /// This function applies a very simplistic algorithm for NRVO: if every return
12160 /// statement in the scope of a variable has the same NRVO candidate, that
12161 /// candidate is an NRVO variable.
12162 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
12163   ReturnStmt **Returns = Scope->Returns.data();
12164 
12165   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
12166     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
12167       if (!NRVOCandidate->isNRVOVariable())
12168         Returns[I]->setNRVOCandidate(nullptr);
12169     }
12170   }
12171 }
12172 
12173 bool Sema::canDelayFunctionBody(const Declarator &D) {
12174   // We can't delay parsing the body of a constexpr function template (yet).
12175   if (D.getDeclSpec().isConstexprSpecified())
12176     return false;
12177 
12178   // We can't delay parsing the body of a function template with a deduced
12179   // return type (yet).
12180   if (D.getDeclSpec().hasAutoTypeSpec()) {
12181     // If the placeholder introduces a non-deduced trailing return type,
12182     // we can still delay parsing it.
12183     if (D.getNumTypeObjects()) {
12184       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
12185       if (Outer.Kind == DeclaratorChunk::Function &&
12186           Outer.Fun.hasTrailingReturnType()) {
12187         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
12188         return Ty.isNull() || !Ty->isUndeducedType();
12189       }
12190     }
12191     return false;
12192   }
12193 
12194   return true;
12195 }
12196 
12197 bool Sema::canSkipFunctionBody(Decl *D) {
12198   // We cannot skip the body of a function (or function template) which is
12199   // constexpr, since we may need to evaluate its body in order to parse the
12200   // rest of the file.
12201   // We cannot skip the body of a function with an undeduced return type,
12202   // because any callers of that function need to know the type.
12203   if (const FunctionDecl *FD = D->getAsFunction())
12204     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
12205       return false;
12206   return Consumer.shouldSkipFunctionBody(D);
12207 }
12208 
12209 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
12210   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
12211     FD->setHasSkippedBody();
12212   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
12213     MD->setHasSkippedBody();
12214   return Decl;
12215 }
12216 
12217 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
12218   return ActOnFinishFunctionBody(D, BodyArg, false);
12219 }
12220 
12221 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
12222                                     bool IsInstantiation) {
12223   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
12224 
12225   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12226   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
12227 
12228   if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
12229     CheckCompletedCoroutineBody(FD, Body);
12230 
12231   if (FD) {
12232     FD->setBody(Body);
12233     FD->setWillHaveBody(false);
12234 
12235     if (getLangOpts().CPlusPlus14) {
12236       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
12237           FD->getReturnType()->isUndeducedType()) {
12238         // If the function has a deduced result type but contains no 'return'
12239         // statements, the result type as written must be exactly 'auto', and
12240         // the deduced result type is 'void'.
12241         if (!FD->getReturnType()->getAs<AutoType>()) {
12242           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
12243               << FD->getReturnType();
12244           FD->setInvalidDecl();
12245         } else {
12246           // Substitute 'void' for the 'auto' in the type.
12247           TypeLoc ResultType = getReturnTypeLoc(FD);
12248           Context.adjustDeducedFunctionResultType(
12249               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
12250         }
12251       }
12252     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
12253       // In C++11, we don't use 'auto' deduction rules for lambda call
12254       // operators because we don't support return type deduction.
12255       auto *LSI = getCurLambda();
12256       if (LSI->HasImplicitReturnType) {
12257         deduceClosureReturnType(*LSI);
12258 
12259         // C++11 [expr.prim.lambda]p4:
12260         //   [...] if there are no return statements in the compound-statement
12261         //   [the deduced type is] the type void
12262         QualType RetType =
12263             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
12264 
12265         // Update the return type to the deduced type.
12266         const FunctionProtoType *Proto =
12267             FD->getType()->getAs<FunctionProtoType>();
12268         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
12269                                             Proto->getExtProtoInfo()));
12270       }
12271     }
12272 
12273     // The only way to be included in UndefinedButUsed is if there is an
12274     // ODR use before the definition. Avoid the expensive map lookup if this
12275     // is the first declaration.
12276     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
12277       if (!FD->isExternallyVisible())
12278         UndefinedButUsed.erase(FD);
12279       else if (FD->isInlined() &&
12280                !LangOpts.GNUInline &&
12281                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
12282         UndefinedButUsed.erase(FD);
12283     }
12284 
12285     // If the function implicitly returns zero (like 'main') or is naked,
12286     // don't complain about missing return statements.
12287     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
12288       WP.disableCheckFallThrough();
12289 
12290     // MSVC permits the use of pure specifier (=0) on function definition,
12291     // defined at class scope, warn about this non-standard construct.
12292     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
12293       Diag(FD->getLocation(), diag::ext_pure_function_definition);
12294 
12295     if (!FD->isInvalidDecl()) {
12296       // Don't diagnose unused parameters of defaulted or deleted functions.
12297       if (!FD->isDeleted() && !FD->isDefaulted())
12298         DiagnoseUnusedParameters(FD->parameters());
12299       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
12300                                              FD->getReturnType(), FD);
12301 
12302       // If this is a structor, we need a vtable.
12303       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
12304         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
12305       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
12306         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
12307 
12308       // Try to apply the named return value optimization. We have to check
12309       // if we can do this here because lambdas keep return statements around
12310       // to deduce an implicit return type.
12311       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
12312           !FD->isDependentContext())
12313         computeNRVO(Body, getCurFunction());
12314     }
12315 
12316     // GNU warning -Wmissing-prototypes:
12317     //   Warn if a global function is defined without a previous
12318     //   prototype declaration. This warning is issued even if the
12319     //   definition itself provides a prototype. The aim is to detect
12320     //   global functions that fail to be declared in header files.
12321     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
12322     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
12323       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
12324 
12325       if (PossibleZeroParamPrototype) {
12326         // We found a declaration that is not a prototype,
12327         // but that could be a zero-parameter prototype
12328         if (TypeSourceInfo *TI =
12329                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
12330           TypeLoc TL = TI->getTypeLoc();
12331           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
12332             Diag(PossibleZeroParamPrototype->getLocation(),
12333                  diag::note_declaration_not_a_prototype)
12334                 << PossibleZeroParamPrototype
12335                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
12336         }
12337       }
12338 
12339       // GNU warning -Wstrict-prototypes
12340       //   Warn if K&R function is defined without a previous declaration.
12341       //   This warning is issued only if the definition itself does not provide
12342       //   a prototype. Only K&R definitions do not provide a prototype.
12343       //   An empty list in a function declarator that is part of a definition
12344       //   of that function specifies that the function has no parameters
12345       //   (C99 6.7.5.3p14)
12346       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
12347           !LangOpts.CPlusPlus) {
12348         TypeSourceInfo *TI = FD->getTypeSourceInfo();
12349         TypeLoc TL = TI->getTypeLoc();
12350         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
12351         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
12352       }
12353     }
12354 
12355     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12356       const CXXMethodDecl *KeyFunction;
12357       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
12358           MD->isVirtual() &&
12359           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
12360           MD == KeyFunction->getCanonicalDecl()) {
12361         // Update the key-function state if necessary for this ABI.
12362         if (FD->isInlined() &&
12363             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12364           Context.setNonKeyFunction(MD);
12365 
12366           // If the newly-chosen key function is already defined, then we
12367           // need to mark the vtable as used retroactively.
12368           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
12369           const FunctionDecl *Definition;
12370           if (KeyFunction && KeyFunction->isDefined(Definition))
12371             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
12372         } else {
12373           // We just defined they key function; mark the vtable as used.
12374           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
12375         }
12376       }
12377     }
12378 
12379     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
12380            "Function parsing confused");
12381   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
12382     assert(MD == getCurMethodDecl() && "Method parsing confused");
12383     MD->setBody(Body);
12384     if (!MD->isInvalidDecl()) {
12385       DiagnoseUnusedParameters(MD->parameters());
12386       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
12387                                              MD->getReturnType(), MD);
12388 
12389       if (Body)
12390         computeNRVO(Body, getCurFunction());
12391     }
12392     if (getCurFunction()->ObjCShouldCallSuper) {
12393       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
12394         << MD->getSelector().getAsString();
12395       getCurFunction()->ObjCShouldCallSuper = false;
12396     }
12397     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12398       const ObjCMethodDecl *InitMethod = nullptr;
12399       bool isDesignated =
12400           MD->isDesignatedInitializerForTheInterface(&InitMethod);
12401       assert(isDesignated && InitMethod);
12402       (void)isDesignated;
12403 
12404       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12405         auto IFace = MD->getClassInterface();
12406         if (!IFace)
12407           return false;
12408         auto SuperD = IFace->getSuperClass();
12409         if (!SuperD)
12410           return false;
12411         return SuperD->getIdentifier() ==
12412             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12413       };
12414       // Don't issue this warning for unavailable inits or direct subclasses
12415       // of NSObject.
12416       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12417         Diag(MD->getLocation(),
12418              diag::warn_objc_designated_init_missing_super_call);
12419         Diag(InitMethod->getLocation(),
12420              diag::note_objc_designated_init_marked_here);
12421       }
12422       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12423     }
12424     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12425       // Don't issue this warning for unavaialable inits.
12426       if (!MD->isUnavailable())
12427         Diag(MD->getLocation(),
12428              diag::warn_objc_secondary_init_missing_init_call);
12429       getCurFunction()->ObjCWarnForNoInitDelegation = false;
12430     }
12431   } else {
12432     return nullptr;
12433   }
12434 
12435   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12436     DiagnoseUnguardedAvailabilityViolations(dcl);
12437 
12438   assert(!getCurFunction()->ObjCShouldCallSuper &&
12439          "This should only be set for ObjC methods, which should have been "
12440          "handled in the block above.");
12441 
12442   // Verify and clean out per-function state.
12443   if (Body && (!FD || !FD->isDefaulted())) {
12444     // C++ constructors that have function-try-blocks can't have return
12445     // statements in the handlers of that block. (C++ [except.handle]p14)
12446     // Verify this.
12447     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12448       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12449 
12450     // Verify that gotos and switch cases don't jump into scopes illegally.
12451     if (getCurFunction()->NeedsScopeChecking() &&
12452         !PP.isCodeCompletionEnabled())
12453       DiagnoseInvalidJumps(Body);
12454 
12455     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12456       if (!Destructor->getParent()->isDependentType())
12457         CheckDestructor(Destructor);
12458 
12459       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12460                                              Destructor->getParent());
12461     }
12462 
12463     // If any errors have occurred, clear out any temporaries that may have
12464     // been leftover. This ensures that these temporaries won't be picked up for
12465     // deletion in some later function.
12466     if (getDiagnostics().hasErrorOccurred() ||
12467         getDiagnostics().getSuppressAllDiagnostics()) {
12468       DiscardCleanupsInEvaluationContext();
12469     }
12470     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12471         !isa<FunctionTemplateDecl>(dcl)) {
12472       // Since the body is valid, issue any analysis-based warnings that are
12473       // enabled.
12474       ActivePolicy = &WP;
12475     }
12476 
12477     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12478         (!CheckConstexprFunctionDecl(FD) ||
12479          !CheckConstexprFunctionBody(FD, Body)))
12480       FD->setInvalidDecl();
12481 
12482     if (FD && FD->hasAttr<NakedAttr>()) {
12483       for (const Stmt *S : Body->children()) {
12484         // Allow local register variables without initializer as they don't
12485         // require prologue.
12486         bool RegisterVariables = false;
12487         if (auto *DS = dyn_cast<DeclStmt>(S)) {
12488           for (const auto *Decl : DS->decls()) {
12489             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12490               RegisterVariables =
12491                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12492               if (!RegisterVariables)
12493                 break;
12494             }
12495           }
12496         }
12497         if (RegisterVariables)
12498           continue;
12499         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12500           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12501           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12502           FD->setInvalidDecl();
12503           break;
12504         }
12505       }
12506     }
12507 
12508     assert(ExprCleanupObjects.size() ==
12509                ExprEvalContexts.back().NumCleanupObjects &&
12510            "Leftover temporaries in function");
12511     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12512     assert(MaybeODRUseExprs.empty() &&
12513            "Leftover expressions for odr-use checking");
12514   }
12515 
12516   if (!IsInstantiation)
12517     PopDeclContext();
12518 
12519   PopFunctionScopeInfo(ActivePolicy, dcl);
12520   // If any errors have occurred, clear out any temporaries that may have
12521   // been leftover. This ensures that these temporaries won't be picked up for
12522   // deletion in some later function.
12523   if (getDiagnostics().hasErrorOccurred()) {
12524     DiscardCleanupsInEvaluationContext();
12525   }
12526 
12527   return dcl;
12528 }
12529 
12530 /// When we finish delayed parsing of an attribute, we must attach it to the
12531 /// relevant Decl.
12532 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12533                                        ParsedAttributes &Attrs) {
12534   // Always attach attributes to the underlying decl.
12535   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12536     D = TD->getTemplatedDecl();
12537   ProcessDeclAttributeList(S, D, Attrs.getList());
12538 
12539   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12540     if (Method->isStatic())
12541       checkThisInStaticMemberFunctionAttributes(Method);
12542 }
12543 
12544 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12545 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12546 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12547                                           IdentifierInfo &II, Scope *S) {
12548   // Before we produce a declaration for an implicitly defined
12549   // function, see whether there was a locally-scoped declaration of
12550   // this name as a function or variable. If so, use that
12551   // (non-visible) declaration, and complain about it.
12552   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
12553     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
12554     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12555     return ExternCPrev;
12556   }
12557 
12558   // Extension in C99.  Legal in C90, but warn about it.
12559   unsigned diag_id;
12560   if (II.getName().startswith("__builtin_"))
12561     diag_id = diag::warn_builtin_unknown;
12562   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
12563   else if (getLangOpts().OpenCL)
12564     diag_id = diag::err_opencl_implicit_function_decl;
12565   else if (getLangOpts().C99)
12566     diag_id = diag::ext_implicit_function_decl;
12567   else
12568     diag_id = diag::warn_implicit_function_decl;
12569   Diag(Loc, diag_id) << &II;
12570 
12571   // Because typo correction is expensive, only do it if the implicit
12572   // function declaration is going to be treated as an error.
12573   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
12574     TypoCorrection Corrected;
12575     if (S &&
12576         (Corrected = CorrectTypo(
12577              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
12578              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
12579       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
12580                    /*ErrorRecovery*/false);
12581   }
12582 
12583   // Set a Declarator for the implicit definition: int foo();
12584   const char *Dummy;
12585   AttributeFactory attrFactory;
12586   DeclSpec DS(attrFactory);
12587   unsigned DiagID;
12588   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
12589                                   Context.getPrintingPolicy());
12590   (void)Error; // Silence warning.
12591   assert(!Error && "Error setting up implicit decl!");
12592   SourceLocation NoLoc;
12593   Declarator D(DS, Declarator::BlockContext);
12594   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
12595                                              /*IsAmbiguous=*/false,
12596                                              /*LParenLoc=*/NoLoc,
12597                                              /*Params=*/nullptr,
12598                                              /*NumParams=*/0,
12599                                              /*EllipsisLoc=*/NoLoc,
12600                                              /*RParenLoc=*/NoLoc,
12601                                              /*TypeQuals=*/0,
12602                                              /*RefQualifierIsLvalueRef=*/true,
12603                                              /*RefQualifierLoc=*/NoLoc,
12604                                              /*ConstQualifierLoc=*/NoLoc,
12605                                              /*VolatileQualifierLoc=*/NoLoc,
12606                                              /*RestrictQualifierLoc=*/NoLoc,
12607                                              /*MutableLoc=*/NoLoc,
12608                                              EST_None,
12609                                              /*ESpecRange=*/SourceRange(),
12610                                              /*Exceptions=*/nullptr,
12611                                              /*ExceptionRanges=*/nullptr,
12612                                              /*NumExceptions=*/0,
12613                                              /*NoexceptExpr=*/nullptr,
12614                                              /*ExceptionSpecTokens=*/nullptr,
12615                                              /*DeclsInPrototype=*/None,
12616                                              Loc, Loc, D),
12617                 DS.getAttributes(),
12618                 SourceLocation());
12619   D.SetIdentifier(&II, Loc);
12620 
12621   // Insert this function into translation-unit scope.
12622 
12623   DeclContext *PrevDC = CurContext;
12624   CurContext = Context.getTranslationUnitDecl();
12625 
12626   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
12627   FD->setImplicit();
12628 
12629   CurContext = PrevDC;
12630 
12631   AddKnownFunctionAttributes(FD);
12632 
12633   return FD;
12634 }
12635 
12636 /// \brief Adds any function attributes that we know a priori based on
12637 /// the declaration of this function.
12638 ///
12639 /// These attributes can apply both to implicitly-declared builtins
12640 /// (like __builtin___printf_chk) or to library-declared functions
12641 /// like NSLog or printf.
12642 ///
12643 /// We need to check for duplicate attributes both here and where user-written
12644 /// attributes are applied to declarations.
12645 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
12646   if (FD->isInvalidDecl())
12647     return;
12648 
12649   // If this is a built-in function, map its builtin attributes to
12650   // actual attributes.
12651   if (unsigned BuiltinID = FD->getBuiltinID()) {
12652     // Handle printf-formatting attributes.
12653     unsigned FormatIdx;
12654     bool HasVAListArg;
12655     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
12656       if (!FD->hasAttr<FormatAttr>()) {
12657         const char *fmt = "printf";
12658         unsigned int NumParams = FD->getNumParams();
12659         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
12660             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
12661           fmt = "NSString";
12662         FD->addAttr(FormatAttr::CreateImplicit(Context,
12663                                                &Context.Idents.get(fmt),
12664                                                FormatIdx+1,
12665                                                HasVAListArg ? 0 : FormatIdx+2,
12666                                                FD->getLocation()));
12667       }
12668     }
12669     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
12670                                              HasVAListArg)) {
12671      if (!FD->hasAttr<FormatAttr>())
12672        FD->addAttr(FormatAttr::CreateImplicit(Context,
12673                                               &Context.Idents.get("scanf"),
12674                                               FormatIdx+1,
12675                                               HasVAListArg ? 0 : FormatIdx+2,
12676                                               FD->getLocation()));
12677     }
12678 
12679     // Mark const if we don't care about errno and that is the only
12680     // thing preventing the function from being const. This allows
12681     // IRgen to use LLVM intrinsics for such functions.
12682     if (!getLangOpts().MathErrno &&
12683         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
12684       if (!FD->hasAttr<ConstAttr>())
12685         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12686     }
12687 
12688     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
12689         !FD->hasAttr<ReturnsTwiceAttr>())
12690       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
12691                                          FD->getLocation()));
12692     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
12693       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12694     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
12695       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
12696     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
12697       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12698     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
12699         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
12700       // Add the appropriate attribute, depending on the CUDA compilation mode
12701       // and which target the builtin belongs to. For example, during host
12702       // compilation, aux builtins are __device__, while the rest are __host__.
12703       if (getLangOpts().CUDAIsDevice !=
12704           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
12705         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
12706       else
12707         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
12708     }
12709   }
12710 
12711   // If C++ exceptions are enabled but we are told extern "C" functions cannot
12712   // throw, add an implicit nothrow attribute to any extern "C" function we come
12713   // across.
12714   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
12715       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
12716     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
12717     if (!FPT || FPT->getExceptionSpecType() == EST_None)
12718       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12719   }
12720 
12721   IdentifierInfo *Name = FD->getIdentifier();
12722   if (!Name)
12723     return;
12724   if ((!getLangOpts().CPlusPlus &&
12725        FD->getDeclContext()->isTranslationUnit()) ||
12726       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
12727        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
12728        LinkageSpecDecl::lang_c)) {
12729     // Okay: this could be a libc/libm/Objective-C function we know
12730     // about.
12731   } else
12732     return;
12733 
12734   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
12735     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
12736     // target-specific builtins, perhaps?
12737     if (!FD->hasAttr<FormatAttr>())
12738       FD->addAttr(FormatAttr::CreateImplicit(Context,
12739                                              &Context.Idents.get("printf"), 2,
12740                                              Name->isStr("vasprintf") ? 0 : 3,
12741                                              FD->getLocation()));
12742   }
12743 
12744   if (Name->isStr("__CFStringMakeConstantString")) {
12745     // We already have a __builtin___CFStringMakeConstantString,
12746     // but builds that use -fno-constant-cfstrings don't go through that.
12747     if (!FD->hasAttr<FormatArgAttr>())
12748       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
12749                                                 FD->getLocation()));
12750   }
12751 }
12752 
12753 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
12754                                     TypeSourceInfo *TInfo) {
12755   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
12756   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
12757 
12758   if (!TInfo) {
12759     assert(D.isInvalidType() && "no declarator info for valid type");
12760     TInfo = Context.getTrivialTypeSourceInfo(T);
12761   }
12762 
12763   // Scope manipulation handled by caller.
12764   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
12765                                            D.getLocStart(),
12766                                            D.getIdentifierLoc(),
12767                                            D.getIdentifier(),
12768                                            TInfo);
12769 
12770   // Bail out immediately if we have an invalid declaration.
12771   if (D.isInvalidType()) {
12772     NewTD->setInvalidDecl();
12773     return NewTD;
12774   }
12775 
12776   if (D.getDeclSpec().isModulePrivateSpecified()) {
12777     if (CurContext->isFunctionOrMethod())
12778       Diag(NewTD->getLocation(), diag::err_module_private_local)
12779         << 2 << NewTD->getDeclName()
12780         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12781         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12782     else
12783       NewTD->setModulePrivate();
12784   }
12785 
12786   // C++ [dcl.typedef]p8:
12787   //   If the typedef declaration defines an unnamed class (or
12788   //   enum), the first typedef-name declared by the declaration
12789   //   to be that class type (or enum type) is used to denote the
12790   //   class type (or enum type) for linkage purposes only.
12791   // We need to check whether the type was declared in the declaration.
12792   switch (D.getDeclSpec().getTypeSpecType()) {
12793   case TST_enum:
12794   case TST_struct:
12795   case TST_interface:
12796   case TST_union:
12797   case TST_class: {
12798     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
12799     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
12800     break;
12801   }
12802 
12803   default:
12804     break;
12805   }
12806 
12807   return NewTD;
12808 }
12809 
12810 /// \brief Check that this is a valid underlying type for an enum declaration.
12811 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
12812   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
12813   QualType T = TI->getType();
12814 
12815   if (T->isDependentType())
12816     return false;
12817 
12818   if (const BuiltinType *BT = T->getAs<BuiltinType>())
12819     if (BT->isInteger())
12820       return false;
12821 
12822   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12823   return true;
12824 }
12825 
12826 /// Check whether this is a valid redeclaration of a previous enumeration.
12827 /// \return true if the redeclaration was invalid.
12828 bool Sema::CheckEnumRedeclaration(
12829     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12830     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12831   bool IsFixed = !EnumUnderlyingTy.isNull();
12832 
12833   if (IsScoped != Prev->isScoped()) {
12834     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12835       << Prev->isScoped();
12836     Diag(Prev->getLocation(), diag::note_previous_declaration);
12837     return true;
12838   }
12839 
12840   if (IsFixed && Prev->isFixed()) {
12841     if (!EnumUnderlyingTy->isDependentType() &&
12842         !Prev->getIntegerType()->isDependentType() &&
12843         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12844                                         Prev->getIntegerType())) {
12845       // TODO: Highlight the underlying type of the redeclaration.
12846       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12847         << EnumUnderlyingTy << Prev->getIntegerType();
12848       Diag(Prev->getLocation(), diag::note_previous_declaration)
12849           << Prev->getIntegerTypeRange();
12850       return true;
12851     }
12852   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12853     ;
12854   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12855     ;
12856   } else if (IsFixed != Prev->isFixed()) {
12857     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12858       << Prev->isFixed();
12859     Diag(Prev->getLocation(), diag::note_previous_declaration);
12860     return true;
12861   }
12862 
12863   return false;
12864 }
12865 
12866 /// \brief Get diagnostic %select index for tag kind for
12867 /// redeclaration diagnostic message.
12868 /// WARNING: Indexes apply to particular diagnostics only!
12869 ///
12870 /// \returns diagnostic %select index.
12871 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12872   switch (Tag) {
12873   case TTK_Struct: return 0;
12874   case TTK_Interface: return 1;
12875   case TTK_Class:  return 2;
12876   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12877   }
12878 }
12879 
12880 /// \brief Determine if tag kind is a class-key compatible with
12881 /// class for redeclaration (class, struct, or __interface).
12882 ///
12883 /// \returns true iff the tag kind is compatible.
12884 static bool isClassCompatTagKind(TagTypeKind Tag)
12885 {
12886   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12887 }
12888 
12889 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
12890                                              TagTypeKind TTK) {
12891   if (isa<TypedefDecl>(PrevDecl))
12892     return NTK_Typedef;
12893   else if (isa<TypeAliasDecl>(PrevDecl))
12894     return NTK_TypeAlias;
12895   else if (isa<ClassTemplateDecl>(PrevDecl))
12896     return NTK_Template;
12897   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
12898     return NTK_TypeAliasTemplate;
12899   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
12900     return NTK_TemplateTemplateArgument;
12901   switch (TTK) {
12902   case TTK_Struct:
12903   case TTK_Interface:
12904   case TTK_Class:
12905     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
12906   case TTK_Union:
12907     return NTK_NonUnion;
12908   case TTK_Enum:
12909     return NTK_NonEnum;
12910   }
12911   llvm_unreachable("invalid TTK");
12912 }
12913 
12914 /// \brief Determine whether a tag with a given kind is acceptable
12915 /// as a redeclaration of the given tag declaration.
12916 ///
12917 /// \returns true if the new tag kind is acceptable, false otherwise.
12918 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12919                                         TagTypeKind NewTag, bool isDefinition,
12920                                         SourceLocation NewTagLoc,
12921                                         const IdentifierInfo *Name) {
12922   // C++ [dcl.type.elab]p3:
12923   //   The class-key or enum keyword present in the
12924   //   elaborated-type-specifier shall agree in kind with the
12925   //   declaration to which the name in the elaborated-type-specifier
12926   //   refers. This rule also applies to the form of
12927   //   elaborated-type-specifier that declares a class-name or
12928   //   friend class since it can be construed as referring to the
12929   //   definition of the class. Thus, in any
12930   //   elaborated-type-specifier, the enum keyword shall be used to
12931   //   refer to an enumeration (7.2), the union class-key shall be
12932   //   used to refer to a union (clause 9), and either the class or
12933   //   struct class-key shall be used to refer to a class (clause 9)
12934   //   declared using the class or struct class-key.
12935   TagTypeKind OldTag = Previous->getTagKind();
12936   if (!isDefinition || !isClassCompatTagKind(NewTag))
12937     if (OldTag == NewTag)
12938       return true;
12939 
12940   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
12941     // Warn about the struct/class tag mismatch.
12942     bool isTemplate = false;
12943     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
12944       isTemplate = Record->getDescribedClassTemplate();
12945 
12946     if (inTemplateInstantiation()) {
12947       // In a template instantiation, do not offer fix-its for tag mismatches
12948       // since they usually mess up the template instead of fixing the problem.
12949       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12950         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12951         << getRedeclDiagFromTagKind(OldTag);
12952       return true;
12953     }
12954 
12955     if (isDefinition) {
12956       // On definitions, check previous tags and issue a fix-it for each
12957       // one that doesn't match the current tag.
12958       if (Previous->getDefinition()) {
12959         // Don't suggest fix-its for redefinitions.
12960         return true;
12961       }
12962 
12963       bool previousMismatch = false;
12964       for (auto I : Previous->redecls()) {
12965         if (I->getTagKind() != NewTag) {
12966           if (!previousMismatch) {
12967             previousMismatch = true;
12968             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
12969               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12970               << getRedeclDiagFromTagKind(I->getTagKind());
12971           }
12972           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
12973             << getRedeclDiagFromTagKind(NewTag)
12974             << FixItHint::CreateReplacement(I->getInnerLocStart(),
12975                  TypeWithKeyword::getTagTypeKindName(NewTag));
12976         }
12977       }
12978       return true;
12979     }
12980 
12981     // Check for a previous definition.  If current tag and definition
12982     // are same type, do nothing.  If no definition, but disagree with
12983     // with previous tag type, give a warning, but no fix-it.
12984     const TagDecl *Redecl = Previous->getDefinition() ?
12985                             Previous->getDefinition() : Previous;
12986     if (Redecl->getTagKind() == NewTag) {
12987       return true;
12988     }
12989 
12990     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12991       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12992       << getRedeclDiagFromTagKind(OldTag);
12993     Diag(Redecl->getLocation(), diag::note_previous_use);
12994 
12995     // If there is a previous definition, suggest a fix-it.
12996     if (Previous->getDefinition()) {
12997         Diag(NewTagLoc, diag::note_struct_class_suggestion)
12998           << getRedeclDiagFromTagKind(Redecl->getTagKind())
12999           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
13000                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
13001     }
13002 
13003     return true;
13004   }
13005   return false;
13006 }
13007 
13008 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
13009 /// from an outer enclosing namespace or file scope inside a friend declaration.
13010 /// This should provide the commented out code in the following snippet:
13011 ///   namespace N {
13012 ///     struct X;
13013 ///     namespace M {
13014 ///       struct Y { friend struct /*N::*/ X; };
13015 ///     }
13016 ///   }
13017 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
13018                                          SourceLocation NameLoc) {
13019   // While the decl is in a namespace, do repeated lookup of that name and see
13020   // if we get the same namespace back.  If we do not, continue until
13021   // translation unit scope, at which point we have a fully qualified NNS.
13022   SmallVector<IdentifierInfo *, 4> Namespaces;
13023   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13024   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
13025     // This tag should be declared in a namespace, which can only be enclosed by
13026     // other namespaces.  Bail if there's an anonymous namespace in the chain.
13027     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
13028     if (!Namespace || Namespace->isAnonymousNamespace())
13029       return FixItHint();
13030     IdentifierInfo *II = Namespace->getIdentifier();
13031     Namespaces.push_back(II);
13032     NamedDecl *Lookup = SemaRef.LookupSingleName(
13033         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
13034     if (Lookup == Namespace)
13035       break;
13036   }
13037 
13038   // Once we have all the namespaces, reverse them to go outermost first, and
13039   // build an NNS.
13040   SmallString<64> Insertion;
13041   llvm::raw_svector_ostream OS(Insertion);
13042   if (DC->isTranslationUnit())
13043     OS << "::";
13044   std::reverse(Namespaces.begin(), Namespaces.end());
13045   for (auto *II : Namespaces)
13046     OS << II->getName() << "::";
13047   return FixItHint::CreateInsertion(NameLoc, Insertion);
13048 }
13049 
13050 /// \brief Determine whether a tag originally declared in context \p OldDC can
13051 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
13052 /// found a declaration in \p OldDC as a previous decl, perhaps through a
13053 /// using-declaration).
13054 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
13055                                          DeclContext *NewDC) {
13056   OldDC = OldDC->getRedeclContext();
13057   NewDC = NewDC->getRedeclContext();
13058 
13059   if (OldDC->Equals(NewDC))
13060     return true;
13061 
13062   // In MSVC mode, we allow a redeclaration if the contexts are related (either
13063   // encloses the other).
13064   if (S.getLangOpts().MSVCCompat &&
13065       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
13066     return true;
13067 
13068   return false;
13069 }
13070 
13071 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
13072 /// former case, Name will be non-null.  In the later case, Name will be null.
13073 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
13074 /// reference/declaration/definition of a tag.
13075 ///
13076 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
13077 /// trailing-type-specifier) other than one in an alias-declaration.
13078 ///
13079 /// \param SkipBody If non-null, will be set to indicate if the caller should
13080 /// skip the definition of this tag and treat it as if it were a declaration.
13081 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
13082                      SourceLocation KWLoc, CXXScopeSpec &SS,
13083                      IdentifierInfo *Name, SourceLocation NameLoc,
13084                      AttributeList *Attr, AccessSpecifier AS,
13085                      SourceLocation ModulePrivateLoc,
13086                      MultiTemplateParamsArg TemplateParameterLists,
13087                      bool &OwnedDecl, bool &IsDependent,
13088                      SourceLocation ScopedEnumKWLoc,
13089                      bool ScopedEnumUsesClassTag,
13090                      TypeResult UnderlyingType,
13091                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
13092                      SkipBodyInfo *SkipBody) {
13093   // If this is not a definition, it must have a name.
13094   IdentifierInfo *OrigName = Name;
13095   assert((Name != nullptr || TUK == TUK_Definition) &&
13096          "Nameless record must be a definition!");
13097   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
13098 
13099   OwnedDecl = false;
13100   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13101   bool ScopedEnum = ScopedEnumKWLoc.isValid();
13102 
13103   // FIXME: Check member specializations more carefully.
13104   bool isMemberSpecialization = false;
13105   bool Invalid = false;
13106 
13107   // We only need to do this matching if we have template parameters
13108   // or a scope specifier, which also conveniently avoids this work
13109   // for non-C++ cases.
13110   if (TemplateParameterLists.size() > 0 ||
13111       (SS.isNotEmpty() && TUK != TUK_Reference)) {
13112     if (TemplateParameterList *TemplateParams =
13113             MatchTemplateParametersToScopeSpecifier(
13114                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
13115                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
13116       if (Kind == TTK_Enum) {
13117         Diag(KWLoc, diag::err_enum_template);
13118         return nullptr;
13119       }
13120 
13121       if (TemplateParams->size() > 0) {
13122         // This is a declaration or definition of a class template (which may
13123         // be a member of another template).
13124 
13125         if (Invalid)
13126           return nullptr;
13127 
13128         OwnedDecl = false;
13129         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
13130                                                SS, Name, NameLoc, Attr,
13131                                                TemplateParams, AS,
13132                                                ModulePrivateLoc,
13133                                                /*FriendLoc*/SourceLocation(),
13134                                                TemplateParameterLists.size()-1,
13135                                                TemplateParameterLists.data(),
13136                                                SkipBody);
13137         return Result.get();
13138       } else {
13139         // The "template<>" header is extraneous.
13140         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13141           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13142         isMemberSpecialization = true;
13143       }
13144     }
13145   }
13146 
13147   // Figure out the underlying type if this a enum declaration. We need to do
13148   // this early, because it's needed to detect if this is an incompatible
13149   // redeclaration.
13150   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
13151   bool EnumUnderlyingIsImplicit = false;
13152 
13153   if (Kind == TTK_Enum) {
13154     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
13155       // No underlying type explicitly specified, or we failed to parse the
13156       // type, default to int.
13157       EnumUnderlying = Context.IntTy.getTypePtr();
13158     else if (UnderlyingType.get()) {
13159       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
13160       // integral type; any cv-qualification is ignored.
13161       TypeSourceInfo *TI = nullptr;
13162       GetTypeFromParser(UnderlyingType.get(), &TI);
13163       EnumUnderlying = TI;
13164 
13165       if (CheckEnumUnderlyingType(TI))
13166         // Recover by falling back to int.
13167         EnumUnderlying = Context.IntTy.getTypePtr();
13168 
13169       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
13170                                           UPPC_FixedUnderlyingType))
13171         EnumUnderlying = Context.IntTy.getTypePtr();
13172 
13173     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13174       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
13175         // Microsoft enums are always of int type.
13176         EnumUnderlying = Context.IntTy.getTypePtr();
13177         EnumUnderlyingIsImplicit = true;
13178       }
13179     }
13180   }
13181 
13182   DeclContext *SearchDC = CurContext;
13183   DeclContext *DC = CurContext;
13184   bool isStdBadAlloc = false;
13185   bool isStdAlignValT = false;
13186 
13187   RedeclarationKind Redecl = ForRedeclaration;
13188   if (TUK == TUK_Friend || TUK == TUK_Reference)
13189     Redecl = NotForRedeclaration;
13190 
13191   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
13192   if (Name && SS.isNotEmpty()) {
13193     // We have a nested-name tag ('struct foo::bar').
13194 
13195     // Check for invalid 'foo::'.
13196     if (SS.isInvalid()) {
13197       Name = nullptr;
13198       goto CreateNewDecl;
13199     }
13200 
13201     // If this is a friend or a reference to a class in a dependent
13202     // context, don't try to make a decl for it.
13203     if (TUK == TUK_Friend || TUK == TUK_Reference) {
13204       DC = computeDeclContext(SS, false);
13205       if (!DC) {
13206         IsDependent = true;
13207         return nullptr;
13208       }
13209     } else {
13210       DC = computeDeclContext(SS, true);
13211       if (!DC) {
13212         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
13213           << SS.getRange();
13214         return nullptr;
13215       }
13216     }
13217 
13218     if (RequireCompleteDeclContext(SS, DC))
13219       return nullptr;
13220 
13221     SearchDC = DC;
13222     // Look-up name inside 'foo::'.
13223     LookupQualifiedName(Previous, DC);
13224 
13225     if (Previous.isAmbiguous())
13226       return nullptr;
13227 
13228     if (Previous.empty()) {
13229       // Name lookup did not find anything. However, if the
13230       // nested-name-specifier refers to the current instantiation,
13231       // and that current instantiation has any dependent base
13232       // classes, we might find something at instantiation time: treat
13233       // this as a dependent elaborated-type-specifier.
13234       // But this only makes any sense for reference-like lookups.
13235       if (Previous.wasNotFoundInCurrentInstantiation() &&
13236           (TUK == TUK_Reference || TUK == TUK_Friend)) {
13237         IsDependent = true;
13238         return nullptr;
13239       }
13240 
13241       // A tag 'foo::bar' must already exist.
13242       Diag(NameLoc, diag::err_not_tag_in_scope)
13243         << Kind << Name << DC << SS.getRange();
13244       Name = nullptr;
13245       Invalid = true;
13246       goto CreateNewDecl;
13247     }
13248   } else if (Name) {
13249     // C++14 [class.mem]p14:
13250     //   If T is the name of a class, then each of the following shall have a
13251     //   name different from T:
13252     //    -- every member of class T that is itself a type
13253     if (TUK != TUK_Reference && TUK != TUK_Friend &&
13254         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
13255       return nullptr;
13256 
13257     // If this is a named struct, check to see if there was a previous forward
13258     // declaration or definition.
13259     // FIXME: We're looking into outer scopes here, even when we
13260     // shouldn't be. Doing so can result in ambiguities that we
13261     // shouldn't be diagnosing.
13262     LookupName(Previous, S);
13263 
13264     // When declaring or defining a tag, ignore ambiguities introduced
13265     // by types using'ed into this scope.
13266     if (Previous.isAmbiguous() &&
13267         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
13268       LookupResult::Filter F = Previous.makeFilter();
13269       while (F.hasNext()) {
13270         NamedDecl *ND = F.next();
13271         if (!ND->getDeclContext()->getRedeclContext()->Equals(
13272                 SearchDC->getRedeclContext()))
13273           F.erase();
13274       }
13275       F.done();
13276     }
13277 
13278     // C++11 [namespace.memdef]p3:
13279     //   If the name in a friend declaration is neither qualified nor
13280     //   a template-id and the declaration is a function or an
13281     //   elaborated-type-specifier, the lookup to determine whether
13282     //   the entity has been previously declared shall not consider
13283     //   any scopes outside the innermost enclosing namespace.
13284     //
13285     // MSVC doesn't implement the above rule for types, so a friend tag
13286     // declaration may be a redeclaration of a type declared in an enclosing
13287     // scope.  They do implement this rule for friend functions.
13288     //
13289     // Does it matter that this should be by scope instead of by
13290     // semantic context?
13291     if (!Previous.empty() && TUK == TUK_Friend) {
13292       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
13293       LookupResult::Filter F = Previous.makeFilter();
13294       bool FriendSawTagOutsideEnclosingNamespace = false;
13295       while (F.hasNext()) {
13296         NamedDecl *ND = F.next();
13297         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13298         if (DC->isFileContext() &&
13299             !EnclosingNS->Encloses(ND->getDeclContext())) {
13300           if (getLangOpts().MSVCCompat)
13301             FriendSawTagOutsideEnclosingNamespace = true;
13302           else
13303             F.erase();
13304         }
13305       }
13306       F.done();
13307 
13308       // Diagnose this MSVC extension in the easy case where lookup would have
13309       // unambiguously found something outside the enclosing namespace.
13310       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
13311         NamedDecl *ND = Previous.getFoundDecl();
13312         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
13313             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
13314       }
13315     }
13316 
13317     // Note:  there used to be some attempt at recovery here.
13318     if (Previous.isAmbiguous())
13319       return nullptr;
13320 
13321     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
13322       // FIXME: This makes sure that we ignore the contexts associated
13323       // with C structs, unions, and enums when looking for a matching
13324       // tag declaration or definition. See the similar lookup tweak
13325       // in Sema::LookupName; is there a better way to deal with this?
13326       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
13327         SearchDC = SearchDC->getParent();
13328     }
13329   }
13330 
13331   if (Previous.isSingleResult() &&
13332       Previous.getFoundDecl()->isTemplateParameter()) {
13333     // Maybe we will complain about the shadowed template parameter.
13334     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
13335     // Just pretend that we didn't see the previous declaration.
13336     Previous.clear();
13337   }
13338 
13339   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
13340       DC->Equals(getStdNamespace())) {
13341     if (Name->isStr("bad_alloc")) {
13342       // This is a declaration of or a reference to "std::bad_alloc".
13343       isStdBadAlloc = true;
13344 
13345       // If std::bad_alloc has been implicitly declared (but made invisible to
13346       // name lookup), fill in this implicit declaration as the previous
13347       // declaration, so that the declarations get chained appropriately.
13348       if (Previous.empty() && StdBadAlloc)
13349         Previous.addDecl(getStdBadAlloc());
13350     } else if (Name->isStr("align_val_t")) {
13351       isStdAlignValT = true;
13352       if (Previous.empty() && StdAlignValT)
13353         Previous.addDecl(getStdAlignValT());
13354     }
13355   }
13356 
13357   // If we didn't find a previous declaration, and this is a reference
13358   // (or friend reference), move to the correct scope.  In C++, we
13359   // also need to do a redeclaration lookup there, just in case
13360   // there's a shadow friend decl.
13361   if (Name && Previous.empty() &&
13362       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
13363     if (Invalid) goto CreateNewDecl;
13364     assert(SS.isEmpty());
13365 
13366     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
13367       // C++ [basic.scope.pdecl]p5:
13368       //   -- for an elaborated-type-specifier of the form
13369       //
13370       //          class-key identifier
13371       //
13372       //      if the elaborated-type-specifier is used in the
13373       //      decl-specifier-seq or parameter-declaration-clause of a
13374       //      function defined in namespace scope, the identifier is
13375       //      declared as a class-name in the namespace that contains
13376       //      the declaration; otherwise, except as a friend
13377       //      declaration, the identifier is declared in the smallest
13378       //      non-class, non-function-prototype scope that contains the
13379       //      declaration.
13380       //
13381       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
13382       // C structs and unions.
13383       //
13384       // It is an error in C++ to declare (rather than define) an enum
13385       // type, including via an elaborated type specifier.  We'll
13386       // diagnose that later; for now, declare the enum in the same
13387       // scope as we would have picked for any other tag type.
13388       //
13389       // GNU C also supports this behavior as part of its incomplete
13390       // enum types extension, while GNU C++ does not.
13391       //
13392       // Find the context where we'll be declaring the tag.
13393       // FIXME: We would like to maintain the current DeclContext as the
13394       // lexical context,
13395       SearchDC = getTagInjectionContext(SearchDC);
13396 
13397       // Find the scope where we'll be declaring the tag.
13398       S = getTagInjectionScope(S, getLangOpts());
13399     } else {
13400       assert(TUK == TUK_Friend);
13401       // C++ [namespace.memdef]p3:
13402       //   If a friend declaration in a non-local class first declares a
13403       //   class or function, the friend class or function is a member of
13404       //   the innermost enclosing namespace.
13405       SearchDC = SearchDC->getEnclosingNamespaceContext();
13406     }
13407 
13408     // In C++, we need to do a redeclaration lookup to properly
13409     // diagnose some problems.
13410     // FIXME: redeclaration lookup is also used (with and without C++) to find a
13411     // hidden declaration so that we don't get ambiguity errors when using a
13412     // type declared by an elaborated-type-specifier.  In C that is not correct
13413     // and we should instead merge compatible types found by lookup.
13414     if (getLangOpts().CPlusPlus) {
13415       Previous.setRedeclarationKind(ForRedeclaration);
13416       LookupQualifiedName(Previous, SearchDC);
13417     } else {
13418       Previous.setRedeclarationKind(ForRedeclaration);
13419       LookupName(Previous, S);
13420     }
13421   }
13422 
13423   // If we have a known previous declaration to use, then use it.
13424   if (Previous.empty() && SkipBody && SkipBody->Previous)
13425     Previous.addDecl(SkipBody->Previous);
13426 
13427   if (!Previous.empty()) {
13428     NamedDecl *PrevDecl = Previous.getFoundDecl();
13429     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13430 
13431     // It's okay to have a tag decl in the same scope as a typedef
13432     // which hides a tag decl in the same scope.  Finding this
13433     // insanity with a redeclaration lookup can only actually happen
13434     // in C++.
13435     //
13436     // This is also okay for elaborated-type-specifiers, which is
13437     // technically forbidden by the current standard but which is
13438     // okay according to the likely resolution of an open issue;
13439     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13440     if (getLangOpts().CPlusPlus) {
13441       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13442         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13443           TagDecl *Tag = TT->getDecl();
13444           if (Tag->getDeclName() == Name &&
13445               Tag->getDeclContext()->getRedeclContext()
13446                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
13447             PrevDecl = Tag;
13448             Previous.clear();
13449             Previous.addDecl(Tag);
13450             Previous.resolveKind();
13451           }
13452         }
13453       }
13454     }
13455 
13456     // If this is a redeclaration of a using shadow declaration, it must
13457     // declare a tag in the same context. In MSVC mode, we allow a
13458     // redefinition if either context is within the other.
13459     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13460       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13461       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13462           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
13463           !(OldTag && isAcceptableTagRedeclContext(
13464                           *this, OldTag->getDeclContext(), SearchDC))) {
13465         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13466         Diag(Shadow->getTargetDecl()->getLocation(),
13467              diag::note_using_decl_target);
13468         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13469             << 0;
13470         // Recover by ignoring the old declaration.
13471         Previous.clear();
13472         goto CreateNewDecl;
13473       }
13474     }
13475 
13476     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13477       // If this is a use of a previous tag, or if the tag is already declared
13478       // in the same scope (so that the definition/declaration completes or
13479       // rementions the tag), reuse the decl.
13480       if (TUK == TUK_Reference || TUK == TUK_Friend ||
13481           isDeclInScope(DirectPrevDecl, SearchDC, S,
13482                         SS.isNotEmpty() || isMemberSpecialization)) {
13483         // Make sure that this wasn't declared as an enum and now used as a
13484         // struct or something similar.
13485         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13486                                           TUK == TUK_Definition, KWLoc,
13487                                           Name)) {
13488           bool SafeToContinue
13489             = (PrevTagDecl->getTagKind() != TTK_Enum &&
13490                Kind != TTK_Enum);
13491           if (SafeToContinue)
13492             Diag(KWLoc, diag::err_use_with_wrong_tag)
13493               << Name
13494               << FixItHint::CreateReplacement(SourceRange(KWLoc),
13495                                               PrevTagDecl->getKindName());
13496           else
13497             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13498           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13499 
13500           if (SafeToContinue)
13501             Kind = PrevTagDecl->getTagKind();
13502           else {
13503             // Recover by making this an anonymous redefinition.
13504             Name = nullptr;
13505             Previous.clear();
13506             Invalid = true;
13507           }
13508         }
13509 
13510         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
13511           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
13512 
13513           // If this is an elaborated-type-specifier for a scoped enumeration,
13514           // the 'class' keyword is not necessary and not permitted.
13515           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13516             if (ScopedEnum)
13517               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
13518                 << PrevEnum->isScoped()
13519                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
13520             return PrevTagDecl;
13521           }
13522 
13523           QualType EnumUnderlyingTy;
13524           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13525             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
13526           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
13527             EnumUnderlyingTy = QualType(T, 0);
13528 
13529           // All conflicts with previous declarations are recovered by
13530           // returning the previous declaration, unless this is a definition,
13531           // in which case we want the caller to bail out.
13532           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
13533                                      ScopedEnum, EnumUnderlyingTy,
13534                                      EnumUnderlyingIsImplicit, PrevEnum))
13535             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
13536         }
13537 
13538         // C++11 [class.mem]p1:
13539         //   A member shall not be declared twice in the member-specification,
13540         //   except that a nested class or member class template can be declared
13541         //   and then later defined.
13542         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
13543             S->isDeclScope(PrevDecl)) {
13544           Diag(NameLoc, diag::ext_member_redeclared);
13545           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
13546         }
13547 
13548         if (!Invalid) {
13549           // If this is a use, just return the declaration we found, unless
13550           // we have attributes.
13551           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13552             if (Attr) {
13553               // FIXME: Diagnose these attributes. For now, we create a new
13554               // declaration to hold them.
13555             } else if (TUK == TUK_Reference &&
13556                        (PrevTagDecl->getFriendObjectKind() ==
13557                             Decl::FOK_Undeclared ||
13558                         PrevDecl->getOwningModule() != getCurrentModule()) &&
13559                        SS.isEmpty()) {
13560               // This declaration is a reference to an existing entity, but
13561               // has different visibility from that entity: it either makes
13562               // a friend visible or it makes a type visible in a new module.
13563               // In either case, create a new declaration. We only do this if
13564               // the declaration would have meant the same thing if no prior
13565               // declaration were found, that is, if it was found in the same
13566               // scope where we would have injected a declaration.
13567               if (!getTagInjectionContext(CurContext)->getRedeclContext()
13568                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
13569                 return PrevTagDecl;
13570               // This is in the injected scope, create a new declaration in
13571               // that scope.
13572               S = getTagInjectionScope(S, getLangOpts());
13573             } else {
13574               return PrevTagDecl;
13575             }
13576           }
13577 
13578           // Diagnose attempts to redefine a tag.
13579           if (TUK == TUK_Definition) {
13580             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
13581               // If we're defining a specialization and the previous definition
13582               // is from an implicit instantiation, don't emit an error
13583               // here; we'll catch this in the general case below.
13584               bool IsExplicitSpecializationAfterInstantiation = false;
13585               if (isMemberSpecialization) {
13586                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
13587                   IsExplicitSpecializationAfterInstantiation =
13588                     RD->getTemplateSpecializationKind() !=
13589                     TSK_ExplicitSpecialization;
13590                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
13591                   IsExplicitSpecializationAfterInstantiation =
13592                     ED->getTemplateSpecializationKind() !=
13593                     TSK_ExplicitSpecialization;
13594               }
13595 
13596               NamedDecl *Hidden = nullptr;
13597               if (SkipBody && getLangOpts().CPlusPlus &&
13598                   !hasVisibleDefinition(Def, &Hidden)) {
13599                 // There is a definition of this tag, but it is not visible. We
13600                 // explicitly make use of C++'s one definition rule here, and
13601                 // assume that this definition is identical to the hidden one
13602                 // we already have. Make the existing definition visible and
13603                 // use it in place of this one.
13604                 SkipBody->ShouldSkip = true;
13605                 makeMergedDefinitionVisible(Hidden);
13606                 return Def;
13607               } else if (!IsExplicitSpecializationAfterInstantiation) {
13608                 // A redeclaration in function prototype scope in C isn't
13609                 // visible elsewhere, so merely issue a warning.
13610                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
13611                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
13612                 else
13613                   Diag(NameLoc, diag::err_redefinition) << Name;
13614                 notePreviousDefinition(Def,
13615                                        NameLoc.isValid() ? NameLoc : KWLoc);
13616                 // If this is a redefinition, recover by making this
13617                 // struct be anonymous, which will make any later
13618                 // references get the previous definition.
13619                 Name = nullptr;
13620                 Previous.clear();
13621                 Invalid = true;
13622               }
13623             } else {
13624               // If the type is currently being defined, complain
13625               // about a nested redefinition.
13626               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
13627               if (TD->isBeingDefined()) {
13628                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
13629                 Diag(PrevTagDecl->getLocation(),
13630                      diag::note_previous_definition);
13631                 Name = nullptr;
13632                 Previous.clear();
13633                 Invalid = true;
13634               }
13635             }
13636 
13637             // Okay, this is definition of a previously declared or referenced
13638             // tag. We're going to create a new Decl for it.
13639           }
13640 
13641           // Okay, we're going to make a redeclaration.  If this is some kind
13642           // of reference, make sure we build the redeclaration in the same DC
13643           // as the original, and ignore the current access specifier.
13644           if (TUK == TUK_Friend || TUK == TUK_Reference) {
13645             SearchDC = PrevTagDecl->getDeclContext();
13646             AS = AS_none;
13647           }
13648         }
13649         // If we get here we have (another) forward declaration or we
13650         // have a definition.  Just create a new decl.
13651 
13652       } else {
13653         // If we get here, this is a definition of a new tag type in a nested
13654         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
13655         // new decl/type.  We set PrevDecl to NULL so that the entities
13656         // have distinct types.
13657         Previous.clear();
13658       }
13659       // If we get here, we're going to create a new Decl. If PrevDecl
13660       // is non-NULL, it's a definition of the tag declared by
13661       // PrevDecl. If it's NULL, we have a new definition.
13662 
13663     // Otherwise, PrevDecl is not a tag, but was found with tag
13664     // lookup.  This is only actually possible in C++, where a few
13665     // things like templates still live in the tag namespace.
13666     } else {
13667       // Use a better diagnostic if an elaborated-type-specifier
13668       // found the wrong kind of type on the first
13669       // (non-redeclaration) lookup.
13670       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
13671           !Previous.isForRedeclaration()) {
13672         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13673         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
13674                                                        << Kind;
13675         Diag(PrevDecl->getLocation(), diag::note_declared_at);
13676         Invalid = true;
13677 
13678       // Otherwise, only diagnose if the declaration is in scope.
13679       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
13680                                 SS.isNotEmpty() || isMemberSpecialization)) {
13681         // do nothing
13682 
13683       // Diagnose implicit declarations introduced by elaborated types.
13684       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
13685         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13686         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
13687         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13688         Invalid = true;
13689 
13690       // Otherwise it's a declaration.  Call out a particularly common
13691       // case here.
13692       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13693         unsigned Kind = 0;
13694         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
13695         Diag(NameLoc, diag::err_tag_definition_of_typedef)
13696           << Name << Kind << TND->getUnderlyingType();
13697         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13698         Invalid = true;
13699 
13700       // Otherwise, diagnose.
13701       } else {
13702         // The tag name clashes with something else in the target scope,
13703         // issue an error and recover by making this tag be anonymous.
13704         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
13705         notePreviousDefinition(PrevDecl, NameLoc);
13706         Name = nullptr;
13707         Invalid = true;
13708       }
13709 
13710       // The existing declaration isn't relevant to us; we're in a
13711       // new scope, so clear out the previous declaration.
13712       Previous.clear();
13713     }
13714   }
13715 
13716 CreateNewDecl:
13717 
13718   TagDecl *PrevDecl = nullptr;
13719   if (Previous.isSingleResult())
13720     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
13721 
13722   // If there is an identifier, use the location of the identifier as the
13723   // location of the decl, otherwise use the location of the struct/union
13724   // keyword.
13725   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13726 
13727   // Otherwise, create a new declaration. If there is a previous
13728   // declaration of the same entity, the two will be linked via
13729   // PrevDecl.
13730   TagDecl *New;
13731 
13732   bool IsForwardReference = false;
13733   if (Kind == TTK_Enum) {
13734     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13735     // enum X { A, B, C } D;    D should chain to X.
13736     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
13737                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
13738                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
13739 
13740     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
13741       StdAlignValT = cast<EnumDecl>(New);
13742 
13743     // If this is an undefined enum, warn.
13744     if (TUK != TUK_Definition && !Invalid) {
13745       TagDecl *Def;
13746       if (!EnumUnderlyingIsImplicit &&
13747           (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
13748           cast<EnumDecl>(New)->isFixed()) {
13749         // C++0x: 7.2p2: opaque-enum-declaration.
13750         // Conflicts are diagnosed above. Do nothing.
13751       }
13752       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
13753         Diag(Loc, diag::ext_forward_ref_enum_def)
13754           << New;
13755         Diag(Def->getLocation(), diag::note_previous_definition);
13756       } else {
13757         unsigned DiagID = diag::ext_forward_ref_enum;
13758         if (getLangOpts().MSVCCompat)
13759           DiagID = diag::ext_ms_forward_ref_enum;
13760         else if (getLangOpts().CPlusPlus)
13761           DiagID = diag::err_forward_ref_enum;
13762         Diag(Loc, DiagID);
13763 
13764         // If this is a forward-declared reference to an enumeration, make a
13765         // note of it; we won't actually be introducing the declaration into
13766         // the declaration context.
13767         if (TUK == TUK_Reference)
13768           IsForwardReference = true;
13769       }
13770     }
13771 
13772     if (EnumUnderlying) {
13773       EnumDecl *ED = cast<EnumDecl>(New);
13774       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13775         ED->setIntegerTypeSourceInfo(TI);
13776       else
13777         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
13778       ED->setPromotionType(ED->getIntegerType());
13779     }
13780   } else {
13781     // struct/union/class
13782 
13783     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13784     // struct X { int A; } D;    D should chain to X.
13785     if (getLangOpts().CPlusPlus) {
13786       // FIXME: Look for a way to use RecordDecl for simple structs.
13787       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13788                                   cast_or_null<CXXRecordDecl>(PrevDecl));
13789 
13790       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
13791         StdBadAlloc = cast<CXXRecordDecl>(New);
13792     } else
13793       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13794                                cast_or_null<RecordDecl>(PrevDecl));
13795   }
13796 
13797   // C++11 [dcl.type]p3:
13798   //   A type-specifier-seq shall not define a class or enumeration [...].
13799   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
13800       TUK == TUK_Definition) {
13801     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
13802       << Context.getTagDeclType(New);
13803     Invalid = true;
13804   }
13805 
13806   // Maybe add qualifier info.
13807   if (SS.isNotEmpty()) {
13808     if (SS.isSet()) {
13809       // If this is either a declaration or a definition, check the
13810       // nested-name-specifier against the current context. We don't do this
13811       // for explicit specializations, because they have similar checking
13812       // (with more specific diagnostics) in the call to
13813       // CheckMemberSpecialization, below.
13814       if (!isMemberSpecialization &&
13815           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
13816           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
13817         Invalid = true;
13818 
13819       New->setQualifierInfo(SS.getWithLocInContext(Context));
13820       if (TemplateParameterLists.size() > 0) {
13821         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
13822       }
13823     }
13824     else
13825       Invalid = true;
13826   }
13827 
13828   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13829     // Add alignment attributes if necessary; these attributes are checked when
13830     // the ASTContext lays out the structure.
13831     //
13832     // It is important for implementing the correct semantics that this
13833     // happen here (in act on tag decl). The #pragma pack stack is
13834     // maintained as a result of parser callbacks which can occur at
13835     // many points during the parsing of a struct declaration (because
13836     // the #pragma tokens are effectively skipped over during the
13837     // parsing of the struct).
13838     if (TUK == TUK_Definition) {
13839       AddAlignmentAttributesForRecord(RD);
13840       AddMsStructLayoutForRecord(RD);
13841     }
13842   }
13843 
13844   if (ModulePrivateLoc.isValid()) {
13845     if (isMemberSpecialization)
13846       Diag(New->getLocation(), diag::err_module_private_specialization)
13847         << 2
13848         << FixItHint::CreateRemoval(ModulePrivateLoc);
13849     // __module_private__ does not apply to local classes. However, we only
13850     // diagnose this as an error when the declaration specifiers are
13851     // freestanding. Here, we just ignore the __module_private__.
13852     else if (!SearchDC->isFunctionOrMethod())
13853       New->setModulePrivate();
13854   }
13855 
13856   // If this is a specialization of a member class (of a class template),
13857   // check the specialization.
13858   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
13859     Invalid = true;
13860 
13861   // If we're declaring or defining a tag in function prototype scope in C,
13862   // note that this type can only be used within the function and add it to
13863   // the list of decls to inject into the function definition scope.
13864   if ((Name || Kind == TTK_Enum) &&
13865       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
13866     if (getLangOpts().CPlusPlus) {
13867       // C++ [dcl.fct]p6:
13868       //   Types shall not be defined in return or parameter types.
13869       if (TUK == TUK_Definition && !IsTypeSpecifier) {
13870         Diag(Loc, diag::err_type_defined_in_param_type)
13871             << Name;
13872         Invalid = true;
13873       }
13874     } else if (!PrevDecl) {
13875       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
13876     }
13877   }
13878 
13879   if (Invalid)
13880     New->setInvalidDecl();
13881 
13882   // Set the lexical context. If the tag has a C++ scope specifier, the
13883   // lexical context will be different from the semantic context.
13884   New->setLexicalDeclContext(CurContext);
13885 
13886   // Mark this as a friend decl if applicable.
13887   // In Microsoft mode, a friend declaration also acts as a forward
13888   // declaration so we always pass true to setObjectOfFriendDecl to make
13889   // the tag name visible.
13890   if (TUK == TUK_Friend)
13891     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
13892 
13893   // Set the access specifier.
13894   if (!Invalid && SearchDC->isRecord())
13895     SetMemberAccessSpecifier(New, PrevDecl, AS);
13896 
13897   if (TUK == TUK_Definition)
13898     New->startDefinition();
13899 
13900   if (Attr)
13901     ProcessDeclAttributeList(S, New, Attr);
13902   AddPragmaAttributes(S, New);
13903 
13904   // If this has an identifier, add it to the scope stack.
13905   if (TUK == TUK_Friend) {
13906     // We might be replacing an existing declaration in the lookup tables;
13907     // if so, borrow its access specifier.
13908     if (PrevDecl)
13909       New->setAccess(PrevDecl->getAccess());
13910 
13911     DeclContext *DC = New->getDeclContext()->getRedeclContext();
13912     DC->makeDeclVisibleInContext(New);
13913     if (Name) // can be null along some error paths
13914       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13915         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
13916   } else if (Name) {
13917     S = getNonFieldDeclScope(S);
13918     PushOnScopeChains(New, S, !IsForwardReference);
13919     if (IsForwardReference)
13920       SearchDC->makeDeclVisibleInContext(New);
13921   } else {
13922     CurContext->addDecl(New);
13923   }
13924 
13925   // If this is the C FILE type, notify the AST context.
13926   if (IdentifierInfo *II = New->getIdentifier())
13927     if (!New->isInvalidDecl() &&
13928         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
13929         II->isStr("FILE"))
13930       Context.setFILEDecl(New);
13931 
13932   if (PrevDecl)
13933     mergeDeclAttributes(New, PrevDecl);
13934 
13935   // If there's a #pragma GCC visibility in scope, set the visibility of this
13936   // record.
13937   AddPushedVisibilityAttribute(New);
13938 
13939   if (isMemberSpecialization && !New->isInvalidDecl())
13940     CompleteMemberSpecialization(New, Previous);
13941 
13942   OwnedDecl = true;
13943   // In C++, don't return an invalid declaration. We can't recover well from
13944   // the cases where we make the type anonymous.
13945   if (Invalid && getLangOpts().CPlusPlus) {
13946     if (New->isBeingDefined())
13947       if (auto RD = dyn_cast<RecordDecl>(New))
13948         RD->completeDefinition();
13949     return nullptr;
13950   } else {
13951     return New;
13952   }
13953 }
13954 
13955 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
13956   AdjustDeclIfTemplate(TagD);
13957   TagDecl *Tag = cast<TagDecl>(TagD);
13958 
13959   // Enter the tag context.
13960   PushDeclContext(S, Tag);
13961 
13962   ActOnDocumentableDecl(TagD);
13963 
13964   // If there's a #pragma GCC visibility in scope, set the visibility of this
13965   // record.
13966   AddPushedVisibilityAttribute(Tag);
13967 }
13968 
13969 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
13970   assert(isa<ObjCContainerDecl>(IDecl) &&
13971          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
13972   DeclContext *OCD = cast<DeclContext>(IDecl);
13973   assert(getContainingDC(OCD) == CurContext &&
13974       "The next DeclContext should be lexically contained in the current one.");
13975   CurContext = OCD;
13976   return IDecl;
13977 }
13978 
13979 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
13980                                            SourceLocation FinalLoc,
13981                                            bool IsFinalSpelledSealed,
13982                                            SourceLocation LBraceLoc) {
13983   AdjustDeclIfTemplate(TagD);
13984   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
13985 
13986   FieldCollector->StartClass();
13987 
13988   if (!Record->getIdentifier())
13989     return;
13990 
13991   if (FinalLoc.isValid())
13992     Record->addAttr(new (Context)
13993                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
13994 
13995   // C++ [class]p2:
13996   //   [...] The class-name is also inserted into the scope of the
13997   //   class itself; this is known as the injected-class-name. For
13998   //   purposes of access checking, the injected-class-name is treated
13999   //   as if it were a public member name.
14000   CXXRecordDecl *InjectedClassName
14001     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
14002                             Record->getLocStart(), Record->getLocation(),
14003                             Record->getIdentifier(),
14004                             /*PrevDecl=*/nullptr,
14005                             /*DelayTypeCreation=*/true);
14006   Context.getTypeDeclType(InjectedClassName, Record);
14007   InjectedClassName->setImplicit();
14008   InjectedClassName->setAccess(AS_public);
14009   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
14010       InjectedClassName->setDescribedClassTemplate(Template);
14011   PushOnScopeChains(InjectedClassName, S);
14012   assert(InjectedClassName->isInjectedClassName() &&
14013          "Broken injected-class-name");
14014 }
14015 
14016 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
14017                                     SourceRange BraceRange) {
14018   AdjustDeclIfTemplate(TagD);
14019   TagDecl *Tag = cast<TagDecl>(TagD);
14020   Tag->setBraceRange(BraceRange);
14021 
14022   // Make sure we "complete" the definition even it is invalid.
14023   if (Tag->isBeingDefined()) {
14024     assert(Tag->isInvalidDecl() && "We should already have completed it");
14025     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14026       RD->completeDefinition();
14027   }
14028 
14029   if (isa<CXXRecordDecl>(Tag)) {
14030     FieldCollector->FinishClass();
14031   }
14032 
14033   // Exit this scope of this tag's definition.
14034   PopDeclContext();
14035 
14036   if (getCurLexicalContext()->isObjCContainer() &&
14037       Tag->getDeclContext()->isFileContext())
14038     Tag->setTopLevelDeclInObjCContainer();
14039 
14040   // Notify the consumer that we've defined a tag.
14041   if (!Tag->isInvalidDecl())
14042     Consumer.HandleTagDeclDefinition(Tag);
14043 }
14044 
14045 void Sema::ActOnObjCContainerFinishDefinition() {
14046   // Exit this scope of this interface definition.
14047   PopDeclContext();
14048 }
14049 
14050 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
14051   assert(DC == CurContext && "Mismatch of container contexts");
14052   OriginalLexicalContext = DC;
14053   ActOnObjCContainerFinishDefinition();
14054 }
14055 
14056 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
14057   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
14058   OriginalLexicalContext = nullptr;
14059 }
14060 
14061 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
14062   AdjustDeclIfTemplate(TagD);
14063   TagDecl *Tag = cast<TagDecl>(TagD);
14064   Tag->setInvalidDecl();
14065 
14066   // Make sure we "complete" the definition even it is invalid.
14067   if (Tag->isBeingDefined()) {
14068     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14069       RD->completeDefinition();
14070   }
14071 
14072   // We're undoing ActOnTagStartDefinition here, not
14073   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
14074   // the FieldCollector.
14075 
14076   PopDeclContext();
14077 }
14078 
14079 // Note that FieldName may be null for anonymous bitfields.
14080 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
14081                                 IdentifierInfo *FieldName,
14082                                 QualType FieldTy, bool IsMsStruct,
14083                                 Expr *BitWidth, bool *ZeroWidth) {
14084   // Default to true; that shouldn't confuse checks for emptiness
14085   if (ZeroWidth)
14086     *ZeroWidth = true;
14087 
14088   // C99 6.7.2.1p4 - verify the field type.
14089   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
14090   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
14091     // Handle incomplete types with specific error.
14092     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
14093       return ExprError();
14094     if (FieldName)
14095       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
14096         << FieldName << FieldTy << BitWidth->getSourceRange();
14097     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
14098       << FieldTy << BitWidth->getSourceRange();
14099   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
14100                                              UPPC_BitFieldWidth))
14101     return ExprError();
14102 
14103   // If the bit-width is type- or value-dependent, don't try to check
14104   // it now.
14105   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
14106     return BitWidth;
14107 
14108   llvm::APSInt Value;
14109   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
14110   if (ICE.isInvalid())
14111     return ICE;
14112   BitWidth = ICE.get();
14113 
14114   if (Value != 0 && ZeroWidth)
14115     *ZeroWidth = false;
14116 
14117   // Zero-width bitfield is ok for anonymous field.
14118   if (Value == 0 && FieldName)
14119     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
14120 
14121   if (Value.isSigned() && Value.isNegative()) {
14122     if (FieldName)
14123       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
14124                << FieldName << Value.toString(10);
14125     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
14126       << Value.toString(10);
14127   }
14128 
14129   if (!FieldTy->isDependentType()) {
14130     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
14131     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
14132     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
14133 
14134     // Over-wide bitfields are an error in C or when using the MSVC bitfield
14135     // ABI.
14136     bool CStdConstraintViolation =
14137         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
14138     bool MSBitfieldViolation =
14139         Value.ugt(TypeStorageSize) &&
14140         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
14141     if (CStdConstraintViolation || MSBitfieldViolation) {
14142       unsigned DiagWidth =
14143           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
14144       if (FieldName)
14145         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
14146                << FieldName << (unsigned)Value.getZExtValue()
14147                << !CStdConstraintViolation << DiagWidth;
14148 
14149       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
14150              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
14151              << DiagWidth;
14152     }
14153 
14154     // Warn on types where the user might conceivably expect to get all
14155     // specified bits as value bits: that's all integral types other than
14156     // 'bool'.
14157     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
14158       if (FieldName)
14159         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
14160             << FieldName << (unsigned)Value.getZExtValue()
14161             << (unsigned)TypeWidth;
14162       else
14163         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
14164             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
14165     }
14166   }
14167 
14168   return BitWidth;
14169 }
14170 
14171 /// ActOnField - Each field of a C struct/union is passed into this in order
14172 /// to create a FieldDecl object for it.
14173 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
14174                        Declarator &D, Expr *BitfieldWidth) {
14175   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
14176                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
14177                                /*InitStyle=*/ICIS_NoInit, AS_public);
14178   return Res;
14179 }
14180 
14181 /// HandleField - Analyze a field of a C struct or a C++ data member.
14182 ///
14183 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
14184                              SourceLocation DeclStart,
14185                              Declarator &D, Expr *BitWidth,
14186                              InClassInitStyle InitStyle,
14187                              AccessSpecifier AS) {
14188   if (D.isDecompositionDeclarator()) {
14189     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
14190     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
14191       << Decomp.getSourceRange();
14192     return nullptr;
14193   }
14194 
14195   IdentifierInfo *II = D.getIdentifier();
14196   SourceLocation Loc = DeclStart;
14197   if (II) Loc = D.getIdentifierLoc();
14198 
14199   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14200   QualType T = TInfo->getType();
14201   if (getLangOpts().CPlusPlus) {
14202     CheckExtraCXXDefaultArguments(D);
14203 
14204     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14205                                         UPPC_DataMemberType)) {
14206       D.setInvalidType();
14207       T = Context.IntTy;
14208       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14209     }
14210   }
14211 
14212   // TR 18037 does not allow fields to be declared with address spaces.
14213   if (T.getQualifiers().hasAddressSpace()) {
14214     Diag(Loc, diag::err_field_with_address_space);
14215     D.setInvalidType();
14216   }
14217 
14218   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
14219   // used as structure or union field: image, sampler, event or block types.
14220   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
14221                           T->isSamplerT() || T->isBlockPointerType())) {
14222     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
14223     D.setInvalidType();
14224   }
14225 
14226   DiagnoseFunctionSpecifiers(D.getDeclSpec());
14227 
14228   if (D.getDeclSpec().isInlineSpecified())
14229     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14230         << getLangOpts().CPlusPlus1z;
14231   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14232     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14233          diag::err_invalid_thread)
14234       << DeclSpec::getSpecifierName(TSCS);
14235 
14236   // Check to see if this name was declared as a member previously
14237   NamedDecl *PrevDecl = nullptr;
14238   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14239   LookupName(Previous, S);
14240   switch (Previous.getResultKind()) {
14241     case LookupResult::Found:
14242     case LookupResult::FoundUnresolvedValue:
14243       PrevDecl = Previous.getAsSingle<NamedDecl>();
14244       break;
14245 
14246     case LookupResult::FoundOverloaded:
14247       PrevDecl = Previous.getRepresentativeDecl();
14248       break;
14249 
14250     case LookupResult::NotFound:
14251     case LookupResult::NotFoundInCurrentInstantiation:
14252     case LookupResult::Ambiguous:
14253       break;
14254   }
14255   Previous.suppressDiagnostics();
14256 
14257   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14258     // Maybe we will complain about the shadowed template parameter.
14259     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14260     // Just pretend that we didn't see the previous declaration.
14261     PrevDecl = nullptr;
14262   }
14263 
14264   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14265     PrevDecl = nullptr;
14266 
14267   bool Mutable
14268     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
14269   SourceLocation TSSL = D.getLocStart();
14270   FieldDecl *NewFD
14271     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
14272                      TSSL, AS, PrevDecl, &D);
14273 
14274   if (NewFD->isInvalidDecl())
14275     Record->setInvalidDecl();
14276 
14277   if (D.getDeclSpec().isModulePrivateSpecified())
14278     NewFD->setModulePrivate();
14279 
14280   if (NewFD->isInvalidDecl() && PrevDecl) {
14281     // Don't introduce NewFD into scope; there's already something
14282     // with the same name in the same scope.
14283   } else if (II) {
14284     PushOnScopeChains(NewFD, S);
14285   } else
14286     Record->addDecl(NewFD);
14287 
14288   return NewFD;
14289 }
14290 
14291 /// \brief Build a new FieldDecl and check its well-formedness.
14292 ///
14293 /// This routine builds a new FieldDecl given the fields name, type,
14294 /// record, etc. \p PrevDecl should refer to any previous declaration
14295 /// with the same name and in the same scope as the field to be
14296 /// created.
14297 ///
14298 /// \returns a new FieldDecl.
14299 ///
14300 /// \todo The Declarator argument is a hack. It will be removed once
14301 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
14302                                 TypeSourceInfo *TInfo,
14303                                 RecordDecl *Record, SourceLocation Loc,
14304                                 bool Mutable, Expr *BitWidth,
14305                                 InClassInitStyle InitStyle,
14306                                 SourceLocation TSSL,
14307                                 AccessSpecifier AS, NamedDecl *PrevDecl,
14308                                 Declarator *D) {
14309   IdentifierInfo *II = Name.getAsIdentifierInfo();
14310   bool InvalidDecl = false;
14311   if (D) InvalidDecl = D->isInvalidType();
14312 
14313   // If we receive a broken type, recover by assuming 'int' and
14314   // marking this declaration as invalid.
14315   if (T.isNull()) {
14316     InvalidDecl = true;
14317     T = Context.IntTy;
14318   }
14319 
14320   QualType EltTy = Context.getBaseElementType(T);
14321   if (!EltTy->isDependentType()) {
14322     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
14323       // Fields of incomplete type force their record to be invalid.
14324       Record->setInvalidDecl();
14325       InvalidDecl = true;
14326     } else {
14327       NamedDecl *Def;
14328       EltTy->isIncompleteType(&Def);
14329       if (Def && Def->isInvalidDecl()) {
14330         Record->setInvalidDecl();
14331         InvalidDecl = true;
14332       }
14333     }
14334   }
14335 
14336   // OpenCL v1.2 s6.9.c: bitfields are not supported.
14337   if (BitWidth && getLangOpts().OpenCL) {
14338     Diag(Loc, diag::err_opencl_bitfields);
14339     InvalidDecl = true;
14340   }
14341 
14342   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14343   // than a variably modified type.
14344   if (!InvalidDecl && T->isVariablyModifiedType()) {
14345     bool SizeIsNegative;
14346     llvm::APSInt Oversized;
14347 
14348     TypeSourceInfo *FixedTInfo =
14349       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
14350                                                     SizeIsNegative,
14351                                                     Oversized);
14352     if (FixedTInfo) {
14353       Diag(Loc, diag::warn_illegal_constant_array_size);
14354       TInfo = FixedTInfo;
14355       T = FixedTInfo->getType();
14356     } else {
14357       if (SizeIsNegative)
14358         Diag(Loc, diag::err_typecheck_negative_array_size);
14359       else if (Oversized.getBoolValue())
14360         Diag(Loc, diag::err_array_too_large)
14361           << Oversized.toString(10);
14362       else
14363         Diag(Loc, diag::err_typecheck_field_variable_size);
14364       InvalidDecl = true;
14365     }
14366   }
14367 
14368   // Fields can not have abstract class types
14369   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
14370                                              diag::err_abstract_type_in_decl,
14371                                              AbstractFieldType))
14372     InvalidDecl = true;
14373 
14374   bool ZeroWidth = false;
14375   if (InvalidDecl)
14376     BitWidth = nullptr;
14377   // If this is declared as a bit-field, check the bit-field.
14378   if (BitWidth) {
14379     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
14380                               &ZeroWidth).get();
14381     if (!BitWidth) {
14382       InvalidDecl = true;
14383       BitWidth = nullptr;
14384       ZeroWidth = false;
14385     }
14386   }
14387 
14388   // Check that 'mutable' is consistent with the type of the declaration.
14389   if (!InvalidDecl && Mutable) {
14390     unsigned DiagID = 0;
14391     if (T->isReferenceType())
14392       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
14393                                         : diag::err_mutable_reference;
14394     else if (T.isConstQualified())
14395       DiagID = diag::err_mutable_const;
14396 
14397     if (DiagID) {
14398       SourceLocation ErrLoc = Loc;
14399       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
14400         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
14401       Diag(ErrLoc, DiagID);
14402       if (DiagID != diag::ext_mutable_reference) {
14403         Mutable = false;
14404         InvalidDecl = true;
14405       }
14406     }
14407   }
14408 
14409   // C++11 [class.union]p8 (DR1460):
14410   //   At most one variant member of a union may have a
14411   //   brace-or-equal-initializer.
14412   if (InitStyle != ICIS_NoInit)
14413     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14414 
14415   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14416                                        BitWidth, Mutable, InitStyle);
14417   if (InvalidDecl)
14418     NewFD->setInvalidDecl();
14419 
14420   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14421     Diag(Loc, diag::err_duplicate_member) << II;
14422     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14423     NewFD->setInvalidDecl();
14424   }
14425 
14426   if (!InvalidDecl && getLangOpts().CPlusPlus) {
14427     if (Record->isUnion()) {
14428       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14429         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14430         if (RDecl->getDefinition()) {
14431           // C++ [class.union]p1: An object of a class with a non-trivial
14432           // constructor, a non-trivial copy constructor, a non-trivial
14433           // destructor, or a non-trivial copy assignment operator
14434           // cannot be a member of a union, nor can an array of such
14435           // objects.
14436           if (CheckNontrivialField(NewFD))
14437             NewFD->setInvalidDecl();
14438         }
14439       }
14440 
14441       // C++ [class.union]p1: If a union contains a member of reference type,
14442       // the program is ill-formed, except when compiling with MSVC extensions
14443       // enabled.
14444       if (EltTy->isReferenceType()) {
14445         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14446                                     diag::ext_union_member_of_reference_type :
14447                                     diag::err_union_member_of_reference_type)
14448           << NewFD->getDeclName() << EltTy;
14449         if (!getLangOpts().MicrosoftExt)
14450           NewFD->setInvalidDecl();
14451       }
14452     }
14453   }
14454 
14455   // FIXME: We need to pass in the attributes given an AST
14456   // representation, not a parser representation.
14457   if (D) {
14458     // FIXME: The current scope is almost... but not entirely... correct here.
14459     ProcessDeclAttributes(getCurScope(), NewFD, *D);
14460 
14461     if (NewFD->hasAttrs())
14462       CheckAlignasUnderalignment(NewFD);
14463   }
14464 
14465   // In auto-retain/release, infer strong retension for fields of
14466   // retainable type.
14467   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
14468     NewFD->setInvalidDecl();
14469 
14470   if (T.isObjCGCWeak())
14471     Diag(Loc, diag::warn_attribute_weak_on_field);
14472 
14473   NewFD->setAccess(AS);
14474   return NewFD;
14475 }
14476 
14477 bool Sema::CheckNontrivialField(FieldDecl *FD) {
14478   assert(FD);
14479   assert(getLangOpts().CPlusPlus && "valid check only for C++");
14480 
14481   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
14482     return false;
14483 
14484   QualType EltTy = Context.getBaseElementType(FD->getType());
14485   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14486     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
14487     if (RDecl->getDefinition()) {
14488       // We check for copy constructors before constructors
14489       // because otherwise we'll never get complaints about
14490       // copy constructors.
14491 
14492       CXXSpecialMember member = CXXInvalid;
14493       // We're required to check for any non-trivial constructors. Since the
14494       // implicit default constructor is suppressed if there are any
14495       // user-declared constructors, we just need to check that there is a
14496       // trivial default constructor and a trivial copy constructor. (We don't
14497       // worry about move constructors here, since this is a C++98 check.)
14498       if (RDecl->hasNonTrivialCopyConstructor())
14499         member = CXXCopyConstructor;
14500       else if (!RDecl->hasTrivialDefaultConstructor())
14501         member = CXXDefaultConstructor;
14502       else if (RDecl->hasNonTrivialCopyAssignment())
14503         member = CXXCopyAssignment;
14504       else if (RDecl->hasNonTrivialDestructor())
14505         member = CXXDestructor;
14506 
14507       if (member != CXXInvalid) {
14508         if (!getLangOpts().CPlusPlus11 &&
14509             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
14510           // Objective-C++ ARC: it is an error to have a non-trivial field of
14511           // a union. However, system headers in Objective-C programs
14512           // occasionally have Objective-C lifetime objects within unions,
14513           // and rather than cause the program to fail, we make those
14514           // members unavailable.
14515           SourceLocation Loc = FD->getLocation();
14516           if (getSourceManager().isInSystemHeader(Loc)) {
14517             if (!FD->hasAttr<UnavailableAttr>())
14518               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14519                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
14520             return false;
14521           }
14522         }
14523 
14524         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
14525                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
14526                diag::err_illegal_union_or_anon_struct_member)
14527           << FD->getParent()->isUnion() << FD->getDeclName() << member;
14528         DiagnoseNontrivial(RDecl, member);
14529         return !getLangOpts().CPlusPlus11;
14530       }
14531     }
14532   }
14533 
14534   return false;
14535 }
14536 
14537 /// TranslateIvarVisibility - Translate visibility from a token ID to an
14538 ///  AST enum value.
14539 static ObjCIvarDecl::AccessControl
14540 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
14541   switch (ivarVisibility) {
14542   default: llvm_unreachable("Unknown visitibility kind");
14543   case tok::objc_private: return ObjCIvarDecl::Private;
14544   case tok::objc_public: return ObjCIvarDecl::Public;
14545   case tok::objc_protected: return ObjCIvarDecl::Protected;
14546   case tok::objc_package: return ObjCIvarDecl::Package;
14547   }
14548 }
14549 
14550 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
14551 /// in order to create an IvarDecl object for it.
14552 Decl *Sema::ActOnIvar(Scope *S,
14553                                 SourceLocation DeclStart,
14554                                 Declarator &D, Expr *BitfieldWidth,
14555                                 tok::ObjCKeywordKind Visibility) {
14556 
14557   IdentifierInfo *II = D.getIdentifier();
14558   Expr *BitWidth = (Expr*)BitfieldWidth;
14559   SourceLocation Loc = DeclStart;
14560   if (II) Loc = D.getIdentifierLoc();
14561 
14562   // FIXME: Unnamed fields can be handled in various different ways, for
14563   // example, unnamed unions inject all members into the struct namespace!
14564 
14565   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14566   QualType T = TInfo->getType();
14567 
14568   if (BitWidth) {
14569     // 6.7.2.1p3, 6.7.2.1p4
14570     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
14571     if (!BitWidth)
14572       D.setInvalidType();
14573   } else {
14574     // Not a bitfield.
14575 
14576     // validate II.
14577 
14578   }
14579   if (T->isReferenceType()) {
14580     Diag(Loc, diag::err_ivar_reference_type);
14581     D.setInvalidType();
14582   }
14583   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14584   // than a variably modified type.
14585   else if (T->isVariablyModifiedType()) {
14586     Diag(Loc, diag::err_typecheck_ivar_variable_size);
14587     D.setInvalidType();
14588   }
14589 
14590   // Get the visibility (access control) for this ivar.
14591   ObjCIvarDecl::AccessControl ac =
14592     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
14593                                         : ObjCIvarDecl::None;
14594   // Must set ivar's DeclContext to its enclosing interface.
14595   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
14596   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
14597     return nullptr;
14598   ObjCContainerDecl *EnclosingContext;
14599   if (ObjCImplementationDecl *IMPDecl =
14600       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14601     if (LangOpts.ObjCRuntime.isFragile()) {
14602     // Case of ivar declared in an implementation. Context is that of its class.
14603       EnclosingContext = IMPDecl->getClassInterface();
14604       assert(EnclosingContext && "Implementation has no class interface!");
14605     }
14606     else
14607       EnclosingContext = EnclosingDecl;
14608   } else {
14609     if (ObjCCategoryDecl *CDecl =
14610         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14611       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
14612         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
14613         return nullptr;
14614       }
14615     }
14616     EnclosingContext = EnclosingDecl;
14617   }
14618 
14619   // Construct the decl.
14620   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
14621                                              DeclStart, Loc, II, T,
14622                                              TInfo, ac, (Expr *)BitfieldWidth);
14623 
14624   if (II) {
14625     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
14626                                            ForRedeclaration);
14627     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
14628         && !isa<TagDecl>(PrevDecl)) {
14629       Diag(Loc, diag::err_duplicate_member) << II;
14630       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14631       NewID->setInvalidDecl();
14632     }
14633   }
14634 
14635   // Process attributes attached to the ivar.
14636   ProcessDeclAttributes(S, NewID, D);
14637 
14638   if (D.isInvalidType())
14639     NewID->setInvalidDecl();
14640 
14641   // In ARC, infer 'retaining' for ivars of retainable type.
14642   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
14643     NewID->setInvalidDecl();
14644 
14645   if (D.getDeclSpec().isModulePrivateSpecified())
14646     NewID->setModulePrivate();
14647 
14648   if (II) {
14649     // FIXME: When interfaces are DeclContexts, we'll need to add
14650     // these to the interface.
14651     S->AddDecl(NewID);
14652     IdResolver.AddDecl(NewID);
14653   }
14654 
14655   if (LangOpts.ObjCRuntime.isNonFragile() &&
14656       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
14657     Diag(Loc, diag::warn_ivars_in_interface);
14658 
14659   return NewID;
14660 }
14661 
14662 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
14663 /// class and class extensions. For every class \@interface and class
14664 /// extension \@interface, if the last ivar is a bitfield of any type,
14665 /// then add an implicit `char :0` ivar to the end of that interface.
14666 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
14667                              SmallVectorImpl<Decl *> &AllIvarDecls) {
14668   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
14669     return;
14670 
14671   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
14672   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
14673 
14674   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
14675     return;
14676   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
14677   if (!ID) {
14678     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
14679       if (!CD->IsClassExtension())
14680         return;
14681     }
14682     // No need to add this to end of @implementation.
14683     else
14684       return;
14685   }
14686   // All conditions are met. Add a new bitfield to the tail end of ivars.
14687   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
14688   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
14689 
14690   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
14691                               DeclLoc, DeclLoc, nullptr,
14692                               Context.CharTy,
14693                               Context.getTrivialTypeSourceInfo(Context.CharTy,
14694                                                                DeclLoc),
14695                               ObjCIvarDecl::Private, BW,
14696                               true);
14697   AllIvarDecls.push_back(Ivar);
14698 }
14699 
14700 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
14701                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
14702                        SourceLocation RBrac, AttributeList *Attr) {
14703   assert(EnclosingDecl && "missing record or interface decl");
14704 
14705   // If this is an Objective-C @implementation or category and we have
14706   // new fields here we should reset the layout of the interface since
14707   // it will now change.
14708   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
14709     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
14710     switch (DC->getKind()) {
14711     default: break;
14712     case Decl::ObjCCategory:
14713       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
14714       break;
14715     case Decl::ObjCImplementation:
14716       Context.
14717         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
14718       break;
14719     }
14720   }
14721 
14722   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
14723 
14724   // Start counting up the number of named members; make sure to include
14725   // members of anonymous structs and unions in the total.
14726   unsigned NumNamedMembers = 0;
14727   if (Record) {
14728     for (const auto *I : Record->decls()) {
14729       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
14730         if (IFD->getDeclName())
14731           ++NumNamedMembers;
14732     }
14733   }
14734 
14735   // Verify that all the fields are okay.
14736   SmallVector<FieldDecl*, 32> RecFields;
14737 
14738   bool ObjCFieldLifetimeErrReported = false;
14739   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
14740        i != end; ++i) {
14741     FieldDecl *FD = cast<FieldDecl>(*i);
14742 
14743     // Get the type for the field.
14744     const Type *FDTy = FD->getType().getTypePtr();
14745 
14746     if (!FD->isAnonymousStructOrUnion()) {
14747       // Remember all fields written by the user.
14748       RecFields.push_back(FD);
14749     }
14750 
14751     // If the field is already invalid for some reason, don't emit more
14752     // diagnostics about it.
14753     if (FD->isInvalidDecl()) {
14754       EnclosingDecl->setInvalidDecl();
14755       continue;
14756     }
14757 
14758     // C99 6.7.2.1p2:
14759     //   A structure or union shall not contain a member with
14760     //   incomplete or function type (hence, a structure shall not
14761     //   contain an instance of itself, but may contain a pointer to
14762     //   an instance of itself), except that the last member of a
14763     //   structure with more than one named member may have incomplete
14764     //   array type; such a structure (and any union containing,
14765     //   possibly recursively, a member that is such a structure)
14766     //   shall not be a member of a structure or an element of an
14767     //   array.
14768     if (FDTy->isFunctionType()) {
14769       // Field declared as a function.
14770       Diag(FD->getLocation(), diag::err_field_declared_as_function)
14771         << FD->getDeclName();
14772       FD->setInvalidDecl();
14773       EnclosingDecl->setInvalidDecl();
14774       continue;
14775     } else if (FDTy->isIncompleteArrayType() && Record &&
14776                ((i + 1 == Fields.end() && !Record->isUnion()) ||
14777                 ((getLangOpts().MicrosoftExt ||
14778                   getLangOpts().CPlusPlus) &&
14779                  (i + 1 == Fields.end() || Record->isUnion())))) {
14780       // Flexible array member.
14781       // Microsoft and g++ is more permissive regarding flexible array.
14782       // It will accept flexible array in union and also
14783       // as the sole element of a struct/class.
14784       unsigned DiagID = 0;
14785       if (Record->isUnion())
14786         DiagID = getLangOpts().MicrosoftExt
14787                      ? diag::ext_flexible_array_union_ms
14788                      : getLangOpts().CPlusPlus
14789                            ? diag::ext_flexible_array_union_gnu
14790                            : diag::err_flexible_array_union;
14791       else if (NumNamedMembers < 1)
14792         DiagID = getLangOpts().MicrosoftExt
14793                      ? diag::ext_flexible_array_empty_aggregate_ms
14794                      : getLangOpts().CPlusPlus
14795                            ? diag::ext_flexible_array_empty_aggregate_gnu
14796                            : diag::err_flexible_array_empty_aggregate;
14797 
14798       if (DiagID)
14799         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
14800                                         << Record->getTagKind();
14801       // While the layout of types that contain virtual bases is not specified
14802       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
14803       // virtual bases after the derived members.  This would make a flexible
14804       // array member declared at the end of an object not adjacent to the end
14805       // of the type.
14806       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
14807         if (RD->getNumVBases() != 0)
14808           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
14809             << FD->getDeclName() << Record->getTagKind();
14810       if (!getLangOpts().C99)
14811         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
14812           << FD->getDeclName() << Record->getTagKind();
14813 
14814       // If the element type has a non-trivial destructor, we would not
14815       // implicitly destroy the elements, so disallow it for now.
14816       //
14817       // FIXME: GCC allows this. We should probably either implicitly delete
14818       // the destructor of the containing class, or just allow this.
14819       QualType BaseElem = Context.getBaseElementType(FD->getType());
14820       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
14821         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
14822           << FD->getDeclName() << FD->getType();
14823         FD->setInvalidDecl();
14824         EnclosingDecl->setInvalidDecl();
14825         continue;
14826       }
14827       // Okay, we have a legal flexible array member at the end of the struct.
14828       Record->setHasFlexibleArrayMember(true);
14829     } else if (!FDTy->isDependentType() &&
14830                RequireCompleteType(FD->getLocation(), FD->getType(),
14831                                    diag::err_field_incomplete)) {
14832       // Incomplete type
14833       FD->setInvalidDecl();
14834       EnclosingDecl->setInvalidDecl();
14835       continue;
14836     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
14837       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
14838         // A type which contains a flexible array member is considered to be a
14839         // flexible array member.
14840         Record->setHasFlexibleArrayMember(true);
14841         if (!Record->isUnion()) {
14842           // If this is a struct/class and this is not the last element, reject
14843           // it.  Note that GCC supports variable sized arrays in the middle of
14844           // structures.
14845           if (i + 1 != Fields.end())
14846             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
14847               << FD->getDeclName() << FD->getType();
14848           else {
14849             // We support flexible arrays at the end of structs in
14850             // other structs as an extension.
14851             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
14852               << FD->getDeclName();
14853           }
14854         }
14855       }
14856       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
14857           RequireNonAbstractType(FD->getLocation(), FD->getType(),
14858                                  diag::err_abstract_type_in_decl,
14859                                  AbstractIvarType)) {
14860         // Ivars can not have abstract class types
14861         FD->setInvalidDecl();
14862       }
14863       if (Record && FDTTy->getDecl()->hasObjectMember())
14864         Record->setHasObjectMember(true);
14865       if (Record && FDTTy->getDecl()->hasVolatileMember())
14866         Record->setHasVolatileMember(true);
14867     } else if (FDTy->isObjCObjectType()) {
14868       /// A field cannot be an Objective-c object
14869       Diag(FD->getLocation(), diag::err_statically_allocated_object)
14870         << FixItHint::CreateInsertion(FD->getLocation(), "*");
14871       QualType T = Context.getObjCObjectPointerType(FD->getType());
14872       FD->setType(T);
14873     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
14874                Record && !ObjCFieldLifetimeErrReported &&
14875                (!getLangOpts().CPlusPlus || Record->isUnion())) {
14876       // It's an error in ARC or Weak if a field has lifetime.
14877       // We don't want to report this in a system header, though,
14878       // so we just make the field unavailable.
14879       // FIXME: that's really not sufficient; we need to make the type
14880       // itself invalid to, say, initialize or copy.
14881       QualType T = FD->getType();
14882       if (T.hasNonTrivialObjCLifetime()) {
14883         SourceLocation loc = FD->getLocation();
14884         if (getSourceManager().isInSystemHeader(loc)) {
14885           if (!FD->hasAttr<UnavailableAttr>()) {
14886             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14887                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
14888           }
14889         } else {
14890           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
14891             << T->isBlockPointerType() << Record->getTagKind();
14892         }
14893         ObjCFieldLifetimeErrReported = true;
14894       }
14895     } else if (getLangOpts().ObjC1 &&
14896                getLangOpts().getGC() != LangOptions::NonGC &&
14897                Record && !Record->hasObjectMember()) {
14898       if (FD->getType()->isObjCObjectPointerType() ||
14899           FD->getType().isObjCGCStrong())
14900         Record->setHasObjectMember(true);
14901       else if (Context.getAsArrayType(FD->getType())) {
14902         QualType BaseType = Context.getBaseElementType(FD->getType());
14903         if (BaseType->isRecordType() &&
14904             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
14905           Record->setHasObjectMember(true);
14906         else if (BaseType->isObjCObjectPointerType() ||
14907                  BaseType.isObjCGCStrong())
14908                Record->setHasObjectMember(true);
14909       }
14910     }
14911     if (Record && FD->getType().isVolatileQualified())
14912       Record->setHasVolatileMember(true);
14913     // Keep track of the number of named members.
14914     if (FD->getIdentifier())
14915       ++NumNamedMembers;
14916   }
14917 
14918   // Okay, we successfully defined 'Record'.
14919   if (Record) {
14920     bool Completed = false;
14921     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14922       if (!CXXRecord->isInvalidDecl()) {
14923         // Set access bits correctly on the directly-declared conversions.
14924         for (CXXRecordDecl::conversion_iterator
14925                I = CXXRecord->conversion_begin(),
14926                E = CXXRecord->conversion_end(); I != E; ++I)
14927           I.setAccess((*I)->getAccess());
14928       }
14929 
14930       if (!CXXRecord->isDependentType()) {
14931         if (CXXRecord->hasUserDeclaredDestructor()) {
14932           // Adjust user-defined destructor exception spec.
14933           if (getLangOpts().CPlusPlus11)
14934             AdjustDestructorExceptionSpec(CXXRecord,
14935                                           CXXRecord->getDestructor());
14936         }
14937 
14938         if (!CXXRecord->isInvalidDecl()) {
14939           // Add any implicitly-declared members to this class.
14940           AddImplicitlyDeclaredMembersToClass(CXXRecord);
14941 
14942           // If we have virtual base classes, we may end up finding multiple
14943           // final overriders for a given virtual function. Check for this
14944           // problem now.
14945           if (CXXRecord->getNumVBases()) {
14946             CXXFinalOverriderMap FinalOverriders;
14947             CXXRecord->getFinalOverriders(FinalOverriders);
14948 
14949             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
14950                                              MEnd = FinalOverriders.end();
14951                  M != MEnd; ++M) {
14952               for (OverridingMethods::iterator SO = M->second.begin(),
14953                                             SOEnd = M->second.end();
14954                    SO != SOEnd; ++SO) {
14955                 assert(SO->second.size() > 0 &&
14956                        "Virtual function without overridding functions?");
14957                 if (SO->second.size() == 1)
14958                   continue;
14959 
14960                 // C++ [class.virtual]p2:
14961                 //   In a derived class, if a virtual member function of a base
14962                 //   class subobject has more than one final overrider the
14963                 //   program is ill-formed.
14964                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
14965                   << (const NamedDecl *)M->first << Record;
14966                 Diag(M->first->getLocation(),
14967                      diag::note_overridden_virtual_function);
14968                 for (OverridingMethods::overriding_iterator
14969                           OM = SO->second.begin(),
14970                        OMEnd = SO->second.end();
14971                      OM != OMEnd; ++OM)
14972                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
14973                     << (const NamedDecl *)M->first << OM->Method->getParent();
14974 
14975                 Record->setInvalidDecl();
14976               }
14977             }
14978             CXXRecord->completeDefinition(&FinalOverriders);
14979             Completed = true;
14980           }
14981         }
14982       }
14983     }
14984 
14985     if (!Completed)
14986       Record->completeDefinition();
14987 
14988     // We may have deferred checking for a deleted destructor. Check now.
14989     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14990       auto *Dtor = CXXRecord->getDestructor();
14991       if (Dtor && Dtor->isImplicit() &&
14992           ShouldDeleteSpecialMember(Dtor, CXXDestructor))
14993         SetDeclDeleted(Dtor, CXXRecord->getLocation());
14994     }
14995 
14996     if (Record->hasAttrs()) {
14997       CheckAlignasUnderalignment(Record);
14998 
14999       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
15000         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
15001                                            IA->getRange(), IA->getBestCase(),
15002                                            IA->getSemanticSpelling());
15003     }
15004 
15005     // Check if the structure/union declaration is a type that can have zero
15006     // size in C. For C this is a language extension, for C++ it may cause
15007     // compatibility problems.
15008     bool CheckForZeroSize;
15009     if (!getLangOpts().CPlusPlus) {
15010       CheckForZeroSize = true;
15011     } else {
15012       // For C++ filter out types that cannot be referenced in C code.
15013       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
15014       CheckForZeroSize =
15015           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
15016           !CXXRecord->isDependentType() &&
15017           CXXRecord->isCLike();
15018     }
15019     if (CheckForZeroSize) {
15020       bool ZeroSize = true;
15021       bool IsEmpty = true;
15022       unsigned NonBitFields = 0;
15023       for (RecordDecl::field_iterator I = Record->field_begin(),
15024                                       E = Record->field_end();
15025            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
15026         IsEmpty = false;
15027         if (I->isUnnamedBitfield()) {
15028           if (I->getBitWidthValue(Context) > 0)
15029             ZeroSize = false;
15030         } else {
15031           ++NonBitFields;
15032           QualType FieldType = I->getType();
15033           if (FieldType->isIncompleteType() ||
15034               !Context.getTypeSizeInChars(FieldType).isZero())
15035             ZeroSize = false;
15036         }
15037       }
15038 
15039       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
15040       // allowed in C++, but warn if its declaration is inside
15041       // extern "C" block.
15042       if (ZeroSize) {
15043         Diag(RecLoc, getLangOpts().CPlusPlus ?
15044                          diag::warn_zero_size_struct_union_in_extern_c :
15045                          diag::warn_zero_size_struct_union_compat)
15046           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
15047       }
15048 
15049       // Structs without named members are extension in C (C99 6.7.2.1p7),
15050       // but are accepted by GCC.
15051       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
15052         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
15053                                diag::ext_no_named_members_in_struct_union)
15054           << Record->isUnion();
15055       }
15056     }
15057   } else {
15058     ObjCIvarDecl **ClsFields =
15059       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
15060     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
15061       ID->setEndOfDefinitionLoc(RBrac);
15062       // Add ivar's to class's DeclContext.
15063       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15064         ClsFields[i]->setLexicalDeclContext(ID);
15065         ID->addDecl(ClsFields[i]);
15066       }
15067       // Must enforce the rule that ivars in the base classes may not be
15068       // duplicates.
15069       if (ID->getSuperClass())
15070         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
15071     } else if (ObjCImplementationDecl *IMPDecl =
15072                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15073       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
15074       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
15075         // Ivar declared in @implementation never belongs to the implementation.
15076         // Only it is in implementation's lexical context.
15077         ClsFields[I]->setLexicalDeclContext(IMPDecl);
15078       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
15079       IMPDecl->setIvarLBraceLoc(LBrac);
15080       IMPDecl->setIvarRBraceLoc(RBrac);
15081     } else if (ObjCCategoryDecl *CDecl =
15082                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15083       // case of ivars in class extension; all other cases have been
15084       // reported as errors elsewhere.
15085       // FIXME. Class extension does not have a LocEnd field.
15086       // CDecl->setLocEnd(RBrac);
15087       // Add ivar's to class extension's DeclContext.
15088       // Diagnose redeclaration of private ivars.
15089       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
15090       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15091         if (IDecl) {
15092           if (const ObjCIvarDecl *ClsIvar =
15093               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
15094             Diag(ClsFields[i]->getLocation(),
15095                  diag::err_duplicate_ivar_declaration);
15096             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
15097             continue;
15098           }
15099           for (const auto *Ext : IDecl->known_extensions()) {
15100             if (const ObjCIvarDecl *ClsExtIvar
15101                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
15102               Diag(ClsFields[i]->getLocation(),
15103                    diag::err_duplicate_ivar_declaration);
15104               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
15105               continue;
15106             }
15107           }
15108         }
15109         ClsFields[i]->setLexicalDeclContext(CDecl);
15110         CDecl->addDecl(ClsFields[i]);
15111       }
15112       CDecl->setIvarLBraceLoc(LBrac);
15113       CDecl->setIvarRBraceLoc(RBrac);
15114     }
15115   }
15116 
15117   if (Attr)
15118     ProcessDeclAttributeList(S, Record, Attr);
15119 }
15120 
15121 /// \brief Determine whether the given integral value is representable within
15122 /// the given type T.
15123 static bool isRepresentableIntegerValue(ASTContext &Context,
15124                                         llvm::APSInt &Value,
15125                                         QualType T) {
15126   assert(T->isIntegralType(Context) && "Integral type required!");
15127   unsigned BitWidth = Context.getIntWidth(T);
15128 
15129   if (Value.isUnsigned() || Value.isNonNegative()) {
15130     if (T->isSignedIntegerOrEnumerationType())
15131       --BitWidth;
15132     return Value.getActiveBits() <= BitWidth;
15133   }
15134   return Value.getMinSignedBits() <= BitWidth;
15135 }
15136 
15137 // \brief Given an integral type, return the next larger integral type
15138 // (or a NULL type of no such type exists).
15139 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
15140   // FIXME: Int128/UInt128 support, which also needs to be introduced into
15141   // enum checking below.
15142   assert(T->isIntegralType(Context) && "Integral type required!");
15143   const unsigned NumTypes = 4;
15144   QualType SignedIntegralTypes[NumTypes] = {
15145     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
15146   };
15147   QualType UnsignedIntegralTypes[NumTypes] = {
15148     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
15149     Context.UnsignedLongLongTy
15150   };
15151 
15152   unsigned BitWidth = Context.getTypeSize(T);
15153   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
15154                                                         : UnsignedIntegralTypes;
15155   for (unsigned I = 0; I != NumTypes; ++I)
15156     if (Context.getTypeSize(Types[I]) > BitWidth)
15157       return Types[I];
15158 
15159   return QualType();
15160 }
15161 
15162 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
15163                                           EnumConstantDecl *LastEnumConst,
15164                                           SourceLocation IdLoc,
15165                                           IdentifierInfo *Id,
15166                                           Expr *Val) {
15167   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15168   llvm::APSInt EnumVal(IntWidth);
15169   QualType EltTy;
15170 
15171   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
15172     Val = nullptr;
15173 
15174   if (Val)
15175     Val = DefaultLvalueConversion(Val).get();
15176 
15177   if (Val) {
15178     if (Enum->isDependentType() || Val->isTypeDependent())
15179       EltTy = Context.DependentTy;
15180     else {
15181       SourceLocation ExpLoc;
15182       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
15183           !getLangOpts().MSVCCompat) {
15184         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
15185         // constant-expression in the enumerator-definition shall be a converted
15186         // constant expression of the underlying type.
15187         EltTy = Enum->getIntegerType();
15188         ExprResult Converted =
15189           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
15190                                            CCEK_Enumerator);
15191         if (Converted.isInvalid())
15192           Val = nullptr;
15193         else
15194           Val = Converted.get();
15195       } else if (!Val->isValueDependent() &&
15196                  !(Val = VerifyIntegerConstantExpression(Val,
15197                                                          &EnumVal).get())) {
15198         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
15199       } else {
15200         if (Enum->isFixed()) {
15201           EltTy = Enum->getIntegerType();
15202 
15203           // In Obj-C and Microsoft mode, require the enumeration value to be
15204           // representable in the underlying type of the enumeration. In C++11,
15205           // we perform a non-narrowing conversion as part of converted constant
15206           // expression checking.
15207           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15208             if (getLangOpts().MSVCCompat) {
15209               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
15210               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
15211             } else
15212               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
15213           } else
15214             Val = ImpCastExprToType(Val, EltTy,
15215                                     EltTy->isBooleanType() ?
15216                                     CK_IntegralToBoolean : CK_IntegralCast)
15217                     .get();
15218         } else if (getLangOpts().CPlusPlus) {
15219           // C++11 [dcl.enum]p5:
15220           //   If the underlying type is not fixed, the type of each enumerator
15221           //   is the type of its initializing value:
15222           //     - If an initializer is specified for an enumerator, the
15223           //       initializing value has the same type as the expression.
15224           EltTy = Val->getType();
15225         } else {
15226           // C99 6.7.2.2p2:
15227           //   The expression that defines the value of an enumeration constant
15228           //   shall be an integer constant expression that has a value
15229           //   representable as an int.
15230 
15231           // Complain if the value is not representable in an int.
15232           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
15233             Diag(IdLoc, diag::ext_enum_value_not_int)
15234               << EnumVal.toString(10) << Val->getSourceRange()
15235               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
15236           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
15237             // Force the type of the expression to 'int'.
15238             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
15239           }
15240           EltTy = Val->getType();
15241         }
15242       }
15243     }
15244   }
15245 
15246   if (!Val) {
15247     if (Enum->isDependentType())
15248       EltTy = Context.DependentTy;
15249     else if (!LastEnumConst) {
15250       // C++0x [dcl.enum]p5:
15251       //   If the underlying type is not fixed, the type of each enumerator
15252       //   is the type of its initializing value:
15253       //     - If no initializer is specified for the first enumerator, the
15254       //       initializing value has an unspecified integral type.
15255       //
15256       // GCC uses 'int' for its unspecified integral type, as does
15257       // C99 6.7.2.2p3.
15258       if (Enum->isFixed()) {
15259         EltTy = Enum->getIntegerType();
15260       }
15261       else {
15262         EltTy = Context.IntTy;
15263       }
15264     } else {
15265       // Assign the last value + 1.
15266       EnumVal = LastEnumConst->getInitVal();
15267       ++EnumVal;
15268       EltTy = LastEnumConst->getType();
15269 
15270       // Check for overflow on increment.
15271       if (EnumVal < LastEnumConst->getInitVal()) {
15272         // C++0x [dcl.enum]p5:
15273         //   If the underlying type is not fixed, the type of each enumerator
15274         //   is the type of its initializing value:
15275         //
15276         //     - Otherwise the type of the initializing value is the same as
15277         //       the type of the initializing value of the preceding enumerator
15278         //       unless the incremented value is not representable in that type,
15279         //       in which case the type is an unspecified integral type
15280         //       sufficient to contain the incremented value. If no such type
15281         //       exists, the program is ill-formed.
15282         QualType T = getNextLargerIntegralType(Context, EltTy);
15283         if (T.isNull() || Enum->isFixed()) {
15284           // There is no integral type larger enough to represent this
15285           // value. Complain, then allow the value to wrap around.
15286           EnumVal = LastEnumConst->getInitVal();
15287           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
15288           ++EnumVal;
15289           if (Enum->isFixed())
15290             // When the underlying type is fixed, this is ill-formed.
15291             Diag(IdLoc, diag::err_enumerator_wrapped)
15292               << EnumVal.toString(10)
15293               << EltTy;
15294           else
15295             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
15296               << EnumVal.toString(10);
15297         } else {
15298           EltTy = T;
15299         }
15300 
15301         // Retrieve the last enumerator's value, extent that type to the
15302         // type that is supposed to be large enough to represent the incremented
15303         // value, then increment.
15304         EnumVal = LastEnumConst->getInitVal();
15305         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15306         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
15307         ++EnumVal;
15308 
15309         // If we're not in C++, diagnose the overflow of enumerator values,
15310         // which in C99 means that the enumerator value is not representable in
15311         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
15312         // permits enumerator values that are representable in some larger
15313         // integral type.
15314         if (!getLangOpts().CPlusPlus && !T.isNull())
15315           Diag(IdLoc, diag::warn_enum_value_overflow);
15316       } else if (!getLangOpts().CPlusPlus &&
15317                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15318         // Enforce C99 6.7.2.2p2 even when we compute the next value.
15319         Diag(IdLoc, diag::ext_enum_value_not_int)
15320           << EnumVal.toString(10) << 1;
15321       }
15322     }
15323   }
15324 
15325   if (!EltTy->isDependentType()) {
15326     // Make the enumerator value match the signedness and size of the
15327     // enumerator's type.
15328     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
15329     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15330   }
15331 
15332   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
15333                                   Val, EnumVal);
15334 }
15335 
15336 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
15337                                                 SourceLocation IILoc) {
15338   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
15339       !getLangOpts().CPlusPlus)
15340     return SkipBodyInfo();
15341 
15342   // We have an anonymous enum definition. Look up the first enumerator to
15343   // determine if we should merge the definition with an existing one and
15344   // skip the body.
15345   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
15346                                          ForRedeclaration);
15347   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
15348   if (!PrevECD)
15349     return SkipBodyInfo();
15350 
15351   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
15352   NamedDecl *Hidden;
15353   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
15354     SkipBodyInfo Skip;
15355     Skip.Previous = Hidden;
15356     return Skip;
15357   }
15358 
15359   return SkipBodyInfo();
15360 }
15361 
15362 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
15363                               SourceLocation IdLoc, IdentifierInfo *Id,
15364                               AttributeList *Attr,
15365                               SourceLocation EqualLoc, Expr *Val) {
15366   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
15367   EnumConstantDecl *LastEnumConst =
15368     cast_or_null<EnumConstantDecl>(lastEnumConst);
15369 
15370   // The scope passed in may not be a decl scope.  Zip up the scope tree until
15371   // we find one that is.
15372   S = getNonFieldDeclScope(S);
15373 
15374   // Verify that there isn't already something declared with this name in this
15375   // scope.
15376   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
15377                                          ForRedeclaration);
15378   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15379     // Maybe we will complain about the shadowed template parameter.
15380     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
15381     // Just pretend that we didn't see the previous declaration.
15382     PrevDecl = nullptr;
15383   }
15384 
15385   // C++ [class.mem]p15:
15386   // If T is the name of a class, then each of the following shall have a name
15387   // different from T:
15388   // - every enumerator of every member of class T that is an unscoped
15389   // enumerated type
15390   if (!TheEnumDecl->isScoped())
15391     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
15392                             DeclarationNameInfo(Id, IdLoc));
15393 
15394   EnumConstantDecl *New =
15395     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
15396   if (!New)
15397     return nullptr;
15398 
15399   if (PrevDecl) {
15400     // When in C++, we may get a TagDecl with the same name; in this case the
15401     // enum constant will 'hide' the tag.
15402     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
15403            "Received TagDecl when not in C++!");
15404     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
15405         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
15406       if (isa<EnumConstantDecl>(PrevDecl))
15407         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15408       else
15409         Diag(IdLoc, diag::err_redefinition) << Id;
15410       notePreviousDefinition(PrevDecl, IdLoc);
15411       return nullptr;
15412     }
15413   }
15414 
15415   // Process attributes.
15416   if (Attr) ProcessDeclAttributeList(S, New, Attr);
15417   AddPragmaAttributes(S, New);
15418 
15419   // Register this decl in the current scope stack.
15420   New->setAccess(TheEnumDecl->getAccess());
15421   PushOnScopeChains(New, S);
15422 
15423   ActOnDocumentableDecl(New);
15424 
15425   return New;
15426 }
15427 
15428 // Returns true when the enum initial expression does not trigger the
15429 // duplicate enum warning.  A few common cases are exempted as follows:
15430 // Element2 = Element1
15431 // Element2 = Element1 + 1
15432 // Element2 = Element1 - 1
15433 // Where Element2 and Element1 are from the same enum.
15434 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
15435   Expr *InitExpr = ECD->getInitExpr();
15436   if (!InitExpr)
15437     return true;
15438   InitExpr = InitExpr->IgnoreImpCasts();
15439 
15440   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
15441     if (!BO->isAdditiveOp())
15442       return true;
15443     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
15444     if (!IL)
15445       return true;
15446     if (IL->getValue() != 1)
15447       return true;
15448 
15449     InitExpr = BO->getLHS();
15450   }
15451 
15452   // This checks if the elements are from the same enum.
15453   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
15454   if (!DRE)
15455     return true;
15456 
15457   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
15458   if (!EnumConstant)
15459     return true;
15460 
15461   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
15462       Enum)
15463     return true;
15464 
15465   return false;
15466 }
15467 
15468 namespace {
15469 struct DupKey {
15470   int64_t val;
15471   bool isTombstoneOrEmptyKey;
15472   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
15473     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
15474 };
15475 
15476 static DupKey GetDupKey(const llvm::APSInt& Val) {
15477   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
15478                 false);
15479 }
15480 
15481 struct DenseMapInfoDupKey {
15482   static DupKey getEmptyKey() { return DupKey(0, true); }
15483   static DupKey getTombstoneKey() { return DupKey(1, true); }
15484   static unsigned getHashValue(const DupKey Key) {
15485     return (unsigned)(Key.val * 37);
15486   }
15487   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
15488     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
15489            LHS.val == RHS.val;
15490   }
15491 };
15492 } // end anonymous namespace
15493 
15494 // Emits a warning when an element is implicitly set a value that
15495 // a previous element has already been set to.
15496 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
15497                                         EnumDecl *Enum,
15498                                         QualType EnumType) {
15499   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
15500     return;
15501   // Avoid anonymous enums
15502   if (!Enum->getIdentifier())
15503     return;
15504 
15505   // Only check for small enums.
15506   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
15507     return;
15508 
15509   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
15510   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
15511 
15512   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
15513   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
15514           ValueToVectorMap;
15515 
15516   DuplicatesVector DupVector;
15517   ValueToVectorMap EnumMap;
15518 
15519   // Populate the EnumMap with all values represented by enum constants without
15520   // an initialier.
15521   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15522     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
15523 
15524     // Null EnumConstantDecl means a previous diagnostic has been emitted for
15525     // this constant.  Skip this enum since it may be ill-formed.
15526     if (!ECD) {
15527       return;
15528     }
15529 
15530     if (ECD->getInitExpr())
15531       continue;
15532 
15533     DupKey Key = GetDupKey(ECD->getInitVal());
15534     DeclOrVector &Entry = EnumMap[Key];
15535 
15536     // First time encountering this value.
15537     if (Entry.isNull())
15538       Entry = ECD;
15539   }
15540 
15541   // Create vectors for any values that has duplicates.
15542   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15543     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
15544     if (!ValidDuplicateEnum(ECD, Enum))
15545       continue;
15546 
15547     DupKey Key = GetDupKey(ECD->getInitVal());
15548 
15549     DeclOrVector& Entry = EnumMap[Key];
15550     if (Entry.isNull())
15551       continue;
15552 
15553     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
15554       // Ensure constants are different.
15555       if (D == ECD)
15556         continue;
15557 
15558       // Create new vector and push values onto it.
15559       ECDVector *Vec = new ECDVector();
15560       Vec->push_back(D);
15561       Vec->push_back(ECD);
15562 
15563       // Update entry to point to the duplicates vector.
15564       Entry = Vec;
15565 
15566       // Store the vector somewhere we can consult later for quick emission of
15567       // diagnostics.
15568       DupVector.push_back(Vec);
15569       continue;
15570     }
15571 
15572     ECDVector *Vec = Entry.get<ECDVector*>();
15573     // Make sure constants are not added more than once.
15574     if (*Vec->begin() == ECD)
15575       continue;
15576 
15577     Vec->push_back(ECD);
15578   }
15579 
15580   // Emit diagnostics.
15581   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
15582                                   DupVectorEnd = DupVector.end();
15583        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
15584     ECDVector *Vec = *DupVectorIter;
15585     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
15586 
15587     // Emit warning for one enum constant.
15588     ECDVector::iterator I = Vec->begin();
15589     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
15590       << (*I)->getName() << (*I)->getInitVal().toString(10)
15591       << (*I)->getSourceRange();
15592     ++I;
15593 
15594     // Emit one note for each of the remaining enum constants with
15595     // the same value.
15596     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
15597       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
15598         << (*I)->getName() << (*I)->getInitVal().toString(10)
15599         << (*I)->getSourceRange();
15600     delete Vec;
15601   }
15602 }
15603 
15604 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
15605                              bool AllowMask) const {
15606   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
15607   assert(ED->isCompleteDefinition() && "expected enum definition");
15608 
15609   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
15610   llvm::APInt &FlagBits = R.first->second;
15611 
15612   if (R.second) {
15613     for (auto *E : ED->enumerators()) {
15614       const auto &EVal = E->getInitVal();
15615       // Only single-bit enumerators introduce new flag values.
15616       if (EVal.isPowerOf2())
15617         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
15618     }
15619   }
15620 
15621   // A value is in a flag enum if either its bits are a subset of the enum's
15622   // flag bits (the first condition) or we are allowing masks and the same is
15623   // true of its complement (the second condition). When masks are allowed, we
15624   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
15625   //
15626   // While it's true that any value could be used as a mask, the assumption is
15627   // that a mask will have all of the insignificant bits set. Anything else is
15628   // likely a logic error.
15629   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
15630   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
15631 }
15632 
15633 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
15634                          Decl *EnumDeclX,
15635                          ArrayRef<Decl *> Elements,
15636                          Scope *S, AttributeList *Attr) {
15637   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
15638   QualType EnumType = Context.getTypeDeclType(Enum);
15639 
15640   if (Attr)
15641     ProcessDeclAttributeList(S, Enum, Attr);
15642 
15643   if (Enum->isDependentType()) {
15644     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15645       EnumConstantDecl *ECD =
15646         cast_or_null<EnumConstantDecl>(Elements[i]);
15647       if (!ECD) continue;
15648 
15649       ECD->setType(EnumType);
15650     }
15651 
15652     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
15653     return;
15654   }
15655 
15656   // TODO: If the result value doesn't fit in an int, it must be a long or long
15657   // long value.  ISO C does not support this, but GCC does as an extension,
15658   // emit a warning.
15659   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15660   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
15661   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
15662 
15663   // Verify that all the values are okay, compute the size of the values, and
15664   // reverse the list.
15665   unsigned NumNegativeBits = 0;
15666   unsigned NumPositiveBits = 0;
15667 
15668   // Keep track of whether all elements have type int.
15669   bool AllElementsInt = true;
15670 
15671   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15672     EnumConstantDecl *ECD =
15673       cast_or_null<EnumConstantDecl>(Elements[i]);
15674     if (!ECD) continue;  // Already issued a diagnostic.
15675 
15676     const llvm::APSInt &InitVal = ECD->getInitVal();
15677 
15678     // Keep track of the size of positive and negative values.
15679     if (InitVal.isUnsigned() || InitVal.isNonNegative())
15680       NumPositiveBits = std::max(NumPositiveBits,
15681                                  (unsigned)InitVal.getActiveBits());
15682     else
15683       NumNegativeBits = std::max(NumNegativeBits,
15684                                  (unsigned)InitVal.getMinSignedBits());
15685 
15686     // Keep track of whether every enum element has type int (very commmon).
15687     if (AllElementsInt)
15688       AllElementsInt = ECD->getType() == Context.IntTy;
15689   }
15690 
15691   // Figure out the type that should be used for this enum.
15692   QualType BestType;
15693   unsigned BestWidth;
15694 
15695   // C++0x N3000 [conv.prom]p3:
15696   //   An rvalue of an unscoped enumeration type whose underlying
15697   //   type is not fixed can be converted to an rvalue of the first
15698   //   of the following types that can represent all the values of
15699   //   the enumeration: int, unsigned int, long int, unsigned long
15700   //   int, long long int, or unsigned long long int.
15701   // C99 6.4.4.3p2:
15702   //   An identifier declared as an enumeration constant has type int.
15703   // The C99 rule is modified by a gcc extension
15704   QualType BestPromotionType;
15705 
15706   bool Packed = Enum->hasAttr<PackedAttr>();
15707   // -fshort-enums is the equivalent to specifying the packed attribute on all
15708   // enum definitions.
15709   if (LangOpts.ShortEnums)
15710     Packed = true;
15711 
15712   if (Enum->isFixed()) {
15713     BestType = Enum->getIntegerType();
15714     if (BestType->isPromotableIntegerType())
15715       BestPromotionType = Context.getPromotedIntegerType(BestType);
15716     else
15717       BestPromotionType = BestType;
15718 
15719     BestWidth = Context.getIntWidth(BestType);
15720   }
15721   else if (NumNegativeBits) {
15722     // If there is a negative value, figure out the smallest integer type (of
15723     // int/long/longlong) that fits.
15724     // If it's packed, check also if it fits a char or a short.
15725     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
15726       BestType = Context.SignedCharTy;
15727       BestWidth = CharWidth;
15728     } else if (Packed && NumNegativeBits <= ShortWidth &&
15729                NumPositiveBits < ShortWidth) {
15730       BestType = Context.ShortTy;
15731       BestWidth = ShortWidth;
15732     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
15733       BestType = Context.IntTy;
15734       BestWidth = IntWidth;
15735     } else {
15736       BestWidth = Context.getTargetInfo().getLongWidth();
15737 
15738       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
15739         BestType = Context.LongTy;
15740       } else {
15741         BestWidth = Context.getTargetInfo().getLongLongWidth();
15742 
15743         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
15744           Diag(Enum->getLocation(), diag::ext_enum_too_large);
15745         BestType = Context.LongLongTy;
15746       }
15747     }
15748     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
15749   } else {
15750     // If there is no negative value, figure out the smallest type that fits
15751     // all of the enumerator values.
15752     // If it's packed, check also if it fits a char or a short.
15753     if (Packed && NumPositiveBits <= CharWidth) {
15754       BestType = Context.UnsignedCharTy;
15755       BestPromotionType = Context.IntTy;
15756       BestWidth = CharWidth;
15757     } else if (Packed && NumPositiveBits <= ShortWidth) {
15758       BestType = Context.UnsignedShortTy;
15759       BestPromotionType = Context.IntTy;
15760       BestWidth = ShortWidth;
15761     } else if (NumPositiveBits <= IntWidth) {
15762       BestType = Context.UnsignedIntTy;
15763       BestWidth = IntWidth;
15764       BestPromotionType
15765         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15766                            ? Context.UnsignedIntTy : Context.IntTy;
15767     } else if (NumPositiveBits <=
15768                (BestWidth = Context.getTargetInfo().getLongWidth())) {
15769       BestType = Context.UnsignedLongTy;
15770       BestPromotionType
15771         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15772                            ? Context.UnsignedLongTy : Context.LongTy;
15773     } else {
15774       BestWidth = Context.getTargetInfo().getLongLongWidth();
15775       assert(NumPositiveBits <= BestWidth &&
15776              "How could an initializer get larger than ULL?");
15777       BestType = Context.UnsignedLongLongTy;
15778       BestPromotionType
15779         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15780                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
15781     }
15782   }
15783 
15784   // Loop over all of the enumerator constants, changing their types to match
15785   // the type of the enum if needed.
15786   for (auto *D : Elements) {
15787     auto *ECD = cast_or_null<EnumConstantDecl>(D);
15788     if (!ECD) continue;  // Already issued a diagnostic.
15789 
15790     // Standard C says the enumerators have int type, but we allow, as an
15791     // extension, the enumerators to be larger than int size.  If each
15792     // enumerator value fits in an int, type it as an int, otherwise type it the
15793     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
15794     // that X has type 'int', not 'unsigned'.
15795 
15796     // Determine whether the value fits into an int.
15797     llvm::APSInt InitVal = ECD->getInitVal();
15798 
15799     // If it fits into an integer type, force it.  Otherwise force it to match
15800     // the enum decl type.
15801     QualType NewTy;
15802     unsigned NewWidth;
15803     bool NewSign;
15804     if (!getLangOpts().CPlusPlus &&
15805         !Enum->isFixed() &&
15806         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
15807       NewTy = Context.IntTy;
15808       NewWidth = IntWidth;
15809       NewSign = true;
15810     } else if (ECD->getType() == BestType) {
15811       // Already the right type!
15812       if (getLangOpts().CPlusPlus)
15813         // C++ [dcl.enum]p4: Following the closing brace of an
15814         // enum-specifier, each enumerator has the type of its
15815         // enumeration.
15816         ECD->setType(EnumType);
15817       continue;
15818     } else {
15819       NewTy = BestType;
15820       NewWidth = BestWidth;
15821       NewSign = BestType->isSignedIntegerOrEnumerationType();
15822     }
15823 
15824     // Adjust the APSInt value.
15825     InitVal = InitVal.extOrTrunc(NewWidth);
15826     InitVal.setIsSigned(NewSign);
15827     ECD->setInitVal(InitVal);
15828 
15829     // Adjust the Expr initializer and type.
15830     if (ECD->getInitExpr() &&
15831         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
15832       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
15833                                                 CK_IntegralCast,
15834                                                 ECD->getInitExpr(),
15835                                                 /*base paths*/ nullptr,
15836                                                 VK_RValue));
15837     if (getLangOpts().CPlusPlus)
15838       // C++ [dcl.enum]p4: Following the closing brace of an
15839       // enum-specifier, each enumerator has the type of its
15840       // enumeration.
15841       ECD->setType(EnumType);
15842     else
15843       ECD->setType(NewTy);
15844   }
15845 
15846   Enum->completeDefinition(BestType, BestPromotionType,
15847                            NumPositiveBits, NumNegativeBits);
15848 
15849   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
15850 
15851   if (Enum->isClosedFlag()) {
15852     for (Decl *D : Elements) {
15853       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
15854       if (!ECD) continue;  // Already issued a diagnostic.
15855 
15856       llvm::APSInt InitVal = ECD->getInitVal();
15857       if (InitVal != 0 && !InitVal.isPowerOf2() &&
15858           !IsValueInFlagEnum(Enum, InitVal, true))
15859         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
15860           << ECD << Enum;
15861     }
15862   }
15863 
15864   // Now that the enum type is defined, ensure it's not been underaligned.
15865   if (Enum->hasAttrs())
15866     CheckAlignasUnderalignment(Enum);
15867 }
15868 
15869 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
15870                                   SourceLocation StartLoc,
15871                                   SourceLocation EndLoc) {
15872   StringLiteral *AsmString = cast<StringLiteral>(expr);
15873 
15874   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
15875                                                    AsmString, StartLoc,
15876                                                    EndLoc);
15877   CurContext->addDecl(New);
15878   return New;
15879 }
15880 
15881 static void checkModuleImportContext(Sema &S, Module *M,
15882                                      SourceLocation ImportLoc, DeclContext *DC,
15883                                      bool FromInclude = false) {
15884   SourceLocation ExternCLoc;
15885 
15886   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
15887     switch (LSD->getLanguage()) {
15888     case LinkageSpecDecl::lang_c:
15889       if (ExternCLoc.isInvalid())
15890         ExternCLoc = LSD->getLocStart();
15891       break;
15892     case LinkageSpecDecl::lang_cxx:
15893       break;
15894     }
15895     DC = LSD->getParent();
15896   }
15897 
15898   while (isa<LinkageSpecDecl>(DC))
15899     DC = DC->getParent();
15900 
15901   if (!isa<TranslationUnitDecl>(DC)) {
15902     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
15903                           ? diag::ext_module_import_not_at_top_level_noop
15904                           : diag::err_module_import_not_at_top_level_fatal)
15905         << M->getFullModuleName() << DC;
15906     S.Diag(cast<Decl>(DC)->getLocStart(),
15907            diag::note_module_import_not_at_top_level) << DC;
15908   } else if (!M->IsExternC && ExternCLoc.isValid()) {
15909     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
15910       << M->getFullModuleName();
15911     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
15912   }
15913 }
15914 
15915 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
15916                                            SourceLocation ModuleLoc,
15917                                            ModuleDeclKind MDK,
15918                                            ModuleIdPath Path) {
15919   // A module implementation unit requires that we are not compiling a module
15920   // of any kind. A module interface unit requires that we are not compiling a
15921   // module map.
15922   switch (getLangOpts().getCompilingModule()) {
15923   case LangOptions::CMK_None:
15924     // It's OK to compile a module interface as a normal translation unit.
15925     break;
15926 
15927   case LangOptions::CMK_ModuleInterface:
15928     if (MDK != ModuleDeclKind::Implementation)
15929       break;
15930 
15931     // We were asked to compile a module interface unit but this is a module
15932     // implementation unit. That indicates the 'export' is missing.
15933     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
15934       << FixItHint::CreateInsertion(ModuleLoc, "export ");
15935     break;
15936 
15937   case LangOptions::CMK_ModuleMap:
15938     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
15939     return nullptr;
15940   }
15941 
15942   // FIXME: Create a ModuleDecl and return it.
15943 
15944   // FIXME: Most of this work should be done by the preprocessor rather than
15945   // here, in order to support macro import.
15946 
15947   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
15948   // modules, the dots here are just another character that can appear in a
15949   // module name.
15950   std::string ModuleName;
15951   for (auto &Piece : Path) {
15952     if (!ModuleName.empty())
15953       ModuleName += ".";
15954     ModuleName += Piece.first->getName();
15955   }
15956 
15957   // If a module name was explicitly specified on the command line, it must be
15958   // correct.
15959   if (!getLangOpts().CurrentModule.empty() &&
15960       getLangOpts().CurrentModule != ModuleName) {
15961     Diag(Path.front().second, diag::err_current_module_name_mismatch)
15962         << SourceRange(Path.front().second, Path.back().second)
15963         << getLangOpts().CurrentModule;
15964     return nullptr;
15965   }
15966   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
15967 
15968   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
15969 
15970   switch (MDK) {
15971   case ModuleDeclKind::Module: {
15972     // FIXME: Check we're not in a submodule.
15973 
15974     // We can't have parsed or imported a definition of this module or parsed a
15975     // module map defining it already.
15976     if (auto *M = Map.findModule(ModuleName)) {
15977       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
15978       if (M->DefinitionLoc.isValid())
15979         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
15980       else if (const auto *FE = M->getASTFile())
15981         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
15982             << FE->getName();
15983       return nullptr;
15984     }
15985 
15986     // Create a Module for the module that we're defining.
15987     Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
15988     assert(Mod && "module creation should not fail");
15989 
15990     // Enter the semantic scope of the module.
15991     ActOnModuleBegin(ModuleLoc, Mod);
15992     return nullptr;
15993   }
15994 
15995   case ModuleDeclKind::Partition:
15996     // FIXME: Check we are in a submodule of the named module.
15997     return nullptr;
15998 
15999   case ModuleDeclKind::Implementation:
16000     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
16001         PP.getIdentifierInfo(ModuleName), Path[0].second);
16002 
16003     DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc);
16004     if (Import.isInvalid())
16005       return nullptr;
16006     return ConvertDeclToDeclGroup(Import.get());
16007   }
16008 
16009   llvm_unreachable("unexpected module decl kind");
16010 }
16011 
16012 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
16013                                    SourceLocation ImportLoc,
16014                                    ModuleIdPath Path) {
16015   Module *Mod =
16016       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
16017                                    /*IsIncludeDirective=*/false);
16018   if (!Mod)
16019     return true;
16020 
16021   VisibleModules.setVisible(Mod, ImportLoc);
16022 
16023   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
16024 
16025   // FIXME: we should support importing a submodule within a different submodule
16026   // of the same top-level module. Until we do, make it an error rather than
16027   // silently ignoring the import.
16028   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
16029   // warn on a redundant import of the current module?
16030   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
16031       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
16032     Diag(ImportLoc, getLangOpts().isCompilingModule()
16033                         ? diag::err_module_self_import
16034                         : diag::err_module_import_in_implementation)
16035         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
16036 
16037   SmallVector<SourceLocation, 2> IdentifierLocs;
16038   Module *ModCheck = Mod;
16039   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
16040     // If we've run out of module parents, just drop the remaining identifiers.
16041     // We need the length to be consistent.
16042     if (!ModCheck)
16043       break;
16044     ModCheck = ModCheck->Parent;
16045 
16046     IdentifierLocs.push_back(Path[I].second);
16047   }
16048 
16049   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16050   ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
16051                                           Mod, IdentifierLocs);
16052   if (!ModuleScopes.empty())
16053     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
16054   TU->addDecl(Import);
16055   return Import;
16056 }
16057 
16058 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16059   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16060   BuildModuleInclude(DirectiveLoc, Mod);
16061 }
16062 
16063 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16064   // Determine whether we're in the #include buffer for a module. The #includes
16065   // in that buffer do not qualify as module imports; they're just an
16066   // implementation detail of us building the module.
16067   //
16068   // FIXME: Should we even get ActOnModuleInclude calls for those?
16069   bool IsInModuleIncludes =
16070       TUKind == TU_Module &&
16071       getSourceManager().isWrittenInMainFile(DirectiveLoc);
16072 
16073   bool ShouldAddImport = !IsInModuleIncludes;
16074 
16075   // If this module import was due to an inclusion directive, create an
16076   // implicit import declaration to capture it in the AST.
16077   if (ShouldAddImport) {
16078     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16079     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16080                                                      DirectiveLoc, Mod,
16081                                                      DirectiveLoc);
16082     if (!ModuleScopes.empty())
16083       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
16084     TU->addDecl(ImportD);
16085     Consumer.HandleImplicitImportDecl(ImportD);
16086   }
16087 
16088   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
16089   VisibleModules.setVisible(Mod, DirectiveLoc);
16090 }
16091 
16092 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
16093   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16094 
16095   ModuleScopes.push_back({});
16096   ModuleScopes.back().Module = Mod;
16097   if (getLangOpts().ModulesLocalVisibility)
16098     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
16099 
16100   VisibleModules.setVisible(Mod, DirectiveLoc);
16101 
16102   // The enclosing context is now part of this module.
16103   // FIXME: Consider creating a child DeclContext to hold the entities
16104   // lexically within the module.
16105   if (getLangOpts().trackLocalOwningModule()) {
16106     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16107       cast<Decl>(DC)->setModuleOwnershipKind(
16108           getLangOpts().ModulesLocalVisibility
16109               ? Decl::ModuleOwnershipKind::VisibleWhenImported
16110               : Decl::ModuleOwnershipKind::Visible);
16111       cast<Decl>(DC)->setLocalOwningModule(Mod);
16112     }
16113   }
16114 }
16115 
16116 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
16117   if (getLangOpts().ModulesLocalVisibility) {
16118     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
16119     // Leaving a module hides namespace names, so our visible namespace cache
16120     // is now out of date.
16121     VisibleNamespaceCache.clear();
16122   }
16123 
16124   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
16125          "left the wrong module scope");
16126   ModuleScopes.pop_back();
16127 
16128   // We got to the end of processing a local module. Create an
16129   // ImportDecl as we would for an imported module.
16130   FileID File = getSourceManager().getFileID(EomLoc);
16131   SourceLocation DirectiveLoc;
16132   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
16133     // We reached the end of a #included module header. Use the #include loc.
16134     assert(File != getSourceManager().getMainFileID() &&
16135            "end of submodule in main source file");
16136     DirectiveLoc = getSourceManager().getIncludeLoc(File);
16137   } else {
16138     // We reached an EOM pragma. Use the pragma location.
16139     DirectiveLoc = EomLoc;
16140   }
16141   BuildModuleInclude(DirectiveLoc, Mod);
16142 
16143   // Any further declarations are in whatever module we returned to.
16144   if (getLangOpts().trackLocalOwningModule()) {
16145     // The parser guarantees that this is the same context that we entered
16146     // the module within.
16147     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16148       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
16149       if (!getCurrentModule())
16150         cast<Decl>(DC)->setModuleOwnershipKind(
16151             Decl::ModuleOwnershipKind::Unowned);
16152     }
16153   }
16154 }
16155 
16156 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
16157                                                       Module *Mod) {
16158   // Bail if we're not allowed to implicitly import a module here.
16159   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
16160       VisibleModules.isVisible(Mod))
16161     return;
16162 
16163   // Create the implicit import declaration.
16164   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16165   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16166                                                    Loc, Mod, Loc);
16167   TU->addDecl(ImportD);
16168   Consumer.HandleImplicitImportDecl(ImportD);
16169 
16170   // Make the module visible.
16171   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
16172   VisibleModules.setVisible(Mod, Loc);
16173 }
16174 
16175 /// We have parsed the start of an export declaration, including the '{'
16176 /// (if present).
16177 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
16178                                  SourceLocation LBraceLoc) {
16179   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
16180 
16181   // C++ Modules TS draft:
16182   //   An export-declaration shall appear in the purview of a module other than
16183   //   the global module.
16184   if (ModuleScopes.empty() || !ModuleScopes.back().Module ||
16185       ModuleScopes.back().Module->Kind != Module::ModuleInterfaceUnit)
16186     Diag(ExportLoc, diag::err_export_not_in_module_interface);
16187 
16188   //   An export-declaration [...] shall not contain more than one
16189   //   export keyword.
16190   //
16191   // The intent here is that an export-declaration cannot appear within another
16192   // export-declaration.
16193   if (D->isExported())
16194     Diag(ExportLoc, diag::err_export_within_export);
16195 
16196   CurContext->addDecl(D);
16197   PushDeclContext(S, D);
16198   return D;
16199 }
16200 
16201 /// Complete the definition of an export declaration.
16202 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
16203   auto *ED = cast<ExportDecl>(D);
16204   if (RBraceLoc.isValid())
16205     ED->setRBraceLoc(RBraceLoc);
16206 
16207   // FIXME: Diagnose export of internal-linkage declaration (including
16208   // anonymous namespace).
16209 
16210   PopDeclContext();
16211   return D;
16212 }
16213 
16214 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
16215                                       IdentifierInfo* AliasName,
16216                                       SourceLocation PragmaLoc,
16217                                       SourceLocation NameLoc,
16218                                       SourceLocation AliasNameLoc) {
16219   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
16220                                          LookupOrdinaryName);
16221   AsmLabelAttr *Attr =
16222       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
16223 
16224   // If a declaration that:
16225   // 1) declares a function or a variable
16226   // 2) has external linkage
16227   // already exists, add a label attribute to it.
16228   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16229     if (isDeclExternC(PrevDecl))
16230       PrevDecl->addAttr(Attr);
16231     else
16232       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
16233           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
16234   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
16235   } else
16236     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
16237 }
16238 
16239 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
16240                              SourceLocation PragmaLoc,
16241                              SourceLocation NameLoc) {
16242   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
16243 
16244   if (PrevDecl) {
16245     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
16246   } else {
16247     (void)WeakUndeclaredIdentifiers.insert(
16248       std::pair<IdentifierInfo*,WeakInfo>
16249         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
16250   }
16251 }
16252 
16253 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
16254                                 IdentifierInfo* AliasName,
16255                                 SourceLocation PragmaLoc,
16256                                 SourceLocation NameLoc,
16257                                 SourceLocation AliasNameLoc) {
16258   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
16259                                     LookupOrdinaryName);
16260   WeakInfo W = WeakInfo(Name, NameLoc);
16261 
16262   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16263     if (!PrevDecl->hasAttr<AliasAttr>())
16264       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
16265         DeclApplyPragmaWeak(TUScope, ND, W);
16266   } else {
16267     (void)WeakUndeclaredIdentifiers.insert(
16268       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
16269   }
16270 }
16271 
16272 Decl *Sema::getObjCDeclContext() const {
16273   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
16274 }
16275