]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaDecl.cpp
Merge ^/head r337586 through r337590.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Sema / SemaDecl.cpp
1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for declarations.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/CommentDiagnostic.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaInternal.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50
51 using namespace clang;
52 using namespace sema;
53
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62
63 namespace {
64
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66  public:
67    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
68                         bool AllowTemplates = false,
69                         bool AllowNonTemplates = true)
70        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
71          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
72      WantExpressionKeywords = false;
73      WantCXXNamedCasts = false;
74      WantRemainingKeywords = false;
75   }
76
77   bool ValidateCandidate(const TypoCorrection &candidate) override {
78     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
79       if (!AllowInvalidDecl && ND->isInvalidDecl())
80         return false;
81
82       if (getAsTypeTemplateDecl(ND))
83         return AllowTemplates;
84
85       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
86       if (!IsType)
87         return false;
88
89       if (AllowNonTemplates)
90         return true;
91
92       // An injected-class-name of a class template (specialization) is valid
93       // as a template or as a non-template.
94       if (AllowTemplates) {
95         auto *RD = dyn_cast<CXXRecordDecl>(ND);
96         if (!RD || !RD->isInjectedClassName())
97           return false;
98         RD = cast<CXXRecordDecl>(RD->getDeclContext());
99         return RD->getDescribedClassTemplate() ||
100                isa<ClassTemplateSpecializationDecl>(RD);
101       }
102
103       return false;
104     }
105
106     return !WantClassName && candidate.isKeyword();
107   }
108
109  private:
110   bool AllowInvalidDecl;
111   bool WantClassName;
112   bool AllowTemplates;
113   bool AllowNonTemplates;
114 };
115
116 } // end anonymous namespace
117
118 /// Determine whether the token kind starts a simple-type-specifier.
119 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
120   switch (Kind) {
121   // FIXME: Take into account the current language when deciding whether a
122   // token kind is a valid type specifier
123   case tok::kw_short:
124   case tok::kw_long:
125   case tok::kw___int64:
126   case tok::kw___int128:
127   case tok::kw_signed:
128   case tok::kw_unsigned:
129   case tok::kw_void:
130   case tok::kw_char:
131   case tok::kw_int:
132   case tok::kw_half:
133   case tok::kw_float:
134   case tok::kw_double:
135   case tok::kw__Float16:
136   case tok::kw___float128:
137   case tok::kw_wchar_t:
138   case tok::kw_bool:
139   case tok::kw___underlying_type:
140   case tok::kw___auto_type:
141     return true;
142
143   case tok::annot_typename:
144   case tok::kw_char16_t:
145   case tok::kw_char32_t:
146   case tok::kw_typeof:
147   case tok::annot_decltype:
148   case tok::kw_decltype:
149     return getLangOpts().CPlusPlus;
150
151   case tok::kw_char8_t:
152     return getLangOpts().Char8;
153
154   default:
155     break;
156   }
157
158   return false;
159 }
160
161 namespace {
162 enum class UnqualifiedTypeNameLookupResult {
163   NotFound,
164   FoundNonType,
165   FoundType
166 };
167 } // end anonymous namespace
168
169 /// Tries to perform unqualified lookup of the type decls in bases for
170 /// dependent class.
171 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
172 /// type decl, \a FoundType if only type decls are found.
173 static UnqualifiedTypeNameLookupResult
174 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
175                                 SourceLocation NameLoc,
176                                 const CXXRecordDecl *RD) {
177   if (!RD->hasDefinition())
178     return UnqualifiedTypeNameLookupResult::NotFound;
179   // Look for type decls in base classes.
180   UnqualifiedTypeNameLookupResult FoundTypeDecl =
181       UnqualifiedTypeNameLookupResult::NotFound;
182   for (const auto &Base : RD->bases()) {
183     const CXXRecordDecl *BaseRD = nullptr;
184     if (auto *BaseTT = Base.getType()->getAs<TagType>())
185       BaseRD = BaseTT->getAsCXXRecordDecl();
186     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
187       // Look for type decls in dependent base classes that have known primary
188       // templates.
189       if (!TST || !TST->isDependentType())
190         continue;
191       auto *TD = TST->getTemplateName().getAsTemplateDecl();
192       if (!TD)
193         continue;
194       if (auto *BasePrimaryTemplate =
195           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
196         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
197           BaseRD = BasePrimaryTemplate;
198         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
199           if (const ClassTemplatePartialSpecializationDecl *PS =
200                   CTD->findPartialSpecialization(Base.getType()))
201             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
202               BaseRD = PS;
203         }
204       }
205     }
206     if (BaseRD) {
207       for (NamedDecl *ND : BaseRD->lookup(&II)) {
208         if (!isa<TypeDecl>(ND))
209           return UnqualifiedTypeNameLookupResult::FoundNonType;
210         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
211       }
212       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
213         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
214         case UnqualifiedTypeNameLookupResult::FoundNonType:
215           return UnqualifiedTypeNameLookupResult::FoundNonType;
216         case UnqualifiedTypeNameLookupResult::FoundType:
217           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
218           break;
219         case UnqualifiedTypeNameLookupResult::NotFound:
220           break;
221         }
222       }
223     }
224   }
225
226   return FoundTypeDecl;
227 }
228
229 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
230                                                       const IdentifierInfo &II,
231                                                       SourceLocation NameLoc) {
232   // Lookup in the parent class template context, if any.
233   const CXXRecordDecl *RD = nullptr;
234   UnqualifiedTypeNameLookupResult FoundTypeDecl =
235       UnqualifiedTypeNameLookupResult::NotFound;
236   for (DeclContext *DC = S.CurContext;
237        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
238        DC = DC->getParent()) {
239     // Look for type decls in dependent base classes that have known primary
240     // templates.
241     RD = dyn_cast<CXXRecordDecl>(DC);
242     if (RD && RD->getDescribedClassTemplate())
243       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
244   }
245   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
246     return nullptr;
247
248   // We found some types in dependent base classes.  Recover as if the user
249   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
250   // lookup during template instantiation.
251   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
252
253   ASTContext &Context = S.Context;
254   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
255                                           cast<Type>(Context.getRecordType(RD)));
256   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
257
258   CXXScopeSpec SS;
259   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
260
261   TypeLocBuilder Builder;
262   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
263   DepTL.setNameLoc(NameLoc);
264   DepTL.setElaboratedKeywordLoc(SourceLocation());
265   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
266   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
267 }
268
269 /// If the identifier refers to a type name within this scope,
270 /// return the declaration of that type.
271 ///
272 /// This routine performs ordinary name lookup of the identifier II
273 /// within the given scope, with optional C++ scope specifier SS, to
274 /// determine whether the name refers to a type. If so, returns an
275 /// opaque pointer (actually a QualType) corresponding to that
276 /// type. Otherwise, returns NULL.
277 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
278                              Scope *S, CXXScopeSpec *SS,
279                              bool isClassName, bool HasTrailingDot,
280                              ParsedType ObjectTypePtr,
281                              bool IsCtorOrDtorName,
282                              bool WantNontrivialTypeSourceInfo,
283                              bool IsClassTemplateDeductionContext,
284                              IdentifierInfo **CorrectedII) {
285   // FIXME: Consider allowing this outside C++1z mode as an extension.
286   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
287                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
288                               !isClassName && !HasTrailingDot;
289
290   // Determine where we will perform name lookup.
291   DeclContext *LookupCtx = nullptr;
292   if (ObjectTypePtr) {
293     QualType ObjectType = ObjectTypePtr.get();
294     if (ObjectType->isRecordType())
295       LookupCtx = computeDeclContext(ObjectType);
296   } else if (SS && SS->isNotEmpty()) {
297     LookupCtx = computeDeclContext(*SS, false);
298
299     if (!LookupCtx) {
300       if (isDependentScopeSpecifier(*SS)) {
301         // C++ [temp.res]p3:
302         //   A qualified-id that refers to a type and in which the
303         //   nested-name-specifier depends on a template-parameter (14.6.2)
304         //   shall be prefixed by the keyword typename to indicate that the
305         //   qualified-id denotes a type, forming an
306         //   elaborated-type-specifier (7.1.5.3).
307         //
308         // We therefore do not perform any name lookup if the result would
309         // refer to a member of an unknown specialization.
310         if (!isClassName && !IsCtorOrDtorName)
311           return nullptr;
312
313         // We know from the grammar that this name refers to a type,
314         // so build a dependent node to describe the type.
315         if (WantNontrivialTypeSourceInfo)
316           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
317
318         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
319         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
320                                        II, NameLoc);
321         return ParsedType::make(T);
322       }
323
324       return nullptr;
325     }
326
327     if (!LookupCtx->isDependentContext() &&
328         RequireCompleteDeclContext(*SS, LookupCtx))
329       return nullptr;
330   }
331
332   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
333   // lookup for class-names.
334   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
335                                       LookupOrdinaryName;
336   LookupResult Result(*this, &II, NameLoc, Kind);
337   if (LookupCtx) {
338     // Perform "qualified" name lookup into the declaration context we
339     // computed, which is either the type of the base of a member access
340     // expression or the declaration context associated with a prior
341     // nested-name-specifier.
342     LookupQualifiedName(Result, LookupCtx);
343
344     if (ObjectTypePtr && Result.empty()) {
345       // C++ [basic.lookup.classref]p3:
346       //   If the unqualified-id is ~type-name, the type-name is looked up
347       //   in the context of the entire postfix-expression. If the type T of
348       //   the object expression is of a class type C, the type-name is also
349       //   looked up in the scope of class C. At least one of the lookups shall
350       //   find a name that refers to (possibly cv-qualified) T.
351       LookupName(Result, S);
352     }
353   } else {
354     // Perform unqualified name lookup.
355     LookupName(Result, S);
356
357     // For unqualified lookup in a class template in MSVC mode, look into
358     // dependent base classes where the primary class template is known.
359     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
360       if (ParsedType TypeInBase =
361               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
362         return TypeInBase;
363     }
364   }
365
366   NamedDecl *IIDecl = nullptr;
367   switch (Result.getResultKind()) {
368   case LookupResult::NotFound:
369   case LookupResult::NotFoundInCurrentInstantiation:
370     if (CorrectedII) {
371       TypoCorrection Correction =
372           CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
373                       llvm::make_unique<TypeNameValidatorCCC>(
374                           true, isClassName, AllowDeducedTemplate),
375                       CTK_ErrorRecovery);
376       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
377       TemplateTy Template;
378       bool MemberOfUnknownSpecialization;
379       UnqualifiedId TemplateName;
380       TemplateName.setIdentifier(NewII, NameLoc);
381       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
382       CXXScopeSpec NewSS, *NewSSPtr = SS;
383       if (SS && NNS) {
384         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
385         NewSSPtr = &NewSS;
386       }
387       if (Correction && (NNS || NewII != &II) &&
388           // Ignore a correction to a template type as the to-be-corrected
389           // identifier is not a template (typo correction for template names
390           // is handled elsewhere).
391           !(getLangOpts().CPlusPlus && NewSSPtr &&
392             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
393                            Template, MemberOfUnknownSpecialization))) {
394         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
395                                     isClassName, HasTrailingDot, ObjectTypePtr,
396                                     IsCtorOrDtorName,
397                                     WantNontrivialTypeSourceInfo,
398                                     IsClassTemplateDeductionContext);
399         if (Ty) {
400           diagnoseTypo(Correction,
401                        PDiag(diag::err_unknown_type_or_class_name_suggest)
402                          << Result.getLookupName() << isClassName);
403           if (SS && NNS)
404             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
405           *CorrectedII = NewII;
406           return Ty;
407         }
408       }
409     }
410     // If typo correction failed or was not performed, fall through
411     LLVM_FALLTHROUGH;
412   case LookupResult::FoundOverloaded:
413   case LookupResult::FoundUnresolvedValue:
414     Result.suppressDiagnostics();
415     return nullptr;
416
417   case LookupResult::Ambiguous:
418     // Recover from type-hiding ambiguities by hiding the type.  We'll
419     // do the lookup again when looking for an object, and we can
420     // diagnose the error then.  If we don't do this, then the error
421     // about hiding the type will be immediately followed by an error
422     // that only makes sense if the identifier was treated like a type.
423     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
424       Result.suppressDiagnostics();
425       return nullptr;
426     }
427
428     // Look to see if we have a type anywhere in the list of results.
429     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
430          Res != ResEnd; ++Res) {
431       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
432           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
433         if (!IIDecl ||
434             (*Res)->getLocation().getRawEncoding() <
435               IIDecl->getLocation().getRawEncoding())
436           IIDecl = *Res;
437       }
438     }
439
440     if (!IIDecl) {
441       // None of the entities we found is a type, so there is no way
442       // to even assume that the result is a type. In this case, don't
443       // complain about the ambiguity. The parser will either try to
444       // perform this lookup again (e.g., as an object name), which
445       // will produce the ambiguity, or will complain that it expected
446       // a type name.
447       Result.suppressDiagnostics();
448       return nullptr;
449     }
450
451     // We found a type within the ambiguous lookup; diagnose the
452     // ambiguity and then return that type. This might be the right
453     // answer, or it might not be, but it suppresses any attempt to
454     // perform the name lookup again.
455     break;
456
457   case LookupResult::Found:
458     IIDecl = Result.getFoundDecl();
459     break;
460   }
461
462   assert(IIDecl && "Didn't find decl");
463
464   QualType T;
465   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
466     // C++ [class.qual]p2: A lookup that would find the injected-class-name
467     // instead names the constructors of the class, except when naming a class.
468     // This is ill-formed when we're not actually forming a ctor or dtor name.
469     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
470     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
471     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
472         FoundRD->isInjectedClassName() &&
473         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
474       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
475           << &II << /*Type*/1;
476
477     DiagnoseUseOfDecl(IIDecl, NameLoc);
478
479     T = Context.getTypeDeclType(TD);
480     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
481   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
482     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
483     if (!HasTrailingDot)
484       T = Context.getObjCInterfaceType(IDecl);
485   } else if (AllowDeducedTemplate) {
486     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
487       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
488                                                        QualType(), false);
489   }
490
491   if (T.isNull()) {
492     // If it's not plausibly a type, suppress diagnostics.
493     Result.suppressDiagnostics();
494     return nullptr;
495   }
496
497   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
498   // constructor or destructor name (in such a case, the scope specifier
499   // will be attached to the enclosing Expr or Decl node).
500   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
501       !isa<ObjCInterfaceDecl>(IIDecl)) {
502     if (WantNontrivialTypeSourceInfo) {
503       // Construct a type with type-source information.
504       TypeLocBuilder Builder;
505       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
506
507       T = getElaboratedType(ETK_None, *SS, T);
508       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
509       ElabTL.setElaboratedKeywordLoc(SourceLocation());
510       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
511       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
512     } else {
513       T = getElaboratedType(ETK_None, *SS, T);
514     }
515   }
516
517   return ParsedType::make(T);
518 }
519
520 // Builds a fake NNS for the given decl context.
521 static NestedNameSpecifier *
522 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
523   for (;; DC = DC->getLookupParent()) {
524     DC = DC->getPrimaryContext();
525     auto *ND = dyn_cast<NamespaceDecl>(DC);
526     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
527       return NestedNameSpecifier::Create(Context, nullptr, ND);
528     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
529       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
530                                          RD->getTypeForDecl());
531     else if (isa<TranslationUnitDecl>(DC))
532       return NestedNameSpecifier::GlobalSpecifier(Context);
533   }
534   llvm_unreachable("something isn't in TU scope?");
535 }
536
537 /// Find the parent class with dependent bases of the innermost enclosing method
538 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
539 /// up allowing unqualified dependent type names at class-level, which MSVC
540 /// correctly rejects.
541 static const CXXRecordDecl *
542 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
543   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
544     DC = DC->getPrimaryContext();
545     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
546       if (MD->getParent()->hasAnyDependentBases())
547         return MD->getParent();
548   }
549   return nullptr;
550 }
551
552 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
553                                           SourceLocation NameLoc,
554                                           bool IsTemplateTypeArg) {
555   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
556
557   NestedNameSpecifier *NNS = nullptr;
558   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
559     // If we weren't able to parse a default template argument, delay lookup
560     // until instantiation time by making a non-dependent DependentTypeName. We
561     // pretend we saw a NestedNameSpecifier referring to the current scope, and
562     // lookup is retried.
563     // FIXME: This hurts our diagnostic quality, since we get errors like "no
564     // type named 'Foo' in 'current_namespace'" when the user didn't write any
565     // name specifiers.
566     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
567     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
568   } else if (const CXXRecordDecl *RD =
569                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
570     // Build a DependentNameType that will perform lookup into RD at
571     // instantiation time.
572     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
573                                       RD->getTypeForDecl());
574
575     // Diagnose that this identifier was undeclared, and retry the lookup during
576     // template instantiation.
577     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
578                                                                       << RD;
579   } else {
580     // This is not a situation that we should recover from.
581     return ParsedType();
582   }
583
584   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
585
586   // Build type location information.  We synthesized the qualifier, so we have
587   // to build a fake NestedNameSpecifierLoc.
588   NestedNameSpecifierLocBuilder NNSLocBuilder;
589   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
590   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
591
592   TypeLocBuilder Builder;
593   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
594   DepTL.setNameLoc(NameLoc);
595   DepTL.setElaboratedKeywordLoc(SourceLocation());
596   DepTL.setQualifierLoc(QualifierLoc);
597   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
598 }
599
600 /// isTagName() - This method is called *for error recovery purposes only*
601 /// to determine if the specified name is a valid tag name ("struct foo").  If
602 /// so, this returns the TST for the tag corresponding to it (TST_enum,
603 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
604 /// cases in C where the user forgot to specify the tag.
605 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
606   // Do a tag name lookup in this scope.
607   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
608   LookupName(R, S, false);
609   R.suppressDiagnostics();
610   if (R.getResultKind() == LookupResult::Found)
611     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
612       switch (TD->getTagKind()) {
613       case TTK_Struct: return DeclSpec::TST_struct;
614       case TTK_Interface: return DeclSpec::TST_interface;
615       case TTK_Union:  return DeclSpec::TST_union;
616       case TTK_Class:  return DeclSpec::TST_class;
617       case TTK_Enum:   return DeclSpec::TST_enum;
618       }
619     }
620
621   return DeclSpec::TST_unspecified;
622 }
623
624 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
625 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
626 /// then downgrade the missing typename error to a warning.
627 /// This is needed for MSVC compatibility; Example:
628 /// @code
629 /// template<class T> class A {
630 /// public:
631 ///   typedef int TYPE;
632 /// };
633 /// template<class T> class B : public A<T> {
634 /// public:
635 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
636 /// };
637 /// @endcode
638 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
639   if (CurContext->isRecord()) {
640     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
641       return true;
642
643     const Type *Ty = SS->getScopeRep()->getAsType();
644
645     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
646     for (const auto &Base : RD->bases())
647       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
648         return true;
649     return S->isFunctionPrototypeScope();
650   }
651   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
652 }
653
654 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
655                                    SourceLocation IILoc,
656                                    Scope *S,
657                                    CXXScopeSpec *SS,
658                                    ParsedType &SuggestedType,
659                                    bool IsTemplateName) {
660   // Don't report typename errors for editor placeholders.
661   if (II->isEditorPlaceholder())
662     return;
663   // We don't have anything to suggest (yet).
664   SuggestedType = nullptr;
665
666   // There may have been a typo in the name of the type. Look up typo
667   // results, in case we have something that we can suggest.
668   if (TypoCorrection Corrected =
669           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
670                       llvm::make_unique<TypeNameValidatorCCC>(
671                           false, false, IsTemplateName, !IsTemplateName),
672                       CTK_ErrorRecovery)) {
673     // FIXME: Support error recovery for the template-name case.
674     bool CanRecover = !IsTemplateName;
675     if (Corrected.isKeyword()) {
676       // We corrected to a keyword.
677       diagnoseTypo(Corrected,
678                    PDiag(IsTemplateName ? diag::err_no_template_suggest
679                                         : diag::err_unknown_typename_suggest)
680                        << II);
681       II = Corrected.getCorrectionAsIdentifierInfo();
682     } else {
683       // We found a similarly-named type or interface; suggest that.
684       if (!SS || !SS->isSet()) {
685         diagnoseTypo(Corrected,
686                      PDiag(IsTemplateName ? diag::err_no_template_suggest
687                                           : diag::err_unknown_typename_suggest)
688                          << II, CanRecover);
689       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
690         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
691         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
692                                 II->getName().equals(CorrectedStr);
693         diagnoseTypo(Corrected,
694                      PDiag(IsTemplateName
695                                ? diag::err_no_member_template_suggest
696                                : diag::err_unknown_nested_typename_suggest)
697                          << II << DC << DroppedSpecifier << SS->getRange(),
698                      CanRecover);
699       } else {
700         llvm_unreachable("could not have corrected a typo here");
701       }
702
703       if (!CanRecover)
704         return;
705
706       CXXScopeSpec tmpSS;
707       if (Corrected.getCorrectionSpecifier())
708         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
709                           SourceRange(IILoc));
710       // FIXME: Support class template argument deduction here.
711       SuggestedType =
712           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
713                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
714                       /*IsCtorOrDtorName=*/false,
715                       /*NonTrivialTypeSourceInfo=*/true);
716     }
717     return;
718   }
719
720   if (getLangOpts().CPlusPlus && !IsTemplateName) {
721     // See if II is a class template that the user forgot to pass arguments to.
722     UnqualifiedId Name;
723     Name.setIdentifier(II, IILoc);
724     CXXScopeSpec EmptySS;
725     TemplateTy TemplateResult;
726     bool MemberOfUnknownSpecialization;
727     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
728                        Name, nullptr, true, TemplateResult,
729                        MemberOfUnknownSpecialization) == TNK_Type_template) {
730       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
731       return;
732     }
733   }
734
735   // FIXME: Should we move the logic that tries to recover from a missing tag
736   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
737
738   if (!SS || (!SS->isSet() && !SS->isInvalid()))
739     Diag(IILoc, IsTemplateName ? diag::err_no_template
740                                : diag::err_unknown_typename)
741         << II;
742   else if (DeclContext *DC = computeDeclContext(*SS, false))
743     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
744                                : diag::err_typename_nested_not_found)
745         << II << DC << SS->getRange();
746   else if (isDependentScopeSpecifier(*SS)) {
747     unsigned DiagID = diag::err_typename_missing;
748     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
749       DiagID = diag::ext_typename_missing;
750
751     Diag(SS->getRange().getBegin(), DiagID)
752       << SS->getScopeRep() << II->getName()
753       << SourceRange(SS->getRange().getBegin(), IILoc)
754       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
755     SuggestedType = ActOnTypenameType(S, SourceLocation(),
756                                       *SS, *II, IILoc).get();
757   } else {
758     assert(SS && SS->isInvalid() &&
759            "Invalid scope specifier has already been diagnosed");
760   }
761 }
762
763 /// Determine whether the given result set contains either a type name
764 /// or
765 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
766   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
767                        NextToken.is(tok::less);
768
769   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
770     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
771       return true;
772
773     if (CheckTemplate && isa<TemplateDecl>(*I))
774       return true;
775   }
776
777   return false;
778 }
779
780 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
781                                     Scope *S, CXXScopeSpec &SS,
782                                     IdentifierInfo *&Name,
783                                     SourceLocation NameLoc) {
784   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
785   SemaRef.LookupParsedName(R, S, &SS);
786   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
787     StringRef FixItTagName;
788     switch (Tag->getTagKind()) {
789       case TTK_Class:
790         FixItTagName = "class ";
791         break;
792
793       case TTK_Enum:
794         FixItTagName = "enum ";
795         break;
796
797       case TTK_Struct:
798         FixItTagName = "struct ";
799         break;
800
801       case TTK_Interface:
802         FixItTagName = "__interface ";
803         break;
804
805       case TTK_Union:
806         FixItTagName = "union ";
807         break;
808     }
809
810     StringRef TagName = FixItTagName.drop_back();
811     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
812       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
813       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
814
815     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
816          I != IEnd; ++I)
817       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
818         << Name << TagName;
819
820     // Replace lookup results with just the tag decl.
821     Result.clear(Sema::LookupTagName);
822     SemaRef.LookupParsedName(Result, S, &SS);
823     return true;
824   }
825
826   return false;
827 }
828
829 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
830 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
831                                   QualType T, SourceLocation NameLoc) {
832   ASTContext &Context = S.Context;
833
834   TypeLocBuilder Builder;
835   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
836
837   T = S.getElaboratedType(ETK_None, SS, T);
838   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
839   ElabTL.setElaboratedKeywordLoc(SourceLocation());
840   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
841   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
842 }
843
844 Sema::NameClassification
845 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
846                    SourceLocation NameLoc, const Token &NextToken,
847                    bool IsAddressOfOperand,
848                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
849   DeclarationNameInfo NameInfo(Name, NameLoc);
850   ObjCMethodDecl *CurMethod = getCurMethodDecl();
851
852   if (NextToken.is(tok::coloncolon)) {
853     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
854     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
855   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
856              isCurrentClassName(*Name, S, &SS)) {
857     // Per [class.qual]p2, this names the constructors of SS, not the
858     // injected-class-name. We don't have a classification for that.
859     // There's not much point caching this result, since the parser
860     // will reject it later.
861     return NameClassification::Unknown();
862   }
863
864   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
865   LookupParsedName(Result, S, &SS, !CurMethod);
866
867   // For unqualified lookup in a class template in MSVC mode, look into
868   // dependent base classes where the primary class template is known.
869   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
870     if (ParsedType TypeInBase =
871             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
872       return TypeInBase;
873   }
874
875   // Perform lookup for Objective-C instance variables (including automatically
876   // synthesized instance variables), if we're in an Objective-C method.
877   // FIXME: This lookup really, really needs to be folded in to the normal
878   // unqualified lookup mechanism.
879   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
880     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
881     if (E.get() || E.isInvalid())
882       return E;
883   }
884
885   bool SecondTry = false;
886   bool IsFilteredTemplateName = false;
887
888 Corrected:
889   switch (Result.getResultKind()) {
890   case LookupResult::NotFound:
891     // If an unqualified-id is followed by a '(', then we have a function
892     // call.
893     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
894       // In C++, this is an ADL-only call.
895       // FIXME: Reference?
896       if (getLangOpts().CPlusPlus)
897         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
898
899       // C90 6.3.2.2:
900       //   If the expression that precedes the parenthesized argument list in a
901       //   function call consists solely of an identifier, and if no
902       //   declaration is visible for this identifier, the identifier is
903       //   implicitly declared exactly as if, in the innermost block containing
904       //   the function call, the declaration
905       //
906       //     extern int identifier ();
907       //
908       //   appeared.
909       //
910       // We also allow this in C99 as an extension.
911       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
912         Result.addDecl(D);
913         Result.resolveKind();
914         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
915       }
916     }
917
918     // In C, we first see whether there is a tag type by the same name, in
919     // which case it's likely that the user just forgot to write "enum",
920     // "struct", or "union".
921     if (!getLangOpts().CPlusPlus && !SecondTry &&
922         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
923       break;
924     }
925
926     // Perform typo correction to determine if there is another name that is
927     // close to this name.
928     if (!SecondTry && CCC) {
929       SecondTry = true;
930       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
931                                                  Result.getLookupKind(), S,
932                                                  &SS, std::move(CCC),
933                                                  CTK_ErrorRecovery)) {
934         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
935         unsigned QualifiedDiag = diag::err_no_member_suggest;
936
937         NamedDecl *FirstDecl = Corrected.getFoundDecl();
938         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
939         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
940             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
941           UnqualifiedDiag = diag::err_no_template_suggest;
942           QualifiedDiag = diag::err_no_member_template_suggest;
943         } else if (UnderlyingFirstDecl &&
944                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
945                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
946                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
947           UnqualifiedDiag = diag::err_unknown_typename_suggest;
948           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
949         }
950
951         if (SS.isEmpty()) {
952           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
953         } else {// FIXME: is this even reachable? Test it.
954           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
955           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
956                                   Name->getName().equals(CorrectedStr);
957           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
958                                     << Name << computeDeclContext(SS, false)
959                                     << DroppedSpecifier << SS.getRange());
960         }
961
962         // Update the name, so that the caller has the new name.
963         Name = Corrected.getCorrectionAsIdentifierInfo();
964
965         // Typo correction corrected to a keyword.
966         if (Corrected.isKeyword())
967           return Name;
968
969         // Also update the LookupResult...
970         // FIXME: This should probably go away at some point
971         Result.clear();
972         Result.setLookupName(Corrected.getCorrection());
973         if (FirstDecl)
974           Result.addDecl(FirstDecl);
975
976         // If we found an Objective-C instance variable, let
977         // LookupInObjCMethod build the appropriate expression to
978         // reference the ivar.
979         // FIXME: This is a gross hack.
980         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
981           Result.clear();
982           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
983           return E;
984         }
985
986         goto Corrected;
987       }
988     }
989
990     // We failed to correct; just fall through and let the parser deal with it.
991     Result.suppressDiagnostics();
992     return NameClassification::Unknown();
993
994   case LookupResult::NotFoundInCurrentInstantiation: {
995     // We performed name lookup into the current instantiation, and there were
996     // dependent bases, so we treat this result the same way as any other
997     // dependent nested-name-specifier.
998
999     // C++ [temp.res]p2:
1000     //   A name used in a template declaration or definition and that is
1001     //   dependent on a template-parameter is assumed not to name a type
1002     //   unless the applicable name lookup finds a type name or the name is
1003     //   qualified by the keyword typename.
1004     //
1005     // FIXME: If the next token is '<', we might want to ask the parser to
1006     // perform some heroics to see if we actually have a
1007     // template-argument-list, which would indicate a missing 'template'
1008     // keyword here.
1009     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1010                                       NameInfo, IsAddressOfOperand,
1011                                       /*TemplateArgs=*/nullptr);
1012   }
1013
1014   case LookupResult::Found:
1015   case LookupResult::FoundOverloaded:
1016   case LookupResult::FoundUnresolvedValue:
1017     break;
1018
1019   case LookupResult::Ambiguous:
1020     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1021         hasAnyAcceptableTemplateNames(Result)) {
1022       // C++ [temp.local]p3:
1023       //   A lookup that finds an injected-class-name (10.2) can result in an
1024       //   ambiguity in certain cases (for example, if it is found in more than
1025       //   one base class). If all of the injected-class-names that are found
1026       //   refer to specializations of the same class template, and if the name
1027       //   is followed by a template-argument-list, the reference refers to the
1028       //   class template itself and not a specialization thereof, and is not
1029       //   ambiguous.
1030       //
1031       // This filtering can make an ambiguous result into an unambiguous one,
1032       // so try again after filtering out template names.
1033       FilterAcceptableTemplateNames(Result);
1034       if (!Result.isAmbiguous()) {
1035         IsFilteredTemplateName = true;
1036         break;
1037       }
1038     }
1039
1040     // Diagnose the ambiguity and return an error.
1041     return NameClassification::Error();
1042   }
1043
1044   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1045       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
1046     // C++ [temp.names]p3:
1047     //   After name lookup (3.4) finds that a name is a template-name or that
1048     //   an operator-function-id or a literal- operator-id refers to a set of
1049     //   overloaded functions any member of which is a function template if
1050     //   this is followed by a <, the < is always taken as the delimiter of a
1051     //   template-argument-list and never as the less-than operator.
1052     if (!IsFilteredTemplateName)
1053       FilterAcceptableTemplateNames(Result);
1054
1055     if (!Result.empty()) {
1056       bool IsFunctionTemplate;
1057       bool IsVarTemplate;
1058       TemplateName Template;
1059       if (Result.end() - Result.begin() > 1) {
1060         IsFunctionTemplate = true;
1061         Template = Context.getOverloadedTemplateName(Result.begin(),
1062                                                      Result.end());
1063       } else {
1064         TemplateDecl *TD
1065           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1066         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1067         IsVarTemplate = isa<VarTemplateDecl>(TD);
1068
1069         if (SS.isSet() && !SS.isInvalid())
1070           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1071                                                     /*TemplateKeyword=*/false,
1072                                                       TD);
1073         else
1074           Template = TemplateName(TD);
1075       }
1076
1077       if (IsFunctionTemplate) {
1078         // Function templates always go through overload resolution, at which
1079         // point we'll perform the various checks (e.g., accessibility) we need
1080         // to based on which function we selected.
1081         Result.suppressDiagnostics();
1082
1083         return NameClassification::FunctionTemplate(Template);
1084       }
1085
1086       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1087                            : NameClassification::TypeTemplate(Template);
1088     }
1089   }
1090
1091   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1092   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1093     DiagnoseUseOfDecl(Type, NameLoc);
1094     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1095     QualType T = Context.getTypeDeclType(Type);
1096     if (SS.isNotEmpty())
1097       return buildNestedType(*this, SS, T, NameLoc);
1098     return ParsedType::make(T);
1099   }
1100
1101   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1102   if (!Class) {
1103     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1104     if (ObjCCompatibleAliasDecl *Alias =
1105             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1106       Class = Alias->getClassInterface();
1107   }
1108
1109   if (Class) {
1110     DiagnoseUseOfDecl(Class, NameLoc);
1111
1112     if (NextToken.is(tok::period)) {
1113       // Interface. <something> is parsed as a property reference expression.
1114       // Just return "unknown" as a fall-through for now.
1115       Result.suppressDiagnostics();
1116       return NameClassification::Unknown();
1117     }
1118
1119     QualType T = Context.getObjCInterfaceType(Class);
1120     return ParsedType::make(T);
1121   }
1122
1123   // We can have a type template here if we're classifying a template argument.
1124   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1125       !isa<VarTemplateDecl>(FirstDecl))
1126     return NameClassification::TypeTemplate(
1127         TemplateName(cast<TemplateDecl>(FirstDecl)));
1128
1129   // Check for a tag type hidden by a non-type decl in a few cases where it
1130   // seems likely a type is wanted instead of the non-type that was found.
1131   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1132   if ((NextToken.is(tok::identifier) ||
1133        (NextIsOp &&
1134         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1135       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1136     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1137     DiagnoseUseOfDecl(Type, NameLoc);
1138     QualType T = Context.getTypeDeclType(Type);
1139     if (SS.isNotEmpty())
1140       return buildNestedType(*this, SS, T, NameLoc);
1141     return ParsedType::make(T);
1142   }
1143
1144   if (FirstDecl->isCXXClassMember())
1145     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1146                                            nullptr, S);
1147
1148   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1149   return BuildDeclarationNameExpr(SS, Result, ADL);
1150 }
1151
1152 Sema::TemplateNameKindForDiagnostics
1153 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1154   auto *TD = Name.getAsTemplateDecl();
1155   if (!TD)
1156     return TemplateNameKindForDiagnostics::DependentTemplate;
1157   if (isa<ClassTemplateDecl>(TD))
1158     return TemplateNameKindForDiagnostics::ClassTemplate;
1159   if (isa<FunctionTemplateDecl>(TD))
1160     return TemplateNameKindForDiagnostics::FunctionTemplate;
1161   if (isa<VarTemplateDecl>(TD))
1162     return TemplateNameKindForDiagnostics::VarTemplate;
1163   if (isa<TypeAliasTemplateDecl>(TD))
1164     return TemplateNameKindForDiagnostics::AliasTemplate;
1165   if (isa<TemplateTemplateParmDecl>(TD))
1166     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1167   return TemplateNameKindForDiagnostics::DependentTemplate;
1168 }
1169
1170 // Determines the context to return to after temporarily entering a
1171 // context.  This depends in an unnecessarily complicated way on the
1172 // exact ordering of callbacks from the parser.
1173 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1174
1175   // Functions defined inline within classes aren't parsed until we've
1176   // finished parsing the top-level class, so the top-level class is
1177   // the context we'll need to return to.
1178   // A Lambda call operator whose parent is a class must not be treated
1179   // as an inline member function.  A Lambda can be used legally
1180   // either as an in-class member initializer or a default argument.  These
1181   // are parsed once the class has been marked complete and so the containing
1182   // context would be the nested class (when the lambda is defined in one);
1183   // If the class is not complete, then the lambda is being used in an
1184   // ill-formed fashion (such as to specify the width of a bit-field, or
1185   // in an array-bound) - in which case we still want to return the
1186   // lexically containing DC (which could be a nested class).
1187   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1188     DC = DC->getLexicalParent();
1189
1190     // A function not defined within a class will always return to its
1191     // lexical context.
1192     if (!isa<CXXRecordDecl>(DC))
1193       return DC;
1194
1195     // A C++ inline method/friend is parsed *after* the topmost class
1196     // it was declared in is fully parsed ("complete");  the topmost
1197     // class is the context we need to return to.
1198     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1199       DC = RD;
1200
1201     // Return the declaration context of the topmost class the inline method is
1202     // declared in.
1203     return DC;
1204   }
1205
1206   return DC->getLexicalParent();
1207 }
1208
1209 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1210   assert(getContainingDC(DC) == CurContext &&
1211       "The next DeclContext should be lexically contained in the current one.");
1212   CurContext = DC;
1213   S->setEntity(DC);
1214 }
1215
1216 void Sema::PopDeclContext() {
1217   assert(CurContext && "DeclContext imbalance!");
1218
1219   CurContext = getContainingDC(CurContext);
1220   assert(CurContext && "Popped translation unit!");
1221 }
1222
1223 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1224                                                                     Decl *D) {
1225   // Unlike PushDeclContext, the context to which we return is not necessarily
1226   // the containing DC of TD, because the new context will be some pre-existing
1227   // TagDecl definition instead of a fresh one.
1228   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1229   CurContext = cast<TagDecl>(D)->getDefinition();
1230   assert(CurContext && "skipping definition of undefined tag");
1231   // Start lookups from the parent of the current context; we don't want to look
1232   // into the pre-existing complete definition.
1233   S->setEntity(CurContext->getLookupParent());
1234   return Result;
1235 }
1236
1237 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1238   CurContext = static_cast<decltype(CurContext)>(Context);
1239 }
1240
1241 /// EnterDeclaratorContext - Used when we must lookup names in the context
1242 /// of a declarator's nested name specifier.
1243 ///
1244 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1245   // C++0x [basic.lookup.unqual]p13:
1246   //   A name used in the definition of a static data member of class
1247   //   X (after the qualified-id of the static member) is looked up as
1248   //   if the name was used in a member function of X.
1249   // C++0x [basic.lookup.unqual]p14:
1250   //   If a variable member of a namespace is defined outside of the
1251   //   scope of its namespace then any name used in the definition of
1252   //   the variable member (after the declarator-id) is looked up as
1253   //   if the definition of the variable member occurred in its
1254   //   namespace.
1255   // Both of these imply that we should push a scope whose context
1256   // is the semantic context of the declaration.  We can't use
1257   // PushDeclContext here because that context is not necessarily
1258   // lexically contained in the current context.  Fortunately,
1259   // the containing scope should have the appropriate information.
1260
1261   assert(!S->getEntity() && "scope already has entity");
1262
1263 #ifndef NDEBUG
1264   Scope *Ancestor = S->getParent();
1265   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1266   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1267 #endif
1268
1269   CurContext = DC;
1270   S->setEntity(DC);
1271 }
1272
1273 void Sema::ExitDeclaratorContext(Scope *S) {
1274   assert(S->getEntity() == CurContext && "Context imbalance!");
1275
1276   // Switch back to the lexical context.  The safety of this is
1277   // enforced by an assert in EnterDeclaratorContext.
1278   Scope *Ancestor = S->getParent();
1279   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1280   CurContext = Ancestor->getEntity();
1281
1282   // We don't need to do anything with the scope, which is going to
1283   // disappear.
1284 }
1285
1286 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1287   // We assume that the caller has already called
1288   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1289   FunctionDecl *FD = D->getAsFunction();
1290   if (!FD)
1291     return;
1292
1293   // Same implementation as PushDeclContext, but enters the context
1294   // from the lexical parent, rather than the top-level class.
1295   assert(CurContext == FD->getLexicalParent() &&
1296     "The next DeclContext should be lexically contained in the current one.");
1297   CurContext = FD;
1298   S->setEntity(CurContext);
1299
1300   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1301     ParmVarDecl *Param = FD->getParamDecl(P);
1302     // If the parameter has an identifier, then add it to the scope
1303     if (Param->getIdentifier()) {
1304       S->AddDecl(Param);
1305       IdResolver.AddDecl(Param);
1306     }
1307   }
1308 }
1309
1310 void Sema::ActOnExitFunctionContext() {
1311   // Same implementation as PopDeclContext, but returns to the lexical parent,
1312   // rather than the top-level class.
1313   assert(CurContext && "DeclContext imbalance!");
1314   CurContext = CurContext->getLexicalParent();
1315   assert(CurContext && "Popped translation unit!");
1316 }
1317
1318 /// Determine whether we allow overloading of the function
1319 /// PrevDecl with another declaration.
1320 ///
1321 /// This routine determines whether overloading is possible, not
1322 /// whether some new function is actually an overload. It will return
1323 /// true in C++ (where we can always provide overloads) or, as an
1324 /// extension, in C when the previous function is already an
1325 /// overloaded function declaration or has the "overloadable"
1326 /// attribute.
1327 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1328                                        ASTContext &Context,
1329                                        const FunctionDecl *New) {
1330   if (Context.getLangOpts().CPlusPlus)
1331     return true;
1332
1333   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1334     return true;
1335
1336   return Previous.getResultKind() == LookupResult::Found &&
1337          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1338           New->hasAttr<OverloadableAttr>());
1339 }
1340
1341 /// Add this decl to the scope shadowed decl chains.
1342 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1343   // Move up the scope chain until we find the nearest enclosing
1344   // non-transparent context. The declaration will be introduced into this
1345   // scope.
1346   while (S->getEntity() && S->getEntity()->isTransparentContext())
1347     S = S->getParent();
1348
1349   // Add scoped declarations into their context, so that they can be
1350   // found later. Declarations without a context won't be inserted
1351   // into any context.
1352   if (AddToContext)
1353     CurContext->addDecl(D);
1354
1355   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1356   // are function-local declarations.
1357   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1358       !D->getDeclContext()->getRedeclContext()->Equals(
1359         D->getLexicalDeclContext()->getRedeclContext()) &&
1360       !D->getLexicalDeclContext()->isFunctionOrMethod())
1361     return;
1362
1363   // Template instantiations should also not be pushed into scope.
1364   if (isa<FunctionDecl>(D) &&
1365       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1366     return;
1367
1368   // If this replaces anything in the current scope,
1369   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1370                                IEnd = IdResolver.end();
1371   for (; I != IEnd; ++I) {
1372     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1373       S->RemoveDecl(*I);
1374       IdResolver.RemoveDecl(*I);
1375
1376       // Should only need to replace one decl.
1377       break;
1378     }
1379   }
1380
1381   S->AddDecl(D);
1382
1383   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1384     // Implicitly-generated labels may end up getting generated in an order that
1385     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1386     // the label at the appropriate place in the identifier chain.
1387     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1388       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1389       if (IDC == CurContext) {
1390         if (!S->isDeclScope(*I))
1391           continue;
1392       } else if (IDC->Encloses(CurContext))
1393         break;
1394     }
1395
1396     IdResolver.InsertDeclAfter(I, D);
1397   } else {
1398     IdResolver.AddDecl(D);
1399   }
1400 }
1401
1402 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1403   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1404     TUScope->AddDecl(D);
1405 }
1406
1407 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1408                          bool AllowInlineNamespace) {
1409   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1410 }
1411
1412 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1413   DeclContext *TargetDC = DC->getPrimaryContext();
1414   do {
1415     if (DeclContext *ScopeDC = S->getEntity())
1416       if (ScopeDC->getPrimaryContext() == TargetDC)
1417         return S;
1418   } while ((S = S->getParent()));
1419
1420   return nullptr;
1421 }
1422
1423 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1424                                             DeclContext*,
1425                                             ASTContext&);
1426
1427 /// Filters out lookup results that don't fall within the given scope
1428 /// as determined by isDeclInScope.
1429 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1430                                 bool ConsiderLinkage,
1431                                 bool AllowInlineNamespace) {
1432   LookupResult::Filter F = R.makeFilter();
1433   while (F.hasNext()) {
1434     NamedDecl *D = F.next();
1435
1436     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1437       continue;
1438
1439     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1440       continue;
1441
1442     F.erase();
1443   }
1444
1445   F.done();
1446 }
1447
1448 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1449 /// have compatible owning modules.
1450 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1451   // FIXME: The Modules TS is not clear about how friend declarations are
1452   // to be treated. It's not meaningful to have different owning modules for
1453   // linkage in redeclarations of the same entity, so for now allow the
1454   // redeclaration and change the owning modules to match.
1455   if (New->getFriendObjectKind() &&
1456       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1457     New->setLocalOwningModule(Old->getOwningModule());
1458     makeMergedDefinitionVisible(New);
1459     return false;
1460   }
1461
1462   Module *NewM = New->getOwningModule();
1463   Module *OldM = Old->getOwningModule();
1464   if (NewM == OldM)
1465     return false;
1466
1467   // FIXME: Check proclaimed-ownership-declarations here too.
1468   bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit;
1469   bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit;
1470   if (NewIsModuleInterface || OldIsModuleInterface) {
1471     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1472     //   if a declaration of D [...] appears in the purview of a module, all
1473     //   other such declarations shall appear in the purview of the same module
1474     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1475       << New
1476       << NewIsModuleInterface
1477       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1478       << OldIsModuleInterface
1479       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1480     Diag(Old->getLocation(), diag::note_previous_declaration);
1481     New->setInvalidDecl();
1482     return true;
1483   }
1484
1485   return false;
1486 }
1487
1488 static bool isUsingDecl(NamedDecl *D) {
1489   return isa<UsingShadowDecl>(D) ||
1490          isa<UnresolvedUsingTypenameDecl>(D) ||
1491          isa<UnresolvedUsingValueDecl>(D);
1492 }
1493
1494 /// Removes using shadow declarations from the lookup results.
1495 static void RemoveUsingDecls(LookupResult &R) {
1496   LookupResult::Filter F = R.makeFilter();
1497   while (F.hasNext())
1498     if (isUsingDecl(F.next()))
1499       F.erase();
1500
1501   F.done();
1502 }
1503
1504 /// Check for this common pattern:
1505 /// @code
1506 /// class S {
1507 ///   S(const S&); // DO NOT IMPLEMENT
1508 ///   void operator=(const S&); // DO NOT IMPLEMENT
1509 /// };
1510 /// @endcode
1511 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1512   // FIXME: Should check for private access too but access is set after we get
1513   // the decl here.
1514   if (D->doesThisDeclarationHaveABody())
1515     return false;
1516
1517   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1518     return CD->isCopyConstructor();
1519   return D->isCopyAssignmentOperator();
1520 }
1521
1522 // We need this to handle
1523 //
1524 // typedef struct {
1525 //   void *foo() { return 0; }
1526 // } A;
1527 //
1528 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1529 // for example. If 'A', foo will have external linkage. If we have '*A',
1530 // foo will have no linkage. Since we can't know until we get to the end
1531 // of the typedef, this function finds out if D might have non-external linkage.
1532 // Callers should verify at the end of the TU if it D has external linkage or
1533 // not.
1534 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1535   const DeclContext *DC = D->getDeclContext();
1536   while (!DC->isTranslationUnit()) {
1537     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1538       if (!RD->hasNameForLinkage())
1539         return true;
1540     }
1541     DC = DC->getParent();
1542   }
1543
1544   return !D->isExternallyVisible();
1545 }
1546
1547 // FIXME: This needs to be refactored; some other isInMainFile users want
1548 // these semantics.
1549 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1550   if (S.TUKind != TU_Complete)
1551     return false;
1552   return S.SourceMgr.isInMainFile(Loc);
1553 }
1554
1555 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1556   assert(D);
1557
1558   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1559     return false;
1560
1561   // Ignore all entities declared within templates, and out-of-line definitions
1562   // of members of class templates.
1563   if (D->getDeclContext()->isDependentContext() ||
1564       D->getLexicalDeclContext()->isDependentContext())
1565     return false;
1566
1567   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1568     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1569       return false;
1570     // A non-out-of-line declaration of a member specialization was implicitly
1571     // instantiated; it's the out-of-line declaration that we're interested in.
1572     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1573         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1574       return false;
1575
1576     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1577       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1578         return false;
1579     } else {
1580       // 'static inline' functions are defined in headers; don't warn.
1581       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1582         return false;
1583     }
1584
1585     if (FD->doesThisDeclarationHaveABody() &&
1586         Context.DeclMustBeEmitted(FD))
1587       return false;
1588   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1589     // Constants and utility variables are defined in headers with internal
1590     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1591     // like "inline".)
1592     if (!isMainFileLoc(*this, VD->getLocation()))
1593       return false;
1594
1595     if (Context.DeclMustBeEmitted(VD))
1596       return false;
1597
1598     if (VD->isStaticDataMember() &&
1599         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1600       return false;
1601     if (VD->isStaticDataMember() &&
1602         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1603         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1604       return false;
1605
1606     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1607       return false;
1608   } else {
1609     return false;
1610   }
1611
1612   // Only warn for unused decls internal to the translation unit.
1613   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1614   // for inline functions defined in the main source file, for instance.
1615   return mightHaveNonExternalLinkage(D);
1616 }
1617
1618 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1619   if (!D)
1620     return;
1621
1622   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1623     const FunctionDecl *First = FD->getFirstDecl();
1624     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1625       return; // First should already be in the vector.
1626   }
1627
1628   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1629     const VarDecl *First = VD->getFirstDecl();
1630     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1631       return; // First should already be in the vector.
1632   }
1633
1634   if (ShouldWarnIfUnusedFileScopedDecl(D))
1635     UnusedFileScopedDecls.push_back(D);
1636 }
1637
1638 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1639   if (D->isInvalidDecl())
1640     return false;
1641
1642   bool Referenced = false;
1643   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1644     // For a decomposition declaration, warn if none of the bindings are
1645     // referenced, instead of if the variable itself is referenced (which
1646     // it is, by the bindings' expressions).
1647     for (auto *BD : DD->bindings()) {
1648       if (BD->isReferenced()) {
1649         Referenced = true;
1650         break;
1651       }
1652     }
1653   } else if (!D->getDeclName()) {
1654     return false;
1655   } else if (D->isReferenced() || D->isUsed()) {
1656     Referenced = true;
1657   }
1658
1659   if (Referenced || D->hasAttr<UnusedAttr>() ||
1660       D->hasAttr<ObjCPreciseLifetimeAttr>())
1661     return false;
1662
1663   if (isa<LabelDecl>(D))
1664     return true;
1665
1666   // Except for labels, we only care about unused decls that are local to
1667   // functions.
1668   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1669   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1670     // For dependent types, the diagnostic is deferred.
1671     WithinFunction =
1672         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1673   if (!WithinFunction)
1674     return false;
1675
1676   if (isa<TypedefNameDecl>(D))
1677     return true;
1678
1679   // White-list anything that isn't a local variable.
1680   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1681     return false;
1682
1683   // Types of valid local variables should be complete, so this should succeed.
1684   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1685
1686     // White-list anything with an __attribute__((unused)) type.
1687     const auto *Ty = VD->getType().getTypePtr();
1688
1689     // Only look at the outermost level of typedef.
1690     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1691       if (TT->getDecl()->hasAttr<UnusedAttr>())
1692         return false;
1693     }
1694
1695     // If we failed to complete the type for some reason, or if the type is
1696     // dependent, don't diagnose the variable.
1697     if (Ty->isIncompleteType() || Ty->isDependentType())
1698       return false;
1699
1700     // Look at the element type to ensure that the warning behaviour is
1701     // consistent for both scalars and arrays.
1702     Ty = Ty->getBaseElementTypeUnsafe();
1703
1704     if (const TagType *TT = Ty->getAs<TagType>()) {
1705       const TagDecl *Tag = TT->getDecl();
1706       if (Tag->hasAttr<UnusedAttr>())
1707         return false;
1708
1709       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1710         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1711           return false;
1712
1713         if (const Expr *Init = VD->getInit()) {
1714           if (const ExprWithCleanups *Cleanups =
1715                   dyn_cast<ExprWithCleanups>(Init))
1716             Init = Cleanups->getSubExpr();
1717           const CXXConstructExpr *Construct =
1718             dyn_cast<CXXConstructExpr>(Init);
1719           if (Construct && !Construct->isElidable()) {
1720             CXXConstructorDecl *CD = Construct->getConstructor();
1721             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1722                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1723               return false;
1724           }
1725         }
1726       }
1727     }
1728
1729     // TODO: __attribute__((unused)) templates?
1730   }
1731
1732   return true;
1733 }
1734
1735 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1736                                      FixItHint &Hint) {
1737   if (isa<LabelDecl>(D)) {
1738     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1739                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1740     if (AfterColon.isInvalid())
1741       return;
1742     Hint = FixItHint::CreateRemoval(CharSourceRange::
1743                                     getCharRange(D->getLocStart(), AfterColon));
1744   }
1745 }
1746
1747 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1748   if (D->getTypeForDecl()->isDependentType())
1749     return;
1750
1751   for (auto *TmpD : D->decls()) {
1752     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1753       DiagnoseUnusedDecl(T);
1754     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1755       DiagnoseUnusedNestedTypedefs(R);
1756   }
1757 }
1758
1759 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1760 /// unless they are marked attr(unused).
1761 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1762   if (!ShouldDiagnoseUnusedDecl(D))
1763     return;
1764
1765   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1766     // typedefs can be referenced later on, so the diagnostics are emitted
1767     // at end-of-translation-unit.
1768     UnusedLocalTypedefNameCandidates.insert(TD);
1769     return;
1770   }
1771
1772   FixItHint Hint;
1773   GenerateFixForUnusedDecl(D, Context, Hint);
1774
1775   unsigned DiagID;
1776   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1777     DiagID = diag::warn_unused_exception_param;
1778   else if (isa<LabelDecl>(D))
1779     DiagID = diag::warn_unused_label;
1780   else
1781     DiagID = diag::warn_unused_variable;
1782
1783   Diag(D->getLocation(), DiagID) << D << Hint;
1784 }
1785
1786 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1787   // Verify that we have no forward references left.  If so, there was a goto
1788   // or address of a label taken, but no definition of it.  Label fwd
1789   // definitions are indicated with a null substmt which is also not a resolved
1790   // MS inline assembly label name.
1791   bool Diagnose = false;
1792   if (L->isMSAsmLabel())
1793     Diagnose = !L->isResolvedMSAsmLabel();
1794   else
1795     Diagnose = L->getStmt() == nullptr;
1796   if (Diagnose)
1797     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1798 }
1799
1800 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1801   S->mergeNRVOIntoParent();
1802
1803   if (S->decl_empty()) return;
1804   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1805          "Scope shouldn't contain decls!");
1806
1807   for (auto *TmpD : S->decls()) {
1808     assert(TmpD && "This decl didn't get pushed??");
1809
1810     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1811     NamedDecl *D = cast<NamedDecl>(TmpD);
1812
1813     // Diagnose unused variables in this scope.
1814     if (!S->hasUnrecoverableErrorOccurred()) {
1815       DiagnoseUnusedDecl(D);
1816       if (const auto *RD = dyn_cast<RecordDecl>(D))
1817         DiagnoseUnusedNestedTypedefs(RD);
1818     }
1819
1820     if (!D->getDeclName()) continue;
1821
1822     // If this was a forward reference to a label, verify it was defined.
1823     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1824       CheckPoppedLabel(LD, *this);
1825
1826     // Remove this name from our lexical scope, and warn on it if we haven't
1827     // already.
1828     IdResolver.RemoveDecl(D);
1829     auto ShadowI = ShadowingDecls.find(D);
1830     if (ShadowI != ShadowingDecls.end()) {
1831       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1832         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1833             << D << FD << FD->getParent();
1834         Diag(FD->getLocation(), diag::note_previous_declaration);
1835       }
1836       ShadowingDecls.erase(ShadowI);
1837     }
1838   }
1839 }
1840
1841 /// Look for an Objective-C class in the translation unit.
1842 ///
1843 /// \param Id The name of the Objective-C class we're looking for. If
1844 /// typo-correction fixes this name, the Id will be updated
1845 /// to the fixed name.
1846 ///
1847 /// \param IdLoc The location of the name in the translation unit.
1848 ///
1849 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1850 /// if there is no class with the given name.
1851 ///
1852 /// \returns The declaration of the named Objective-C class, or NULL if the
1853 /// class could not be found.
1854 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1855                                               SourceLocation IdLoc,
1856                                               bool DoTypoCorrection) {
1857   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1858   // creation from this context.
1859   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1860
1861   if (!IDecl && DoTypoCorrection) {
1862     // Perform typo correction at the given location, but only if we
1863     // find an Objective-C class name.
1864     if (TypoCorrection C = CorrectTypo(
1865             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1866             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1867             CTK_ErrorRecovery)) {
1868       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1869       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1870       Id = IDecl->getIdentifier();
1871     }
1872   }
1873   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1874   // This routine must always return a class definition, if any.
1875   if (Def && Def->getDefinition())
1876       Def = Def->getDefinition();
1877   return Def;
1878 }
1879
1880 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1881 /// from S, where a non-field would be declared. This routine copes
1882 /// with the difference between C and C++ scoping rules in structs and
1883 /// unions. For example, the following code is well-formed in C but
1884 /// ill-formed in C++:
1885 /// @code
1886 /// struct S6 {
1887 ///   enum { BAR } e;
1888 /// };
1889 ///
1890 /// void test_S6() {
1891 ///   struct S6 a;
1892 ///   a.e = BAR;
1893 /// }
1894 /// @endcode
1895 /// For the declaration of BAR, this routine will return a different
1896 /// scope. The scope S will be the scope of the unnamed enumeration
1897 /// within S6. In C++, this routine will return the scope associated
1898 /// with S6, because the enumeration's scope is a transparent
1899 /// context but structures can contain non-field names. In C, this
1900 /// routine will return the translation unit scope, since the
1901 /// enumeration's scope is a transparent context and structures cannot
1902 /// contain non-field names.
1903 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1904   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1905          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1906          (S->isClassScope() && !getLangOpts().CPlusPlus))
1907     S = S->getParent();
1908   return S;
1909 }
1910
1911 /// Looks up the declaration of "struct objc_super" and
1912 /// saves it for later use in building builtin declaration of
1913 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1914 /// pre-existing declaration exists no action takes place.
1915 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1916                                         IdentifierInfo *II) {
1917   if (!II->isStr("objc_msgSendSuper"))
1918     return;
1919   ASTContext &Context = ThisSema.Context;
1920
1921   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1922                       SourceLocation(), Sema::LookupTagName);
1923   ThisSema.LookupName(Result, S);
1924   if (Result.getResultKind() == LookupResult::Found)
1925     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1926       Context.setObjCSuperType(Context.getTagDeclType(TD));
1927 }
1928
1929 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1930   switch (Error) {
1931   case ASTContext::GE_None:
1932     return "";
1933   case ASTContext::GE_Missing_stdio:
1934     return "stdio.h";
1935   case ASTContext::GE_Missing_setjmp:
1936     return "setjmp.h";
1937   case ASTContext::GE_Missing_ucontext:
1938     return "ucontext.h";
1939   }
1940   llvm_unreachable("unhandled error kind");
1941 }
1942
1943 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1944 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1945 /// if we're creating this built-in in anticipation of redeclaring the
1946 /// built-in.
1947 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1948                                      Scope *S, bool ForRedeclaration,
1949                                      SourceLocation Loc) {
1950   LookupPredefedObjCSuperType(*this, S, II);
1951
1952   ASTContext::GetBuiltinTypeError Error;
1953   QualType R = Context.GetBuiltinType(ID, Error);
1954   if (Error) {
1955     if (ForRedeclaration)
1956       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1957           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1958     return nullptr;
1959   }
1960
1961   if (!ForRedeclaration &&
1962       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1963        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1964     Diag(Loc, diag::ext_implicit_lib_function_decl)
1965         << Context.BuiltinInfo.getName(ID) << R;
1966     if (Context.BuiltinInfo.getHeaderName(ID) &&
1967         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1968       Diag(Loc, diag::note_include_header_or_declare)
1969           << Context.BuiltinInfo.getHeaderName(ID)
1970           << Context.BuiltinInfo.getName(ID);
1971   }
1972
1973   if (R.isNull())
1974     return nullptr;
1975
1976   DeclContext *Parent = Context.getTranslationUnitDecl();
1977   if (getLangOpts().CPlusPlus) {
1978     LinkageSpecDecl *CLinkageDecl =
1979         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1980                                 LinkageSpecDecl::lang_c, false);
1981     CLinkageDecl->setImplicit();
1982     Parent->addDecl(CLinkageDecl);
1983     Parent = CLinkageDecl;
1984   }
1985
1986   FunctionDecl *New = FunctionDecl::Create(Context,
1987                                            Parent,
1988                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1989                                            SC_Extern,
1990                                            false,
1991                                            R->isFunctionProtoType());
1992   New->setImplicit();
1993
1994   // Create Decl objects for each parameter, adding them to the
1995   // FunctionDecl.
1996   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1997     SmallVector<ParmVarDecl*, 16> Params;
1998     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1999       ParmVarDecl *parm =
2000           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2001                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2002                               SC_None, nullptr);
2003       parm->setScopeInfo(0, i);
2004       Params.push_back(parm);
2005     }
2006     New->setParams(Params);
2007   }
2008
2009   AddKnownFunctionAttributes(New);
2010   RegisterLocallyScopedExternCDecl(New, S);
2011
2012   // TUScope is the translation-unit scope to insert this function into.
2013   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2014   // relate Scopes to DeclContexts, and probably eliminate CurContext
2015   // entirely, but we're not there yet.
2016   DeclContext *SavedContext = CurContext;
2017   CurContext = Parent;
2018   PushOnScopeChains(New, TUScope);
2019   CurContext = SavedContext;
2020   return New;
2021 }
2022
2023 /// Typedef declarations don't have linkage, but they still denote the same
2024 /// entity if their types are the same.
2025 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2026 /// isSameEntity.
2027 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2028                                                      TypedefNameDecl *Decl,
2029                                                      LookupResult &Previous) {
2030   // This is only interesting when modules are enabled.
2031   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2032     return;
2033
2034   // Empty sets are uninteresting.
2035   if (Previous.empty())
2036     return;
2037
2038   LookupResult::Filter Filter = Previous.makeFilter();
2039   while (Filter.hasNext()) {
2040     NamedDecl *Old = Filter.next();
2041
2042     // Non-hidden declarations are never ignored.
2043     if (S.isVisible(Old))
2044       continue;
2045
2046     // Declarations of the same entity are not ignored, even if they have
2047     // different linkages.
2048     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2049       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2050                                 Decl->getUnderlyingType()))
2051         continue;
2052
2053       // If both declarations give a tag declaration a typedef name for linkage
2054       // purposes, then they declare the same entity.
2055       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2056           Decl->getAnonDeclWithTypedefName())
2057         continue;
2058     }
2059
2060     Filter.erase();
2061   }
2062
2063   Filter.done();
2064 }
2065
2066 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2067   QualType OldType;
2068   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2069     OldType = OldTypedef->getUnderlyingType();
2070   else
2071     OldType = Context.getTypeDeclType(Old);
2072   QualType NewType = New->getUnderlyingType();
2073
2074   if (NewType->isVariablyModifiedType()) {
2075     // Must not redefine a typedef with a variably-modified type.
2076     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2077     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2078       << Kind << NewType;
2079     if (Old->getLocation().isValid())
2080       notePreviousDefinition(Old, New->getLocation());
2081     New->setInvalidDecl();
2082     return true;
2083   }
2084
2085   if (OldType != NewType &&
2086       !OldType->isDependentType() &&
2087       !NewType->isDependentType() &&
2088       !Context.hasSameType(OldType, NewType)) {
2089     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2090     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2091       << Kind << NewType << OldType;
2092     if (Old->getLocation().isValid())
2093       notePreviousDefinition(Old, New->getLocation());
2094     New->setInvalidDecl();
2095     return true;
2096   }
2097   return false;
2098 }
2099
2100 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2101 /// same name and scope as a previous declaration 'Old'.  Figure out
2102 /// how to resolve this situation, merging decls or emitting
2103 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2104 ///
2105 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2106                                 LookupResult &OldDecls) {
2107   // If the new decl is known invalid already, don't bother doing any
2108   // merging checks.
2109   if (New->isInvalidDecl()) return;
2110
2111   // Allow multiple definitions for ObjC built-in typedefs.
2112   // FIXME: Verify the underlying types are equivalent!
2113   if (getLangOpts().ObjC1) {
2114     const IdentifierInfo *TypeID = New->getIdentifier();
2115     switch (TypeID->getLength()) {
2116     default: break;
2117     case 2:
2118       {
2119         if (!TypeID->isStr("id"))
2120           break;
2121         QualType T = New->getUnderlyingType();
2122         if (!T->isPointerType())
2123           break;
2124         if (!T->isVoidPointerType()) {
2125           QualType PT = T->getAs<PointerType>()->getPointeeType();
2126           if (!PT->isStructureType())
2127             break;
2128         }
2129         Context.setObjCIdRedefinitionType(T);
2130         // Install the built-in type for 'id', ignoring the current definition.
2131         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2132         return;
2133       }
2134     case 5:
2135       if (!TypeID->isStr("Class"))
2136         break;
2137       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2138       // Install the built-in type for 'Class', ignoring the current definition.
2139       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2140       return;
2141     case 3:
2142       if (!TypeID->isStr("SEL"))
2143         break;
2144       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2145       // Install the built-in type for 'SEL', ignoring the current definition.
2146       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2147       return;
2148     }
2149     // Fall through - the typedef name was not a builtin type.
2150   }
2151
2152   // Verify the old decl was also a type.
2153   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2154   if (!Old) {
2155     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2156       << New->getDeclName();
2157
2158     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2159     if (OldD->getLocation().isValid())
2160       notePreviousDefinition(OldD, New->getLocation());
2161
2162     return New->setInvalidDecl();
2163   }
2164
2165   // If the old declaration is invalid, just give up here.
2166   if (Old->isInvalidDecl())
2167     return New->setInvalidDecl();
2168
2169   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2170     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2171     auto *NewTag = New->getAnonDeclWithTypedefName();
2172     NamedDecl *Hidden = nullptr;
2173     if (OldTag && NewTag &&
2174         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2175         !hasVisibleDefinition(OldTag, &Hidden)) {
2176       // There is a definition of this tag, but it is not visible. Use it
2177       // instead of our tag.
2178       New->setTypeForDecl(OldTD->getTypeForDecl());
2179       if (OldTD->isModed())
2180         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2181                                     OldTD->getUnderlyingType());
2182       else
2183         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2184
2185       // Make the old tag definition visible.
2186       makeMergedDefinitionVisible(Hidden);
2187
2188       // If this was an unscoped enumeration, yank all of its enumerators
2189       // out of the scope.
2190       if (isa<EnumDecl>(NewTag)) {
2191         Scope *EnumScope = getNonFieldDeclScope(S);
2192         for (auto *D : NewTag->decls()) {
2193           auto *ED = cast<EnumConstantDecl>(D);
2194           assert(EnumScope->isDeclScope(ED));
2195           EnumScope->RemoveDecl(ED);
2196           IdResolver.RemoveDecl(ED);
2197           ED->getLexicalDeclContext()->removeDecl(ED);
2198         }
2199       }
2200     }
2201   }
2202
2203   // If the typedef types are not identical, reject them in all languages and
2204   // with any extensions enabled.
2205   if (isIncompatibleTypedef(Old, New))
2206     return;
2207
2208   // The types match.  Link up the redeclaration chain and merge attributes if
2209   // the old declaration was a typedef.
2210   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2211     New->setPreviousDecl(Typedef);
2212     mergeDeclAttributes(New, Old);
2213   }
2214
2215   if (getLangOpts().MicrosoftExt)
2216     return;
2217
2218   if (getLangOpts().CPlusPlus) {
2219     // C++ [dcl.typedef]p2:
2220     //   In a given non-class scope, a typedef specifier can be used to
2221     //   redefine the name of any type declared in that scope to refer
2222     //   to the type to which it already refers.
2223     if (!isa<CXXRecordDecl>(CurContext))
2224       return;
2225
2226     // C++0x [dcl.typedef]p4:
2227     //   In a given class scope, a typedef specifier can be used to redefine
2228     //   any class-name declared in that scope that is not also a typedef-name
2229     //   to refer to the type to which it already refers.
2230     //
2231     // This wording came in via DR424, which was a correction to the
2232     // wording in DR56, which accidentally banned code like:
2233     //
2234     //   struct S {
2235     //     typedef struct A { } A;
2236     //   };
2237     //
2238     // in the C++03 standard. We implement the C++0x semantics, which
2239     // allow the above but disallow
2240     //
2241     //   struct S {
2242     //     typedef int I;
2243     //     typedef int I;
2244     //   };
2245     //
2246     // since that was the intent of DR56.
2247     if (!isa<TypedefNameDecl>(Old))
2248       return;
2249
2250     Diag(New->getLocation(), diag::err_redefinition)
2251       << New->getDeclName();
2252     notePreviousDefinition(Old, New->getLocation());
2253     return New->setInvalidDecl();
2254   }
2255
2256   // Modules always permit redefinition of typedefs, as does C11.
2257   if (getLangOpts().Modules || getLangOpts().C11)
2258     return;
2259
2260   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2261   // is normally mapped to an error, but can be controlled with
2262   // -Wtypedef-redefinition.  If either the original or the redefinition is
2263   // in a system header, don't emit this for compatibility with GCC.
2264   if (getDiagnostics().getSuppressSystemWarnings() &&
2265       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2266       (Old->isImplicit() ||
2267        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2268        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2269     return;
2270
2271   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2272     << New->getDeclName();
2273   notePreviousDefinition(Old, New->getLocation());
2274 }
2275
2276 /// DeclhasAttr - returns true if decl Declaration already has the target
2277 /// attribute.
2278 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2279   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2280   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2281   for (const auto *i : D->attrs())
2282     if (i->getKind() == A->getKind()) {
2283       if (Ann) {
2284         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2285           return true;
2286         continue;
2287       }
2288       // FIXME: Don't hardcode this check
2289       if (OA && isa<OwnershipAttr>(i))
2290         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2291       return true;
2292     }
2293
2294   return false;
2295 }
2296
2297 static bool isAttributeTargetADefinition(Decl *D) {
2298   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2299     return VD->isThisDeclarationADefinition();
2300   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2301     return TD->isCompleteDefinition() || TD->isBeingDefined();
2302   return true;
2303 }
2304
2305 /// Merge alignment attributes from \p Old to \p New, taking into account the
2306 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2307 ///
2308 /// \return \c true if any attributes were added to \p New.
2309 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2310   // Look for alignas attributes on Old, and pick out whichever attribute
2311   // specifies the strictest alignment requirement.
2312   AlignedAttr *OldAlignasAttr = nullptr;
2313   AlignedAttr *OldStrictestAlignAttr = nullptr;
2314   unsigned OldAlign = 0;
2315   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2316     // FIXME: We have no way of representing inherited dependent alignments
2317     // in a case like:
2318     //   template<int A, int B> struct alignas(A) X;
2319     //   template<int A, int B> struct alignas(B) X {};
2320     // For now, we just ignore any alignas attributes which are not on the
2321     // definition in such a case.
2322     if (I->isAlignmentDependent())
2323       return false;
2324
2325     if (I->isAlignas())
2326       OldAlignasAttr = I;
2327
2328     unsigned Align = I->getAlignment(S.Context);
2329     if (Align > OldAlign) {
2330       OldAlign = Align;
2331       OldStrictestAlignAttr = I;
2332     }
2333   }
2334
2335   // Look for alignas attributes on New.
2336   AlignedAttr *NewAlignasAttr = nullptr;
2337   unsigned NewAlign = 0;
2338   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2339     if (I->isAlignmentDependent())
2340       return false;
2341
2342     if (I->isAlignas())
2343       NewAlignasAttr = I;
2344
2345     unsigned Align = I->getAlignment(S.Context);
2346     if (Align > NewAlign)
2347       NewAlign = Align;
2348   }
2349
2350   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2351     // Both declarations have 'alignas' attributes. We require them to match.
2352     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2353     // fall short. (If two declarations both have alignas, they must both match
2354     // every definition, and so must match each other if there is a definition.)
2355
2356     // If either declaration only contains 'alignas(0)' specifiers, then it
2357     // specifies the natural alignment for the type.
2358     if (OldAlign == 0 || NewAlign == 0) {
2359       QualType Ty;
2360       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2361         Ty = VD->getType();
2362       else
2363         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2364
2365       if (OldAlign == 0)
2366         OldAlign = S.Context.getTypeAlign(Ty);
2367       if (NewAlign == 0)
2368         NewAlign = S.Context.getTypeAlign(Ty);
2369     }
2370
2371     if (OldAlign != NewAlign) {
2372       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2373         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2374         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2375       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2376     }
2377   }
2378
2379   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2380     // C++11 [dcl.align]p6:
2381     //   if any declaration of an entity has an alignment-specifier,
2382     //   every defining declaration of that entity shall specify an
2383     //   equivalent alignment.
2384     // C11 6.7.5/7:
2385     //   If the definition of an object does not have an alignment
2386     //   specifier, any other declaration of that object shall also
2387     //   have no alignment specifier.
2388     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2389       << OldAlignasAttr;
2390     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2391       << OldAlignasAttr;
2392   }
2393
2394   bool AnyAdded = false;
2395
2396   // Ensure we have an attribute representing the strictest alignment.
2397   if (OldAlign > NewAlign) {
2398     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2399     Clone->setInherited(true);
2400     New->addAttr(Clone);
2401     AnyAdded = true;
2402   }
2403
2404   // Ensure we have an alignas attribute if the old declaration had one.
2405   if (OldAlignasAttr && !NewAlignasAttr &&
2406       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2407     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2408     Clone->setInherited(true);
2409     New->addAttr(Clone);
2410     AnyAdded = true;
2411   }
2412
2413   return AnyAdded;
2414 }
2415
2416 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2417                                const InheritableAttr *Attr,
2418                                Sema::AvailabilityMergeKind AMK) {
2419   // This function copies an attribute Attr from a previous declaration to the
2420   // new declaration D if the new declaration doesn't itself have that attribute
2421   // yet or if that attribute allows duplicates.
2422   // If you're adding a new attribute that requires logic different from
2423   // "use explicit attribute on decl if present, else use attribute from
2424   // previous decl", for example if the attribute needs to be consistent
2425   // between redeclarations, you need to call a custom merge function here.
2426   InheritableAttr *NewAttr = nullptr;
2427   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2428   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2429     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2430                                       AA->isImplicit(), AA->getIntroduced(),
2431                                       AA->getDeprecated(),
2432                                       AA->getObsoleted(), AA->getUnavailable(),
2433                                       AA->getMessage(), AA->getStrict(),
2434                                       AA->getReplacement(), AMK,
2435                                       AttrSpellingListIndex);
2436   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2437     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2438                                     AttrSpellingListIndex);
2439   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2440     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2441                                         AttrSpellingListIndex);
2442   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2443     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2444                                    AttrSpellingListIndex);
2445   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2446     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2447                                    AttrSpellingListIndex);
2448   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2449     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2450                                 FA->getFormatIdx(), FA->getFirstArg(),
2451                                 AttrSpellingListIndex);
2452   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2453     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2454                                  AttrSpellingListIndex);
2455   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2456     NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(),
2457                                  AttrSpellingListIndex);
2458   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2459     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2460                                        AttrSpellingListIndex,
2461                                        IA->getSemanticSpelling());
2462   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2463     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2464                                       &S.Context.Idents.get(AA->getSpelling()),
2465                                       AttrSpellingListIndex);
2466   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2467            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2468             isa<CUDAGlobalAttr>(Attr))) {
2469     // CUDA target attributes are part of function signature for
2470     // overloading purposes and must not be merged.
2471     return false;
2472   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2473     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2474   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2475     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2476   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2477     NewAttr = S.mergeInternalLinkageAttr(
2478         D, InternalLinkageA->getRange(),
2479         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2480         AttrSpellingListIndex);
2481   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2482     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2483                                 &S.Context.Idents.get(CommonA->getSpelling()),
2484                                 AttrSpellingListIndex);
2485   else if (isa<AlignedAttr>(Attr))
2486     // AlignedAttrs are handled separately, because we need to handle all
2487     // such attributes on a declaration at the same time.
2488     NewAttr = nullptr;
2489   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2490            (AMK == Sema::AMK_Override ||
2491             AMK == Sema::AMK_ProtocolImplementation))
2492     NewAttr = nullptr;
2493   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2494     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2495                               UA->getGuid());
2496   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2497     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2498
2499   if (NewAttr) {
2500     NewAttr->setInherited(true);
2501     D->addAttr(NewAttr);
2502     if (isa<MSInheritanceAttr>(NewAttr))
2503       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2504     return true;
2505   }
2506
2507   return false;
2508 }
2509
2510 static const NamedDecl *getDefinition(const Decl *D) {
2511   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2512     return TD->getDefinition();
2513   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2514     const VarDecl *Def = VD->getDefinition();
2515     if (Def)
2516       return Def;
2517     return VD->getActingDefinition();
2518   }
2519   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2520     return FD->getDefinition();
2521   return nullptr;
2522 }
2523
2524 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2525   for (const auto *Attribute : D->attrs())
2526     if (Attribute->getKind() == Kind)
2527       return true;
2528   return false;
2529 }
2530
2531 /// checkNewAttributesAfterDef - If we already have a definition, check that
2532 /// there are no new attributes in this declaration.
2533 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2534   if (!New->hasAttrs())
2535     return;
2536
2537   const NamedDecl *Def = getDefinition(Old);
2538   if (!Def || Def == New)
2539     return;
2540
2541   AttrVec &NewAttributes = New->getAttrs();
2542   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2543     const Attr *NewAttribute = NewAttributes[I];
2544
2545     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2546       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2547         Sema::SkipBodyInfo SkipBody;
2548         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2549
2550         // If we're skipping this definition, drop the "alias" attribute.
2551         if (SkipBody.ShouldSkip) {
2552           NewAttributes.erase(NewAttributes.begin() + I);
2553           --E;
2554           continue;
2555         }
2556       } else {
2557         VarDecl *VD = cast<VarDecl>(New);
2558         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2559                                 VarDecl::TentativeDefinition
2560                             ? diag::err_alias_after_tentative
2561                             : diag::err_redefinition;
2562         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2563         if (Diag == diag::err_redefinition)
2564           S.notePreviousDefinition(Def, VD->getLocation());
2565         else
2566           S.Diag(Def->getLocation(), diag::note_previous_definition);
2567         VD->setInvalidDecl();
2568       }
2569       ++I;
2570       continue;
2571     }
2572
2573     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2574       // Tentative definitions are only interesting for the alias check above.
2575       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2576         ++I;
2577         continue;
2578       }
2579     }
2580
2581     if (hasAttribute(Def, NewAttribute->getKind())) {
2582       ++I;
2583       continue; // regular attr merging will take care of validating this.
2584     }
2585
2586     if (isa<C11NoReturnAttr>(NewAttribute)) {
2587       // C's _Noreturn is allowed to be added to a function after it is defined.
2588       ++I;
2589       continue;
2590     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2591       if (AA->isAlignas()) {
2592         // C++11 [dcl.align]p6:
2593         //   if any declaration of an entity has an alignment-specifier,
2594         //   every defining declaration of that entity shall specify an
2595         //   equivalent alignment.
2596         // C11 6.7.5/7:
2597         //   If the definition of an object does not have an alignment
2598         //   specifier, any other declaration of that object shall also
2599         //   have no alignment specifier.
2600         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2601           << AA;
2602         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2603           << AA;
2604         NewAttributes.erase(NewAttributes.begin() + I);
2605         --E;
2606         continue;
2607       }
2608     }
2609
2610     S.Diag(NewAttribute->getLocation(),
2611            diag::warn_attribute_precede_definition);
2612     S.Diag(Def->getLocation(), diag::note_previous_definition);
2613     NewAttributes.erase(NewAttributes.begin() + I);
2614     --E;
2615   }
2616 }
2617
2618 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2619 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2620                                AvailabilityMergeKind AMK) {
2621   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2622     UsedAttr *NewAttr = OldAttr->clone(Context);
2623     NewAttr->setInherited(true);
2624     New->addAttr(NewAttr);
2625   }
2626
2627   if (!Old->hasAttrs() && !New->hasAttrs())
2628     return;
2629
2630   // Attributes declared post-definition are currently ignored.
2631   checkNewAttributesAfterDef(*this, New, Old);
2632
2633   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2634     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2635       if (OldA->getLabel() != NewA->getLabel()) {
2636         // This redeclaration changes __asm__ label.
2637         Diag(New->getLocation(), diag::err_different_asm_label);
2638         Diag(OldA->getLocation(), diag::note_previous_declaration);
2639       }
2640     } else if (Old->isUsed()) {
2641       // This redeclaration adds an __asm__ label to a declaration that has
2642       // already been ODR-used.
2643       Diag(New->getLocation(), diag::err_late_asm_label_name)
2644         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2645     }
2646   }
2647
2648   // Re-declaration cannot add abi_tag's.
2649   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2650     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2651       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2652         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2653                       NewTag) == OldAbiTagAttr->tags_end()) {
2654           Diag(NewAbiTagAttr->getLocation(),
2655                diag::err_new_abi_tag_on_redeclaration)
2656               << NewTag;
2657           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2658         }
2659       }
2660     } else {
2661       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2662       Diag(Old->getLocation(), diag::note_previous_declaration);
2663     }
2664   }
2665
2666   // This redeclaration adds a section attribute.
2667   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2668     if (auto *VD = dyn_cast<VarDecl>(New)) {
2669       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2670         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2671         Diag(Old->getLocation(), diag::note_previous_declaration);
2672       }
2673     }
2674   }
2675
2676   // Redeclaration adds code-seg attribute.
2677   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2678   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2679       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2680     Diag(New->getLocation(), diag::warn_mismatched_section)
2681          << 0 /*codeseg*/;
2682     Diag(Old->getLocation(), diag::note_previous_declaration);
2683   }
2684
2685   if (!Old->hasAttrs())
2686     return;
2687
2688   bool foundAny = New->hasAttrs();
2689
2690   // Ensure that any moving of objects within the allocated map is done before
2691   // we process them.
2692   if (!foundAny) New->setAttrs(AttrVec());
2693
2694   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2695     // Ignore deprecated/unavailable/availability attributes if requested.
2696     AvailabilityMergeKind LocalAMK = AMK_None;
2697     if (isa<DeprecatedAttr>(I) ||
2698         isa<UnavailableAttr>(I) ||
2699         isa<AvailabilityAttr>(I)) {
2700       switch (AMK) {
2701       case AMK_None:
2702         continue;
2703
2704       case AMK_Redeclaration:
2705       case AMK_Override:
2706       case AMK_ProtocolImplementation:
2707         LocalAMK = AMK;
2708         break;
2709       }
2710     }
2711
2712     // Already handled.
2713     if (isa<UsedAttr>(I))
2714       continue;
2715
2716     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2717       foundAny = true;
2718   }
2719
2720   if (mergeAlignedAttrs(*this, New, Old))
2721     foundAny = true;
2722
2723   if (!foundAny) New->dropAttrs();
2724 }
2725
2726 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2727 /// to the new one.
2728 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2729                                      const ParmVarDecl *oldDecl,
2730                                      Sema &S) {
2731   // C++11 [dcl.attr.depend]p2:
2732   //   The first declaration of a function shall specify the
2733   //   carries_dependency attribute for its declarator-id if any declaration
2734   //   of the function specifies the carries_dependency attribute.
2735   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2736   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2737     S.Diag(CDA->getLocation(),
2738            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2739     // Find the first declaration of the parameter.
2740     // FIXME: Should we build redeclaration chains for function parameters?
2741     const FunctionDecl *FirstFD =
2742       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2743     const ParmVarDecl *FirstVD =
2744       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2745     S.Diag(FirstVD->getLocation(),
2746            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2747   }
2748
2749   if (!oldDecl->hasAttrs())
2750     return;
2751
2752   bool foundAny = newDecl->hasAttrs();
2753
2754   // Ensure that any moving of objects within the allocated map is
2755   // done before we process them.
2756   if (!foundAny) newDecl->setAttrs(AttrVec());
2757
2758   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2759     if (!DeclHasAttr(newDecl, I)) {
2760       InheritableAttr *newAttr =
2761         cast<InheritableParamAttr>(I->clone(S.Context));
2762       newAttr->setInherited(true);
2763       newDecl->addAttr(newAttr);
2764       foundAny = true;
2765     }
2766   }
2767
2768   if (!foundAny) newDecl->dropAttrs();
2769 }
2770
2771 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2772                                 const ParmVarDecl *OldParam,
2773                                 Sema &S) {
2774   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2775     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2776       if (*Oldnullability != *Newnullability) {
2777         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2778           << DiagNullabilityKind(
2779                *Newnullability,
2780                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2781                 != 0))
2782           << DiagNullabilityKind(
2783                *Oldnullability,
2784                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2785                 != 0));
2786         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2787       }
2788     } else {
2789       QualType NewT = NewParam->getType();
2790       NewT = S.Context.getAttributedType(
2791                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2792                          NewT, NewT);
2793       NewParam->setType(NewT);
2794     }
2795   }
2796 }
2797
2798 namespace {
2799
2800 /// Used in MergeFunctionDecl to keep track of function parameters in
2801 /// C.
2802 struct GNUCompatibleParamWarning {
2803   ParmVarDecl *OldParm;
2804   ParmVarDecl *NewParm;
2805   QualType PromotedType;
2806 };
2807
2808 } // end anonymous namespace
2809
2810 /// getSpecialMember - get the special member enum for a method.
2811 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2812   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2813     if (Ctor->isDefaultConstructor())
2814       return Sema::CXXDefaultConstructor;
2815
2816     if (Ctor->isCopyConstructor())
2817       return Sema::CXXCopyConstructor;
2818
2819     if (Ctor->isMoveConstructor())
2820       return Sema::CXXMoveConstructor;
2821   } else if (isa<CXXDestructorDecl>(MD)) {
2822     return Sema::CXXDestructor;
2823   } else if (MD->isCopyAssignmentOperator()) {
2824     return Sema::CXXCopyAssignment;
2825   } else if (MD->isMoveAssignmentOperator()) {
2826     return Sema::CXXMoveAssignment;
2827   }
2828
2829   return Sema::CXXInvalid;
2830 }
2831
2832 // Determine whether the previous declaration was a definition, implicit
2833 // declaration, or a declaration.
2834 template <typename T>
2835 static std::pair<diag::kind, SourceLocation>
2836 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2837   diag::kind PrevDiag;
2838   SourceLocation OldLocation = Old->getLocation();
2839   if (Old->isThisDeclarationADefinition())
2840     PrevDiag = diag::note_previous_definition;
2841   else if (Old->isImplicit()) {
2842     PrevDiag = diag::note_previous_implicit_declaration;
2843     if (OldLocation.isInvalid())
2844       OldLocation = New->getLocation();
2845   } else
2846     PrevDiag = diag::note_previous_declaration;
2847   return std::make_pair(PrevDiag, OldLocation);
2848 }
2849
2850 /// canRedefineFunction - checks if a function can be redefined. Currently,
2851 /// only extern inline functions can be redefined, and even then only in
2852 /// GNU89 mode.
2853 static bool canRedefineFunction(const FunctionDecl *FD,
2854                                 const LangOptions& LangOpts) {
2855   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2856           !LangOpts.CPlusPlus &&
2857           FD->isInlineSpecified() &&
2858           FD->getStorageClass() == SC_Extern);
2859 }
2860
2861 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2862   const AttributedType *AT = T->getAs<AttributedType>();
2863   while (AT && !AT->isCallingConv())
2864     AT = AT->getModifiedType()->getAs<AttributedType>();
2865   return AT;
2866 }
2867
2868 template <typename T>
2869 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2870   const DeclContext *DC = Old->getDeclContext();
2871   if (DC->isRecord())
2872     return false;
2873
2874   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2875   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2876     return true;
2877   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2878     return true;
2879   return false;
2880 }
2881
2882 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2883 static bool isExternC(VarTemplateDecl *) { return false; }
2884
2885 /// Check whether a redeclaration of an entity introduced by a
2886 /// using-declaration is valid, given that we know it's not an overload
2887 /// (nor a hidden tag declaration).
2888 template<typename ExpectedDecl>
2889 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2890                                    ExpectedDecl *New) {
2891   // C++11 [basic.scope.declarative]p4:
2892   //   Given a set of declarations in a single declarative region, each of
2893   //   which specifies the same unqualified name,
2894   //   -- they shall all refer to the same entity, or all refer to functions
2895   //      and function templates; or
2896   //   -- exactly one declaration shall declare a class name or enumeration
2897   //      name that is not a typedef name and the other declarations shall all
2898   //      refer to the same variable or enumerator, or all refer to functions
2899   //      and function templates; in this case the class name or enumeration
2900   //      name is hidden (3.3.10).
2901
2902   // C++11 [namespace.udecl]p14:
2903   //   If a function declaration in namespace scope or block scope has the
2904   //   same name and the same parameter-type-list as a function introduced
2905   //   by a using-declaration, and the declarations do not declare the same
2906   //   function, the program is ill-formed.
2907
2908   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2909   if (Old &&
2910       !Old->getDeclContext()->getRedeclContext()->Equals(
2911           New->getDeclContext()->getRedeclContext()) &&
2912       !(isExternC(Old) && isExternC(New)))
2913     Old = nullptr;
2914
2915   if (!Old) {
2916     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2917     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2918     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2919     return true;
2920   }
2921   return false;
2922 }
2923
2924 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2925                                             const FunctionDecl *B) {
2926   assert(A->getNumParams() == B->getNumParams());
2927
2928   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2929     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2930     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2931     if (AttrA == AttrB)
2932       return true;
2933     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2934   };
2935
2936   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2937 }
2938
2939 /// If necessary, adjust the semantic declaration context for a qualified
2940 /// declaration to name the correct inline namespace within the qualifier.
2941 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
2942                                                DeclaratorDecl *OldD) {
2943   // The only case where we need to update the DeclContext is when
2944   // redeclaration lookup for a qualified name finds a declaration
2945   // in an inline namespace within the context named by the qualifier:
2946   //
2947   //   inline namespace N { int f(); }
2948   //   int ::f(); // Sema DC needs adjusting from :: to N::.
2949   //
2950   // For unqualified declarations, the semantic context *can* change
2951   // along the redeclaration chain (for local extern declarations,
2952   // extern "C" declarations, and friend declarations in particular).
2953   if (!NewD->getQualifier())
2954     return;
2955
2956   // NewD is probably already in the right context.
2957   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
2958   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
2959   if (NamedDC->Equals(SemaDC))
2960     return;
2961
2962   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
2963           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
2964          "unexpected context for redeclaration");
2965
2966   auto *LexDC = NewD->getLexicalDeclContext();
2967   auto FixSemaDC = [=](NamedDecl *D) {
2968     if (!D)
2969       return;
2970     D->setDeclContext(SemaDC);
2971     D->setLexicalDeclContext(LexDC);
2972   };
2973
2974   FixSemaDC(NewD);
2975   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
2976     FixSemaDC(FD->getDescribedFunctionTemplate());
2977   else if (auto *VD = dyn_cast<VarDecl>(NewD))
2978     FixSemaDC(VD->getDescribedVarTemplate());
2979 }
2980
2981 /// MergeFunctionDecl - We just parsed a function 'New' from
2982 /// declarator D which has the same name and scope as a previous
2983 /// declaration 'Old'.  Figure out how to resolve this situation,
2984 /// merging decls or emitting diagnostics as appropriate.
2985 ///
2986 /// In C++, New and Old must be declarations that are not
2987 /// overloaded. Use IsOverload to determine whether New and Old are
2988 /// overloaded, and to select the Old declaration that New should be
2989 /// merged with.
2990 ///
2991 /// Returns true if there was an error, false otherwise.
2992 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2993                              Scope *S, bool MergeTypeWithOld) {
2994   // Verify the old decl was also a function.
2995   FunctionDecl *Old = OldD->getAsFunction();
2996   if (!Old) {
2997     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2998       if (New->getFriendObjectKind()) {
2999         Diag(New->getLocation(), diag::err_using_decl_friend);
3000         Diag(Shadow->getTargetDecl()->getLocation(),
3001              diag::note_using_decl_target);
3002         Diag(Shadow->getUsingDecl()->getLocation(),
3003              diag::note_using_decl) << 0;
3004         return true;
3005       }
3006
3007       // Check whether the two declarations might declare the same function.
3008       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3009         return true;
3010       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3011     } else {
3012       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3013         << New->getDeclName();
3014       notePreviousDefinition(OldD, New->getLocation());
3015       return true;
3016     }
3017   }
3018
3019   // If the old declaration is invalid, just give up here.
3020   if (Old->isInvalidDecl())
3021     return true;
3022
3023   // Disallow redeclaration of some builtins.
3024   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3025     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3026     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3027         << Old << Old->getType();
3028     return true;
3029   }
3030
3031   diag::kind PrevDiag;
3032   SourceLocation OldLocation;
3033   std::tie(PrevDiag, OldLocation) =
3034       getNoteDiagForInvalidRedeclaration(Old, New);
3035
3036   // Don't complain about this if we're in GNU89 mode and the old function
3037   // is an extern inline function.
3038   // Don't complain about specializations. They are not supposed to have
3039   // storage classes.
3040   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3041       New->getStorageClass() == SC_Static &&
3042       Old->hasExternalFormalLinkage() &&
3043       !New->getTemplateSpecializationInfo() &&
3044       !canRedefineFunction(Old, getLangOpts())) {
3045     if (getLangOpts().MicrosoftExt) {
3046       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3047       Diag(OldLocation, PrevDiag);
3048     } else {
3049       Diag(New->getLocation(), diag::err_static_non_static) << New;
3050       Diag(OldLocation, PrevDiag);
3051       return true;
3052     }
3053   }
3054
3055   if (New->hasAttr<InternalLinkageAttr>() &&
3056       !Old->hasAttr<InternalLinkageAttr>()) {
3057     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3058         << New->getDeclName();
3059     notePreviousDefinition(Old, New->getLocation());
3060     New->dropAttr<InternalLinkageAttr>();
3061   }
3062
3063   if (CheckRedeclarationModuleOwnership(New, Old))
3064     return true;
3065
3066   if (!getLangOpts().CPlusPlus) {
3067     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3068     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3069       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3070         << New << OldOvl;
3071
3072       // Try our best to find a decl that actually has the overloadable
3073       // attribute for the note. In most cases (e.g. programs with only one
3074       // broken declaration/definition), this won't matter.
3075       //
3076       // FIXME: We could do this if we juggled some extra state in
3077       // OverloadableAttr, rather than just removing it.
3078       const Decl *DiagOld = Old;
3079       if (OldOvl) {
3080         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3081           const auto *A = D->getAttr<OverloadableAttr>();
3082           return A && !A->isImplicit();
3083         });
3084         // If we've implicitly added *all* of the overloadable attrs to this
3085         // chain, emitting a "previous redecl" note is pointless.
3086         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3087       }
3088
3089       if (DiagOld)
3090         Diag(DiagOld->getLocation(),
3091              diag::note_attribute_overloadable_prev_overload)
3092           << OldOvl;
3093
3094       if (OldOvl)
3095         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3096       else
3097         New->dropAttr<OverloadableAttr>();
3098     }
3099   }
3100
3101   // If a function is first declared with a calling convention, but is later
3102   // declared or defined without one, all following decls assume the calling
3103   // convention of the first.
3104   //
3105   // It's OK if a function is first declared without a calling convention,
3106   // but is later declared or defined with the default calling convention.
3107   //
3108   // To test if either decl has an explicit calling convention, we look for
3109   // AttributedType sugar nodes on the type as written.  If they are missing or
3110   // were canonicalized away, we assume the calling convention was implicit.
3111   //
3112   // Note also that we DO NOT return at this point, because we still have
3113   // other tests to run.
3114   QualType OldQType = Context.getCanonicalType(Old->getType());
3115   QualType NewQType = Context.getCanonicalType(New->getType());
3116   const FunctionType *OldType = cast<FunctionType>(OldQType);
3117   const FunctionType *NewType = cast<FunctionType>(NewQType);
3118   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3119   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3120   bool RequiresAdjustment = false;
3121
3122   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3123     FunctionDecl *First = Old->getFirstDecl();
3124     const FunctionType *FT =
3125         First->getType().getCanonicalType()->castAs<FunctionType>();
3126     FunctionType::ExtInfo FI = FT->getExtInfo();
3127     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3128     if (!NewCCExplicit) {
3129       // Inherit the CC from the previous declaration if it was specified
3130       // there but not here.
3131       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3132       RequiresAdjustment = true;
3133     } else {
3134       // Calling conventions aren't compatible, so complain.
3135       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3136       Diag(New->getLocation(), diag::err_cconv_change)
3137         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3138         << !FirstCCExplicit
3139         << (!FirstCCExplicit ? "" :
3140             FunctionType::getNameForCallConv(FI.getCC()));
3141
3142       // Put the note on the first decl, since it is the one that matters.
3143       Diag(First->getLocation(), diag::note_previous_declaration);
3144       return true;
3145     }
3146   }
3147
3148   // FIXME: diagnose the other way around?
3149   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3150     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3151     RequiresAdjustment = true;
3152   }
3153
3154   // Merge regparm attribute.
3155   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3156       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3157     if (NewTypeInfo.getHasRegParm()) {
3158       Diag(New->getLocation(), diag::err_regparm_mismatch)
3159         << NewType->getRegParmType()
3160         << OldType->getRegParmType();
3161       Diag(OldLocation, diag::note_previous_declaration);
3162       return true;
3163     }
3164
3165     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3166     RequiresAdjustment = true;
3167   }
3168
3169   // Merge ns_returns_retained attribute.
3170   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3171     if (NewTypeInfo.getProducesResult()) {
3172       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3173           << "'ns_returns_retained'";
3174       Diag(OldLocation, diag::note_previous_declaration);
3175       return true;
3176     }
3177
3178     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3179     RequiresAdjustment = true;
3180   }
3181
3182   if (OldTypeInfo.getNoCallerSavedRegs() !=
3183       NewTypeInfo.getNoCallerSavedRegs()) {
3184     if (NewTypeInfo.getNoCallerSavedRegs()) {
3185       AnyX86NoCallerSavedRegistersAttr *Attr =
3186         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3187       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3188       Diag(OldLocation, diag::note_previous_declaration);
3189       return true;
3190     }
3191
3192     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3193     RequiresAdjustment = true;
3194   }
3195
3196   if (RequiresAdjustment) {
3197     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3198     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3199     New->setType(QualType(AdjustedType, 0));
3200     NewQType = Context.getCanonicalType(New->getType());
3201     NewType = cast<FunctionType>(NewQType);
3202   }
3203
3204   // If this redeclaration makes the function inline, we may need to add it to
3205   // UndefinedButUsed.
3206   if (!Old->isInlined() && New->isInlined() &&
3207       !New->hasAttr<GNUInlineAttr>() &&
3208       !getLangOpts().GNUInline &&
3209       Old->isUsed(false) &&
3210       !Old->isDefined() && !New->isThisDeclarationADefinition())
3211     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3212                                            SourceLocation()));
3213
3214   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3215   // about it.
3216   if (New->hasAttr<GNUInlineAttr>() &&
3217       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3218     UndefinedButUsed.erase(Old->getCanonicalDecl());
3219   }
3220
3221   // If pass_object_size params don't match up perfectly, this isn't a valid
3222   // redeclaration.
3223   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3224       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3225     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3226         << New->getDeclName();
3227     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3228     return true;
3229   }
3230
3231   if (getLangOpts().CPlusPlus) {
3232     // C++1z [over.load]p2
3233     //   Certain function declarations cannot be overloaded:
3234     //     -- Function declarations that differ only in the return type,
3235     //        the exception specification, or both cannot be overloaded.
3236
3237     // Check the exception specifications match. This may recompute the type of
3238     // both Old and New if it resolved exception specifications, so grab the
3239     // types again after this. Because this updates the type, we do this before
3240     // any of the other checks below, which may update the "de facto" NewQType
3241     // but do not necessarily update the type of New.
3242     if (CheckEquivalentExceptionSpec(Old, New))
3243       return true;
3244     OldQType = Context.getCanonicalType(Old->getType());
3245     NewQType = Context.getCanonicalType(New->getType());
3246
3247     // Go back to the type source info to compare the declared return types,
3248     // per C++1y [dcl.type.auto]p13:
3249     //   Redeclarations or specializations of a function or function template
3250     //   with a declared return type that uses a placeholder type shall also
3251     //   use that placeholder, not a deduced type.
3252     QualType OldDeclaredReturnType =
3253         (Old->getTypeSourceInfo()
3254              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3255              : OldType)->getReturnType();
3256     QualType NewDeclaredReturnType =
3257         (New->getTypeSourceInfo()
3258              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3259              : NewType)->getReturnType();
3260     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3261         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3262           New->isLocalExternDecl())) {
3263       QualType ResQT;
3264       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3265           OldDeclaredReturnType->isObjCObjectPointerType())
3266         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3267       if (ResQT.isNull()) {
3268         if (New->isCXXClassMember() && New->isOutOfLine())
3269           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3270               << New << New->getReturnTypeSourceRange();
3271         else
3272           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3273               << New->getReturnTypeSourceRange();
3274         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3275                                     << Old->getReturnTypeSourceRange();
3276         return true;
3277       }
3278       else
3279         NewQType = ResQT;
3280     }
3281
3282     QualType OldReturnType = OldType->getReturnType();
3283     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3284     if (OldReturnType != NewReturnType) {
3285       // If this function has a deduced return type and has already been
3286       // defined, copy the deduced value from the old declaration.
3287       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3288       if (OldAT && OldAT->isDeduced()) {
3289         New->setType(
3290             SubstAutoType(New->getType(),
3291                           OldAT->isDependentType() ? Context.DependentTy
3292                                                    : OldAT->getDeducedType()));
3293         NewQType = Context.getCanonicalType(
3294             SubstAutoType(NewQType,
3295                           OldAT->isDependentType() ? Context.DependentTy
3296                                                    : OldAT->getDeducedType()));
3297       }
3298     }
3299
3300     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3301     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3302     if (OldMethod && NewMethod) {
3303       // Preserve triviality.
3304       NewMethod->setTrivial(OldMethod->isTrivial());
3305
3306       // MSVC allows explicit template specialization at class scope:
3307       // 2 CXXMethodDecls referring to the same function will be injected.
3308       // We don't want a redeclaration error.
3309       bool IsClassScopeExplicitSpecialization =
3310                               OldMethod->isFunctionTemplateSpecialization() &&
3311                               NewMethod->isFunctionTemplateSpecialization();
3312       bool isFriend = NewMethod->getFriendObjectKind();
3313
3314       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3315           !IsClassScopeExplicitSpecialization) {
3316         //    -- Member function declarations with the same name and the
3317         //       same parameter types cannot be overloaded if any of them
3318         //       is a static member function declaration.
3319         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3320           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3321           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3322           return true;
3323         }
3324
3325         // C++ [class.mem]p1:
3326         //   [...] A member shall not be declared twice in the
3327         //   member-specification, except that a nested class or member
3328         //   class template can be declared and then later defined.
3329         if (!inTemplateInstantiation()) {
3330           unsigned NewDiag;
3331           if (isa<CXXConstructorDecl>(OldMethod))
3332             NewDiag = diag::err_constructor_redeclared;
3333           else if (isa<CXXDestructorDecl>(NewMethod))
3334             NewDiag = diag::err_destructor_redeclared;
3335           else if (isa<CXXConversionDecl>(NewMethod))
3336             NewDiag = diag::err_conv_function_redeclared;
3337           else
3338             NewDiag = diag::err_member_redeclared;
3339
3340           Diag(New->getLocation(), NewDiag);
3341         } else {
3342           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3343             << New << New->getType();
3344         }
3345         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3346         return true;
3347
3348       // Complain if this is an explicit declaration of a special
3349       // member that was initially declared implicitly.
3350       //
3351       // As an exception, it's okay to befriend such methods in order
3352       // to permit the implicit constructor/destructor/operator calls.
3353       } else if (OldMethod->isImplicit()) {
3354         if (isFriend) {
3355           NewMethod->setImplicit();
3356         } else {
3357           Diag(NewMethod->getLocation(),
3358                diag::err_definition_of_implicitly_declared_member)
3359             << New << getSpecialMember(OldMethod);
3360           return true;
3361         }
3362       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3363         Diag(NewMethod->getLocation(),
3364              diag::err_definition_of_explicitly_defaulted_member)
3365           << getSpecialMember(OldMethod);
3366         return true;
3367       }
3368     }
3369
3370     // C++11 [dcl.attr.noreturn]p1:
3371     //   The first declaration of a function shall specify the noreturn
3372     //   attribute if any declaration of that function specifies the noreturn
3373     //   attribute.
3374     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3375     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3376       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3377       Diag(Old->getFirstDecl()->getLocation(),
3378            diag::note_noreturn_missing_first_decl);
3379     }
3380
3381     // C++11 [dcl.attr.depend]p2:
3382     //   The first declaration of a function shall specify the
3383     //   carries_dependency attribute for its declarator-id if any declaration
3384     //   of the function specifies the carries_dependency attribute.
3385     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3386     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3387       Diag(CDA->getLocation(),
3388            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3389       Diag(Old->getFirstDecl()->getLocation(),
3390            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3391     }
3392
3393     // (C++98 8.3.5p3):
3394     //   All declarations for a function shall agree exactly in both the
3395     //   return type and the parameter-type-list.
3396     // We also want to respect all the extended bits except noreturn.
3397
3398     // noreturn should now match unless the old type info didn't have it.
3399     QualType OldQTypeForComparison = OldQType;
3400     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3401       auto *OldType = OldQType->castAs<FunctionProtoType>();
3402       const FunctionType *OldTypeForComparison
3403         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3404       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3405       assert(OldQTypeForComparison.isCanonical());
3406     }
3407
3408     if (haveIncompatibleLanguageLinkages(Old, New)) {
3409       // As a special case, retain the language linkage from previous
3410       // declarations of a friend function as an extension.
3411       //
3412       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3413       // and is useful because there's otherwise no way to specify language
3414       // linkage within class scope.
3415       //
3416       // Check cautiously as the friend object kind isn't yet complete.
3417       if (New->getFriendObjectKind() != Decl::FOK_None) {
3418         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3419         Diag(OldLocation, PrevDiag);
3420       } else {
3421         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3422         Diag(OldLocation, PrevDiag);
3423         return true;
3424       }
3425     }
3426
3427     if (OldQTypeForComparison == NewQType)
3428       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3429
3430     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3431         New->isLocalExternDecl()) {
3432       // It's OK if we couldn't merge types for a local function declaraton
3433       // if either the old or new type is dependent. We'll merge the types
3434       // when we instantiate the function.
3435       return false;
3436     }
3437
3438     // Fall through for conflicting redeclarations and redefinitions.
3439   }
3440
3441   // C: Function types need to be compatible, not identical. This handles
3442   // duplicate function decls like "void f(int); void f(enum X);" properly.
3443   if (!getLangOpts().CPlusPlus &&
3444       Context.typesAreCompatible(OldQType, NewQType)) {
3445     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3446     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3447     const FunctionProtoType *OldProto = nullptr;
3448     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3449         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3450       // The old declaration provided a function prototype, but the
3451       // new declaration does not. Merge in the prototype.
3452       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3453       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3454       NewQType =
3455           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3456                                   OldProto->getExtProtoInfo());
3457       New->setType(NewQType);
3458       New->setHasInheritedPrototype();
3459
3460       // Synthesize parameters with the same types.
3461       SmallVector<ParmVarDecl*, 16> Params;
3462       for (const auto &ParamType : OldProto->param_types()) {
3463         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3464                                                  SourceLocation(), nullptr,
3465                                                  ParamType, /*TInfo=*/nullptr,
3466                                                  SC_None, nullptr);
3467         Param->setScopeInfo(0, Params.size());
3468         Param->setImplicit();
3469         Params.push_back(Param);
3470       }
3471
3472       New->setParams(Params);
3473     }
3474
3475     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3476   }
3477
3478   // GNU C permits a K&R definition to follow a prototype declaration
3479   // if the declared types of the parameters in the K&R definition
3480   // match the types in the prototype declaration, even when the
3481   // promoted types of the parameters from the K&R definition differ
3482   // from the types in the prototype. GCC then keeps the types from
3483   // the prototype.
3484   //
3485   // If a variadic prototype is followed by a non-variadic K&R definition,
3486   // the K&R definition becomes variadic.  This is sort of an edge case, but
3487   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3488   // C99 6.9.1p8.
3489   if (!getLangOpts().CPlusPlus &&
3490       Old->hasPrototype() && !New->hasPrototype() &&
3491       New->getType()->getAs<FunctionProtoType>() &&
3492       Old->getNumParams() == New->getNumParams()) {
3493     SmallVector<QualType, 16> ArgTypes;
3494     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3495     const FunctionProtoType *OldProto
3496       = Old->getType()->getAs<FunctionProtoType>();
3497     const FunctionProtoType *NewProto
3498       = New->getType()->getAs<FunctionProtoType>();
3499
3500     // Determine whether this is the GNU C extension.
3501     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3502                                                NewProto->getReturnType());
3503     bool LooseCompatible = !MergedReturn.isNull();
3504     for (unsigned Idx = 0, End = Old->getNumParams();
3505          LooseCompatible && Idx != End; ++Idx) {
3506       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3507       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3508       if (Context.typesAreCompatible(OldParm->getType(),
3509                                      NewProto->getParamType(Idx))) {
3510         ArgTypes.push_back(NewParm->getType());
3511       } else if (Context.typesAreCompatible(OldParm->getType(),
3512                                             NewParm->getType(),
3513                                             /*CompareUnqualified=*/true)) {
3514         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3515                                            NewProto->getParamType(Idx) };
3516         Warnings.push_back(Warn);
3517         ArgTypes.push_back(NewParm->getType());
3518       } else
3519         LooseCompatible = false;
3520     }
3521
3522     if (LooseCompatible) {
3523       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3524         Diag(Warnings[Warn].NewParm->getLocation(),
3525              diag::ext_param_promoted_not_compatible_with_prototype)
3526           << Warnings[Warn].PromotedType
3527           << Warnings[Warn].OldParm->getType();
3528         if (Warnings[Warn].OldParm->getLocation().isValid())
3529           Diag(Warnings[Warn].OldParm->getLocation(),
3530                diag::note_previous_declaration);
3531       }
3532
3533       if (MergeTypeWithOld)
3534         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3535                                              OldProto->getExtProtoInfo()));
3536       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3537     }
3538
3539     // Fall through to diagnose conflicting types.
3540   }
3541
3542   // A function that has already been declared has been redeclared or
3543   // defined with a different type; show an appropriate diagnostic.
3544
3545   // If the previous declaration was an implicitly-generated builtin
3546   // declaration, then at the very least we should use a specialized note.
3547   unsigned BuiltinID;
3548   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3549     // If it's actually a library-defined builtin function like 'malloc'
3550     // or 'printf', just warn about the incompatible redeclaration.
3551     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3552       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3553       Diag(OldLocation, diag::note_previous_builtin_declaration)
3554         << Old << Old->getType();
3555
3556       // If this is a global redeclaration, just forget hereafter
3557       // about the "builtin-ness" of the function.
3558       //
3559       // Doing this for local extern declarations is problematic.  If
3560       // the builtin declaration remains visible, a second invalid
3561       // local declaration will produce a hard error; if it doesn't
3562       // remain visible, a single bogus local redeclaration (which is
3563       // actually only a warning) could break all the downstream code.
3564       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3565         New->getIdentifier()->revertBuiltin();
3566
3567       return false;
3568     }
3569
3570     PrevDiag = diag::note_previous_builtin_declaration;
3571   }
3572
3573   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3574   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3575   return true;
3576 }
3577
3578 /// Completes the merge of two function declarations that are
3579 /// known to be compatible.
3580 ///
3581 /// This routine handles the merging of attributes and other
3582 /// properties of function declarations from the old declaration to
3583 /// the new declaration, once we know that New is in fact a
3584 /// redeclaration of Old.
3585 ///
3586 /// \returns false
3587 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3588                                         Scope *S, bool MergeTypeWithOld) {
3589   // Merge the attributes
3590   mergeDeclAttributes(New, Old);
3591
3592   // Merge "pure" flag.
3593   if (Old->isPure())
3594     New->setPure();
3595
3596   // Merge "used" flag.
3597   if (Old->getMostRecentDecl()->isUsed(false))
3598     New->setIsUsed();
3599
3600   // Merge attributes from the parameters.  These can mismatch with K&R
3601   // declarations.
3602   if (New->getNumParams() == Old->getNumParams())
3603       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3604         ParmVarDecl *NewParam = New->getParamDecl(i);
3605         ParmVarDecl *OldParam = Old->getParamDecl(i);
3606         mergeParamDeclAttributes(NewParam, OldParam, *this);
3607         mergeParamDeclTypes(NewParam, OldParam, *this);
3608       }
3609
3610   if (getLangOpts().CPlusPlus)
3611     return MergeCXXFunctionDecl(New, Old, S);
3612
3613   // Merge the function types so the we get the composite types for the return
3614   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3615   // was visible.
3616   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3617   if (!Merged.isNull() && MergeTypeWithOld)
3618     New->setType(Merged);
3619
3620   return false;
3621 }
3622
3623 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3624                                 ObjCMethodDecl *oldMethod) {
3625   // Merge the attributes, including deprecated/unavailable
3626   AvailabilityMergeKind MergeKind =
3627     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3628       ? AMK_ProtocolImplementation
3629       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3630                                                        : AMK_Override;
3631
3632   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3633
3634   // Merge attributes from the parameters.
3635   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3636                                        oe = oldMethod->param_end();
3637   for (ObjCMethodDecl::param_iterator
3638          ni = newMethod->param_begin(), ne = newMethod->param_end();
3639        ni != ne && oi != oe; ++ni, ++oi)
3640     mergeParamDeclAttributes(*ni, *oi, *this);
3641
3642   CheckObjCMethodOverride(newMethod, oldMethod);
3643 }
3644
3645 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3646   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3647
3648   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3649          ? diag::err_redefinition_different_type
3650          : diag::err_redeclaration_different_type)
3651     << New->getDeclName() << New->getType() << Old->getType();
3652
3653   diag::kind PrevDiag;
3654   SourceLocation OldLocation;
3655   std::tie(PrevDiag, OldLocation)
3656     = getNoteDiagForInvalidRedeclaration(Old, New);
3657   S.Diag(OldLocation, PrevDiag);
3658   New->setInvalidDecl();
3659 }
3660
3661 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3662 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3663 /// emitting diagnostics as appropriate.
3664 ///
3665 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3666 /// to here in AddInitializerToDecl. We can't check them before the initializer
3667 /// is attached.
3668 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3669                              bool MergeTypeWithOld) {
3670   if (New->isInvalidDecl() || Old->isInvalidDecl())
3671     return;
3672
3673   QualType MergedT;
3674   if (getLangOpts().CPlusPlus) {
3675     if (New->getType()->isUndeducedType()) {
3676       // We don't know what the new type is until the initializer is attached.
3677       return;
3678     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3679       // These could still be something that needs exception specs checked.
3680       return MergeVarDeclExceptionSpecs(New, Old);
3681     }
3682     // C++ [basic.link]p10:
3683     //   [...] the types specified by all declarations referring to a given
3684     //   object or function shall be identical, except that declarations for an
3685     //   array object can specify array types that differ by the presence or
3686     //   absence of a major array bound (8.3.4).
3687     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3688       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3689       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3690
3691       // We are merging a variable declaration New into Old. If it has an array
3692       // bound, and that bound differs from Old's bound, we should diagnose the
3693       // mismatch.
3694       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3695         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3696              PrevVD = PrevVD->getPreviousDecl()) {
3697           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3698           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3699             continue;
3700
3701           if (!Context.hasSameType(NewArray, PrevVDTy))
3702             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3703         }
3704       }
3705
3706       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3707         if (Context.hasSameType(OldArray->getElementType(),
3708                                 NewArray->getElementType()))
3709           MergedT = New->getType();
3710       }
3711       // FIXME: Check visibility. New is hidden but has a complete type. If New
3712       // has no array bound, it should not inherit one from Old, if Old is not
3713       // visible.
3714       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3715         if (Context.hasSameType(OldArray->getElementType(),
3716                                 NewArray->getElementType()))
3717           MergedT = Old->getType();
3718       }
3719     }
3720     else if (New->getType()->isObjCObjectPointerType() &&
3721                Old->getType()->isObjCObjectPointerType()) {
3722       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3723                                               Old->getType());
3724     }
3725   } else {
3726     // C 6.2.7p2:
3727     //   All declarations that refer to the same object or function shall have
3728     //   compatible type.
3729     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3730   }
3731   if (MergedT.isNull()) {
3732     // It's OK if we couldn't merge types if either type is dependent, for a
3733     // block-scope variable. In other cases (static data members of class
3734     // templates, variable templates, ...), we require the types to be
3735     // equivalent.
3736     // FIXME: The C++ standard doesn't say anything about this.
3737     if ((New->getType()->isDependentType() ||
3738          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3739       // If the old type was dependent, we can't merge with it, so the new type
3740       // becomes dependent for now. We'll reproduce the original type when we
3741       // instantiate the TypeSourceInfo for the variable.
3742       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3743         New->setType(Context.DependentTy);
3744       return;
3745     }
3746     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3747   }
3748
3749   // Don't actually update the type on the new declaration if the old
3750   // declaration was an extern declaration in a different scope.
3751   if (MergeTypeWithOld)
3752     New->setType(MergedT);
3753 }
3754
3755 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3756                                   LookupResult &Previous) {
3757   // C11 6.2.7p4:
3758   //   For an identifier with internal or external linkage declared
3759   //   in a scope in which a prior declaration of that identifier is
3760   //   visible, if the prior declaration specifies internal or
3761   //   external linkage, the type of the identifier at the later
3762   //   declaration becomes the composite type.
3763   //
3764   // If the variable isn't visible, we do not merge with its type.
3765   if (Previous.isShadowed())
3766     return false;
3767
3768   if (S.getLangOpts().CPlusPlus) {
3769     // C++11 [dcl.array]p3:
3770     //   If there is a preceding declaration of the entity in the same
3771     //   scope in which the bound was specified, an omitted array bound
3772     //   is taken to be the same as in that earlier declaration.
3773     return NewVD->isPreviousDeclInSameBlockScope() ||
3774            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3775             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3776   } else {
3777     // If the old declaration was function-local, don't merge with its
3778     // type unless we're in the same function.
3779     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3780            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3781   }
3782 }
3783
3784 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3785 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3786 /// situation, merging decls or emitting diagnostics as appropriate.
3787 ///
3788 /// Tentative definition rules (C99 6.9.2p2) are checked by
3789 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3790 /// definitions here, since the initializer hasn't been attached.
3791 ///
3792 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3793   // If the new decl is already invalid, don't do any other checking.
3794   if (New->isInvalidDecl())
3795     return;
3796
3797   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3798     return;
3799
3800   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3801
3802   // Verify the old decl was also a variable or variable template.
3803   VarDecl *Old = nullptr;
3804   VarTemplateDecl *OldTemplate = nullptr;
3805   if (Previous.isSingleResult()) {
3806     if (NewTemplate) {
3807       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3808       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3809
3810       if (auto *Shadow =
3811               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3812         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3813           return New->setInvalidDecl();
3814     } else {
3815       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3816
3817       if (auto *Shadow =
3818               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3819         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3820           return New->setInvalidDecl();
3821     }
3822   }
3823   if (!Old) {
3824     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3825         << New->getDeclName();
3826     notePreviousDefinition(Previous.getRepresentativeDecl(),
3827                            New->getLocation());
3828     return New->setInvalidDecl();
3829   }
3830
3831   // Ensure the template parameters are compatible.
3832   if (NewTemplate &&
3833       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3834                                       OldTemplate->getTemplateParameters(),
3835                                       /*Complain=*/true, TPL_TemplateMatch))
3836     return New->setInvalidDecl();
3837
3838   // C++ [class.mem]p1:
3839   //   A member shall not be declared twice in the member-specification [...]
3840   //
3841   // Here, we need only consider static data members.
3842   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3843     Diag(New->getLocation(), diag::err_duplicate_member)
3844       << New->getIdentifier();
3845     Diag(Old->getLocation(), diag::note_previous_declaration);
3846     New->setInvalidDecl();
3847   }
3848
3849   mergeDeclAttributes(New, Old);
3850   // Warn if an already-declared variable is made a weak_import in a subsequent
3851   // declaration
3852   if (New->hasAttr<WeakImportAttr>() &&
3853       Old->getStorageClass() == SC_None &&
3854       !Old->hasAttr<WeakImportAttr>()) {
3855     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3856     notePreviousDefinition(Old, New->getLocation());
3857     // Remove weak_import attribute on new declaration.
3858     New->dropAttr<WeakImportAttr>();
3859   }
3860
3861   if (New->hasAttr<InternalLinkageAttr>() &&
3862       !Old->hasAttr<InternalLinkageAttr>()) {
3863     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3864         << New->getDeclName();
3865     notePreviousDefinition(Old, New->getLocation());
3866     New->dropAttr<InternalLinkageAttr>();
3867   }
3868
3869   // Merge the types.
3870   VarDecl *MostRecent = Old->getMostRecentDecl();
3871   if (MostRecent != Old) {
3872     MergeVarDeclTypes(New, MostRecent,
3873                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3874     if (New->isInvalidDecl())
3875       return;
3876   }
3877
3878   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3879   if (New->isInvalidDecl())
3880     return;
3881
3882   diag::kind PrevDiag;
3883   SourceLocation OldLocation;
3884   std::tie(PrevDiag, OldLocation) =
3885       getNoteDiagForInvalidRedeclaration(Old, New);
3886
3887   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3888   if (New->getStorageClass() == SC_Static &&
3889       !New->isStaticDataMember() &&
3890       Old->hasExternalFormalLinkage()) {
3891     if (getLangOpts().MicrosoftExt) {
3892       Diag(New->getLocation(), diag::ext_static_non_static)
3893           << New->getDeclName();
3894       Diag(OldLocation, PrevDiag);
3895     } else {
3896       Diag(New->getLocation(), diag::err_static_non_static)
3897           << New->getDeclName();
3898       Diag(OldLocation, PrevDiag);
3899       return New->setInvalidDecl();
3900     }
3901   }
3902   // C99 6.2.2p4:
3903   //   For an identifier declared with the storage-class specifier
3904   //   extern in a scope in which a prior declaration of that
3905   //   identifier is visible,23) if the prior declaration specifies
3906   //   internal or external linkage, the linkage of the identifier at
3907   //   the later declaration is the same as the linkage specified at
3908   //   the prior declaration. If no prior declaration is visible, or
3909   //   if the prior declaration specifies no linkage, then the
3910   //   identifier has external linkage.
3911   if (New->hasExternalStorage() && Old->hasLinkage())
3912     /* Okay */;
3913   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3914            !New->isStaticDataMember() &&
3915            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3916     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3917     Diag(OldLocation, PrevDiag);
3918     return New->setInvalidDecl();
3919   }
3920
3921   // Check if extern is followed by non-extern and vice-versa.
3922   if (New->hasExternalStorage() &&
3923       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3924     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3925     Diag(OldLocation, PrevDiag);
3926     return New->setInvalidDecl();
3927   }
3928   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3929       !New->hasExternalStorage()) {
3930     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3931     Diag(OldLocation, PrevDiag);
3932     return New->setInvalidDecl();
3933   }
3934
3935   if (CheckRedeclarationModuleOwnership(New, Old))
3936     return;
3937
3938   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3939
3940   // FIXME: The test for external storage here seems wrong? We still
3941   // need to check for mismatches.
3942   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3943       // Don't complain about out-of-line definitions of static members.
3944       !(Old->getLexicalDeclContext()->isRecord() &&
3945         !New->getLexicalDeclContext()->isRecord())) {
3946     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3947     Diag(OldLocation, PrevDiag);
3948     return New->setInvalidDecl();
3949   }
3950
3951   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3952     if (VarDecl *Def = Old->getDefinition()) {
3953       // C++1z [dcl.fcn.spec]p4:
3954       //   If the definition of a variable appears in a translation unit before
3955       //   its first declaration as inline, the program is ill-formed.
3956       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3957       Diag(Def->getLocation(), diag::note_previous_definition);
3958     }
3959   }
3960
3961   // If this redeclaration makes the variable inline, we may need to add it to
3962   // UndefinedButUsed.
3963   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3964       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3965     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3966                                            SourceLocation()));
3967
3968   if (New->getTLSKind() != Old->getTLSKind()) {
3969     if (!Old->getTLSKind()) {
3970       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3971       Diag(OldLocation, PrevDiag);
3972     } else if (!New->getTLSKind()) {
3973       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3974       Diag(OldLocation, PrevDiag);
3975     } else {
3976       // Do not allow redeclaration to change the variable between requiring
3977       // static and dynamic initialization.
3978       // FIXME: GCC allows this, but uses the TLS keyword on the first
3979       // declaration to determine the kind. Do we need to be compatible here?
3980       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3981         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3982       Diag(OldLocation, PrevDiag);
3983     }
3984   }
3985
3986   // C++ doesn't have tentative definitions, so go right ahead and check here.
3987   if (getLangOpts().CPlusPlus &&
3988       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3989     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3990         Old->getCanonicalDecl()->isConstexpr()) {
3991       // This definition won't be a definition any more once it's been merged.
3992       Diag(New->getLocation(),
3993            diag::warn_deprecated_redundant_constexpr_static_def);
3994     } else if (VarDecl *Def = Old->getDefinition()) {
3995       if (checkVarDeclRedefinition(Def, New))
3996         return;
3997     }
3998   }
3999
4000   if (haveIncompatibleLanguageLinkages(Old, New)) {
4001     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4002     Diag(OldLocation, PrevDiag);
4003     New->setInvalidDecl();
4004     return;
4005   }
4006
4007   // Merge "used" flag.
4008   if (Old->getMostRecentDecl()->isUsed(false))
4009     New->setIsUsed();
4010
4011   // Keep a chain of previous declarations.
4012   New->setPreviousDecl(Old);
4013   if (NewTemplate)
4014     NewTemplate->setPreviousDecl(OldTemplate);
4015   adjustDeclContextForDeclaratorDecl(New, Old);
4016
4017   // Inherit access appropriately.
4018   New->setAccess(Old->getAccess());
4019   if (NewTemplate)
4020     NewTemplate->setAccess(New->getAccess());
4021
4022   if (Old->isInline())
4023     New->setImplicitlyInline();
4024 }
4025
4026 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4027   SourceManager &SrcMgr = getSourceManager();
4028   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4029   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4030   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4031   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4032   auto &HSI = PP.getHeaderSearchInfo();
4033   StringRef HdrFilename =
4034       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4035
4036   auto noteFromModuleOrInclude = [&](Module *Mod,
4037                                      SourceLocation IncLoc) -> bool {
4038     // Redefinition errors with modules are common with non modular mapped
4039     // headers, example: a non-modular header H in module A that also gets
4040     // included directly in a TU. Pointing twice to the same header/definition
4041     // is confusing, try to get better diagnostics when modules is on.
4042     if (IncLoc.isValid()) {
4043       if (Mod) {
4044         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4045             << HdrFilename.str() << Mod->getFullModuleName();
4046         if (!Mod->DefinitionLoc.isInvalid())
4047           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4048               << Mod->getFullModuleName();
4049       } else {
4050         Diag(IncLoc, diag::note_redefinition_include_same_file)
4051             << HdrFilename.str();
4052       }
4053       return true;
4054     }
4055
4056     return false;
4057   };
4058
4059   // Is it the same file and same offset? Provide more information on why
4060   // this leads to a redefinition error.
4061   bool EmittedDiag = false;
4062   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4063     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4064     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4065     EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4066     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4067
4068     // If the header has no guards, emit a note suggesting one.
4069     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4070       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4071
4072     if (EmittedDiag)
4073       return;
4074   }
4075
4076   // Redefinition coming from different files or couldn't do better above.
4077   if (Old->getLocation().isValid())
4078     Diag(Old->getLocation(), diag::note_previous_definition);
4079 }
4080
4081 /// We've just determined that \p Old and \p New both appear to be definitions
4082 /// of the same variable. Either diagnose or fix the problem.
4083 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4084   if (!hasVisibleDefinition(Old) &&
4085       (New->getFormalLinkage() == InternalLinkage ||
4086        New->isInline() ||
4087        New->getDescribedVarTemplate() ||
4088        New->getNumTemplateParameterLists() ||
4089        New->getDeclContext()->isDependentContext())) {
4090     // The previous definition is hidden, and multiple definitions are
4091     // permitted (in separate TUs). Demote this to a declaration.
4092     New->demoteThisDefinitionToDeclaration();
4093
4094     // Make the canonical definition visible.
4095     if (auto *OldTD = Old->getDescribedVarTemplate())
4096       makeMergedDefinitionVisible(OldTD);
4097     makeMergedDefinitionVisible(Old);
4098     return false;
4099   } else {
4100     Diag(New->getLocation(), diag::err_redefinition) << New;
4101     notePreviousDefinition(Old, New->getLocation());
4102     New->setInvalidDecl();
4103     return true;
4104   }
4105 }
4106
4107 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4108 /// no declarator (e.g. "struct foo;") is parsed.
4109 Decl *
4110 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4111                                  RecordDecl *&AnonRecord) {
4112   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4113                                     AnonRecord);
4114 }
4115
4116 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4117 // disambiguate entities defined in different scopes.
4118 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4119 // compatibility.
4120 // We will pick our mangling number depending on which version of MSVC is being
4121 // targeted.
4122 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4123   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4124              ? S->getMSCurManglingNumber()
4125              : S->getMSLastManglingNumber();
4126 }
4127
4128 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4129   if (!Context.getLangOpts().CPlusPlus)
4130     return;
4131
4132   if (isa<CXXRecordDecl>(Tag->getParent())) {
4133     // If this tag is the direct child of a class, number it if
4134     // it is anonymous.
4135     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4136       return;
4137     MangleNumberingContext &MCtx =
4138         Context.getManglingNumberContext(Tag->getParent());
4139     Context.setManglingNumber(
4140         Tag, MCtx.getManglingNumber(
4141                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4142     return;
4143   }
4144
4145   // If this tag isn't a direct child of a class, number it if it is local.
4146   Decl *ManglingContextDecl;
4147   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4148           Tag->getDeclContext(), ManglingContextDecl)) {
4149     Context.setManglingNumber(
4150         Tag, MCtx->getManglingNumber(
4151                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4152   }
4153 }
4154
4155 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4156                                         TypedefNameDecl *NewTD) {
4157   if (TagFromDeclSpec->isInvalidDecl())
4158     return;
4159
4160   // Do nothing if the tag already has a name for linkage purposes.
4161   if (TagFromDeclSpec->hasNameForLinkage())
4162     return;
4163
4164   // A well-formed anonymous tag must always be a TUK_Definition.
4165   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4166
4167   // The type must match the tag exactly;  no qualifiers allowed.
4168   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4169                            Context.getTagDeclType(TagFromDeclSpec))) {
4170     if (getLangOpts().CPlusPlus)
4171       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4172     return;
4173   }
4174
4175   // If we've already computed linkage for the anonymous tag, then
4176   // adding a typedef name for the anonymous decl can change that
4177   // linkage, which might be a serious problem.  Diagnose this as
4178   // unsupported and ignore the typedef name.  TODO: we should
4179   // pursue this as a language defect and establish a formal rule
4180   // for how to handle it.
4181   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4182     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4183
4184     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4185     tagLoc = getLocForEndOfToken(tagLoc);
4186
4187     llvm::SmallString<40> textToInsert;
4188     textToInsert += ' ';
4189     textToInsert += NewTD->getIdentifier()->getName();
4190     Diag(tagLoc, diag::note_typedef_changes_linkage)
4191         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4192     return;
4193   }
4194
4195   // Otherwise, set this is the anon-decl typedef for the tag.
4196   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4197 }
4198
4199 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4200   switch (T) {
4201   case DeclSpec::TST_class:
4202     return 0;
4203   case DeclSpec::TST_struct:
4204     return 1;
4205   case DeclSpec::TST_interface:
4206     return 2;
4207   case DeclSpec::TST_union:
4208     return 3;
4209   case DeclSpec::TST_enum:
4210     return 4;
4211   default:
4212     llvm_unreachable("unexpected type specifier");
4213   }
4214 }
4215
4216 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4217 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4218 /// parameters to cope with template friend declarations.
4219 Decl *
4220 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4221                                  MultiTemplateParamsArg TemplateParams,
4222                                  bool IsExplicitInstantiation,
4223                                  RecordDecl *&AnonRecord) {
4224   Decl *TagD = nullptr;
4225   TagDecl *Tag = nullptr;
4226   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4227       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4228       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4229       DS.getTypeSpecType() == DeclSpec::TST_union ||
4230       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4231     TagD = DS.getRepAsDecl();
4232
4233     if (!TagD) // We probably had an error
4234       return nullptr;
4235
4236     // Note that the above type specs guarantee that the
4237     // type rep is a Decl, whereas in many of the others
4238     // it's a Type.
4239     if (isa<TagDecl>(TagD))
4240       Tag = cast<TagDecl>(TagD);
4241     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4242       Tag = CTD->getTemplatedDecl();
4243   }
4244
4245   if (Tag) {
4246     handleTagNumbering(Tag, S);
4247     Tag->setFreeStanding();
4248     if (Tag->isInvalidDecl())
4249       return Tag;
4250   }
4251
4252   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4253     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4254     // or incomplete types shall not be restrict-qualified."
4255     if (TypeQuals & DeclSpec::TQ_restrict)
4256       Diag(DS.getRestrictSpecLoc(),
4257            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4258            << DS.getSourceRange();
4259   }
4260
4261   if (DS.isInlineSpecified())
4262     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4263         << getLangOpts().CPlusPlus17;
4264
4265   if (DS.isConstexprSpecified()) {
4266     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4267     // and definitions of functions and variables.
4268     if (Tag)
4269       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4270           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4271     else
4272       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4273     // Don't emit warnings after this error.
4274     return TagD;
4275   }
4276
4277   DiagnoseFunctionSpecifiers(DS);
4278
4279   if (DS.isFriendSpecified()) {
4280     // If we're dealing with a decl but not a TagDecl, assume that
4281     // whatever routines created it handled the friendship aspect.
4282     if (TagD && !Tag)
4283       return nullptr;
4284     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4285   }
4286
4287   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4288   bool IsExplicitSpecialization =
4289     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4290   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4291       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4292       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4293     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4294     // nested-name-specifier unless it is an explicit instantiation
4295     // or an explicit specialization.
4296     //
4297     // FIXME: We allow class template partial specializations here too, per the
4298     // obvious intent of DR1819.
4299     //
4300     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4301     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4302         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4303     return nullptr;
4304   }
4305
4306   // Track whether this decl-specifier declares anything.
4307   bool DeclaresAnything = true;
4308
4309   // Handle anonymous struct definitions.
4310   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4311     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4312         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4313       if (getLangOpts().CPlusPlus ||
4314           Record->getDeclContext()->isRecord()) {
4315         // If CurContext is a DeclContext that can contain statements,
4316         // RecursiveASTVisitor won't visit the decls that
4317         // BuildAnonymousStructOrUnion() will put into CurContext.
4318         // Also store them here so that they can be part of the
4319         // DeclStmt that gets created in this case.
4320         // FIXME: Also return the IndirectFieldDecls created by
4321         // BuildAnonymousStructOr union, for the same reason?
4322         if (CurContext->isFunctionOrMethod())
4323           AnonRecord = Record;
4324         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4325                                            Context.getPrintingPolicy());
4326       }
4327
4328       DeclaresAnything = false;
4329     }
4330   }
4331
4332   // C11 6.7.2.1p2:
4333   //   A struct-declaration that does not declare an anonymous structure or
4334   //   anonymous union shall contain a struct-declarator-list.
4335   //
4336   // This rule also existed in C89 and C99; the grammar for struct-declaration
4337   // did not permit a struct-declaration without a struct-declarator-list.
4338   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4339       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4340     // Check for Microsoft C extension: anonymous struct/union member.
4341     // Handle 2 kinds of anonymous struct/union:
4342     //   struct STRUCT;
4343     //   union UNION;
4344     // and
4345     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4346     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4347     if ((Tag && Tag->getDeclName()) ||
4348         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4349       RecordDecl *Record = nullptr;
4350       if (Tag)
4351         Record = dyn_cast<RecordDecl>(Tag);
4352       else if (const RecordType *RT =
4353                    DS.getRepAsType().get()->getAsStructureType())
4354         Record = RT->getDecl();
4355       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4356         Record = UT->getDecl();
4357
4358       if (Record && getLangOpts().MicrosoftExt) {
4359         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4360           << Record->isUnion() << DS.getSourceRange();
4361         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4362       }
4363
4364       DeclaresAnything = false;
4365     }
4366   }
4367
4368   // Skip all the checks below if we have a type error.
4369   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4370       (TagD && TagD->isInvalidDecl()))
4371     return TagD;
4372
4373   if (getLangOpts().CPlusPlus &&
4374       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4375     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4376       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4377           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4378         DeclaresAnything = false;
4379
4380   if (!DS.isMissingDeclaratorOk()) {
4381     // Customize diagnostic for a typedef missing a name.
4382     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4383       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4384         << DS.getSourceRange();
4385     else
4386       DeclaresAnything = false;
4387   }
4388
4389   if (DS.isModulePrivateSpecified() &&
4390       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4391     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4392       << Tag->getTagKind()
4393       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4394
4395   ActOnDocumentableDecl(TagD);
4396
4397   // C 6.7/2:
4398   //   A declaration [...] shall declare at least a declarator [...], a tag,
4399   //   or the members of an enumeration.
4400   // C++ [dcl.dcl]p3:
4401   //   [If there are no declarators], and except for the declaration of an
4402   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4403   //   names into the program, or shall redeclare a name introduced by a
4404   //   previous declaration.
4405   if (!DeclaresAnything) {
4406     // In C, we allow this as a (popular) extension / bug. Don't bother
4407     // producing further diagnostics for redundant qualifiers after this.
4408     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4409     return TagD;
4410   }
4411
4412   // C++ [dcl.stc]p1:
4413   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4414   //   init-declarator-list of the declaration shall not be empty.
4415   // C++ [dcl.fct.spec]p1:
4416   //   If a cv-qualifier appears in a decl-specifier-seq, the
4417   //   init-declarator-list of the declaration shall not be empty.
4418   //
4419   // Spurious qualifiers here appear to be valid in C.
4420   unsigned DiagID = diag::warn_standalone_specifier;
4421   if (getLangOpts().CPlusPlus)
4422     DiagID = diag::ext_standalone_specifier;
4423
4424   // Note that a linkage-specification sets a storage class, but
4425   // 'extern "C" struct foo;' is actually valid and not theoretically
4426   // useless.
4427   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4428     if (SCS == DeclSpec::SCS_mutable)
4429       // Since mutable is not a viable storage class specifier in C, there is
4430       // no reason to treat it as an extension. Instead, diagnose as an error.
4431       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4432     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4433       Diag(DS.getStorageClassSpecLoc(), DiagID)
4434         << DeclSpec::getSpecifierName(SCS);
4435   }
4436
4437   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4438     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4439       << DeclSpec::getSpecifierName(TSCS);
4440   if (DS.getTypeQualifiers()) {
4441     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4442       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4443     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4444       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4445     // Restrict is covered above.
4446     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4447       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4448     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4449       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4450   }
4451
4452   // Warn about ignored type attributes, for example:
4453   // __attribute__((aligned)) struct A;
4454   // Attributes should be placed after tag to apply to type declaration.
4455   if (!DS.getAttributes().empty()) {
4456     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4457     if (TypeSpecType == DeclSpec::TST_class ||
4458         TypeSpecType == DeclSpec::TST_struct ||
4459         TypeSpecType == DeclSpec::TST_interface ||
4460         TypeSpecType == DeclSpec::TST_union ||
4461         TypeSpecType == DeclSpec::TST_enum) {
4462       for (const ParsedAttr &AL : DS.getAttributes())
4463         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4464             << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4465     }
4466   }
4467
4468   return TagD;
4469 }
4470
4471 /// We are trying to inject an anonymous member into the given scope;
4472 /// check if there's an existing declaration that can't be overloaded.
4473 ///
4474 /// \return true if this is a forbidden redeclaration
4475 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4476                                          Scope *S,
4477                                          DeclContext *Owner,
4478                                          DeclarationName Name,
4479                                          SourceLocation NameLoc,
4480                                          bool IsUnion) {
4481   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4482                  Sema::ForVisibleRedeclaration);
4483   if (!SemaRef.LookupName(R, S)) return false;
4484
4485   // Pick a representative declaration.
4486   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4487   assert(PrevDecl && "Expected a non-null Decl");
4488
4489   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4490     return false;
4491
4492   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4493     << IsUnion << Name;
4494   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4495
4496   return true;
4497 }
4498
4499 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4500 /// anonymous struct or union AnonRecord into the owning context Owner
4501 /// and scope S. This routine will be invoked just after we realize
4502 /// that an unnamed union or struct is actually an anonymous union or
4503 /// struct, e.g.,
4504 ///
4505 /// @code
4506 /// union {
4507 ///   int i;
4508 ///   float f;
4509 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4510 ///    // f into the surrounding scope.x
4511 /// @endcode
4512 ///
4513 /// This routine is recursive, injecting the names of nested anonymous
4514 /// structs/unions into the owning context and scope as well.
4515 static bool
4516 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4517                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4518                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4519   bool Invalid = false;
4520
4521   // Look every FieldDecl and IndirectFieldDecl with a name.
4522   for (auto *D : AnonRecord->decls()) {
4523     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4524         cast<NamedDecl>(D)->getDeclName()) {
4525       ValueDecl *VD = cast<ValueDecl>(D);
4526       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4527                                        VD->getLocation(),
4528                                        AnonRecord->isUnion())) {
4529         // C++ [class.union]p2:
4530         //   The names of the members of an anonymous union shall be
4531         //   distinct from the names of any other entity in the
4532         //   scope in which the anonymous union is declared.
4533         Invalid = true;
4534       } else {
4535         // C++ [class.union]p2:
4536         //   For the purpose of name lookup, after the anonymous union
4537         //   definition, the members of the anonymous union are
4538         //   considered to have been defined in the scope in which the
4539         //   anonymous union is declared.
4540         unsigned OldChainingSize = Chaining.size();
4541         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4542           Chaining.append(IF->chain_begin(), IF->chain_end());
4543         else
4544           Chaining.push_back(VD);
4545
4546         assert(Chaining.size() >= 2);
4547         NamedDecl **NamedChain =
4548           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4549         for (unsigned i = 0; i < Chaining.size(); i++)
4550           NamedChain[i] = Chaining[i];
4551
4552         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4553             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4554             VD->getType(), {NamedChain, Chaining.size()});
4555
4556         for (const auto *Attr : VD->attrs())
4557           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4558
4559         IndirectField->setAccess(AS);
4560         IndirectField->setImplicit();
4561         SemaRef.PushOnScopeChains(IndirectField, S);
4562
4563         // That includes picking up the appropriate access specifier.
4564         if (AS != AS_none) IndirectField->setAccess(AS);
4565
4566         Chaining.resize(OldChainingSize);
4567       }
4568     }
4569   }
4570
4571   return Invalid;
4572 }
4573
4574 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4575 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4576 /// illegal input values are mapped to SC_None.
4577 static StorageClass
4578 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4579   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4580   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4581          "Parser allowed 'typedef' as storage class VarDecl.");
4582   switch (StorageClassSpec) {
4583   case DeclSpec::SCS_unspecified:    return SC_None;
4584   case DeclSpec::SCS_extern:
4585     if (DS.isExternInLinkageSpec())
4586       return SC_None;
4587     return SC_Extern;
4588   case DeclSpec::SCS_static:         return SC_Static;
4589   case DeclSpec::SCS_auto:           return SC_Auto;
4590   case DeclSpec::SCS_register:       return SC_Register;
4591   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4592     // Illegal SCSs map to None: error reporting is up to the caller.
4593   case DeclSpec::SCS_mutable:        // Fall through.
4594   case DeclSpec::SCS_typedef:        return SC_None;
4595   }
4596   llvm_unreachable("unknown storage class specifier");
4597 }
4598
4599 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4600   assert(Record->hasInClassInitializer());
4601
4602   for (const auto *I : Record->decls()) {
4603     const auto *FD = dyn_cast<FieldDecl>(I);
4604     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4605       FD = IFD->getAnonField();
4606     if (FD && FD->hasInClassInitializer())
4607       return FD->getLocation();
4608   }
4609
4610   llvm_unreachable("couldn't find in-class initializer");
4611 }
4612
4613 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4614                                       SourceLocation DefaultInitLoc) {
4615   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4616     return;
4617
4618   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4619   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4620 }
4621
4622 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4623                                       CXXRecordDecl *AnonUnion) {
4624   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4625     return;
4626
4627   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4628 }
4629
4630 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4631 /// anonymous structure or union. Anonymous unions are a C++ feature
4632 /// (C++ [class.union]) and a C11 feature; anonymous structures
4633 /// are a C11 feature and GNU C++ extension.
4634 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4635                                         AccessSpecifier AS,
4636                                         RecordDecl *Record,
4637                                         const PrintingPolicy &Policy) {
4638   DeclContext *Owner = Record->getDeclContext();
4639
4640   // Diagnose whether this anonymous struct/union is an extension.
4641   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4642     Diag(Record->getLocation(), diag::ext_anonymous_union);
4643   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4644     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4645   else if (!Record->isUnion() && !getLangOpts().C11)
4646     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4647
4648   // C and C++ require different kinds of checks for anonymous
4649   // structs/unions.
4650   bool Invalid = false;
4651   if (getLangOpts().CPlusPlus) {
4652     const char *PrevSpec = nullptr;
4653     unsigned DiagID;
4654     if (Record->isUnion()) {
4655       // C++ [class.union]p6:
4656       // C++17 [class.union.anon]p2:
4657       //   Anonymous unions declared in a named namespace or in the
4658       //   global namespace shall be declared static.
4659       DeclContext *OwnerScope = Owner->getRedeclContext();
4660       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4661           (OwnerScope->isTranslationUnit() ||
4662            (OwnerScope->isNamespace() &&
4663             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4664         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4665           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4666
4667         // Recover by adding 'static'.
4668         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4669                                PrevSpec, DiagID, Policy);
4670       }
4671       // C++ [class.union]p6:
4672       //   A storage class is not allowed in a declaration of an
4673       //   anonymous union in a class scope.
4674       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4675                isa<RecordDecl>(Owner)) {
4676         Diag(DS.getStorageClassSpecLoc(),
4677              diag::err_anonymous_union_with_storage_spec)
4678           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4679
4680         // Recover by removing the storage specifier.
4681         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4682                                SourceLocation(),
4683                                PrevSpec, DiagID, Context.getPrintingPolicy());
4684       }
4685     }
4686
4687     // Ignore const/volatile/restrict qualifiers.
4688     if (DS.getTypeQualifiers()) {
4689       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4690         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4691           << Record->isUnion() << "const"
4692           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4693       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4694         Diag(DS.getVolatileSpecLoc(),
4695              diag::ext_anonymous_struct_union_qualified)
4696           << Record->isUnion() << "volatile"
4697           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4698       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4699         Diag(DS.getRestrictSpecLoc(),
4700              diag::ext_anonymous_struct_union_qualified)
4701           << Record->isUnion() << "restrict"
4702           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4703       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4704         Diag(DS.getAtomicSpecLoc(),
4705              diag::ext_anonymous_struct_union_qualified)
4706           << Record->isUnion() << "_Atomic"
4707           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4708       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4709         Diag(DS.getUnalignedSpecLoc(),
4710              diag::ext_anonymous_struct_union_qualified)
4711           << Record->isUnion() << "__unaligned"
4712           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4713
4714       DS.ClearTypeQualifiers();
4715     }
4716
4717     // C++ [class.union]p2:
4718     //   The member-specification of an anonymous union shall only
4719     //   define non-static data members. [Note: nested types and
4720     //   functions cannot be declared within an anonymous union. ]
4721     for (auto *Mem : Record->decls()) {
4722       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4723         // C++ [class.union]p3:
4724         //   An anonymous union shall not have private or protected
4725         //   members (clause 11).
4726         assert(FD->getAccess() != AS_none);
4727         if (FD->getAccess() != AS_public) {
4728           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4729             << Record->isUnion() << (FD->getAccess() == AS_protected);
4730           Invalid = true;
4731         }
4732
4733         // C++ [class.union]p1
4734         //   An object of a class with a non-trivial constructor, a non-trivial
4735         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4736         //   assignment operator cannot be a member of a union, nor can an
4737         //   array of such objects.
4738         if (CheckNontrivialField(FD))
4739           Invalid = true;
4740       } else if (Mem->isImplicit()) {
4741         // Any implicit members are fine.
4742       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4743         // This is a type that showed up in an
4744         // elaborated-type-specifier inside the anonymous struct or
4745         // union, but which actually declares a type outside of the
4746         // anonymous struct or union. It's okay.
4747       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4748         if (!MemRecord->isAnonymousStructOrUnion() &&
4749             MemRecord->getDeclName()) {
4750           // Visual C++ allows type definition in anonymous struct or union.
4751           if (getLangOpts().MicrosoftExt)
4752             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4753               << Record->isUnion();
4754           else {
4755             // This is a nested type declaration.
4756             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4757               << Record->isUnion();
4758             Invalid = true;
4759           }
4760         } else {
4761           // This is an anonymous type definition within another anonymous type.
4762           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4763           // not part of standard C++.
4764           Diag(MemRecord->getLocation(),
4765                diag::ext_anonymous_record_with_anonymous_type)
4766             << Record->isUnion();
4767         }
4768       } else if (isa<AccessSpecDecl>(Mem)) {
4769         // Any access specifier is fine.
4770       } else if (isa<StaticAssertDecl>(Mem)) {
4771         // In C++1z, static_assert declarations are also fine.
4772       } else {
4773         // We have something that isn't a non-static data
4774         // member. Complain about it.
4775         unsigned DK = diag::err_anonymous_record_bad_member;
4776         if (isa<TypeDecl>(Mem))
4777           DK = diag::err_anonymous_record_with_type;
4778         else if (isa<FunctionDecl>(Mem))
4779           DK = diag::err_anonymous_record_with_function;
4780         else if (isa<VarDecl>(Mem))
4781           DK = diag::err_anonymous_record_with_static;
4782
4783         // Visual C++ allows type definition in anonymous struct or union.
4784         if (getLangOpts().MicrosoftExt &&
4785             DK == diag::err_anonymous_record_with_type)
4786           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4787             << Record->isUnion();
4788         else {
4789           Diag(Mem->getLocation(), DK) << Record->isUnion();
4790           Invalid = true;
4791         }
4792       }
4793     }
4794
4795     // C++11 [class.union]p8 (DR1460):
4796     //   At most one variant member of a union may have a
4797     //   brace-or-equal-initializer.
4798     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4799         Owner->isRecord())
4800       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4801                                 cast<CXXRecordDecl>(Record));
4802   }
4803
4804   if (!Record->isUnion() && !Owner->isRecord()) {
4805     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4806       << getLangOpts().CPlusPlus;
4807     Invalid = true;
4808   }
4809
4810   // Mock up a declarator.
4811   Declarator Dc(DS, DeclaratorContext::MemberContext);
4812   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4813   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4814
4815   // Create a declaration for this anonymous struct/union.
4816   NamedDecl *Anon = nullptr;
4817   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4818     Anon = FieldDecl::Create(Context, OwningClass,
4819                              DS.getLocStart(),
4820                              Record->getLocation(),
4821                              /*IdentifierInfo=*/nullptr,
4822                              Context.getTypeDeclType(Record),
4823                              TInfo,
4824                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4825                              /*InitStyle=*/ICIS_NoInit);
4826     Anon->setAccess(AS);
4827     if (getLangOpts().CPlusPlus)
4828       FieldCollector->Add(cast<FieldDecl>(Anon));
4829   } else {
4830     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4831     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4832     if (SCSpec == DeclSpec::SCS_mutable) {
4833       // mutable can only appear on non-static class members, so it's always
4834       // an error here
4835       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4836       Invalid = true;
4837       SC = SC_None;
4838     }
4839
4840     Anon = VarDecl::Create(Context, Owner,
4841                            DS.getLocStart(),
4842                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4843                            Context.getTypeDeclType(Record),
4844                            TInfo, SC);
4845
4846     // Default-initialize the implicit variable. This initialization will be
4847     // trivial in almost all cases, except if a union member has an in-class
4848     // initializer:
4849     //   union { int n = 0; };
4850     ActOnUninitializedDecl(Anon);
4851   }
4852   Anon->setImplicit();
4853
4854   // Mark this as an anonymous struct/union type.
4855   Record->setAnonymousStructOrUnion(true);
4856
4857   // Add the anonymous struct/union object to the current
4858   // context. We'll be referencing this object when we refer to one of
4859   // its members.
4860   Owner->addDecl(Anon);
4861
4862   // Inject the members of the anonymous struct/union into the owning
4863   // context and into the identifier resolver chain for name lookup
4864   // purposes.
4865   SmallVector<NamedDecl*, 2> Chain;
4866   Chain.push_back(Anon);
4867
4868   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4869     Invalid = true;
4870
4871   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4872     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4873       Decl *ManglingContextDecl;
4874       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4875               NewVD->getDeclContext(), ManglingContextDecl)) {
4876         Context.setManglingNumber(
4877             NewVD, MCtx->getManglingNumber(
4878                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4879         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4880       }
4881     }
4882   }
4883
4884   if (Invalid)
4885     Anon->setInvalidDecl();
4886
4887   return Anon;
4888 }
4889
4890 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4891 /// Microsoft C anonymous structure.
4892 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4893 /// Example:
4894 ///
4895 /// struct A { int a; };
4896 /// struct B { struct A; int b; };
4897 ///
4898 /// void foo() {
4899 ///   B var;
4900 ///   var.a = 3;
4901 /// }
4902 ///
4903 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4904                                            RecordDecl *Record) {
4905   assert(Record && "expected a record!");
4906
4907   // Mock up a declarator.
4908   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
4909   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4910   assert(TInfo && "couldn't build declarator info for anonymous struct");
4911
4912   auto *ParentDecl = cast<RecordDecl>(CurContext);
4913   QualType RecTy = Context.getTypeDeclType(Record);
4914
4915   // Create a declaration for this anonymous struct.
4916   NamedDecl *Anon = FieldDecl::Create(Context,
4917                              ParentDecl,
4918                              DS.getLocStart(),
4919                              DS.getLocStart(),
4920                              /*IdentifierInfo=*/nullptr,
4921                              RecTy,
4922                              TInfo,
4923                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4924                              /*InitStyle=*/ICIS_NoInit);
4925   Anon->setImplicit();
4926
4927   // Add the anonymous struct object to the current context.
4928   CurContext->addDecl(Anon);
4929
4930   // Inject the members of the anonymous struct into the current
4931   // context and into the identifier resolver chain for name lookup
4932   // purposes.
4933   SmallVector<NamedDecl*, 2> Chain;
4934   Chain.push_back(Anon);
4935
4936   RecordDecl *RecordDef = Record->getDefinition();
4937   if (RequireCompleteType(Anon->getLocation(), RecTy,
4938                           diag::err_field_incomplete) ||
4939       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4940                                           AS_none, Chain)) {
4941     Anon->setInvalidDecl();
4942     ParentDecl->setInvalidDecl();
4943   }
4944
4945   return Anon;
4946 }
4947
4948 /// GetNameForDeclarator - Determine the full declaration name for the
4949 /// given Declarator.
4950 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4951   return GetNameFromUnqualifiedId(D.getName());
4952 }
4953
4954 /// Retrieves the declaration name from a parsed unqualified-id.
4955 DeclarationNameInfo
4956 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4957   DeclarationNameInfo NameInfo;
4958   NameInfo.setLoc(Name.StartLocation);
4959
4960   switch (Name.getKind()) {
4961
4962   case UnqualifiedIdKind::IK_ImplicitSelfParam:
4963   case UnqualifiedIdKind::IK_Identifier:
4964     NameInfo.setName(Name.Identifier);
4965     NameInfo.setLoc(Name.StartLocation);
4966     return NameInfo;
4967
4968   case UnqualifiedIdKind::IK_DeductionGuideName: {
4969     // C++ [temp.deduct.guide]p3:
4970     //   The simple-template-id shall name a class template specialization.
4971     //   The template-name shall be the same identifier as the template-name
4972     //   of the simple-template-id.
4973     // These together intend to imply that the template-name shall name a
4974     // class template.
4975     // FIXME: template<typename T> struct X {};
4976     //        template<typename T> using Y = X<T>;
4977     //        Y(int) -> Y<int>;
4978     //   satisfies these rules but does not name a class template.
4979     TemplateName TN = Name.TemplateName.get().get();
4980     auto *Template = TN.getAsTemplateDecl();
4981     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4982       Diag(Name.StartLocation,
4983            diag::err_deduction_guide_name_not_class_template)
4984         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4985       if (Template)
4986         Diag(Template->getLocation(), diag::note_template_decl_here);
4987       return DeclarationNameInfo();
4988     }
4989
4990     NameInfo.setName(
4991         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4992     NameInfo.setLoc(Name.StartLocation);
4993     return NameInfo;
4994   }
4995
4996   case UnqualifiedIdKind::IK_OperatorFunctionId:
4997     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4998                                            Name.OperatorFunctionId.Operator));
4999     NameInfo.setLoc(Name.StartLocation);
5000     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5001       = Name.OperatorFunctionId.SymbolLocations[0];
5002     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5003       = Name.EndLocation.getRawEncoding();
5004     return NameInfo;
5005
5006   case UnqualifiedIdKind::IK_LiteralOperatorId:
5007     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5008                                                            Name.Identifier));
5009     NameInfo.setLoc(Name.StartLocation);
5010     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5011     return NameInfo;
5012
5013   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5014     TypeSourceInfo *TInfo;
5015     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5016     if (Ty.isNull())
5017       return DeclarationNameInfo();
5018     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5019                                                Context.getCanonicalType(Ty)));
5020     NameInfo.setLoc(Name.StartLocation);
5021     NameInfo.setNamedTypeInfo(TInfo);
5022     return NameInfo;
5023   }
5024
5025   case UnqualifiedIdKind::IK_ConstructorName: {
5026     TypeSourceInfo *TInfo;
5027     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5028     if (Ty.isNull())
5029       return DeclarationNameInfo();
5030     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5031                                               Context.getCanonicalType(Ty)));
5032     NameInfo.setLoc(Name.StartLocation);
5033     NameInfo.setNamedTypeInfo(TInfo);
5034     return NameInfo;
5035   }
5036
5037   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5038     // In well-formed code, we can only have a constructor
5039     // template-id that refers to the current context, so go there
5040     // to find the actual type being constructed.
5041     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5042     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5043       return DeclarationNameInfo();
5044
5045     // Determine the type of the class being constructed.
5046     QualType CurClassType = Context.getTypeDeclType(CurClass);
5047
5048     // FIXME: Check two things: that the template-id names the same type as
5049     // CurClassType, and that the template-id does not occur when the name
5050     // was qualified.
5051
5052     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5053                                     Context.getCanonicalType(CurClassType)));
5054     NameInfo.setLoc(Name.StartLocation);
5055     // FIXME: should we retrieve TypeSourceInfo?
5056     NameInfo.setNamedTypeInfo(nullptr);
5057     return NameInfo;
5058   }
5059
5060   case UnqualifiedIdKind::IK_DestructorName: {
5061     TypeSourceInfo *TInfo;
5062     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5063     if (Ty.isNull())
5064       return DeclarationNameInfo();
5065     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5066                                               Context.getCanonicalType(Ty)));
5067     NameInfo.setLoc(Name.StartLocation);
5068     NameInfo.setNamedTypeInfo(TInfo);
5069     return NameInfo;
5070   }
5071
5072   case UnqualifiedIdKind::IK_TemplateId: {
5073     TemplateName TName = Name.TemplateId->Template.get();
5074     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5075     return Context.getNameForTemplate(TName, TNameLoc);
5076   }
5077
5078   } // switch (Name.getKind())
5079
5080   llvm_unreachable("Unknown name kind");
5081 }
5082
5083 static QualType getCoreType(QualType Ty) {
5084   do {
5085     if (Ty->isPointerType() || Ty->isReferenceType())
5086       Ty = Ty->getPointeeType();
5087     else if (Ty->isArrayType())
5088       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5089     else
5090       return Ty.withoutLocalFastQualifiers();
5091   } while (true);
5092 }
5093
5094 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5095 /// and Definition have "nearly" matching parameters. This heuristic is
5096 /// used to improve diagnostics in the case where an out-of-line function
5097 /// definition doesn't match any declaration within the class or namespace.
5098 /// Also sets Params to the list of indices to the parameters that differ
5099 /// between the declaration and the definition. If hasSimilarParameters
5100 /// returns true and Params is empty, then all of the parameters match.
5101 static bool hasSimilarParameters(ASTContext &Context,
5102                                      FunctionDecl *Declaration,
5103                                      FunctionDecl *Definition,
5104                                      SmallVectorImpl<unsigned> &Params) {
5105   Params.clear();
5106   if (Declaration->param_size() != Definition->param_size())
5107     return false;
5108   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5109     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5110     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5111
5112     // The parameter types are identical
5113     if (Context.hasSameType(DefParamTy, DeclParamTy))
5114       continue;
5115
5116     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5117     QualType DefParamBaseTy = getCoreType(DefParamTy);
5118     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5119     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5120
5121     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5122         (DeclTyName && DeclTyName == DefTyName))
5123       Params.push_back(Idx);
5124     else  // The two parameters aren't even close
5125       return false;
5126   }
5127
5128   return true;
5129 }
5130
5131 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5132 /// declarator needs to be rebuilt in the current instantiation.
5133 /// Any bits of declarator which appear before the name are valid for
5134 /// consideration here.  That's specifically the type in the decl spec
5135 /// and the base type in any member-pointer chunks.
5136 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5137                                                     DeclarationName Name) {
5138   // The types we specifically need to rebuild are:
5139   //   - typenames, typeofs, and decltypes
5140   //   - types which will become injected class names
5141   // Of course, we also need to rebuild any type referencing such a
5142   // type.  It's safest to just say "dependent", but we call out a
5143   // few cases here.
5144
5145   DeclSpec &DS = D.getMutableDeclSpec();
5146   switch (DS.getTypeSpecType()) {
5147   case DeclSpec::TST_typename:
5148   case DeclSpec::TST_typeofType:
5149   case DeclSpec::TST_underlyingType:
5150   case DeclSpec::TST_atomic: {
5151     // Grab the type from the parser.
5152     TypeSourceInfo *TSI = nullptr;
5153     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5154     if (T.isNull() || !T->isDependentType()) break;
5155
5156     // Make sure there's a type source info.  This isn't really much
5157     // of a waste; most dependent types should have type source info
5158     // attached already.
5159     if (!TSI)
5160       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5161
5162     // Rebuild the type in the current instantiation.
5163     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5164     if (!TSI) return true;
5165
5166     // Store the new type back in the decl spec.
5167     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5168     DS.UpdateTypeRep(LocType);
5169     break;
5170   }
5171
5172   case DeclSpec::TST_decltype:
5173   case DeclSpec::TST_typeofExpr: {
5174     Expr *E = DS.getRepAsExpr();
5175     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5176     if (Result.isInvalid()) return true;
5177     DS.UpdateExprRep(Result.get());
5178     break;
5179   }
5180
5181   default:
5182     // Nothing to do for these decl specs.
5183     break;
5184   }
5185
5186   // It doesn't matter what order we do this in.
5187   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5188     DeclaratorChunk &Chunk = D.getTypeObject(I);
5189
5190     // The only type information in the declarator which can come
5191     // before the declaration name is the base type of a member
5192     // pointer.
5193     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5194       continue;
5195
5196     // Rebuild the scope specifier in-place.
5197     CXXScopeSpec &SS = Chunk.Mem.Scope();
5198     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5199       return true;
5200   }
5201
5202   return false;
5203 }
5204
5205 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5206   D.setFunctionDefinitionKind(FDK_Declaration);
5207   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5208
5209   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5210       Dcl && Dcl->getDeclContext()->isFileContext())
5211     Dcl->setTopLevelDeclInObjCContainer();
5212
5213   if (getLangOpts().OpenCL)
5214     setCurrentOpenCLExtensionForDecl(Dcl);
5215
5216   return Dcl;
5217 }
5218
5219 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5220 ///   If T is the name of a class, then each of the following shall have a
5221 ///   name different from T:
5222 ///     - every static data member of class T;
5223 ///     - every member function of class T
5224 ///     - every member of class T that is itself a type;
5225 /// \returns true if the declaration name violates these rules.
5226 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5227                                    DeclarationNameInfo NameInfo) {
5228   DeclarationName Name = NameInfo.getName();
5229
5230   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5231   while (Record && Record->isAnonymousStructOrUnion())
5232     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5233   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5234     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5235     return true;
5236   }
5237
5238   return false;
5239 }
5240
5241 /// Diagnose a declaration whose declarator-id has the given
5242 /// nested-name-specifier.
5243 ///
5244 /// \param SS The nested-name-specifier of the declarator-id.
5245 ///
5246 /// \param DC The declaration context to which the nested-name-specifier
5247 /// resolves.
5248 ///
5249 /// \param Name The name of the entity being declared.
5250 ///
5251 /// \param Loc The location of the name of the entity being declared.
5252 ///
5253 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5254 /// we're declaring an explicit / partial specialization / instantiation.
5255 ///
5256 /// \returns true if we cannot safely recover from this error, false otherwise.
5257 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5258                                         DeclarationName Name,
5259                                         SourceLocation Loc, bool IsTemplateId) {
5260   DeclContext *Cur = CurContext;
5261   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5262     Cur = Cur->getParent();
5263
5264   // If the user provided a superfluous scope specifier that refers back to the
5265   // class in which the entity is already declared, diagnose and ignore it.
5266   //
5267   // class X {
5268   //   void X::f();
5269   // };
5270   //
5271   // Note, it was once ill-formed to give redundant qualification in all
5272   // contexts, but that rule was removed by DR482.
5273   if (Cur->Equals(DC)) {
5274     if (Cur->isRecord()) {
5275       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5276                                       : diag::err_member_extra_qualification)
5277         << Name << FixItHint::CreateRemoval(SS.getRange());
5278       SS.clear();
5279     } else {
5280       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5281     }
5282     return false;
5283   }
5284
5285   // Check whether the qualifying scope encloses the scope of the original
5286   // declaration. For a template-id, we perform the checks in
5287   // CheckTemplateSpecializationScope.
5288   if (!Cur->Encloses(DC) && !IsTemplateId) {
5289     if (Cur->isRecord())
5290       Diag(Loc, diag::err_member_qualification)
5291         << Name << SS.getRange();
5292     else if (isa<TranslationUnitDecl>(DC))
5293       Diag(Loc, diag::err_invalid_declarator_global_scope)
5294         << Name << SS.getRange();
5295     else if (isa<FunctionDecl>(Cur))
5296       Diag(Loc, diag::err_invalid_declarator_in_function)
5297         << Name << SS.getRange();
5298     else if (isa<BlockDecl>(Cur))
5299       Diag(Loc, diag::err_invalid_declarator_in_block)
5300         << Name << SS.getRange();
5301     else
5302       Diag(Loc, diag::err_invalid_declarator_scope)
5303       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5304
5305     return true;
5306   }
5307
5308   if (Cur->isRecord()) {
5309     // Cannot qualify members within a class.
5310     Diag(Loc, diag::err_member_qualification)
5311       << Name << SS.getRange();
5312     SS.clear();
5313
5314     // C++ constructors and destructors with incorrect scopes can break
5315     // our AST invariants by having the wrong underlying types. If
5316     // that's the case, then drop this declaration entirely.
5317     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5318          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5319         !Context.hasSameType(Name.getCXXNameType(),
5320                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5321       return true;
5322
5323     return false;
5324   }
5325
5326   // C++11 [dcl.meaning]p1:
5327   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5328   //   not begin with a decltype-specifer"
5329   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5330   while (SpecLoc.getPrefix())
5331     SpecLoc = SpecLoc.getPrefix();
5332   if (dyn_cast_or_null<DecltypeType>(
5333         SpecLoc.getNestedNameSpecifier()->getAsType()))
5334     Diag(Loc, diag::err_decltype_in_declarator)
5335       << SpecLoc.getTypeLoc().getSourceRange();
5336
5337   return false;
5338 }
5339
5340 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5341                                   MultiTemplateParamsArg TemplateParamLists) {
5342   // TODO: consider using NameInfo for diagnostic.
5343   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5344   DeclarationName Name = NameInfo.getName();
5345
5346   // All of these full declarators require an identifier.  If it doesn't have
5347   // one, the ParsedFreeStandingDeclSpec action should be used.
5348   if (D.isDecompositionDeclarator()) {
5349     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5350   } else if (!Name) {
5351     if (!D.isInvalidType())  // Reject this if we think it is valid.
5352       Diag(D.getDeclSpec().getLocStart(),
5353            diag::err_declarator_need_ident)
5354         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5355     return nullptr;
5356   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5357     return nullptr;
5358
5359   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5360   // we find one that is.
5361   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5362          (S->getFlags() & Scope::TemplateParamScope) != 0)
5363     S = S->getParent();
5364
5365   DeclContext *DC = CurContext;
5366   if (D.getCXXScopeSpec().isInvalid())
5367     D.setInvalidType();
5368   else if (D.getCXXScopeSpec().isSet()) {
5369     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5370                                         UPPC_DeclarationQualifier))
5371       return nullptr;
5372
5373     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5374     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5375     if (!DC || isa<EnumDecl>(DC)) {
5376       // If we could not compute the declaration context, it's because the
5377       // declaration context is dependent but does not refer to a class,
5378       // class template, or class template partial specialization. Complain
5379       // and return early, to avoid the coming semantic disaster.
5380       Diag(D.getIdentifierLoc(),
5381            diag::err_template_qualified_declarator_no_match)
5382         << D.getCXXScopeSpec().getScopeRep()
5383         << D.getCXXScopeSpec().getRange();
5384       return nullptr;
5385     }
5386     bool IsDependentContext = DC->isDependentContext();
5387
5388     if (!IsDependentContext &&
5389         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5390       return nullptr;
5391
5392     // If a class is incomplete, do not parse entities inside it.
5393     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5394       Diag(D.getIdentifierLoc(),
5395            diag::err_member_def_undefined_record)
5396         << Name << DC << D.getCXXScopeSpec().getRange();
5397       return nullptr;
5398     }
5399     if (!D.getDeclSpec().isFriendSpecified()) {
5400       if (diagnoseQualifiedDeclaration(
5401               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5402               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5403         if (DC->isRecord())
5404           return nullptr;
5405
5406         D.setInvalidType();
5407       }
5408     }
5409
5410     // Check whether we need to rebuild the type of the given
5411     // declaration in the current instantiation.
5412     if (EnteringContext && IsDependentContext &&
5413         TemplateParamLists.size() != 0) {
5414       ContextRAII SavedContext(*this, DC);
5415       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5416         D.setInvalidType();
5417     }
5418   }
5419
5420   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5421   QualType R = TInfo->getType();
5422
5423   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5424                                       UPPC_DeclarationType))
5425     D.setInvalidType();
5426
5427   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5428                         forRedeclarationInCurContext());
5429
5430   // See if this is a redefinition of a variable in the same scope.
5431   if (!D.getCXXScopeSpec().isSet()) {
5432     bool IsLinkageLookup = false;
5433     bool CreateBuiltins = false;
5434
5435     // If the declaration we're planning to build will be a function
5436     // or object with linkage, then look for another declaration with
5437     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5438     //
5439     // If the declaration we're planning to build will be declared with
5440     // external linkage in the translation unit, create any builtin with
5441     // the same name.
5442     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5443       /* Do nothing*/;
5444     else if (CurContext->isFunctionOrMethod() &&
5445              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5446               R->isFunctionType())) {
5447       IsLinkageLookup = true;
5448       CreateBuiltins =
5449           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5450     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5451                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5452       CreateBuiltins = true;
5453
5454     if (IsLinkageLookup) {
5455       Previous.clear(LookupRedeclarationWithLinkage);
5456       Previous.setRedeclarationKind(ForExternalRedeclaration);
5457     }
5458
5459     LookupName(Previous, S, CreateBuiltins);
5460   } else { // Something like "int foo::x;"
5461     LookupQualifiedName(Previous, DC);
5462
5463     // C++ [dcl.meaning]p1:
5464     //   When the declarator-id is qualified, the declaration shall refer to a
5465     //  previously declared member of the class or namespace to which the
5466     //  qualifier refers (or, in the case of a namespace, of an element of the
5467     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5468     //  thereof; [...]
5469     //
5470     // Note that we already checked the context above, and that we do not have
5471     // enough information to make sure that Previous contains the declaration
5472     // we want to match. For example, given:
5473     //
5474     //   class X {
5475     //     void f();
5476     //     void f(float);
5477     //   };
5478     //
5479     //   void X::f(int) { } // ill-formed
5480     //
5481     // In this case, Previous will point to the overload set
5482     // containing the two f's declared in X, but neither of them
5483     // matches.
5484
5485     // C++ [dcl.meaning]p1:
5486     //   [...] the member shall not merely have been introduced by a
5487     //   using-declaration in the scope of the class or namespace nominated by
5488     //   the nested-name-specifier of the declarator-id.
5489     RemoveUsingDecls(Previous);
5490   }
5491
5492   if (Previous.isSingleResult() &&
5493       Previous.getFoundDecl()->isTemplateParameter()) {
5494     // Maybe we will complain about the shadowed template parameter.
5495     if (!D.isInvalidType())
5496       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5497                                       Previous.getFoundDecl());
5498
5499     // Just pretend that we didn't see the previous declaration.
5500     Previous.clear();
5501   }
5502
5503   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5504     // Forget that the previous declaration is the injected-class-name.
5505     Previous.clear();
5506
5507   // In C++, the previous declaration we find might be a tag type
5508   // (class or enum). In this case, the new declaration will hide the
5509   // tag type. Note that this applies to functions, function templates, and
5510   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5511   if (Previous.isSingleTagDecl() &&
5512       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5513       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5514     Previous.clear();
5515
5516   // Check that there are no default arguments other than in the parameters
5517   // of a function declaration (C++ only).
5518   if (getLangOpts().CPlusPlus)
5519     CheckExtraCXXDefaultArguments(D);
5520
5521   NamedDecl *New;
5522
5523   bool AddToScope = true;
5524   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5525     if (TemplateParamLists.size()) {
5526       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5527       return nullptr;
5528     }
5529
5530     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5531   } else if (R->isFunctionType()) {
5532     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5533                                   TemplateParamLists,
5534                                   AddToScope);
5535   } else {
5536     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5537                                   AddToScope);
5538   }
5539
5540   if (!New)
5541     return nullptr;
5542
5543   // If this has an identifier and is not a function template specialization,
5544   // add it to the scope stack.
5545   if (New->getDeclName() && AddToScope) {
5546     // Only make a locally-scoped extern declaration visible if it is the first
5547     // declaration of this entity. Qualified lookup for such an entity should
5548     // only find this declaration if there is no visible declaration of it.
5549     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5550     PushOnScopeChains(New, S, AddToContext);
5551     if (!AddToContext)
5552       CurContext->addHiddenDecl(New);
5553   }
5554
5555   if (isInOpenMPDeclareTargetContext())
5556     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5557
5558   return New;
5559 }
5560
5561 /// Helper method to turn variable array types into constant array
5562 /// types in certain situations which would otherwise be errors (for
5563 /// GCC compatibility).
5564 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5565                                                     ASTContext &Context,
5566                                                     bool &SizeIsNegative,
5567                                                     llvm::APSInt &Oversized) {
5568   // This method tries to turn a variable array into a constant
5569   // array even when the size isn't an ICE.  This is necessary
5570   // for compatibility with code that depends on gcc's buggy
5571   // constant expression folding, like struct {char x[(int)(char*)2];}
5572   SizeIsNegative = false;
5573   Oversized = 0;
5574
5575   if (T->isDependentType())
5576     return QualType();
5577
5578   QualifierCollector Qs;
5579   const Type *Ty = Qs.strip(T);
5580
5581   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5582     QualType Pointee = PTy->getPointeeType();
5583     QualType FixedType =
5584         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5585                                             Oversized);
5586     if (FixedType.isNull()) return FixedType;
5587     FixedType = Context.getPointerType(FixedType);
5588     return Qs.apply(Context, FixedType);
5589   }
5590   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5591     QualType Inner = PTy->getInnerType();
5592     QualType FixedType =
5593         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5594                                             Oversized);
5595     if (FixedType.isNull()) return FixedType;
5596     FixedType = Context.getParenType(FixedType);
5597     return Qs.apply(Context, FixedType);
5598   }
5599
5600   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5601   if (!VLATy)
5602     return QualType();
5603   // FIXME: We should probably handle this case
5604   if (VLATy->getElementType()->isVariablyModifiedType())
5605     return QualType();
5606
5607   llvm::APSInt Res;
5608   if (!VLATy->getSizeExpr() ||
5609       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5610     return QualType();
5611
5612   // Check whether the array size is negative.
5613   if (Res.isSigned() && Res.isNegative()) {
5614     SizeIsNegative = true;
5615     return QualType();
5616   }
5617
5618   // Check whether the array is too large to be addressed.
5619   unsigned ActiveSizeBits
5620     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5621                                               Res);
5622   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5623     Oversized = Res;
5624     return QualType();
5625   }
5626
5627   return Context.getConstantArrayType(VLATy->getElementType(),
5628                                       Res, ArrayType::Normal, 0);
5629 }
5630
5631 static void
5632 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5633   SrcTL = SrcTL.getUnqualifiedLoc();
5634   DstTL = DstTL.getUnqualifiedLoc();
5635   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5636     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5637     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5638                                       DstPTL.getPointeeLoc());
5639     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5640     return;
5641   }
5642   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5643     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5644     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5645                                       DstPTL.getInnerLoc());
5646     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5647     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5648     return;
5649   }
5650   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5651   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5652   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5653   TypeLoc DstElemTL = DstATL.getElementLoc();
5654   DstElemTL.initializeFullCopy(SrcElemTL);
5655   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5656   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5657   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5658 }
5659
5660 /// Helper method to turn variable array types into constant array
5661 /// types in certain situations which would otherwise be errors (for
5662 /// GCC compatibility).
5663 static TypeSourceInfo*
5664 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5665                                               ASTContext &Context,
5666                                               bool &SizeIsNegative,
5667                                               llvm::APSInt &Oversized) {
5668   QualType FixedTy
5669     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5670                                           SizeIsNegative, Oversized);
5671   if (FixedTy.isNull())
5672     return nullptr;
5673   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5674   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5675                                     FixedTInfo->getTypeLoc());
5676   return FixedTInfo;
5677 }
5678
5679 /// Register the given locally-scoped extern "C" declaration so
5680 /// that it can be found later for redeclarations. We include any extern "C"
5681 /// declaration that is not visible in the translation unit here, not just
5682 /// function-scope declarations.
5683 void
5684 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5685   if (!getLangOpts().CPlusPlus &&
5686       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5687     // Don't need to track declarations in the TU in C.
5688     return;
5689
5690   // Note that we have a locally-scoped external with this name.
5691   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5692 }
5693
5694 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5695   // FIXME: We can have multiple results via __attribute__((overloadable)).
5696   auto Result = Context.getExternCContextDecl()->lookup(Name);
5697   return Result.empty() ? nullptr : *Result.begin();
5698 }
5699
5700 /// Diagnose function specifiers on a declaration of an identifier that
5701 /// does not identify a function.
5702 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5703   // FIXME: We should probably indicate the identifier in question to avoid
5704   // confusion for constructs like "virtual int a(), b;"
5705   if (DS.isVirtualSpecified())
5706     Diag(DS.getVirtualSpecLoc(),
5707          diag::err_virtual_non_function);
5708
5709   if (DS.isExplicitSpecified())
5710     Diag(DS.getExplicitSpecLoc(),
5711          diag::err_explicit_non_function);
5712
5713   if (DS.isNoreturnSpecified())
5714     Diag(DS.getNoreturnSpecLoc(),
5715          diag::err_noreturn_non_function);
5716 }
5717
5718 NamedDecl*
5719 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5720                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5721   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5722   if (D.getCXXScopeSpec().isSet()) {
5723     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5724       << D.getCXXScopeSpec().getRange();
5725     D.setInvalidType();
5726     // Pretend we didn't see the scope specifier.
5727     DC = CurContext;
5728     Previous.clear();
5729   }
5730
5731   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5732
5733   if (D.getDeclSpec().isInlineSpecified())
5734     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5735         << getLangOpts().CPlusPlus17;
5736   if (D.getDeclSpec().isConstexprSpecified())
5737     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5738       << 1;
5739
5740   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5741     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5742       Diag(D.getName().StartLocation,
5743            diag::err_deduction_guide_invalid_specifier)
5744           << "typedef";
5745     else
5746       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5747           << D.getName().getSourceRange();
5748     return nullptr;
5749   }
5750
5751   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5752   if (!NewTD) return nullptr;
5753
5754   // Handle attributes prior to checking for duplicates in MergeVarDecl
5755   ProcessDeclAttributes(S, NewTD, D);
5756
5757   CheckTypedefForVariablyModifiedType(S, NewTD);
5758
5759   bool Redeclaration = D.isRedeclaration();
5760   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5761   D.setRedeclaration(Redeclaration);
5762   return ND;
5763 }
5764
5765 void
5766 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5767   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5768   // then it shall have block scope.
5769   // Note that variably modified types must be fixed before merging the decl so
5770   // that redeclarations will match.
5771   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5772   QualType T = TInfo->getType();
5773   if (T->isVariablyModifiedType()) {
5774     setFunctionHasBranchProtectedScope();
5775
5776     if (S->getFnParent() == nullptr) {
5777       bool SizeIsNegative;
5778       llvm::APSInt Oversized;
5779       TypeSourceInfo *FixedTInfo =
5780         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5781                                                       SizeIsNegative,
5782                                                       Oversized);
5783       if (FixedTInfo) {
5784         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5785         NewTD->setTypeSourceInfo(FixedTInfo);
5786       } else {
5787         if (SizeIsNegative)
5788           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5789         else if (T->isVariableArrayType())
5790           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5791         else if (Oversized.getBoolValue())
5792           Diag(NewTD->getLocation(), diag::err_array_too_large)
5793             << Oversized.toString(10);
5794         else
5795           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5796         NewTD->setInvalidDecl();
5797       }
5798     }
5799   }
5800 }
5801
5802 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5803 /// declares a typedef-name, either using the 'typedef' type specifier or via
5804 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5805 NamedDecl*
5806 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5807                            LookupResult &Previous, bool &Redeclaration) {
5808
5809   // Find the shadowed declaration before filtering for scope.
5810   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5811
5812   // Merge the decl with the existing one if appropriate. If the decl is
5813   // in an outer scope, it isn't the same thing.
5814   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5815                        /*AllowInlineNamespace*/false);
5816   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5817   if (!Previous.empty()) {
5818     Redeclaration = true;
5819     MergeTypedefNameDecl(S, NewTD, Previous);
5820   }
5821
5822   if (ShadowedDecl && !Redeclaration)
5823     CheckShadow(NewTD, ShadowedDecl, Previous);
5824
5825   // If this is the C FILE type, notify the AST context.
5826   if (IdentifierInfo *II = NewTD->getIdentifier())
5827     if (!NewTD->isInvalidDecl() &&
5828         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5829       if (II->isStr("FILE"))
5830         Context.setFILEDecl(NewTD);
5831       else if (II->isStr("jmp_buf"))
5832         Context.setjmp_bufDecl(NewTD);
5833       else if (II->isStr("sigjmp_buf"))
5834         Context.setsigjmp_bufDecl(NewTD);
5835       else if (II->isStr("ucontext_t"))
5836         Context.setucontext_tDecl(NewTD);
5837     }
5838
5839   return NewTD;
5840 }
5841
5842 /// Determines whether the given declaration is an out-of-scope
5843 /// previous declaration.
5844 ///
5845 /// This routine should be invoked when name lookup has found a
5846 /// previous declaration (PrevDecl) that is not in the scope where a
5847 /// new declaration by the same name is being introduced. If the new
5848 /// declaration occurs in a local scope, previous declarations with
5849 /// linkage may still be considered previous declarations (C99
5850 /// 6.2.2p4-5, C++ [basic.link]p6).
5851 ///
5852 /// \param PrevDecl the previous declaration found by name
5853 /// lookup
5854 ///
5855 /// \param DC the context in which the new declaration is being
5856 /// declared.
5857 ///
5858 /// \returns true if PrevDecl is an out-of-scope previous declaration
5859 /// for a new delcaration with the same name.
5860 static bool
5861 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5862                                 ASTContext &Context) {
5863   if (!PrevDecl)
5864     return false;
5865
5866   if (!PrevDecl->hasLinkage())
5867     return false;
5868
5869   if (Context.getLangOpts().CPlusPlus) {
5870     // C++ [basic.link]p6:
5871     //   If there is a visible declaration of an entity with linkage
5872     //   having the same name and type, ignoring entities declared
5873     //   outside the innermost enclosing namespace scope, the block
5874     //   scope declaration declares that same entity and receives the
5875     //   linkage of the previous declaration.
5876     DeclContext *OuterContext = DC->getRedeclContext();
5877     if (!OuterContext->isFunctionOrMethod())
5878       // This rule only applies to block-scope declarations.
5879       return false;
5880
5881     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5882     if (PrevOuterContext->isRecord())
5883       // We found a member function: ignore it.
5884       return false;
5885
5886     // Find the innermost enclosing namespace for the new and
5887     // previous declarations.
5888     OuterContext = OuterContext->getEnclosingNamespaceContext();
5889     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5890
5891     // The previous declaration is in a different namespace, so it
5892     // isn't the same function.
5893     if (!OuterContext->Equals(PrevOuterContext))
5894       return false;
5895   }
5896
5897   return true;
5898 }
5899
5900 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5901   CXXScopeSpec &SS = D.getCXXScopeSpec();
5902   if (!SS.isSet()) return;
5903   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5904 }
5905
5906 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5907   QualType type = decl->getType();
5908   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5909   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5910     // Various kinds of declaration aren't allowed to be __autoreleasing.
5911     unsigned kind = -1U;
5912     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5913       if (var->hasAttr<BlocksAttr>())
5914         kind = 0; // __block
5915       else if (!var->hasLocalStorage())
5916         kind = 1; // global
5917     } else if (isa<ObjCIvarDecl>(decl)) {
5918       kind = 3; // ivar
5919     } else if (isa<FieldDecl>(decl)) {
5920       kind = 2; // field
5921     }
5922
5923     if (kind != -1U) {
5924       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5925         << kind;
5926     }
5927   } else if (lifetime == Qualifiers::OCL_None) {
5928     // Try to infer lifetime.
5929     if (!type->isObjCLifetimeType())
5930       return false;
5931
5932     lifetime = type->getObjCARCImplicitLifetime();
5933     type = Context.getLifetimeQualifiedType(type, lifetime);
5934     decl->setType(type);
5935   }
5936
5937   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5938     // Thread-local variables cannot have lifetime.
5939     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5940         var->getTLSKind()) {
5941       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5942         << var->getType();
5943       return true;
5944     }
5945   }
5946
5947   return false;
5948 }
5949
5950 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5951   // Ensure that an auto decl is deduced otherwise the checks below might cache
5952   // the wrong linkage.
5953   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5954
5955   // 'weak' only applies to declarations with external linkage.
5956   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5957     if (!ND.isExternallyVisible()) {
5958       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5959       ND.dropAttr<WeakAttr>();
5960     }
5961   }
5962   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5963     if (ND.isExternallyVisible()) {
5964       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5965       ND.dropAttr<WeakRefAttr>();
5966       ND.dropAttr<AliasAttr>();
5967     }
5968   }
5969
5970   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5971     if (VD->hasInit()) {
5972       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5973         assert(VD->isThisDeclarationADefinition() &&
5974                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5975         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5976         VD->dropAttr<AliasAttr>();
5977       }
5978     }
5979   }
5980
5981   // 'selectany' only applies to externally visible variable declarations.
5982   // It does not apply to functions.
5983   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5984     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5985       S.Diag(Attr->getLocation(),
5986              diag::err_attribute_selectany_non_extern_data);
5987       ND.dropAttr<SelectAnyAttr>();
5988     }
5989   }
5990
5991   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5992     // dll attributes require external linkage. Static locals may have external
5993     // linkage but still cannot be explicitly imported or exported.
5994     auto *VD = dyn_cast<VarDecl>(&ND);
5995     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5996       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5997         << &ND << Attr;
5998       ND.setInvalidDecl();
5999     }
6000   }
6001
6002   // Virtual functions cannot be marked as 'notail'.
6003   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6004     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6005       if (MD->isVirtual()) {
6006         S.Diag(ND.getLocation(),
6007                diag::err_invalid_attribute_on_virtual_function)
6008             << Attr;
6009         ND.dropAttr<NotTailCalledAttr>();
6010       }
6011
6012   // Check the attributes on the function type, if any.
6013   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6014     // Don't declare this variable in the second operand of the for-statement;
6015     // GCC miscompiles that by ending its lifetime before evaluating the
6016     // third operand. See gcc.gnu.org/PR86769.
6017     AttributedTypeLoc ATL;
6018     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6019          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6020          TL = ATL.getModifiedLoc()) {
6021       // The [[lifetimebound]] attribute can be applied to the implicit object
6022       // parameter of a non-static member function (other than a ctor or dtor)
6023       // by applying it to the function type.
6024       if (ATL.getAttrKind() == AttributedType::attr_lifetimebound) {
6025         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6026         if (!MD || MD->isStatic()) {
6027           S.Diag(ATL.getAttrNameLoc(), diag::err_lifetimebound_no_object_param)
6028               << !MD << ATL.getLocalSourceRange();
6029         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6030           S.Diag(ATL.getAttrNameLoc(), diag::err_lifetimebound_ctor_dtor)
6031               << isa<CXXDestructorDecl>(MD) << ATL.getLocalSourceRange();
6032         }
6033       }
6034     }
6035   }
6036 }
6037
6038 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6039                                            NamedDecl *NewDecl,
6040                                            bool IsSpecialization,
6041                                            bool IsDefinition) {
6042   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6043     return;
6044
6045   bool IsTemplate = false;
6046   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6047     OldDecl = OldTD->getTemplatedDecl();
6048     IsTemplate = true;
6049     if (!IsSpecialization)
6050       IsDefinition = false;
6051   }
6052   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6053     NewDecl = NewTD->getTemplatedDecl();
6054     IsTemplate = true;
6055   }
6056
6057   if (!OldDecl || !NewDecl)
6058     return;
6059
6060   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6061   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6062   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6063   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6064
6065   // dllimport and dllexport are inheritable attributes so we have to exclude
6066   // inherited attribute instances.
6067   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6068                     (NewExportAttr && !NewExportAttr->isInherited());
6069
6070   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6071   // the only exception being explicit specializations.
6072   // Implicitly generated declarations are also excluded for now because there
6073   // is no other way to switch these to use dllimport or dllexport.
6074   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6075
6076   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6077     // Allow with a warning for free functions and global variables.
6078     bool JustWarn = false;
6079     if (!OldDecl->isCXXClassMember()) {
6080       auto *VD = dyn_cast<VarDecl>(OldDecl);
6081       if (VD && !VD->getDescribedVarTemplate())
6082         JustWarn = true;
6083       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6084       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6085         JustWarn = true;
6086     }
6087
6088     // We cannot change a declaration that's been used because IR has already
6089     // been emitted. Dllimported functions will still work though (modulo
6090     // address equality) as they can use the thunk.
6091     if (OldDecl->isUsed())
6092       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6093         JustWarn = false;
6094
6095     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6096                                : diag::err_attribute_dll_redeclaration;
6097     S.Diag(NewDecl->getLocation(), DiagID)
6098         << NewDecl
6099         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6100     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6101     if (!JustWarn) {
6102       NewDecl->setInvalidDecl();
6103       return;
6104     }
6105   }
6106
6107   // A redeclaration is not allowed to drop a dllimport attribute, the only
6108   // exceptions being inline function definitions (except for function
6109   // templates), local extern declarations, qualified friend declarations or
6110   // special MSVC extension: in the last case, the declaration is treated as if
6111   // it were marked dllexport.
6112   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6113   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6114   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6115     // Ignore static data because out-of-line definitions are diagnosed
6116     // separately.
6117     IsStaticDataMember = VD->isStaticDataMember();
6118     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6119                    VarDecl::DeclarationOnly;
6120   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6121     IsInline = FD->isInlined();
6122     IsQualifiedFriend = FD->getQualifier() &&
6123                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6124   }
6125
6126   if (OldImportAttr && !HasNewAttr &&
6127       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6128       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6129     if (IsMicrosoft && IsDefinition) {
6130       S.Diag(NewDecl->getLocation(),
6131              diag::warn_redeclaration_without_import_attribute)
6132           << NewDecl;
6133       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6134       NewDecl->dropAttr<DLLImportAttr>();
6135       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6136           NewImportAttr->getRange(), S.Context,
6137           NewImportAttr->getSpellingListIndex()));
6138     } else {
6139       S.Diag(NewDecl->getLocation(),
6140              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6141           << NewDecl << OldImportAttr;
6142       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6143       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6144       OldDecl->dropAttr<DLLImportAttr>();
6145       NewDecl->dropAttr<DLLImportAttr>();
6146     }
6147   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6148     // In MinGW, seeing a function declared inline drops the dllimport
6149     // attribute.
6150     OldDecl->dropAttr<DLLImportAttr>();
6151     NewDecl->dropAttr<DLLImportAttr>();
6152     S.Diag(NewDecl->getLocation(),
6153            diag::warn_dllimport_dropped_from_inline_function)
6154         << NewDecl << OldImportAttr;
6155   }
6156
6157   // A specialization of a class template member function is processed here
6158   // since it's a redeclaration. If the parent class is dllexport, the
6159   // specialization inherits that attribute. This doesn't happen automatically
6160   // since the parent class isn't instantiated until later.
6161   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6162     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6163         !NewImportAttr && !NewExportAttr) {
6164       if (const DLLExportAttr *ParentExportAttr =
6165               MD->getParent()->getAttr<DLLExportAttr>()) {
6166         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6167         NewAttr->setInherited(true);
6168         NewDecl->addAttr(NewAttr);
6169       }
6170     }
6171   }
6172 }
6173
6174 /// Given that we are within the definition of the given function,
6175 /// will that definition behave like C99's 'inline', where the
6176 /// definition is discarded except for optimization purposes?
6177 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6178   // Try to avoid calling GetGVALinkageForFunction.
6179
6180   // All cases of this require the 'inline' keyword.
6181   if (!FD->isInlined()) return false;
6182
6183   // This is only possible in C++ with the gnu_inline attribute.
6184   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6185     return false;
6186
6187   // Okay, go ahead and call the relatively-more-expensive function.
6188   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6189 }
6190
6191 /// Determine whether a variable is extern "C" prior to attaching
6192 /// an initializer. We can't just call isExternC() here, because that
6193 /// will also compute and cache whether the declaration is externally
6194 /// visible, which might change when we attach the initializer.
6195 ///
6196 /// This can only be used if the declaration is known to not be a
6197 /// redeclaration of an internal linkage declaration.
6198 ///
6199 /// For instance:
6200 ///
6201 ///   auto x = []{};
6202 ///
6203 /// Attaching the initializer here makes this declaration not externally
6204 /// visible, because its type has internal linkage.
6205 ///
6206 /// FIXME: This is a hack.
6207 template<typename T>
6208 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6209   if (S.getLangOpts().CPlusPlus) {
6210     // In C++, the overloadable attribute negates the effects of extern "C".
6211     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6212       return false;
6213
6214     // So do CUDA's host/device attributes.
6215     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6216                                  D->template hasAttr<CUDAHostAttr>()))
6217       return false;
6218   }
6219   return D->isExternC();
6220 }
6221
6222 static bool shouldConsiderLinkage(const VarDecl *VD) {
6223   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6224   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
6225     return VD->hasExternalStorage();
6226   if (DC->isFileContext())
6227     return true;
6228   if (DC->isRecord())
6229     return false;
6230   llvm_unreachable("Unexpected context");
6231 }
6232
6233 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6234   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6235   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6236       isa<OMPDeclareReductionDecl>(DC))
6237     return true;
6238   if (DC->isRecord())
6239     return false;
6240   llvm_unreachable("Unexpected context");
6241 }
6242
6243 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6244                           ParsedAttr::Kind Kind) {
6245   // Check decl attributes on the DeclSpec.
6246   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6247     return true;
6248
6249   // Walk the declarator structure, checking decl attributes that were in a type
6250   // position to the decl itself.
6251   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6252     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6253       return true;
6254   }
6255
6256   // Finally, check attributes on the decl itself.
6257   return PD.getAttributes().hasAttribute(Kind);
6258 }
6259
6260 /// Adjust the \c DeclContext for a function or variable that might be a
6261 /// function-local external declaration.
6262 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6263   if (!DC->isFunctionOrMethod())
6264     return false;
6265
6266   // If this is a local extern function or variable declared within a function
6267   // template, don't add it into the enclosing namespace scope until it is
6268   // instantiated; it might have a dependent type right now.
6269   if (DC->isDependentContext())
6270     return true;
6271
6272   // C++11 [basic.link]p7:
6273   //   When a block scope declaration of an entity with linkage is not found to
6274   //   refer to some other declaration, then that entity is a member of the
6275   //   innermost enclosing namespace.
6276   //
6277   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6278   // semantically-enclosing namespace, not a lexically-enclosing one.
6279   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6280     DC = DC->getParent();
6281   return true;
6282 }
6283
6284 /// Returns true if given declaration has external C language linkage.
6285 static bool isDeclExternC(const Decl *D) {
6286   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6287     return FD->isExternC();
6288   if (const auto *VD = dyn_cast<VarDecl>(D))
6289     return VD->isExternC();
6290
6291   llvm_unreachable("Unknown type of decl!");
6292 }
6293
6294 NamedDecl *Sema::ActOnVariableDeclarator(
6295     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6296     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6297     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6298   QualType R = TInfo->getType();
6299   DeclarationName Name = GetNameForDeclarator(D).getName();
6300
6301   IdentifierInfo *II = Name.getAsIdentifierInfo();
6302
6303   if (D.isDecompositionDeclarator()) {
6304     // Take the name of the first declarator as our name for diagnostic
6305     // purposes.
6306     auto &Decomp = D.getDecompositionDeclarator();
6307     if (!Decomp.bindings().empty()) {
6308       II = Decomp.bindings()[0].Name;
6309       Name = II;
6310     }
6311   } else if (!II) {
6312     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6313     return nullptr;
6314   }
6315
6316   if (getLangOpts().OpenCL) {
6317     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6318     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6319     // argument.
6320     if (R->isImageType() || R->isPipeType()) {
6321       Diag(D.getIdentifierLoc(),
6322            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6323           << R;
6324       D.setInvalidType();
6325       return nullptr;
6326     }
6327
6328     // OpenCL v1.2 s6.9.r:
6329     // The event type cannot be used to declare a program scope variable.
6330     // OpenCL v2.0 s6.9.q:
6331     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6332     if (NULL == S->getParent()) {
6333       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6334         Diag(D.getIdentifierLoc(),
6335              diag::err_invalid_type_for_program_scope_var) << R;
6336         D.setInvalidType();
6337         return nullptr;
6338       }
6339     }
6340
6341     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6342     QualType NR = R;
6343     while (NR->isPointerType()) {
6344       if (NR->isFunctionPointerType()) {
6345         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6346         D.setInvalidType();
6347         break;
6348       }
6349       NR = NR->getPointeeType();
6350     }
6351
6352     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6353       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6354       // half array type (unless the cl_khr_fp16 extension is enabled).
6355       if (Context.getBaseElementType(R)->isHalfType()) {
6356         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6357         D.setInvalidType();
6358       }
6359     }
6360
6361     if (R->isSamplerT()) {
6362       // OpenCL v1.2 s6.9.b p4:
6363       // The sampler type cannot be used with the __local and __global address
6364       // space qualifiers.
6365       if (R.getAddressSpace() == LangAS::opencl_local ||
6366           R.getAddressSpace() == LangAS::opencl_global) {
6367         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6368       }
6369
6370       // OpenCL v1.2 s6.12.14.1:
6371       // A global sampler must be declared with either the constant address
6372       // space qualifier or with the const qualifier.
6373       if (DC->isTranslationUnit() &&
6374           !(R.getAddressSpace() == LangAS::opencl_constant ||
6375           R.isConstQualified())) {
6376         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6377         D.setInvalidType();
6378       }
6379     }
6380
6381     // OpenCL v1.2 s6.9.r:
6382     // The event type cannot be used with the __local, __constant and __global
6383     // address space qualifiers.
6384     if (R->isEventT()) {
6385       if (R.getAddressSpace() != LangAS::opencl_private) {
6386         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6387         D.setInvalidType();
6388       }
6389     }
6390
6391     // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not
6392     // supported.  OpenCL C does not support thread_local either, and
6393     // also reject all other thread storage class specifiers.
6394     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6395     if (TSC != TSCS_unspecified) {
6396       bool IsCXX = getLangOpts().OpenCLCPlusPlus;
6397       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6398            diag::err_opencl_unknown_type_specifier)
6399           << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
6400           << DeclSpec::getSpecifierName(TSC) << 1;
6401       D.setInvalidType();
6402       return nullptr;
6403     }
6404   }
6405
6406   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6407   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6408
6409   // dllimport globals without explicit storage class are treated as extern. We
6410   // have to change the storage class this early to get the right DeclContext.
6411   if (SC == SC_None && !DC->isRecord() &&
6412       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6413       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6414     SC = SC_Extern;
6415
6416   DeclContext *OriginalDC = DC;
6417   bool IsLocalExternDecl = SC == SC_Extern &&
6418                            adjustContextForLocalExternDecl(DC);
6419
6420   if (SCSpec == DeclSpec::SCS_mutable) {
6421     // mutable can only appear on non-static class members, so it's always
6422     // an error here
6423     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6424     D.setInvalidType();
6425     SC = SC_None;
6426   }
6427
6428   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6429       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6430                               D.getDeclSpec().getStorageClassSpecLoc())) {
6431     // In C++11, the 'register' storage class specifier is deprecated.
6432     // Suppress the warning in system macros, it's used in macros in some
6433     // popular C system headers, such as in glibc's htonl() macro.
6434     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6435          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6436                                    : diag::warn_deprecated_register)
6437       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6438   }
6439
6440   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6441
6442   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6443     // C99 6.9p2: The storage-class specifiers auto and register shall not
6444     // appear in the declaration specifiers in an external declaration.
6445     // Global Register+Asm is a GNU extension we support.
6446     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6447       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6448       D.setInvalidType();
6449     }
6450   }
6451
6452   bool IsMemberSpecialization = false;
6453   bool IsVariableTemplateSpecialization = false;
6454   bool IsPartialSpecialization = false;
6455   bool IsVariableTemplate = false;
6456   VarDecl *NewVD = nullptr;
6457   VarTemplateDecl *NewTemplate = nullptr;
6458   TemplateParameterList *TemplateParams = nullptr;
6459   if (!getLangOpts().CPlusPlus) {
6460     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6461                             D.getIdentifierLoc(), II,
6462                             R, TInfo, SC);
6463
6464     if (R->getContainedDeducedType())
6465       ParsingInitForAutoVars.insert(NewVD);
6466
6467     if (D.isInvalidType())
6468       NewVD->setInvalidDecl();
6469   } else {
6470     bool Invalid = false;
6471
6472     if (DC->isRecord() && !CurContext->isRecord()) {
6473       // This is an out-of-line definition of a static data member.
6474       switch (SC) {
6475       case SC_None:
6476         break;
6477       case SC_Static:
6478         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6479              diag::err_static_out_of_line)
6480           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6481         break;
6482       case SC_Auto:
6483       case SC_Register:
6484       case SC_Extern:
6485         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6486         // to names of variables declared in a block or to function parameters.
6487         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6488         // of class members
6489
6490         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6491              diag::err_storage_class_for_static_member)
6492           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6493         break;
6494       case SC_PrivateExtern:
6495         llvm_unreachable("C storage class in c++!");
6496       }
6497     }
6498
6499     if (SC == SC_Static && CurContext->isRecord()) {
6500       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6501         if (RD->isLocalClass())
6502           Diag(D.getIdentifierLoc(),
6503                diag::err_static_data_member_not_allowed_in_local_class)
6504             << Name << RD->getDeclName();
6505
6506         // C++98 [class.union]p1: If a union contains a static data member,
6507         // the program is ill-formed. C++11 drops this restriction.
6508         if (RD->isUnion())
6509           Diag(D.getIdentifierLoc(),
6510                getLangOpts().CPlusPlus11
6511                  ? diag::warn_cxx98_compat_static_data_member_in_union
6512                  : diag::ext_static_data_member_in_union) << Name;
6513         // We conservatively disallow static data members in anonymous structs.
6514         else if (!RD->getDeclName())
6515           Diag(D.getIdentifierLoc(),
6516                diag::err_static_data_member_not_allowed_in_anon_struct)
6517             << Name << RD->isUnion();
6518       }
6519     }
6520
6521     // Match up the template parameter lists with the scope specifier, then
6522     // determine whether we have a template or a template specialization.
6523     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6524         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6525         D.getCXXScopeSpec(),
6526         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6527             ? D.getName().TemplateId
6528             : nullptr,
6529         TemplateParamLists,
6530         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6531
6532     if (TemplateParams) {
6533       if (!TemplateParams->size() &&
6534           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6535         // There is an extraneous 'template<>' for this variable. Complain
6536         // about it, but allow the declaration of the variable.
6537         Diag(TemplateParams->getTemplateLoc(),
6538              diag::err_template_variable_noparams)
6539           << II
6540           << SourceRange(TemplateParams->getTemplateLoc(),
6541                          TemplateParams->getRAngleLoc());
6542         TemplateParams = nullptr;
6543       } else {
6544         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6545           // This is an explicit specialization or a partial specialization.
6546           // FIXME: Check that we can declare a specialization here.
6547           IsVariableTemplateSpecialization = true;
6548           IsPartialSpecialization = TemplateParams->size() > 0;
6549         } else { // if (TemplateParams->size() > 0)
6550           // This is a template declaration.
6551           IsVariableTemplate = true;
6552
6553           // Check that we can declare a template here.
6554           if (CheckTemplateDeclScope(S, TemplateParams))
6555             return nullptr;
6556
6557           // Only C++1y supports variable templates (N3651).
6558           Diag(D.getIdentifierLoc(),
6559                getLangOpts().CPlusPlus14
6560                    ? diag::warn_cxx11_compat_variable_template
6561                    : diag::ext_variable_template);
6562         }
6563       }
6564     } else {
6565       assert((Invalid ||
6566               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6567              "should have a 'template<>' for this decl");
6568     }
6569
6570     if (IsVariableTemplateSpecialization) {
6571       SourceLocation TemplateKWLoc =
6572           TemplateParamLists.size() > 0
6573               ? TemplateParamLists[0]->getTemplateLoc()
6574               : SourceLocation();
6575       DeclResult Res = ActOnVarTemplateSpecialization(
6576           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6577           IsPartialSpecialization);
6578       if (Res.isInvalid())
6579         return nullptr;
6580       NewVD = cast<VarDecl>(Res.get());
6581       AddToScope = false;
6582     } else if (D.isDecompositionDeclarator()) {
6583       NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6584                                         D.getIdentifierLoc(), R, TInfo, SC,
6585                                         Bindings);
6586     } else
6587       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6588                               D.getIdentifierLoc(), II, R, TInfo, SC);
6589
6590     // If this is supposed to be a variable template, create it as such.
6591     if (IsVariableTemplate) {
6592       NewTemplate =
6593           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6594                                   TemplateParams, NewVD);
6595       NewVD->setDescribedVarTemplate(NewTemplate);
6596     }
6597
6598     // If this decl has an auto type in need of deduction, make a note of the
6599     // Decl so we can diagnose uses of it in its own initializer.
6600     if (R->getContainedDeducedType())
6601       ParsingInitForAutoVars.insert(NewVD);
6602
6603     if (D.isInvalidType() || Invalid) {
6604       NewVD->setInvalidDecl();
6605       if (NewTemplate)
6606         NewTemplate->setInvalidDecl();
6607     }
6608
6609     SetNestedNameSpecifier(NewVD, D);
6610
6611     // If we have any template parameter lists that don't directly belong to
6612     // the variable (matching the scope specifier), store them.
6613     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6614     if (TemplateParamLists.size() > VDTemplateParamLists)
6615       NewVD->setTemplateParameterListsInfo(
6616           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6617
6618     if (D.getDeclSpec().isConstexprSpecified()) {
6619       NewVD->setConstexpr(true);
6620       // C++1z [dcl.spec.constexpr]p1:
6621       //   A static data member declared with the constexpr specifier is
6622       //   implicitly an inline variable.
6623       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
6624         NewVD->setImplicitlyInline();
6625     }
6626   }
6627
6628   if (D.getDeclSpec().isInlineSpecified()) {
6629     if (!getLangOpts().CPlusPlus) {
6630       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6631           << 0;
6632     } else if (CurContext->isFunctionOrMethod()) {
6633       // 'inline' is not allowed on block scope variable declaration.
6634       Diag(D.getDeclSpec().getInlineSpecLoc(),
6635            diag::err_inline_declaration_block_scope) << Name
6636         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6637     } else {
6638       Diag(D.getDeclSpec().getInlineSpecLoc(),
6639            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6640                                      : diag::ext_inline_variable);
6641       NewVD->setInlineSpecified();
6642     }
6643   }
6644
6645   // Set the lexical context. If the declarator has a C++ scope specifier, the
6646   // lexical context will be different from the semantic context.
6647   NewVD->setLexicalDeclContext(CurContext);
6648   if (NewTemplate)
6649     NewTemplate->setLexicalDeclContext(CurContext);
6650
6651   if (IsLocalExternDecl) {
6652     if (D.isDecompositionDeclarator())
6653       for (auto *B : Bindings)
6654         B->setLocalExternDecl();
6655     else
6656       NewVD->setLocalExternDecl();
6657   }
6658
6659   bool EmitTLSUnsupportedError = false;
6660   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6661     // C++11 [dcl.stc]p4:
6662     //   When thread_local is applied to a variable of block scope the
6663     //   storage-class-specifier static is implied if it does not appear
6664     //   explicitly.
6665     // Core issue: 'static' is not implied if the variable is declared
6666     //   'extern'.
6667     if (NewVD->hasLocalStorage() &&
6668         (SCSpec != DeclSpec::SCS_unspecified ||
6669          TSCS != DeclSpec::TSCS_thread_local ||
6670          !DC->isFunctionOrMethod()))
6671       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6672            diag::err_thread_non_global)
6673         << DeclSpec::getSpecifierName(TSCS);
6674     else if (!Context.getTargetInfo().isTLSSupported()) {
6675       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6676         // Postpone error emission until we've collected attributes required to
6677         // figure out whether it's a host or device variable and whether the
6678         // error should be ignored.
6679         EmitTLSUnsupportedError = true;
6680         // We still need to mark the variable as TLS so it shows up in AST with
6681         // proper storage class for other tools to use even if we're not going
6682         // to emit any code for it.
6683         NewVD->setTSCSpec(TSCS);
6684       } else
6685         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6686              diag::err_thread_unsupported);
6687     } else
6688       NewVD->setTSCSpec(TSCS);
6689   }
6690
6691   // C99 6.7.4p3
6692   //   An inline definition of a function with external linkage shall
6693   //   not contain a definition of a modifiable object with static or
6694   //   thread storage duration...
6695   // We only apply this when the function is required to be defined
6696   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6697   // that a local variable with thread storage duration still has to
6698   // be marked 'static'.  Also note that it's possible to get these
6699   // semantics in C++ using __attribute__((gnu_inline)).
6700   if (SC == SC_Static && S->getFnParent() != nullptr &&
6701       !NewVD->getType().isConstQualified()) {
6702     FunctionDecl *CurFD = getCurFunctionDecl();
6703     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6704       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6705            diag::warn_static_local_in_extern_inline);
6706       MaybeSuggestAddingStaticToDecl(CurFD);
6707     }
6708   }
6709
6710   if (D.getDeclSpec().isModulePrivateSpecified()) {
6711     if (IsVariableTemplateSpecialization)
6712       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6713           << (IsPartialSpecialization ? 1 : 0)
6714           << FixItHint::CreateRemoval(
6715                  D.getDeclSpec().getModulePrivateSpecLoc());
6716     else if (IsMemberSpecialization)
6717       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6718         << 2
6719         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6720     else if (NewVD->hasLocalStorage())
6721       Diag(NewVD->getLocation(), diag::err_module_private_local)
6722         << 0 << NewVD->getDeclName()
6723         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6724         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6725     else {
6726       NewVD->setModulePrivate();
6727       if (NewTemplate)
6728         NewTemplate->setModulePrivate();
6729       for (auto *B : Bindings)
6730         B->setModulePrivate();
6731     }
6732   }
6733
6734   // Handle attributes prior to checking for duplicates in MergeVarDecl
6735   ProcessDeclAttributes(S, NewVD, D);
6736
6737   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6738     if (EmitTLSUnsupportedError &&
6739         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6740          (getLangOpts().OpenMPIsDevice &&
6741           NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6742       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6743            diag::err_thread_unsupported);
6744     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6745     // storage [duration]."
6746     if (SC == SC_None && S->getFnParent() != nullptr &&
6747         (NewVD->hasAttr<CUDASharedAttr>() ||
6748          NewVD->hasAttr<CUDAConstantAttr>())) {
6749       NewVD->setStorageClass(SC_Static);
6750     }
6751   }
6752
6753   // Ensure that dllimport globals without explicit storage class are treated as
6754   // extern. The storage class is set above using parsed attributes. Now we can
6755   // check the VarDecl itself.
6756   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6757          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6758          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6759
6760   // In auto-retain/release, infer strong retension for variables of
6761   // retainable type.
6762   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6763     NewVD->setInvalidDecl();
6764
6765   // Handle GNU asm-label extension (encoded as an attribute).
6766   if (Expr *E = (Expr*)D.getAsmLabel()) {
6767     // The parser guarantees this is a string.
6768     StringLiteral *SE = cast<StringLiteral>(E);
6769     StringRef Label = SE->getString();
6770     if (S->getFnParent() != nullptr) {
6771       switch (SC) {
6772       case SC_None:
6773       case SC_Auto:
6774         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6775         break;
6776       case SC_Register:
6777         // Local Named register
6778         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6779             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6780           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6781         break;
6782       case SC_Static:
6783       case SC_Extern:
6784       case SC_PrivateExtern:
6785         break;
6786       }
6787     } else if (SC == SC_Register) {
6788       // Global Named register
6789       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6790         const auto &TI = Context.getTargetInfo();
6791         bool HasSizeMismatch;
6792
6793         if (!TI.isValidGCCRegisterName(Label))
6794           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6795         else if (!TI.validateGlobalRegisterVariable(Label,
6796                                                     Context.getTypeSize(R),
6797                                                     HasSizeMismatch))
6798           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6799         else if (HasSizeMismatch)
6800           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6801       }
6802
6803       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6804         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6805         NewVD->setInvalidDecl(true);
6806       }
6807     }
6808
6809     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6810                                                 Context, Label, 0));
6811   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6812     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6813       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6814     if (I != ExtnameUndeclaredIdentifiers.end()) {
6815       if (isDeclExternC(NewVD)) {
6816         NewVD->addAttr(I->second);
6817         ExtnameUndeclaredIdentifiers.erase(I);
6818       } else
6819         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6820             << /*Variable*/1 << NewVD;
6821     }
6822   }
6823
6824   // Find the shadowed declaration before filtering for scope.
6825   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6826                                 ? getShadowedDeclaration(NewVD, Previous)
6827                                 : nullptr;
6828
6829   // Don't consider existing declarations that are in a different
6830   // scope and are out-of-semantic-context declarations (if the new
6831   // declaration has linkage).
6832   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6833                        D.getCXXScopeSpec().isNotEmpty() ||
6834                        IsMemberSpecialization ||
6835                        IsVariableTemplateSpecialization);
6836
6837   // Check whether the previous declaration is in the same block scope. This
6838   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6839   if (getLangOpts().CPlusPlus &&
6840       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6841     NewVD->setPreviousDeclInSameBlockScope(
6842         Previous.isSingleResult() && !Previous.isShadowed() &&
6843         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6844
6845   if (!getLangOpts().CPlusPlus) {
6846     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6847   } else {
6848     // If this is an explicit specialization of a static data member, check it.
6849     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6850         CheckMemberSpecialization(NewVD, Previous))
6851       NewVD->setInvalidDecl();
6852
6853     // Merge the decl with the existing one if appropriate.
6854     if (!Previous.empty()) {
6855       if (Previous.isSingleResult() &&
6856           isa<FieldDecl>(Previous.getFoundDecl()) &&
6857           D.getCXXScopeSpec().isSet()) {
6858         // The user tried to define a non-static data member
6859         // out-of-line (C++ [dcl.meaning]p1).
6860         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6861           << D.getCXXScopeSpec().getRange();
6862         Previous.clear();
6863         NewVD->setInvalidDecl();
6864       }
6865     } else if (D.getCXXScopeSpec().isSet()) {
6866       // No previous declaration in the qualifying scope.
6867       Diag(D.getIdentifierLoc(), diag::err_no_member)
6868         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6869         << D.getCXXScopeSpec().getRange();
6870       NewVD->setInvalidDecl();
6871     }
6872
6873     if (!IsVariableTemplateSpecialization)
6874       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6875
6876     if (NewTemplate) {
6877       VarTemplateDecl *PrevVarTemplate =
6878           NewVD->getPreviousDecl()
6879               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6880               : nullptr;
6881
6882       // Check the template parameter list of this declaration, possibly
6883       // merging in the template parameter list from the previous variable
6884       // template declaration.
6885       if (CheckTemplateParameterList(
6886               TemplateParams,
6887               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6888                               : nullptr,
6889               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6890                DC->isDependentContext())
6891                   ? TPC_ClassTemplateMember
6892                   : TPC_VarTemplate))
6893         NewVD->setInvalidDecl();
6894
6895       // If we are providing an explicit specialization of a static variable
6896       // template, make a note of that.
6897       if (PrevVarTemplate &&
6898           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6899         PrevVarTemplate->setMemberSpecialization();
6900     }
6901   }
6902
6903   // Diagnose shadowed variables iff this isn't a redeclaration.
6904   if (ShadowedDecl && !D.isRedeclaration())
6905     CheckShadow(NewVD, ShadowedDecl, Previous);
6906
6907   ProcessPragmaWeak(S, NewVD);
6908
6909   // If this is the first declaration of an extern C variable, update
6910   // the map of such variables.
6911   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6912       isIncompleteDeclExternC(*this, NewVD))
6913     RegisterLocallyScopedExternCDecl(NewVD, S);
6914
6915   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6916     Decl *ManglingContextDecl;
6917     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6918             NewVD->getDeclContext(), ManglingContextDecl)) {
6919       Context.setManglingNumber(
6920           NewVD, MCtx->getManglingNumber(
6921                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6922       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6923     }
6924   }
6925
6926   // Special handling of variable named 'main'.
6927   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6928       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6929       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6930
6931     // C++ [basic.start.main]p3
6932     // A program that declares a variable main at global scope is ill-formed.
6933     if (getLangOpts().CPlusPlus)
6934       Diag(D.getLocStart(), diag::err_main_global_variable);
6935
6936     // In C, and external-linkage variable named main results in undefined
6937     // behavior.
6938     else if (NewVD->hasExternalFormalLinkage())
6939       Diag(D.getLocStart(), diag::warn_main_redefined);
6940   }
6941
6942   if (D.isRedeclaration() && !Previous.empty()) {
6943     NamedDecl *Prev = Previous.getRepresentativeDecl();
6944     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
6945                                    D.isFunctionDefinition());
6946   }
6947
6948   if (NewTemplate) {
6949     if (NewVD->isInvalidDecl())
6950       NewTemplate->setInvalidDecl();
6951     ActOnDocumentableDecl(NewTemplate);
6952     return NewTemplate;
6953   }
6954
6955   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6956     CompleteMemberSpecialization(NewVD, Previous);
6957
6958   return NewVD;
6959 }
6960
6961 /// Enum describing the %select options in diag::warn_decl_shadow.
6962 enum ShadowedDeclKind {
6963   SDK_Local,
6964   SDK_Global,
6965   SDK_StaticMember,
6966   SDK_Field,
6967   SDK_Typedef,
6968   SDK_Using
6969 };
6970
6971 /// Determine what kind of declaration we're shadowing.
6972 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6973                                                 const DeclContext *OldDC) {
6974   if (isa<TypeAliasDecl>(ShadowedDecl))
6975     return SDK_Using;
6976   else if (isa<TypedefDecl>(ShadowedDecl))
6977     return SDK_Typedef;
6978   else if (isa<RecordDecl>(OldDC))
6979     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6980
6981   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6982 }
6983
6984 /// Return the location of the capture if the given lambda captures the given
6985 /// variable \p VD, or an invalid source location otherwise.
6986 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6987                                          const VarDecl *VD) {
6988   for (const Capture &Capture : LSI->Captures) {
6989     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6990       return Capture.getLocation();
6991   }
6992   return SourceLocation();
6993 }
6994
6995 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6996                                      const LookupResult &R) {
6997   // Only diagnose if we're shadowing an unambiguous field or variable.
6998   if (R.getResultKind() != LookupResult::Found)
6999     return false;
7000
7001   // Return false if warning is ignored.
7002   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7003 }
7004
7005 /// Return the declaration shadowed by the given variable \p D, or null
7006 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7007 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7008                                         const LookupResult &R) {
7009   if (!shouldWarnIfShadowedDecl(Diags, R))
7010     return nullptr;
7011
7012   // Don't diagnose declarations at file scope.
7013   if (D->hasGlobalStorage())
7014     return nullptr;
7015
7016   NamedDecl *ShadowedDecl = R.getFoundDecl();
7017   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7018              ? ShadowedDecl
7019              : nullptr;
7020 }
7021
7022 /// Return the declaration shadowed by the given typedef \p D, or null
7023 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7024 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7025                                         const LookupResult &R) {
7026   // Don't warn if typedef declaration is part of a class
7027   if (D->getDeclContext()->isRecord())
7028     return nullptr;
7029
7030   if (!shouldWarnIfShadowedDecl(Diags, R))
7031     return nullptr;
7032
7033   NamedDecl *ShadowedDecl = R.getFoundDecl();
7034   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7035 }
7036
7037 /// Diagnose variable or built-in function shadowing.  Implements
7038 /// -Wshadow.
7039 ///
7040 /// This method is called whenever a VarDecl is added to a "useful"
7041 /// scope.
7042 ///
7043 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7044 /// \param R the lookup of the name
7045 ///
7046 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7047                        const LookupResult &R) {
7048   DeclContext *NewDC = D->getDeclContext();
7049
7050   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7051     // Fields are not shadowed by variables in C++ static methods.
7052     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7053       if (MD->isStatic())
7054         return;
7055
7056     // Fields shadowed by constructor parameters are a special case. Usually
7057     // the constructor initializes the field with the parameter.
7058     if (isa<CXXConstructorDecl>(NewDC))
7059       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7060         // Remember that this was shadowed so we can either warn about its
7061         // modification or its existence depending on warning settings.
7062         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7063         return;
7064       }
7065   }
7066
7067   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7068     if (shadowedVar->isExternC()) {
7069       // For shadowing external vars, make sure that we point to the global
7070       // declaration, not a locally scoped extern declaration.
7071       for (auto I : shadowedVar->redecls())
7072         if (I->isFileVarDecl()) {
7073           ShadowedDecl = I;
7074           break;
7075         }
7076     }
7077
7078   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7079
7080   unsigned WarningDiag = diag::warn_decl_shadow;
7081   SourceLocation CaptureLoc;
7082   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7083       isa<CXXMethodDecl>(NewDC)) {
7084     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7085       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7086         if (RD->getLambdaCaptureDefault() == LCD_None) {
7087           // Try to avoid warnings for lambdas with an explicit capture list.
7088           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7089           // Warn only when the lambda captures the shadowed decl explicitly.
7090           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7091           if (CaptureLoc.isInvalid())
7092             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7093         } else {
7094           // Remember that this was shadowed so we can avoid the warning if the
7095           // shadowed decl isn't captured and the warning settings allow it.
7096           cast<LambdaScopeInfo>(getCurFunction())
7097               ->ShadowingDecls.push_back(
7098                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7099           return;
7100         }
7101       }
7102
7103       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7104         // A variable can't shadow a local variable in an enclosing scope, if
7105         // they are separated by a non-capturing declaration context.
7106         for (DeclContext *ParentDC = NewDC;
7107              ParentDC && !ParentDC->Equals(OldDC);
7108              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7109           // Only block literals, captured statements, and lambda expressions
7110           // can capture; other scopes don't.
7111           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7112               !isLambdaCallOperator(ParentDC)) {
7113             return;
7114           }
7115         }
7116       }
7117     }
7118   }
7119
7120   // Only warn about certain kinds of shadowing for class members.
7121   if (NewDC && NewDC->isRecord()) {
7122     // In particular, don't warn about shadowing non-class members.
7123     if (!OldDC->isRecord())
7124       return;
7125
7126     // TODO: should we warn about static data members shadowing
7127     // static data members from base classes?
7128
7129     // TODO: don't diagnose for inaccessible shadowed members.
7130     // This is hard to do perfectly because we might friend the
7131     // shadowing context, but that's just a false negative.
7132   }
7133
7134
7135   DeclarationName Name = R.getLookupName();
7136
7137   // Emit warning and note.
7138   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7139     return;
7140   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7141   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7142   if (!CaptureLoc.isInvalid())
7143     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7144         << Name << /*explicitly*/ 1;
7145   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7146 }
7147
7148 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7149 /// when these variables are captured by the lambda.
7150 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7151   for (const auto &Shadow : LSI->ShadowingDecls) {
7152     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7153     // Try to avoid the warning when the shadowed decl isn't captured.
7154     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7155     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7156     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7157                                        ? diag::warn_decl_shadow_uncaptured_local
7158                                        : diag::warn_decl_shadow)
7159         << Shadow.VD->getDeclName()
7160         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7161     if (!CaptureLoc.isInvalid())
7162       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7163           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7164     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7165   }
7166 }
7167
7168 /// Check -Wshadow without the advantage of a previous lookup.
7169 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7170   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7171     return;
7172
7173   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7174                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7175   LookupName(R, S);
7176   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7177     CheckShadow(D, ShadowedDecl, R);
7178 }
7179
7180 /// Check if 'E', which is an expression that is about to be modified, refers
7181 /// to a constructor parameter that shadows a field.
7182 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7183   // Quickly ignore expressions that can't be shadowing ctor parameters.
7184   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7185     return;
7186   E = E->IgnoreParenImpCasts();
7187   auto *DRE = dyn_cast<DeclRefExpr>(E);
7188   if (!DRE)
7189     return;
7190   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7191   auto I = ShadowingDecls.find(D);
7192   if (I == ShadowingDecls.end())
7193     return;
7194   const NamedDecl *ShadowedDecl = I->second;
7195   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7196   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7197   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7198   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7199
7200   // Avoid issuing multiple warnings about the same decl.
7201   ShadowingDecls.erase(I);
7202 }
7203
7204 /// Check for conflict between this global or extern "C" declaration and
7205 /// previous global or extern "C" declarations. This is only used in C++.
7206 template<typename T>
7207 static bool checkGlobalOrExternCConflict(
7208     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7209   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7210   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7211
7212   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7213     // The common case: this global doesn't conflict with any extern "C"
7214     // declaration.
7215     return false;
7216   }
7217
7218   if (Prev) {
7219     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7220       // Both the old and new declarations have C language linkage. This is a
7221       // redeclaration.
7222       Previous.clear();
7223       Previous.addDecl(Prev);
7224       return true;
7225     }
7226
7227     // This is a global, non-extern "C" declaration, and there is a previous
7228     // non-global extern "C" declaration. Diagnose if this is a variable
7229     // declaration.
7230     if (!isa<VarDecl>(ND))
7231       return false;
7232   } else {
7233     // The declaration is extern "C". Check for any declaration in the
7234     // translation unit which might conflict.
7235     if (IsGlobal) {
7236       // We have already performed the lookup into the translation unit.
7237       IsGlobal = false;
7238       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7239            I != E; ++I) {
7240         if (isa<VarDecl>(*I)) {
7241           Prev = *I;
7242           break;
7243         }
7244       }
7245     } else {
7246       DeclContext::lookup_result R =
7247           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7248       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7249            I != E; ++I) {
7250         if (isa<VarDecl>(*I)) {
7251           Prev = *I;
7252           break;
7253         }
7254         // FIXME: If we have any other entity with this name in global scope,
7255         // the declaration is ill-formed, but that is a defect: it breaks the
7256         // 'stat' hack, for instance. Only variables can have mangled name
7257         // clashes with extern "C" declarations, so only they deserve a
7258         // diagnostic.
7259       }
7260     }
7261
7262     if (!Prev)
7263       return false;
7264   }
7265
7266   // Use the first declaration's location to ensure we point at something which
7267   // is lexically inside an extern "C" linkage-spec.
7268   assert(Prev && "should have found a previous declaration to diagnose");
7269   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7270     Prev = FD->getFirstDecl();
7271   else
7272     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7273
7274   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7275     << IsGlobal << ND;
7276   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7277     << IsGlobal;
7278   return false;
7279 }
7280
7281 /// Apply special rules for handling extern "C" declarations. Returns \c true
7282 /// if we have found that this is a redeclaration of some prior entity.
7283 ///
7284 /// Per C++ [dcl.link]p6:
7285 ///   Two declarations [for a function or variable] with C language linkage
7286 ///   with the same name that appear in different scopes refer to the same
7287 ///   [entity]. An entity with C language linkage shall not be declared with
7288 ///   the same name as an entity in global scope.
7289 template<typename T>
7290 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7291                                                   LookupResult &Previous) {
7292   if (!S.getLangOpts().CPlusPlus) {
7293     // In C, when declaring a global variable, look for a corresponding 'extern'
7294     // variable declared in function scope. We don't need this in C++, because
7295     // we find local extern decls in the surrounding file-scope DeclContext.
7296     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7297       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7298         Previous.clear();
7299         Previous.addDecl(Prev);
7300         return true;
7301       }
7302     }
7303     return false;
7304   }
7305
7306   // A declaration in the translation unit can conflict with an extern "C"
7307   // declaration.
7308   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7309     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7310
7311   // An extern "C" declaration can conflict with a declaration in the
7312   // translation unit or can be a redeclaration of an extern "C" declaration
7313   // in another scope.
7314   if (isIncompleteDeclExternC(S,ND))
7315     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7316
7317   // Neither global nor extern "C": nothing to do.
7318   return false;
7319 }
7320
7321 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7322   // If the decl is already known invalid, don't check it.
7323   if (NewVD->isInvalidDecl())
7324     return;
7325
7326   QualType T = NewVD->getType();
7327
7328   // Defer checking an 'auto' type until its initializer is attached.
7329   if (T->isUndeducedType())
7330     return;
7331
7332   if (NewVD->hasAttrs())
7333     CheckAlignasUnderalignment(NewVD);
7334
7335   if (T->isObjCObjectType()) {
7336     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7337       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7338     T = Context.getObjCObjectPointerType(T);
7339     NewVD->setType(T);
7340   }
7341
7342   // Emit an error if an address space was applied to decl with local storage.
7343   // This includes arrays of objects with address space qualifiers, but not
7344   // automatic variables that point to other address spaces.
7345   // ISO/IEC TR 18037 S5.1.2
7346   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7347       T.getAddressSpace() != LangAS::Default) {
7348     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7349     NewVD->setInvalidDecl();
7350     return;
7351   }
7352
7353   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7354   // scope.
7355   if (getLangOpts().OpenCLVersion == 120 &&
7356       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7357       NewVD->isStaticLocal()) {
7358     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7359     NewVD->setInvalidDecl();
7360     return;
7361   }
7362
7363   if (getLangOpts().OpenCL) {
7364     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7365     if (NewVD->hasAttr<BlocksAttr>()) {
7366       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7367       return;
7368     }
7369
7370     if (T->isBlockPointerType()) {
7371       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7372       // can't use 'extern' storage class.
7373       if (!T.isConstQualified()) {
7374         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7375             << 0 /*const*/;
7376         NewVD->setInvalidDecl();
7377         return;
7378       }
7379       if (NewVD->hasExternalStorage()) {
7380         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7381         NewVD->setInvalidDecl();
7382         return;
7383       }
7384     }
7385     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7386     // __constant address space.
7387     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7388     // variables inside a function can also be declared in the global
7389     // address space.
7390     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7391         NewVD->hasExternalStorage()) {
7392       if (!T->isSamplerT() &&
7393           !(T.getAddressSpace() == LangAS::opencl_constant ||
7394             (T.getAddressSpace() == LangAS::opencl_global &&
7395              getLangOpts().OpenCLVersion == 200))) {
7396         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7397         if (getLangOpts().OpenCLVersion == 200)
7398           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7399               << Scope << "global or constant";
7400         else
7401           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7402               << Scope << "constant";
7403         NewVD->setInvalidDecl();
7404         return;
7405       }
7406     } else {
7407       if (T.getAddressSpace() == LangAS::opencl_global) {
7408         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7409             << 1 /*is any function*/ << "global";
7410         NewVD->setInvalidDecl();
7411         return;
7412       }
7413       if (T.getAddressSpace() == LangAS::opencl_constant ||
7414           T.getAddressSpace() == LangAS::opencl_local) {
7415         FunctionDecl *FD = getCurFunctionDecl();
7416         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7417         // in functions.
7418         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7419           if (T.getAddressSpace() == LangAS::opencl_constant)
7420             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7421                 << 0 /*non-kernel only*/ << "constant";
7422           else
7423             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7424                 << 0 /*non-kernel only*/ << "local";
7425           NewVD->setInvalidDecl();
7426           return;
7427         }
7428         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7429         // in the outermost scope of a kernel function.
7430         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7431           if (!getCurScope()->isFunctionScope()) {
7432             if (T.getAddressSpace() == LangAS::opencl_constant)
7433               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7434                   << "constant";
7435             else
7436               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7437                   << "local";
7438             NewVD->setInvalidDecl();
7439             return;
7440           }
7441         }
7442       } else if (T.getAddressSpace() != LangAS::opencl_private) {
7443         // Do not allow other address spaces on automatic variable.
7444         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7445         NewVD->setInvalidDecl();
7446         return;
7447       }
7448     }
7449   }
7450
7451   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7452       && !NewVD->hasAttr<BlocksAttr>()) {
7453     if (getLangOpts().getGC() != LangOptions::NonGC)
7454       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7455     else {
7456       assert(!getLangOpts().ObjCAutoRefCount);
7457       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7458     }
7459   }
7460
7461   bool isVM = T->isVariablyModifiedType();
7462   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7463       NewVD->hasAttr<BlocksAttr>())
7464     setFunctionHasBranchProtectedScope();
7465
7466   if ((isVM && NewVD->hasLinkage()) ||
7467       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7468     bool SizeIsNegative;
7469     llvm::APSInt Oversized;
7470     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7471         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7472     QualType FixedT;
7473     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7474       FixedT = FixedTInfo->getType();
7475     else if (FixedTInfo) {
7476       // Type and type-as-written are canonically different. We need to fix up
7477       // both types separately.
7478       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7479                                                    Oversized);
7480     }
7481     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7482       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7483       // FIXME: This won't give the correct result for
7484       // int a[10][n];
7485       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7486
7487       if (NewVD->isFileVarDecl())
7488         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7489         << SizeRange;
7490       else if (NewVD->isStaticLocal())
7491         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7492         << SizeRange;
7493       else
7494         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7495         << SizeRange;
7496       NewVD->setInvalidDecl();
7497       return;
7498     }
7499
7500     if (!FixedTInfo) {
7501       if (NewVD->isFileVarDecl())
7502         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7503       else
7504         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7505       NewVD->setInvalidDecl();
7506       return;
7507     }
7508
7509     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7510     NewVD->setType(FixedT);
7511     NewVD->setTypeSourceInfo(FixedTInfo);
7512   }
7513
7514   if (T->isVoidType()) {
7515     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7516     //                    of objects and functions.
7517     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7518       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7519         << T;
7520       NewVD->setInvalidDecl();
7521       return;
7522     }
7523   }
7524
7525   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7526     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7527     NewVD->setInvalidDecl();
7528     return;
7529   }
7530
7531   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7532     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7533     NewVD->setInvalidDecl();
7534     return;
7535   }
7536
7537   if (NewVD->isConstexpr() && !T->isDependentType() &&
7538       RequireLiteralType(NewVD->getLocation(), T,
7539                          diag::err_constexpr_var_non_literal)) {
7540     NewVD->setInvalidDecl();
7541     return;
7542   }
7543 }
7544
7545 /// Perform semantic checking on a newly-created variable
7546 /// declaration.
7547 ///
7548 /// This routine performs all of the type-checking required for a
7549 /// variable declaration once it has been built. It is used both to
7550 /// check variables after they have been parsed and their declarators
7551 /// have been translated into a declaration, and to check variables
7552 /// that have been instantiated from a template.
7553 ///
7554 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7555 ///
7556 /// Returns true if the variable declaration is a redeclaration.
7557 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7558   CheckVariableDeclarationType(NewVD);
7559
7560   // If the decl is already known invalid, don't check it.
7561   if (NewVD->isInvalidDecl())
7562     return false;
7563
7564   // If we did not find anything by this name, look for a non-visible
7565   // extern "C" declaration with the same name.
7566   if (Previous.empty() &&
7567       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7568     Previous.setShadowed();
7569
7570   if (!Previous.empty()) {
7571     MergeVarDecl(NewVD, Previous);
7572     return true;
7573   }
7574   return false;
7575 }
7576
7577 namespace {
7578 struct FindOverriddenMethod {
7579   Sema *S;
7580   CXXMethodDecl *Method;
7581
7582   /// Member lookup function that determines whether a given C++
7583   /// method overrides a method in a base class, to be used with
7584   /// CXXRecordDecl::lookupInBases().
7585   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7586     RecordDecl *BaseRecord =
7587         Specifier->getType()->getAs<RecordType>()->getDecl();
7588
7589     DeclarationName Name = Method->getDeclName();
7590
7591     // FIXME: Do we care about other names here too?
7592     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7593       // We really want to find the base class destructor here.
7594       QualType T = S->Context.getTypeDeclType(BaseRecord);
7595       CanQualType CT = S->Context.getCanonicalType(T);
7596
7597       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7598     }
7599
7600     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7601          Path.Decls = Path.Decls.slice(1)) {
7602       NamedDecl *D = Path.Decls.front();
7603       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7604         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7605           return true;
7606       }
7607     }
7608
7609     return false;
7610   }
7611 };
7612
7613 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7614 } // end anonymous namespace
7615
7616 /// Report an error regarding overriding, along with any relevant
7617 /// overridden methods.
7618 ///
7619 /// \param DiagID the primary error to report.
7620 /// \param MD the overriding method.
7621 /// \param OEK which overrides to include as notes.
7622 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7623                             OverrideErrorKind OEK = OEK_All) {
7624   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7625   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7626     // This check (& the OEK parameter) could be replaced by a predicate, but
7627     // without lambdas that would be overkill. This is still nicer than writing
7628     // out the diag loop 3 times.
7629     if ((OEK == OEK_All) ||
7630         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7631         (OEK == OEK_Deleted && O->isDeleted()))
7632       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7633   }
7634 }
7635
7636 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7637 /// and if so, check that it's a valid override and remember it.
7638 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7639   // Look for methods in base classes that this method might override.
7640   CXXBasePaths Paths;
7641   FindOverriddenMethod FOM;
7642   FOM.Method = MD;
7643   FOM.S = this;
7644   bool hasDeletedOverridenMethods = false;
7645   bool hasNonDeletedOverridenMethods = false;
7646   bool AddedAny = false;
7647   if (DC->lookupInBases(FOM, Paths)) {
7648     for (auto *I : Paths.found_decls()) {
7649       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7650         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7651         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7652             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7653             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7654             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7655           hasDeletedOverridenMethods |= OldMD->isDeleted();
7656           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7657           AddedAny = true;
7658         }
7659       }
7660     }
7661   }
7662
7663   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7664     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7665   }
7666   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7667     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7668   }
7669
7670   return AddedAny;
7671 }
7672
7673 namespace {
7674   // Struct for holding all of the extra arguments needed by
7675   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7676   struct ActOnFDArgs {
7677     Scope *S;
7678     Declarator &D;
7679     MultiTemplateParamsArg TemplateParamLists;
7680     bool AddToScope;
7681   };
7682 } // end anonymous namespace
7683
7684 namespace {
7685
7686 // Callback to only accept typo corrections that have a non-zero edit distance.
7687 // Also only accept corrections that have the same parent decl.
7688 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7689  public:
7690   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7691                             CXXRecordDecl *Parent)
7692       : Context(Context), OriginalFD(TypoFD),
7693         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7694
7695   bool ValidateCandidate(const TypoCorrection &candidate) override {
7696     if (candidate.getEditDistance() == 0)
7697       return false;
7698
7699     SmallVector<unsigned, 1> MismatchedParams;
7700     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7701                                           CDeclEnd = candidate.end();
7702          CDecl != CDeclEnd; ++CDecl) {
7703       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7704
7705       if (FD && !FD->hasBody() &&
7706           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7707         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7708           CXXRecordDecl *Parent = MD->getParent();
7709           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7710             return true;
7711         } else if (!ExpectedParent) {
7712           return true;
7713         }
7714       }
7715     }
7716
7717     return false;
7718   }
7719
7720  private:
7721   ASTContext &Context;
7722   FunctionDecl *OriginalFD;
7723   CXXRecordDecl *ExpectedParent;
7724 };
7725
7726 } // end anonymous namespace
7727
7728 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7729   TypoCorrectedFunctionDefinitions.insert(F);
7730 }
7731
7732 /// Generate diagnostics for an invalid function redeclaration.
7733 ///
7734 /// This routine handles generating the diagnostic messages for an invalid
7735 /// function redeclaration, including finding possible similar declarations
7736 /// or performing typo correction if there are no previous declarations with
7737 /// the same name.
7738 ///
7739 /// Returns a NamedDecl iff typo correction was performed and substituting in
7740 /// the new declaration name does not cause new errors.
7741 static NamedDecl *DiagnoseInvalidRedeclaration(
7742     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7743     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7744   DeclarationName Name = NewFD->getDeclName();
7745   DeclContext *NewDC = NewFD->getDeclContext();
7746   SmallVector<unsigned, 1> MismatchedParams;
7747   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7748   TypoCorrection Correction;
7749   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7750   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7751                                    : diag::err_member_decl_does_not_match;
7752   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7753                     IsLocalFriend ? Sema::LookupLocalFriendName
7754                                   : Sema::LookupOrdinaryName,
7755                     Sema::ForVisibleRedeclaration);
7756
7757   NewFD->setInvalidDecl();
7758   if (IsLocalFriend)
7759     SemaRef.LookupName(Prev, S);
7760   else
7761     SemaRef.LookupQualifiedName(Prev, NewDC);
7762   assert(!Prev.isAmbiguous() &&
7763          "Cannot have an ambiguity in previous-declaration lookup");
7764   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7765   if (!Prev.empty()) {
7766     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7767          Func != FuncEnd; ++Func) {
7768       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7769       if (FD &&
7770           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7771         // Add 1 to the index so that 0 can mean the mismatch didn't
7772         // involve a parameter
7773         unsigned ParamNum =
7774             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7775         NearMatches.push_back(std::make_pair(FD, ParamNum));
7776       }
7777     }
7778   // If the qualified name lookup yielded nothing, try typo correction
7779   } else if ((Correction = SemaRef.CorrectTypo(
7780                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7781                   &ExtraArgs.D.getCXXScopeSpec(),
7782                   llvm::make_unique<DifferentNameValidatorCCC>(
7783                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7784                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7785     // Set up everything for the call to ActOnFunctionDeclarator
7786     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7787                               ExtraArgs.D.getIdentifierLoc());
7788     Previous.clear();
7789     Previous.setLookupName(Correction.getCorrection());
7790     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7791                                     CDeclEnd = Correction.end();
7792          CDecl != CDeclEnd; ++CDecl) {
7793       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7794       if (FD && !FD->hasBody() &&
7795           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7796         Previous.addDecl(FD);
7797       }
7798     }
7799     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7800
7801     NamedDecl *Result;
7802     // Retry building the function declaration with the new previous
7803     // declarations, and with errors suppressed.
7804     {
7805       // Trap errors.
7806       Sema::SFINAETrap Trap(SemaRef);
7807
7808       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7809       // pieces need to verify the typo-corrected C++ declaration and hopefully
7810       // eliminate the need for the parameter pack ExtraArgs.
7811       Result = SemaRef.ActOnFunctionDeclarator(
7812           ExtraArgs.S, ExtraArgs.D,
7813           Correction.getCorrectionDecl()->getDeclContext(),
7814           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7815           ExtraArgs.AddToScope);
7816
7817       if (Trap.hasErrorOccurred())
7818         Result = nullptr;
7819     }
7820
7821     if (Result) {
7822       // Determine which correction we picked.
7823       Decl *Canonical = Result->getCanonicalDecl();
7824       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7825            I != E; ++I)
7826         if ((*I)->getCanonicalDecl() == Canonical)
7827           Correction.setCorrectionDecl(*I);
7828
7829       // Let Sema know about the correction.
7830       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7831       SemaRef.diagnoseTypo(
7832           Correction,
7833           SemaRef.PDiag(IsLocalFriend
7834                           ? diag::err_no_matching_local_friend_suggest
7835                           : diag::err_member_decl_does_not_match_suggest)
7836             << Name << NewDC << IsDefinition);
7837       return Result;
7838     }
7839
7840     // Pretend the typo correction never occurred
7841     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7842                               ExtraArgs.D.getIdentifierLoc());
7843     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7844     Previous.clear();
7845     Previous.setLookupName(Name);
7846   }
7847
7848   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7849       << Name << NewDC << IsDefinition << NewFD->getLocation();
7850
7851   bool NewFDisConst = false;
7852   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7853     NewFDisConst = NewMD->isConst();
7854
7855   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7856        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7857        NearMatch != NearMatchEnd; ++NearMatch) {
7858     FunctionDecl *FD = NearMatch->first;
7859     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7860     bool FDisConst = MD && MD->isConst();
7861     bool IsMember = MD || !IsLocalFriend;
7862
7863     // FIXME: These notes are poorly worded for the local friend case.
7864     if (unsigned Idx = NearMatch->second) {
7865       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7866       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7867       if (Loc.isInvalid()) Loc = FD->getLocation();
7868       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7869                                  : diag::note_local_decl_close_param_match)
7870         << Idx << FDParam->getType()
7871         << NewFD->getParamDecl(Idx - 1)->getType();
7872     } else if (FDisConst != NewFDisConst) {
7873       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7874           << NewFDisConst << FD->getSourceRange().getEnd();
7875     } else
7876       SemaRef.Diag(FD->getLocation(),
7877                    IsMember ? diag::note_member_def_close_match
7878                             : diag::note_local_decl_close_match);
7879   }
7880   return nullptr;
7881 }
7882
7883 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7884   switch (D.getDeclSpec().getStorageClassSpec()) {
7885   default: llvm_unreachable("Unknown storage class!");
7886   case DeclSpec::SCS_auto:
7887   case DeclSpec::SCS_register:
7888   case DeclSpec::SCS_mutable:
7889     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7890                  diag::err_typecheck_sclass_func);
7891     D.getMutableDeclSpec().ClearStorageClassSpecs();
7892     D.setInvalidType();
7893     break;
7894   case DeclSpec::SCS_unspecified: break;
7895   case DeclSpec::SCS_extern:
7896     if (D.getDeclSpec().isExternInLinkageSpec())
7897       return SC_None;
7898     return SC_Extern;
7899   case DeclSpec::SCS_static: {
7900     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7901       // C99 6.7.1p5:
7902       //   The declaration of an identifier for a function that has
7903       //   block scope shall have no explicit storage-class specifier
7904       //   other than extern
7905       // See also (C++ [dcl.stc]p4).
7906       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7907                    diag::err_static_block_func);
7908       break;
7909     } else
7910       return SC_Static;
7911   }
7912   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7913   }
7914
7915   // No explicit storage class has already been returned
7916   return SC_None;
7917 }
7918
7919 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7920                                            DeclContext *DC, QualType &R,
7921                                            TypeSourceInfo *TInfo,
7922                                            StorageClass SC,
7923                                            bool &IsVirtualOkay) {
7924   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7925   DeclarationName Name = NameInfo.getName();
7926
7927   FunctionDecl *NewFD = nullptr;
7928   bool isInline = D.getDeclSpec().isInlineSpecified();
7929
7930   if (!SemaRef.getLangOpts().CPlusPlus) {
7931     // Determine whether the function was written with a
7932     // prototype. This true when:
7933     //   - there is a prototype in the declarator, or
7934     //   - the type R of the function is some kind of typedef or other non-
7935     //     attributed reference to a type name (which eventually refers to a
7936     //     function type).
7937     bool HasPrototype =
7938       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7939       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7940
7941     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7942                                  D.getLocStart(), NameInfo, R,
7943                                  TInfo, SC, isInline,
7944                                  HasPrototype, false);
7945     if (D.isInvalidType())
7946       NewFD->setInvalidDecl();
7947
7948     return NewFD;
7949   }
7950
7951   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7952   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7953
7954   // Check that the return type is not an abstract class type.
7955   // For record types, this is done by the AbstractClassUsageDiagnoser once
7956   // the class has been completely parsed.
7957   if (!DC->isRecord() &&
7958       SemaRef.RequireNonAbstractType(
7959           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7960           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7961     D.setInvalidType();
7962
7963   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7964     // This is a C++ constructor declaration.
7965     assert(DC->isRecord() &&
7966            "Constructors can only be declared in a member context");
7967
7968     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7969     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7970                                       D.getLocStart(), NameInfo,
7971                                       R, TInfo, isExplicit, isInline,
7972                                       /*isImplicitlyDeclared=*/false,
7973                                       isConstexpr);
7974
7975   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7976     // This is a C++ destructor declaration.
7977     if (DC->isRecord()) {
7978       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7979       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7980       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7981                                         SemaRef.Context, Record,
7982                                         D.getLocStart(),
7983                                         NameInfo, R, TInfo, isInline,
7984                                         /*isImplicitlyDeclared=*/false);
7985
7986       // If the class is complete, then we now create the implicit exception
7987       // specification. If the class is incomplete or dependent, we can't do
7988       // it yet.
7989       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7990           Record->getDefinition() && !Record->isBeingDefined() &&
7991           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7992         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7993       }
7994
7995       IsVirtualOkay = true;
7996       return NewDD;
7997
7998     } else {
7999       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8000       D.setInvalidType();
8001
8002       // Create a FunctionDecl to satisfy the function definition parsing
8003       // code path.
8004       return FunctionDecl::Create(SemaRef.Context, DC,
8005                                   D.getLocStart(),
8006                                   D.getIdentifierLoc(), Name, R, TInfo,
8007                                   SC, isInline,
8008                                   /*hasPrototype=*/true, isConstexpr);
8009     }
8010
8011   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8012     if (!DC->isRecord()) {
8013       SemaRef.Diag(D.getIdentifierLoc(),
8014            diag::err_conv_function_not_member);
8015       return nullptr;
8016     }
8017
8018     SemaRef.CheckConversionDeclarator(D, R, SC);
8019     IsVirtualOkay = true;
8020     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
8021                                      D.getLocStart(), NameInfo,
8022                                      R, TInfo, isInline, isExplicit,
8023                                      isConstexpr, SourceLocation());
8024
8025   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8026     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8027
8028     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
8029                                          isExplicit, NameInfo, R, TInfo,
8030                                          D.getLocEnd());
8031   } else if (DC->isRecord()) {
8032     // If the name of the function is the same as the name of the record,
8033     // then this must be an invalid constructor that has a return type.
8034     // (The parser checks for a return type and makes the declarator a
8035     // constructor if it has no return type).
8036     if (Name.getAsIdentifierInfo() &&
8037         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8038       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8039         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8040         << SourceRange(D.getIdentifierLoc());
8041       return nullptr;
8042     }
8043
8044     // This is a C++ method declaration.
8045     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
8046                                                cast<CXXRecordDecl>(DC),
8047                                                D.getLocStart(), NameInfo, R,
8048                                                TInfo, SC, isInline,
8049                                                isConstexpr, SourceLocation());
8050     IsVirtualOkay = !Ret->isStatic();
8051     return Ret;
8052   } else {
8053     bool isFriend =
8054         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8055     if (!isFriend && SemaRef.CurContext->isRecord())
8056       return nullptr;
8057
8058     // Determine whether the function was written with a
8059     // prototype. This true when:
8060     //   - we're in C++ (where every function has a prototype),
8061     return FunctionDecl::Create(SemaRef.Context, DC,
8062                                 D.getLocStart(),
8063                                 NameInfo, R, TInfo, SC, isInline,
8064                                 true/*HasPrototype*/, isConstexpr);
8065   }
8066 }
8067
8068 enum OpenCLParamType {
8069   ValidKernelParam,
8070   PtrPtrKernelParam,
8071   PtrKernelParam,
8072   InvalidAddrSpacePtrKernelParam,
8073   InvalidKernelParam,
8074   RecordKernelParam
8075 };
8076
8077 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8078   // Size dependent types are just typedefs to normal integer types
8079   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8080   // integers other than by their names.
8081   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8082
8083   // Remove typedefs one by one until we reach a typedef
8084   // for a size dependent type.
8085   QualType DesugaredTy = Ty;
8086   do {
8087     ArrayRef<StringRef> Names(SizeTypeNames);
8088     auto Match =
8089         std::find(Names.begin(), Names.end(), DesugaredTy.getAsString());
8090     if (Names.end() != Match)
8091       return true;
8092
8093     Ty = DesugaredTy;
8094     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8095   } while (DesugaredTy != Ty);
8096
8097   return false;
8098 }
8099
8100 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8101   if (PT->isPointerType()) {
8102     QualType PointeeType = PT->getPointeeType();
8103     if (PointeeType->isPointerType())
8104       return PtrPtrKernelParam;
8105     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8106         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8107         PointeeType.getAddressSpace() == LangAS::Default)
8108       return InvalidAddrSpacePtrKernelParam;
8109     return PtrKernelParam;
8110   }
8111
8112   // OpenCL v1.2 s6.9.k:
8113   // Arguments to kernel functions in a program cannot be declared with the
8114   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8115   // uintptr_t or a struct and/or union that contain fields declared to be one
8116   // of these built-in scalar types.
8117   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8118     return InvalidKernelParam;
8119
8120   if (PT->isImageType())
8121     return PtrKernelParam;
8122
8123   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8124     return InvalidKernelParam;
8125
8126   // OpenCL extension spec v1.2 s9.5:
8127   // This extension adds support for half scalar and vector types as built-in
8128   // types that can be used for arithmetic operations, conversions etc.
8129   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8130     return InvalidKernelParam;
8131
8132   if (PT->isRecordType())
8133     return RecordKernelParam;
8134
8135   // Look into an array argument to check if it has a forbidden type.
8136   if (PT->isArrayType()) {
8137     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8138     // Call ourself to check an underlying type of an array. Since the
8139     // getPointeeOrArrayElementType returns an innermost type which is not an
8140     // array, this recusive call only happens once.
8141     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8142   }
8143
8144   return ValidKernelParam;
8145 }
8146
8147 static void checkIsValidOpenCLKernelParameter(
8148   Sema &S,
8149   Declarator &D,
8150   ParmVarDecl *Param,
8151   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8152   QualType PT = Param->getType();
8153
8154   // Cache the valid types we encounter to avoid rechecking structs that are
8155   // used again
8156   if (ValidTypes.count(PT.getTypePtr()))
8157     return;
8158
8159   switch (getOpenCLKernelParameterType(S, PT)) {
8160   case PtrPtrKernelParam:
8161     // OpenCL v1.2 s6.9.a:
8162     // A kernel function argument cannot be declared as a
8163     // pointer to a pointer type.
8164     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8165     D.setInvalidType();
8166     return;
8167
8168   case InvalidAddrSpacePtrKernelParam:
8169     // OpenCL v1.0 s6.5:
8170     // __kernel function arguments declared to be a pointer of a type can point
8171     // to one of the following address spaces only : __global, __local or
8172     // __constant.
8173     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8174     D.setInvalidType();
8175     return;
8176
8177     // OpenCL v1.2 s6.9.k:
8178     // Arguments to kernel functions in a program cannot be declared with the
8179     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8180     // uintptr_t or a struct and/or union that contain fields declared to be
8181     // one of these built-in scalar types.
8182
8183   case InvalidKernelParam:
8184     // OpenCL v1.2 s6.8 n:
8185     // A kernel function argument cannot be declared
8186     // of event_t type.
8187     // Do not diagnose half type since it is diagnosed as invalid argument
8188     // type for any function elsewhere.
8189     if (!PT->isHalfType()) {
8190       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8191
8192       // Explain what typedefs are involved.
8193       const TypedefType *Typedef = nullptr;
8194       while ((Typedef = PT->getAs<TypedefType>())) {
8195         SourceLocation Loc = Typedef->getDecl()->getLocation();
8196         // SourceLocation may be invalid for a built-in type.
8197         if (Loc.isValid())
8198           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8199         PT = Typedef->desugar();
8200       }
8201     }
8202
8203     D.setInvalidType();
8204     return;
8205
8206   case PtrKernelParam:
8207   case ValidKernelParam:
8208     ValidTypes.insert(PT.getTypePtr());
8209     return;
8210
8211   case RecordKernelParam:
8212     break;
8213   }
8214
8215   // Track nested structs we will inspect
8216   SmallVector<const Decl *, 4> VisitStack;
8217
8218   // Track where we are in the nested structs. Items will migrate from
8219   // VisitStack to HistoryStack as we do the DFS for bad field.
8220   SmallVector<const FieldDecl *, 4> HistoryStack;
8221   HistoryStack.push_back(nullptr);
8222
8223   // At this point we already handled everything except of a RecordType or
8224   // an ArrayType of a RecordType.
8225   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8226   const RecordType *RecTy =
8227       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8228   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8229
8230   VisitStack.push_back(RecTy->getDecl());
8231   assert(VisitStack.back() && "First decl null?");
8232
8233   do {
8234     const Decl *Next = VisitStack.pop_back_val();
8235     if (!Next) {
8236       assert(!HistoryStack.empty());
8237       // Found a marker, we have gone up a level
8238       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8239         ValidTypes.insert(Hist->getType().getTypePtr());
8240
8241       continue;
8242     }
8243
8244     // Adds everything except the original parameter declaration (which is not a
8245     // field itself) to the history stack.
8246     const RecordDecl *RD;
8247     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8248       HistoryStack.push_back(Field);
8249
8250       QualType FieldTy = Field->getType();
8251       // Other field types (known to be valid or invalid) are handled while we
8252       // walk around RecordDecl::fields().
8253       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8254              "Unexpected type.");
8255       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8256
8257       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8258     } else {
8259       RD = cast<RecordDecl>(Next);
8260     }
8261
8262     // Add a null marker so we know when we've gone back up a level
8263     VisitStack.push_back(nullptr);
8264
8265     for (const auto *FD : RD->fields()) {
8266       QualType QT = FD->getType();
8267
8268       if (ValidTypes.count(QT.getTypePtr()))
8269         continue;
8270
8271       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8272       if (ParamType == ValidKernelParam)
8273         continue;
8274
8275       if (ParamType == RecordKernelParam) {
8276         VisitStack.push_back(FD);
8277         continue;
8278       }
8279
8280       // OpenCL v1.2 s6.9.p:
8281       // Arguments to kernel functions that are declared to be a struct or union
8282       // do not allow OpenCL objects to be passed as elements of the struct or
8283       // union.
8284       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8285           ParamType == InvalidAddrSpacePtrKernelParam) {
8286         S.Diag(Param->getLocation(),
8287                diag::err_record_with_pointers_kernel_param)
8288           << PT->isUnionType()
8289           << PT;
8290       } else {
8291         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8292       }
8293
8294       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8295           << OrigRecDecl->getDeclName();
8296
8297       // We have an error, now let's go back up through history and show where
8298       // the offending field came from
8299       for (ArrayRef<const FieldDecl *>::const_iterator
8300                I = HistoryStack.begin() + 1,
8301                E = HistoryStack.end();
8302            I != E; ++I) {
8303         const FieldDecl *OuterField = *I;
8304         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8305           << OuterField->getType();
8306       }
8307
8308       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8309         << QT->isPointerType()
8310         << QT;
8311       D.setInvalidType();
8312       return;
8313     }
8314   } while (!VisitStack.empty());
8315 }
8316
8317 /// Find the DeclContext in which a tag is implicitly declared if we see an
8318 /// elaborated type specifier in the specified context, and lookup finds
8319 /// nothing.
8320 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8321   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8322     DC = DC->getParent();
8323   return DC;
8324 }
8325
8326 /// Find the Scope in which a tag is implicitly declared if we see an
8327 /// elaborated type specifier in the specified context, and lookup finds
8328 /// nothing.
8329 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8330   while (S->isClassScope() ||
8331          (LangOpts.CPlusPlus &&
8332           S->isFunctionPrototypeScope()) ||
8333          ((S->getFlags() & Scope::DeclScope) == 0) ||
8334          (S->getEntity() && S->getEntity()->isTransparentContext()))
8335     S = S->getParent();
8336   return S;
8337 }
8338
8339 NamedDecl*
8340 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8341                               TypeSourceInfo *TInfo, LookupResult &Previous,
8342                               MultiTemplateParamsArg TemplateParamLists,
8343                               bool &AddToScope) {
8344   QualType R = TInfo->getType();
8345
8346   assert(R->isFunctionType());
8347
8348   // TODO: consider using NameInfo for diagnostic.
8349   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8350   DeclarationName Name = NameInfo.getName();
8351   StorageClass SC = getFunctionStorageClass(*this, D);
8352
8353   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8354     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8355          diag::err_invalid_thread)
8356       << DeclSpec::getSpecifierName(TSCS);
8357
8358   if (D.isFirstDeclarationOfMember())
8359     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8360                            D.getIdentifierLoc());
8361
8362   bool isFriend = false;
8363   FunctionTemplateDecl *FunctionTemplate = nullptr;
8364   bool isMemberSpecialization = false;
8365   bool isFunctionTemplateSpecialization = false;
8366
8367   bool isDependentClassScopeExplicitSpecialization = false;
8368   bool HasExplicitTemplateArgs = false;
8369   TemplateArgumentListInfo TemplateArgs;
8370
8371   bool isVirtualOkay = false;
8372
8373   DeclContext *OriginalDC = DC;
8374   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8375
8376   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8377                                               isVirtualOkay);
8378   if (!NewFD) return nullptr;
8379
8380   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8381     NewFD->setTopLevelDeclInObjCContainer();
8382
8383   // Set the lexical context. If this is a function-scope declaration, or has a
8384   // C++ scope specifier, or is the object of a friend declaration, the lexical
8385   // context will be different from the semantic context.
8386   NewFD->setLexicalDeclContext(CurContext);
8387
8388   if (IsLocalExternDecl)
8389     NewFD->setLocalExternDecl();
8390
8391   if (getLangOpts().CPlusPlus) {
8392     bool isInline = D.getDeclSpec().isInlineSpecified();
8393     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8394     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8395     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8396     isFriend = D.getDeclSpec().isFriendSpecified();
8397     if (isFriend && !isInline && D.isFunctionDefinition()) {
8398       // C++ [class.friend]p5
8399       //   A function can be defined in a friend declaration of a
8400       //   class . . . . Such a function is implicitly inline.
8401       NewFD->setImplicitlyInline();
8402     }
8403
8404     // If this is a method defined in an __interface, and is not a constructor
8405     // or an overloaded operator, then set the pure flag (isVirtual will already
8406     // return true).
8407     if (const CXXRecordDecl *Parent =
8408           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8409       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8410         NewFD->setPure(true);
8411
8412       // C++ [class.union]p2
8413       //   A union can have member functions, but not virtual functions.
8414       if (isVirtual && Parent->isUnion())
8415         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8416     }
8417
8418     SetNestedNameSpecifier(NewFD, D);
8419     isMemberSpecialization = false;
8420     isFunctionTemplateSpecialization = false;
8421     if (D.isInvalidType())
8422       NewFD->setInvalidDecl();
8423
8424     // Match up the template parameter lists with the scope specifier, then
8425     // determine whether we have a template or a template specialization.
8426     bool Invalid = false;
8427     if (TemplateParameterList *TemplateParams =
8428             MatchTemplateParametersToScopeSpecifier(
8429                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
8430                 D.getCXXScopeSpec(),
8431                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8432                     ? D.getName().TemplateId
8433                     : nullptr,
8434                 TemplateParamLists, isFriend, isMemberSpecialization,
8435                 Invalid)) {
8436       if (TemplateParams->size() > 0) {
8437         // This is a function template
8438
8439         // Check that we can declare a template here.
8440         if (CheckTemplateDeclScope(S, TemplateParams))
8441           NewFD->setInvalidDecl();
8442
8443         // A destructor cannot be a template.
8444         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8445           Diag(NewFD->getLocation(), diag::err_destructor_template);
8446           NewFD->setInvalidDecl();
8447         }
8448
8449         // If we're adding a template to a dependent context, we may need to
8450         // rebuilding some of the types used within the template parameter list,
8451         // now that we know what the current instantiation is.
8452         if (DC->isDependentContext()) {
8453           ContextRAII SavedContext(*this, DC);
8454           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8455             Invalid = true;
8456         }
8457
8458         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8459                                                         NewFD->getLocation(),
8460                                                         Name, TemplateParams,
8461                                                         NewFD);
8462         FunctionTemplate->setLexicalDeclContext(CurContext);
8463         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8464
8465         // For source fidelity, store the other template param lists.
8466         if (TemplateParamLists.size() > 1) {
8467           NewFD->setTemplateParameterListsInfo(Context,
8468                                                TemplateParamLists.drop_back(1));
8469         }
8470       } else {
8471         // This is a function template specialization.
8472         isFunctionTemplateSpecialization = true;
8473         // For source fidelity, store all the template param lists.
8474         if (TemplateParamLists.size() > 0)
8475           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8476
8477         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8478         if (isFriend) {
8479           // We want to remove the "template<>", found here.
8480           SourceRange RemoveRange = TemplateParams->getSourceRange();
8481
8482           // If we remove the template<> and the name is not a
8483           // template-id, we're actually silently creating a problem:
8484           // the friend declaration will refer to an untemplated decl,
8485           // and clearly the user wants a template specialization.  So
8486           // we need to insert '<>' after the name.
8487           SourceLocation InsertLoc;
8488           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8489             InsertLoc = D.getName().getSourceRange().getEnd();
8490             InsertLoc = getLocForEndOfToken(InsertLoc);
8491           }
8492
8493           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8494             << Name << RemoveRange
8495             << FixItHint::CreateRemoval(RemoveRange)
8496             << FixItHint::CreateInsertion(InsertLoc, "<>");
8497         }
8498       }
8499     }
8500     else {
8501       // All template param lists were matched against the scope specifier:
8502       // this is NOT (an explicit specialization of) a template.
8503       if (TemplateParamLists.size() > 0)
8504         // For source fidelity, store all the template param lists.
8505         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8506     }
8507
8508     if (Invalid) {
8509       NewFD->setInvalidDecl();
8510       if (FunctionTemplate)
8511         FunctionTemplate->setInvalidDecl();
8512     }
8513
8514     // C++ [dcl.fct.spec]p5:
8515     //   The virtual specifier shall only be used in declarations of
8516     //   nonstatic class member functions that appear within a
8517     //   member-specification of a class declaration; see 10.3.
8518     //
8519     if (isVirtual && !NewFD->isInvalidDecl()) {
8520       if (!isVirtualOkay) {
8521         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8522              diag::err_virtual_non_function);
8523       } else if (!CurContext->isRecord()) {
8524         // 'virtual' was specified outside of the class.
8525         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8526              diag::err_virtual_out_of_class)
8527           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8528       } else if (NewFD->getDescribedFunctionTemplate()) {
8529         // C++ [temp.mem]p3:
8530         //  A member function template shall not be virtual.
8531         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8532              diag::err_virtual_member_function_template)
8533           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8534       } else {
8535         // Okay: Add virtual to the method.
8536         NewFD->setVirtualAsWritten(true);
8537       }
8538
8539       if (getLangOpts().CPlusPlus14 &&
8540           NewFD->getReturnType()->isUndeducedType())
8541         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8542     }
8543
8544     if (getLangOpts().CPlusPlus14 &&
8545         (NewFD->isDependentContext() ||
8546          (isFriend && CurContext->isDependentContext())) &&
8547         NewFD->getReturnType()->isUndeducedType()) {
8548       // If the function template is referenced directly (for instance, as a
8549       // member of the current instantiation), pretend it has a dependent type.
8550       // This is not really justified by the standard, but is the only sane
8551       // thing to do.
8552       // FIXME: For a friend function, we have not marked the function as being
8553       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8554       const FunctionProtoType *FPT =
8555           NewFD->getType()->castAs<FunctionProtoType>();
8556       QualType Result =
8557           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8558       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8559                                              FPT->getExtProtoInfo()));
8560     }
8561
8562     // C++ [dcl.fct.spec]p3:
8563     //  The inline specifier shall not appear on a block scope function
8564     //  declaration.
8565     if (isInline && !NewFD->isInvalidDecl()) {
8566       if (CurContext->isFunctionOrMethod()) {
8567         // 'inline' is not allowed on block scope function declaration.
8568         Diag(D.getDeclSpec().getInlineSpecLoc(),
8569              diag::err_inline_declaration_block_scope) << Name
8570           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8571       }
8572     }
8573
8574     // C++ [dcl.fct.spec]p6:
8575     //  The explicit specifier shall be used only in the declaration of a
8576     //  constructor or conversion function within its class definition;
8577     //  see 12.3.1 and 12.3.2.
8578     if (isExplicit && !NewFD->isInvalidDecl() &&
8579         !isa<CXXDeductionGuideDecl>(NewFD)) {
8580       if (!CurContext->isRecord()) {
8581         // 'explicit' was specified outside of the class.
8582         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8583              diag::err_explicit_out_of_class)
8584           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8585       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8586                  !isa<CXXConversionDecl>(NewFD)) {
8587         // 'explicit' was specified on a function that wasn't a constructor
8588         // or conversion function.
8589         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8590              diag::err_explicit_non_ctor_or_conv_function)
8591           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8592       }
8593     }
8594
8595     if (isConstexpr) {
8596       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8597       // are implicitly inline.
8598       NewFD->setImplicitlyInline();
8599
8600       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8601       // be either constructors or to return a literal type. Therefore,
8602       // destructors cannot be declared constexpr.
8603       if (isa<CXXDestructorDecl>(NewFD))
8604         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8605     }
8606
8607     // If __module_private__ was specified, mark the function accordingly.
8608     if (D.getDeclSpec().isModulePrivateSpecified()) {
8609       if (isFunctionTemplateSpecialization) {
8610         SourceLocation ModulePrivateLoc
8611           = D.getDeclSpec().getModulePrivateSpecLoc();
8612         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8613           << 0
8614           << FixItHint::CreateRemoval(ModulePrivateLoc);
8615       } else {
8616         NewFD->setModulePrivate();
8617         if (FunctionTemplate)
8618           FunctionTemplate->setModulePrivate();
8619       }
8620     }
8621
8622     if (isFriend) {
8623       if (FunctionTemplate) {
8624         FunctionTemplate->setObjectOfFriendDecl();
8625         FunctionTemplate->setAccess(AS_public);
8626       }
8627       NewFD->setObjectOfFriendDecl();
8628       NewFD->setAccess(AS_public);
8629     }
8630
8631     // If a function is defined as defaulted or deleted, mark it as such now.
8632     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8633     // definition kind to FDK_Definition.
8634     switch (D.getFunctionDefinitionKind()) {
8635       case FDK_Declaration:
8636       case FDK_Definition:
8637         break;
8638
8639       case FDK_Defaulted:
8640         NewFD->setDefaulted();
8641         break;
8642
8643       case FDK_Deleted:
8644         NewFD->setDeletedAsWritten();
8645         break;
8646     }
8647
8648     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8649         D.isFunctionDefinition()) {
8650       // C++ [class.mfct]p2:
8651       //   A member function may be defined (8.4) in its class definition, in
8652       //   which case it is an inline member function (7.1.2)
8653       NewFD->setImplicitlyInline();
8654     }
8655
8656     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8657         !CurContext->isRecord()) {
8658       // C++ [class.static]p1:
8659       //   A data or function member of a class may be declared static
8660       //   in a class definition, in which case it is a static member of
8661       //   the class.
8662
8663       // Complain about the 'static' specifier if it's on an out-of-line
8664       // member function definition.
8665       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8666            diag::err_static_out_of_line)
8667         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8668     }
8669
8670     // C++11 [except.spec]p15:
8671     //   A deallocation function with no exception-specification is treated
8672     //   as if it were specified with noexcept(true).
8673     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8674     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8675          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8676         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8677       NewFD->setType(Context.getFunctionType(
8678           FPT->getReturnType(), FPT->getParamTypes(),
8679           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8680   }
8681
8682   // Filter out previous declarations that don't match the scope.
8683   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8684                        D.getCXXScopeSpec().isNotEmpty() ||
8685                        isMemberSpecialization ||
8686                        isFunctionTemplateSpecialization);
8687
8688   // Handle GNU asm-label extension (encoded as an attribute).
8689   if (Expr *E = (Expr*) D.getAsmLabel()) {
8690     // The parser guarantees this is a string.
8691     StringLiteral *SE = cast<StringLiteral>(E);
8692     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8693                                                 SE->getString(), 0));
8694   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8695     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8696       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8697     if (I != ExtnameUndeclaredIdentifiers.end()) {
8698       if (isDeclExternC(NewFD)) {
8699         NewFD->addAttr(I->second);
8700         ExtnameUndeclaredIdentifiers.erase(I);
8701       } else
8702         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8703             << /*Variable*/0 << NewFD;
8704     }
8705   }
8706
8707   // Copy the parameter declarations from the declarator D to the function
8708   // declaration NewFD, if they are available.  First scavenge them into Params.
8709   SmallVector<ParmVarDecl*, 16> Params;
8710   unsigned FTIIdx;
8711   if (D.isFunctionDeclarator(FTIIdx)) {
8712     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8713
8714     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8715     // function that takes no arguments, not a function that takes a
8716     // single void argument.
8717     // We let through "const void" here because Sema::GetTypeForDeclarator
8718     // already checks for that case.
8719     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8720       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8721         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8722         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8723         Param->setDeclContext(NewFD);
8724         Params.push_back(Param);
8725
8726         if (Param->isInvalidDecl())
8727           NewFD->setInvalidDecl();
8728       }
8729     }
8730
8731     if (!getLangOpts().CPlusPlus) {
8732       // In C, find all the tag declarations from the prototype and move them
8733       // into the function DeclContext. Remove them from the surrounding tag
8734       // injection context of the function, which is typically but not always
8735       // the TU.
8736       DeclContext *PrototypeTagContext =
8737           getTagInjectionContext(NewFD->getLexicalDeclContext());
8738       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8739         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8740
8741         // We don't want to reparent enumerators. Look at their parent enum
8742         // instead.
8743         if (!TD) {
8744           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8745             TD = cast<EnumDecl>(ECD->getDeclContext());
8746         }
8747         if (!TD)
8748           continue;
8749         DeclContext *TagDC = TD->getLexicalDeclContext();
8750         if (!TagDC->containsDecl(TD))
8751           continue;
8752         TagDC->removeDecl(TD);
8753         TD->setDeclContext(NewFD);
8754         NewFD->addDecl(TD);
8755
8756         // Preserve the lexical DeclContext if it is not the surrounding tag
8757         // injection context of the FD. In this example, the semantic context of
8758         // E will be f and the lexical context will be S, while both the
8759         // semantic and lexical contexts of S will be f:
8760         //   void f(struct S { enum E { a } f; } s);
8761         if (TagDC != PrototypeTagContext)
8762           TD->setLexicalDeclContext(TagDC);
8763       }
8764     }
8765   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8766     // When we're declaring a function with a typedef, typeof, etc as in the
8767     // following example, we'll need to synthesize (unnamed)
8768     // parameters for use in the declaration.
8769     //
8770     // @code
8771     // typedef void fn(int);
8772     // fn f;
8773     // @endcode
8774
8775     // Synthesize a parameter for each argument type.
8776     for (const auto &AI : FT->param_types()) {
8777       ParmVarDecl *Param =
8778           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8779       Param->setScopeInfo(0, Params.size());
8780       Params.push_back(Param);
8781     }
8782   } else {
8783     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8784            "Should not need args for typedef of non-prototype fn");
8785   }
8786
8787   // Finally, we know we have the right number of parameters, install them.
8788   NewFD->setParams(Params);
8789
8790   if (D.getDeclSpec().isNoreturnSpecified())
8791     NewFD->addAttr(
8792         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8793                                        Context, 0));
8794
8795   // Functions returning a variably modified type violate C99 6.7.5.2p2
8796   // because all functions have linkage.
8797   if (!NewFD->isInvalidDecl() &&
8798       NewFD->getReturnType()->isVariablyModifiedType()) {
8799     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8800     NewFD->setInvalidDecl();
8801   }
8802
8803   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8804   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8805       !NewFD->hasAttr<SectionAttr>()) {
8806     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8807                                                  PragmaClangTextSection.SectionName,
8808                                                  PragmaClangTextSection.PragmaLocation));
8809   }
8810
8811   // Apply an implicit SectionAttr if #pragma code_seg is active.
8812   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8813       !NewFD->hasAttr<SectionAttr>()) {
8814     NewFD->addAttr(
8815         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8816                                     CodeSegStack.CurrentValue->getString(),
8817                                     CodeSegStack.CurrentPragmaLocation));
8818     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8819                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8820                          ASTContext::PSF_Read,
8821                      NewFD))
8822       NewFD->dropAttr<SectionAttr>();
8823   }
8824
8825   // Apply an implicit CodeSegAttr from class declspec or
8826   // apply an implicit SectionAttr from #pragma code_seg if active.
8827   if (!NewFD->hasAttr<CodeSegAttr>()) {
8828     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
8829                                                                  D.isFunctionDefinition())) {
8830       NewFD->addAttr(SAttr);
8831     }
8832   }
8833
8834   // Handle attributes.
8835   ProcessDeclAttributes(S, NewFD, D);
8836
8837   if (getLangOpts().OpenCL) {
8838     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8839     // type declaration will generate a compilation error.
8840     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
8841     if (AddressSpace != LangAS::Default) {
8842       Diag(NewFD->getLocation(),
8843            diag::err_opencl_return_value_with_address_space);
8844       NewFD->setInvalidDecl();
8845     }
8846   }
8847
8848   if (!getLangOpts().CPlusPlus) {
8849     // Perform semantic checking on the function declaration.
8850     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8851       CheckMain(NewFD, D.getDeclSpec());
8852
8853     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8854       CheckMSVCRTEntryPoint(NewFD);
8855
8856     if (!NewFD->isInvalidDecl())
8857       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8858                                                   isMemberSpecialization));
8859     else if (!Previous.empty())
8860       // Recover gracefully from an invalid redeclaration.
8861       D.setRedeclaration(true);
8862     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8863             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8864            "previous declaration set still overloaded");
8865
8866     // Diagnose no-prototype function declarations with calling conventions that
8867     // don't support variadic calls. Only do this in C and do it after merging
8868     // possibly prototyped redeclarations.
8869     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8870     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8871       CallingConv CC = FT->getExtInfo().getCC();
8872       if (!supportsVariadicCall(CC)) {
8873         // Windows system headers sometimes accidentally use stdcall without
8874         // (void) parameters, so we relax this to a warning.
8875         int DiagID =
8876             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8877         Diag(NewFD->getLocation(), DiagID)
8878             << FunctionType::getNameForCallConv(CC);
8879       }
8880     }
8881   } else {
8882     // C++11 [replacement.functions]p3:
8883     //  The program's definitions shall not be specified as inline.
8884     //
8885     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8886     //
8887     // Suppress the diagnostic if the function is __attribute__((used)), since
8888     // that forces an external definition to be emitted.
8889     if (D.getDeclSpec().isInlineSpecified() &&
8890         NewFD->isReplaceableGlobalAllocationFunction() &&
8891         !NewFD->hasAttr<UsedAttr>())
8892       Diag(D.getDeclSpec().getInlineSpecLoc(),
8893            diag::ext_operator_new_delete_declared_inline)
8894         << NewFD->getDeclName();
8895
8896     // If the declarator is a template-id, translate the parser's template
8897     // argument list into our AST format.
8898     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
8899       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8900       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8901       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8902       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8903                                          TemplateId->NumArgs);
8904       translateTemplateArguments(TemplateArgsPtr,
8905                                  TemplateArgs);
8906
8907       HasExplicitTemplateArgs = true;
8908
8909       if (NewFD->isInvalidDecl()) {
8910         HasExplicitTemplateArgs = false;
8911       } else if (FunctionTemplate) {
8912         // Function template with explicit template arguments.
8913         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8914           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8915
8916         HasExplicitTemplateArgs = false;
8917       } else {
8918         assert((isFunctionTemplateSpecialization ||
8919                 D.getDeclSpec().isFriendSpecified()) &&
8920                "should have a 'template<>' for this decl");
8921         // "friend void foo<>(int);" is an implicit specialization decl.
8922         isFunctionTemplateSpecialization = true;
8923       }
8924     } else if (isFriend && isFunctionTemplateSpecialization) {
8925       // This combination is only possible in a recovery case;  the user
8926       // wrote something like:
8927       //   template <> friend void foo(int);
8928       // which we're recovering from as if the user had written:
8929       //   friend void foo<>(int);
8930       // Go ahead and fake up a template id.
8931       HasExplicitTemplateArgs = true;
8932       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8933       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8934     }
8935
8936     // We do not add HD attributes to specializations here because
8937     // they may have different constexpr-ness compared to their
8938     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8939     // may end up with different effective targets. Instead, a
8940     // specialization inherits its target attributes from its template
8941     // in the CheckFunctionTemplateSpecialization() call below.
8942     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8943       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8944
8945     // If it's a friend (and only if it's a friend), it's possible
8946     // that either the specialized function type or the specialized
8947     // template is dependent, and therefore matching will fail.  In
8948     // this case, don't check the specialization yet.
8949     bool InstantiationDependent = false;
8950     if (isFunctionTemplateSpecialization && isFriend &&
8951         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8952          TemplateSpecializationType::anyDependentTemplateArguments(
8953             TemplateArgs,
8954             InstantiationDependent))) {
8955       assert(HasExplicitTemplateArgs &&
8956              "friend function specialization without template args");
8957       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8958                                                        Previous))
8959         NewFD->setInvalidDecl();
8960     } else if (isFunctionTemplateSpecialization) {
8961       if (CurContext->isDependentContext() && CurContext->isRecord()
8962           && !isFriend) {
8963         isDependentClassScopeExplicitSpecialization = true;
8964       } else if (!NewFD->isInvalidDecl() &&
8965                  CheckFunctionTemplateSpecialization(
8966                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
8967                      Previous))
8968         NewFD->setInvalidDecl();
8969
8970       // C++ [dcl.stc]p1:
8971       //   A storage-class-specifier shall not be specified in an explicit
8972       //   specialization (14.7.3)
8973       FunctionTemplateSpecializationInfo *Info =
8974           NewFD->getTemplateSpecializationInfo();
8975       if (Info && SC != SC_None) {
8976         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8977           Diag(NewFD->getLocation(),
8978                diag::err_explicit_specialization_inconsistent_storage_class)
8979             << SC
8980             << FixItHint::CreateRemoval(
8981                                       D.getDeclSpec().getStorageClassSpecLoc());
8982
8983         else
8984           Diag(NewFD->getLocation(),
8985                diag::ext_explicit_specialization_storage_class)
8986             << FixItHint::CreateRemoval(
8987                                       D.getDeclSpec().getStorageClassSpecLoc());
8988       }
8989     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8990       if (CheckMemberSpecialization(NewFD, Previous))
8991           NewFD->setInvalidDecl();
8992     }
8993
8994     // Perform semantic checking on the function declaration.
8995     if (!isDependentClassScopeExplicitSpecialization) {
8996       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8997         CheckMain(NewFD, D.getDeclSpec());
8998
8999       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9000         CheckMSVCRTEntryPoint(NewFD);
9001
9002       if (!NewFD->isInvalidDecl())
9003         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9004                                                     isMemberSpecialization));
9005       else if (!Previous.empty())
9006         // Recover gracefully from an invalid redeclaration.
9007         D.setRedeclaration(true);
9008     }
9009
9010     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9011             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9012            "previous declaration set still overloaded");
9013
9014     NamedDecl *PrincipalDecl = (FunctionTemplate
9015                                 ? cast<NamedDecl>(FunctionTemplate)
9016                                 : NewFD);
9017
9018     if (isFriend && NewFD->getPreviousDecl()) {
9019       AccessSpecifier Access = AS_public;
9020       if (!NewFD->isInvalidDecl())
9021         Access = NewFD->getPreviousDecl()->getAccess();
9022
9023       NewFD->setAccess(Access);
9024       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9025     }
9026
9027     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9028         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9029       PrincipalDecl->setNonMemberOperator();
9030
9031     // If we have a function template, check the template parameter
9032     // list. This will check and merge default template arguments.
9033     if (FunctionTemplate) {
9034       FunctionTemplateDecl *PrevTemplate =
9035                                      FunctionTemplate->getPreviousDecl();
9036       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9037                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9038                                     : nullptr,
9039                             D.getDeclSpec().isFriendSpecified()
9040                               ? (D.isFunctionDefinition()
9041                                    ? TPC_FriendFunctionTemplateDefinition
9042                                    : TPC_FriendFunctionTemplate)
9043                               : (D.getCXXScopeSpec().isSet() &&
9044                                  DC && DC->isRecord() &&
9045                                  DC->isDependentContext())
9046                                   ? TPC_ClassTemplateMember
9047                                   : TPC_FunctionTemplate);
9048     }
9049
9050     if (NewFD->isInvalidDecl()) {
9051       // Ignore all the rest of this.
9052     } else if (!D.isRedeclaration()) {
9053       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9054                                        AddToScope };
9055       // Fake up an access specifier if it's supposed to be a class member.
9056       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9057         NewFD->setAccess(AS_public);
9058
9059       // Qualified decls generally require a previous declaration.
9060       if (D.getCXXScopeSpec().isSet()) {
9061         // ...with the major exception of templated-scope or
9062         // dependent-scope friend declarations.
9063
9064         // TODO: we currently also suppress this check in dependent
9065         // contexts because (1) the parameter depth will be off when
9066         // matching friend templates and (2) we might actually be
9067         // selecting a friend based on a dependent factor.  But there
9068         // are situations where these conditions don't apply and we
9069         // can actually do this check immediately.
9070         if (isFriend &&
9071             (TemplateParamLists.size() ||
9072              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9073              CurContext->isDependentContext())) {
9074           // ignore these
9075         } else {
9076           // The user tried to provide an out-of-line definition for a
9077           // function that is a member of a class or namespace, but there
9078           // was no such member function declared (C++ [class.mfct]p2,
9079           // C++ [namespace.memdef]p2). For example:
9080           //
9081           // class X {
9082           //   void f() const;
9083           // };
9084           //
9085           // void X::f() { } // ill-formed
9086           //
9087           // Complain about this problem, and attempt to suggest close
9088           // matches (e.g., those that differ only in cv-qualifiers and
9089           // whether the parameter types are references).
9090
9091           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9092                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9093             AddToScope = ExtraArgs.AddToScope;
9094             return Result;
9095           }
9096         }
9097
9098         // Unqualified local friend declarations are required to resolve
9099         // to something.
9100       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9101         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9102                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9103           AddToScope = ExtraArgs.AddToScope;
9104           return Result;
9105         }
9106       }
9107     } else if (!D.isFunctionDefinition() &&
9108                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9109                !isFriend && !isFunctionTemplateSpecialization &&
9110                !isMemberSpecialization) {
9111       // An out-of-line member function declaration must also be a
9112       // definition (C++ [class.mfct]p2).
9113       // Note that this is not the case for explicit specializations of
9114       // function templates or member functions of class templates, per
9115       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9116       // extension for compatibility with old SWIG code which likes to
9117       // generate them.
9118       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9119         << D.getCXXScopeSpec().getRange();
9120     }
9121   }
9122
9123   ProcessPragmaWeak(S, NewFD);
9124   checkAttributesAfterMerging(*this, *NewFD);
9125
9126   AddKnownFunctionAttributes(NewFD);
9127
9128   if (NewFD->hasAttr<OverloadableAttr>() &&
9129       !NewFD->getType()->getAs<FunctionProtoType>()) {
9130     Diag(NewFD->getLocation(),
9131          diag::err_attribute_overloadable_no_prototype)
9132       << NewFD;
9133
9134     // Turn this into a variadic function with no parameters.
9135     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9136     FunctionProtoType::ExtProtoInfo EPI(
9137         Context.getDefaultCallingConvention(true, false));
9138     EPI.Variadic = true;
9139     EPI.ExtInfo = FT->getExtInfo();
9140
9141     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9142     NewFD->setType(R);
9143   }
9144
9145   // If there's a #pragma GCC visibility in scope, and this isn't a class
9146   // member, set the visibility of this function.
9147   if (!DC->isRecord() && NewFD->isExternallyVisible())
9148     AddPushedVisibilityAttribute(NewFD);
9149
9150   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9151   // marking the function.
9152   AddCFAuditedAttribute(NewFD);
9153
9154   // If this is a function definition, check if we have to apply optnone due to
9155   // a pragma.
9156   if(D.isFunctionDefinition())
9157     AddRangeBasedOptnone(NewFD);
9158
9159   // If this is the first declaration of an extern C variable, update
9160   // the map of such variables.
9161   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9162       isIncompleteDeclExternC(*this, NewFD))
9163     RegisterLocallyScopedExternCDecl(NewFD, S);
9164
9165   // Set this FunctionDecl's range up to the right paren.
9166   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9167
9168   if (D.isRedeclaration() && !Previous.empty()) {
9169     NamedDecl *Prev = Previous.getRepresentativeDecl();
9170     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9171                                    isMemberSpecialization ||
9172                                        isFunctionTemplateSpecialization,
9173                                    D.isFunctionDefinition());
9174   }
9175
9176   if (getLangOpts().CUDA) {
9177     IdentifierInfo *II = NewFD->getIdentifier();
9178     if (II &&
9179         II->isStr(getLangOpts().HIP ? "hipConfigureCall"
9180                                     : "cudaConfigureCall") &&
9181         !NewFD->isInvalidDecl() &&
9182         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9183       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9184         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
9185       Context.setcudaConfigureCallDecl(NewFD);
9186     }
9187
9188     // Variadic functions, other than a *declaration* of printf, are not allowed
9189     // in device-side CUDA code, unless someone passed
9190     // -fcuda-allow-variadic-functions.
9191     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9192         (NewFD->hasAttr<CUDADeviceAttr>() ||
9193          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9194         !(II && II->isStr("printf") && NewFD->isExternC() &&
9195           !D.isFunctionDefinition())) {
9196       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9197     }
9198   }
9199
9200   MarkUnusedFileScopedDecl(NewFD);
9201
9202   if (getLangOpts().CPlusPlus) {
9203     if (FunctionTemplate) {
9204       if (NewFD->isInvalidDecl())
9205         FunctionTemplate->setInvalidDecl();
9206       return FunctionTemplate;
9207     }
9208
9209     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9210       CompleteMemberSpecialization(NewFD, Previous);
9211   }
9212
9213   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9214     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9215     if ((getLangOpts().OpenCLVersion >= 120)
9216         && (SC == SC_Static)) {
9217       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9218       D.setInvalidType();
9219     }
9220
9221     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9222     if (!NewFD->getReturnType()->isVoidType()) {
9223       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9224       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9225           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9226                                 : FixItHint());
9227       D.setInvalidType();
9228     }
9229
9230     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9231     for (auto Param : NewFD->parameters())
9232       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9233   }
9234   for (const ParmVarDecl *Param : NewFD->parameters()) {
9235     QualType PT = Param->getType();
9236
9237     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9238     // types.
9239     if (getLangOpts().OpenCLVersion >= 200) {
9240       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9241         QualType ElemTy = PipeTy->getElementType();
9242           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9243             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9244             D.setInvalidType();
9245           }
9246       }
9247     }
9248   }
9249
9250   // Here we have an function template explicit specialization at class scope.
9251   // The actual specialization will be postponed to template instatiation
9252   // time via the ClassScopeFunctionSpecializationDecl node.
9253   if (isDependentClassScopeExplicitSpecialization) {
9254     ClassScopeFunctionSpecializationDecl *NewSpec =
9255                          ClassScopeFunctionSpecializationDecl::Create(
9256                                 Context, CurContext, NewFD->getLocation(),
9257                                 cast<CXXMethodDecl>(NewFD),
9258                                 HasExplicitTemplateArgs, TemplateArgs);
9259     CurContext->addDecl(NewSpec);
9260     AddToScope = false;
9261   }
9262
9263   // Diagnose availability attributes. Availability cannot be used on functions
9264   // that are run during load/unload.
9265   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9266     if (NewFD->hasAttr<ConstructorAttr>()) {
9267       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9268           << 1;
9269       NewFD->dropAttr<AvailabilityAttr>();
9270     }
9271     if (NewFD->hasAttr<DestructorAttr>()) {
9272       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9273           << 2;
9274       NewFD->dropAttr<AvailabilityAttr>();
9275     }
9276   }
9277
9278   return NewFD;
9279 }
9280
9281 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9282 /// when __declspec(code_seg) "is applied to a class, all member functions of
9283 /// the class and nested classes -- this includes compiler-generated special
9284 /// member functions -- are put in the specified segment."
9285 /// The actual behavior is a little more complicated. The Microsoft compiler
9286 /// won't check outer classes if there is an active value from #pragma code_seg.
9287 /// The CodeSeg is always applied from the direct parent but only from outer
9288 /// classes when the #pragma code_seg stack is empty. See:
9289 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9290 /// available since MS has removed the page.
9291 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9292   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9293   if (!Method)
9294     return nullptr;
9295   const CXXRecordDecl *Parent = Method->getParent();
9296   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9297     Attr *NewAttr = SAttr->clone(S.getASTContext());
9298     NewAttr->setImplicit(true);
9299     return NewAttr;
9300   }
9301
9302   // The Microsoft compiler won't check outer classes for the CodeSeg
9303   // when the #pragma code_seg stack is active.
9304   if (S.CodeSegStack.CurrentValue)
9305    return nullptr;
9306
9307   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9308     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9309       Attr *NewAttr = SAttr->clone(S.getASTContext());
9310       NewAttr->setImplicit(true);
9311       return NewAttr;
9312     }
9313   }
9314   return nullptr;
9315 }
9316
9317 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9318 /// containing class. Otherwise it will return implicit SectionAttr if the
9319 /// function is a definition and there is an active value on CodeSegStack
9320 /// (from the current #pragma code-seg value).
9321 ///
9322 /// \param FD Function being declared.
9323 /// \param IsDefinition Whether it is a definition or just a declarartion.
9324 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9325 ///          nullptr if no attribute should be added.
9326 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9327                                                        bool IsDefinition) {
9328   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9329     return A;
9330   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9331       CodeSegStack.CurrentValue) {
9332     return SectionAttr::CreateImplicit(getASTContext(),
9333                                        SectionAttr::Declspec_allocate,
9334                                        CodeSegStack.CurrentValue->getString(),
9335                                        CodeSegStack.CurrentPragmaLocation);
9336   }
9337   return nullptr;
9338 }
9339 /// Checks if the new declaration declared in dependent context must be
9340 /// put in the same redeclaration chain as the specified declaration.
9341 ///
9342 /// \param D Declaration that is checked.
9343 /// \param PrevDecl Previous declaration found with proper lookup method for the
9344 ///                 same declaration name.
9345 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9346 ///          belongs to.
9347 ///
9348 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9349   // Any declarations should be put into redeclaration chains except for
9350   // friend declaration in a dependent context that names a function in
9351   // namespace scope.
9352   //
9353   // This allows to compile code like:
9354   //
9355   //       void func();
9356   //       template<typename T> class C1 { friend void func() { } };
9357   //       template<typename T> class C2 { friend void func() { } };
9358   //
9359   // This code snippet is a valid code unless both templates are instantiated.
9360   return !(D->getLexicalDeclContext()->isDependentContext() &&
9361            D->getDeclContext()->isFileContext() &&
9362            D->getFriendObjectKind() != Decl::FOK_None);
9363 }
9364
9365 namespace MultiVersioning {
9366 enum Type { None, Target, CPUSpecific, CPUDispatch};
9367 } // MultiVersionType
9368
9369 static MultiVersioning::Type
9370 getMultiVersionType(const FunctionDecl *FD) {
9371   if (FD->hasAttr<TargetAttr>())
9372     return MultiVersioning::Target;
9373   if (FD->hasAttr<CPUDispatchAttr>())
9374     return MultiVersioning::CPUDispatch;
9375   if (FD->hasAttr<CPUSpecificAttr>())
9376     return MultiVersioning::CPUSpecific;
9377   return MultiVersioning::None;
9378 }
9379 /// Check the target attribute of the function for MultiVersion
9380 /// validity.
9381 ///
9382 /// Returns true if there was an error, false otherwise.
9383 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9384   const auto *TA = FD->getAttr<TargetAttr>();
9385   assert(TA && "MultiVersion Candidate requires a target attribute");
9386   TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9387   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9388   enum ErrType { Feature = 0, Architecture = 1 };
9389
9390   if (!ParseInfo.Architecture.empty() &&
9391       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9392     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9393         << Architecture << ParseInfo.Architecture;
9394     return true;
9395   }
9396
9397   for (const auto &Feat : ParseInfo.Features) {
9398     auto BareFeat = StringRef{Feat}.substr(1);
9399     if (Feat[0] == '-') {
9400       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9401           << Feature << ("no-" + BareFeat).str();
9402       return true;
9403     }
9404
9405     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9406         !TargetInfo.isValidFeatureName(BareFeat)) {
9407       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9408           << Feature << BareFeat;
9409       return true;
9410     }
9411   }
9412   return false;
9413 }
9414
9415 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9416                                              const FunctionDecl *NewFD,
9417                                              bool CausesMV,
9418                                              MultiVersioning::Type MVType) {
9419   enum DoesntSupport {
9420     FuncTemplates = 0,
9421     VirtFuncs = 1,
9422     DeducedReturn = 2,
9423     Constructors = 3,
9424     Destructors = 4,
9425     DeletedFuncs = 5,
9426     DefaultedFuncs = 6,
9427     ConstexprFuncs = 7,
9428   };
9429   enum Different {
9430     CallingConv = 0,
9431     ReturnType = 1,
9432     ConstexprSpec = 2,
9433     InlineSpec = 3,
9434     StorageClass = 4,
9435     Linkage = 5
9436   };
9437
9438   bool IsCPUSpecificCPUDispatchMVType =
9439       MVType == MultiVersioning::CPUDispatch ||
9440       MVType == MultiVersioning::CPUSpecific;
9441
9442   if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
9443     S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
9444     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9445     return true;
9446   }
9447
9448   if (!NewFD->getType()->getAs<FunctionProtoType>())
9449     return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
9450
9451   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9452     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9453     if (OldFD)
9454       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9455     return true;
9456   }
9457
9458   // For now, disallow all other attributes.  These should be opt-in, but
9459   // an analysis of all of them is a future FIXME.
9460   if (CausesMV && OldFD &&
9461       std::distance(OldFD->attr_begin(), OldFD->attr_end()) != 1) {
9462     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9463         << IsCPUSpecificCPUDispatchMVType;
9464     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9465     return true;
9466   }
9467
9468   if (std::distance(NewFD->attr_begin(), NewFD->attr_end()) != 1)
9469     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9470            << IsCPUSpecificCPUDispatchMVType;
9471
9472   if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9473     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9474            << IsCPUSpecificCPUDispatchMVType << FuncTemplates;
9475
9476   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9477     if (NewCXXFD->isVirtual())
9478       return S.Diag(NewCXXFD->getLocation(),
9479                     diag::err_multiversion_doesnt_support)
9480              << IsCPUSpecificCPUDispatchMVType << VirtFuncs;
9481
9482     if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
9483       return S.Diag(NewCXXCtor->getLocation(),
9484                     diag::err_multiversion_doesnt_support)
9485              << IsCPUSpecificCPUDispatchMVType << Constructors;
9486
9487     if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
9488       return S.Diag(NewCXXDtor->getLocation(),
9489                     diag::err_multiversion_doesnt_support)
9490              << IsCPUSpecificCPUDispatchMVType << Destructors;
9491   }
9492
9493   if (NewFD->isDeleted())
9494     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9495            << IsCPUSpecificCPUDispatchMVType << DeletedFuncs;
9496
9497   if (NewFD->isDefaulted())
9498     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9499            << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs;
9500
9501   if (NewFD->isConstexpr() && (MVType == MultiVersioning::CPUDispatch ||
9502                                MVType == MultiVersioning::CPUSpecific))
9503     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9504            << IsCPUSpecificCPUDispatchMVType << ConstexprFuncs;
9505
9506   QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
9507   const auto *NewType = cast<FunctionType>(NewQType);
9508   QualType NewReturnType = NewType->getReturnType();
9509
9510   if (NewReturnType->isUndeducedType())
9511     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9512            << IsCPUSpecificCPUDispatchMVType << DeducedReturn;
9513
9514   // Only allow transition to MultiVersion if it hasn't been used.
9515   if (OldFD && CausesMV && OldFD->isUsed(false))
9516     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9517
9518   // Ensure the return type is identical.
9519   if (OldFD) {
9520     QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
9521     const auto *OldType = cast<FunctionType>(OldQType);
9522     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9523     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9524
9525     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9526       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9527              << CallingConv;
9528
9529     QualType OldReturnType = OldType->getReturnType();
9530
9531     if (OldReturnType != NewReturnType)
9532       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9533              << ReturnType;
9534
9535     if (OldFD->isConstexpr() != NewFD->isConstexpr())
9536       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9537              << ConstexprSpec;
9538
9539     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9540       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9541              << InlineSpec;
9542
9543     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9544       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9545              << StorageClass;
9546
9547     if (OldFD->isExternC() != NewFD->isExternC())
9548       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9549              << Linkage;
9550
9551     if (S.CheckEquivalentExceptionSpec(
9552             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9553             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9554       return true;
9555   }
9556   return false;
9557 }
9558
9559 /// Check the validity of a multiversion function declaration that is the
9560 /// first of its kind. Also sets the multiversion'ness' of the function itself.
9561 ///
9562 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9563 ///
9564 /// Returns true if there was an error, false otherwise.
9565 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
9566                                            MultiVersioning::Type MVType,
9567                                            const TargetAttr *TA,
9568                                            const CPUDispatchAttr *CPUDisp,
9569                                            const CPUSpecificAttr *CPUSpec) {
9570   assert(MVType != MultiVersioning::None &&
9571          "Function lacks multiversion attribute");
9572
9573   // Target only causes MV if it is default, otherwise this is a normal
9574   // function.
9575   if (MVType == MultiVersioning::Target && !TA->isDefaultVersion())
9576     return false;
9577
9578   if (MVType == MultiVersioning::Target && CheckMultiVersionValue(S, FD)) {
9579     FD->setInvalidDecl();
9580     return true;
9581   }
9582
9583   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
9584     FD->setInvalidDecl();
9585     return true;
9586   }
9587
9588   FD->setIsMultiVersion();
9589   return false;
9590 }
9591
9592 static bool CheckTargetCausesMultiVersioning(
9593     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
9594     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9595     LookupResult &Previous) {
9596   const auto *OldTA = OldFD->getAttr<TargetAttr>();
9597   TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9598   // Sort order doesn't matter, it just needs to be consistent.
9599   llvm::sort(NewParsed.Features.begin(), NewParsed.Features.end());
9600
9601   // If the old decl is NOT MultiVersioned yet, and we don't cause that
9602   // to change, this is a simple redeclaration.
9603   if (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())
9604     return false;
9605
9606   // Otherwise, this decl causes MultiVersioning.
9607   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9608     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9609     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9610     NewFD->setInvalidDecl();
9611     return true;
9612   }
9613
9614   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
9615                                        MultiVersioning::Target)) {
9616     NewFD->setInvalidDecl();
9617     return true;
9618   }
9619
9620   if (CheckMultiVersionValue(S, NewFD)) {
9621     NewFD->setInvalidDecl();
9622     return true;
9623   }
9624
9625   if (CheckMultiVersionValue(S, OldFD)) {
9626     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9627     NewFD->setInvalidDecl();
9628     return true;
9629   }
9630
9631   TargetAttr::ParsedTargetAttr OldParsed =
9632       OldTA->parse(std::less<std::string>());
9633
9634   if (OldParsed == NewParsed) {
9635     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9636     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9637     NewFD->setInvalidDecl();
9638     return true;
9639   }
9640
9641   for (const auto *FD : OldFD->redecls()) {
9642     const auto *CurTA = FD->getAttr<TargetAttr>();
9643     if (!CurTA || CurTA->isInherited()) {
9644       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
9645           << 0;
9646       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9647       NewFD->setInvalidDecl();
9648       return true;
9649     }
9650   }
9651
9652   OldFD->setIsMultiVersion();
9653   NewFD->setIsMultiVersion();
9654   Redeclaration = false;
9655   MergeTypeWithPrevious = false;
9656   OldDecl = nullptr;
9657   Previous.clear();
9658   return false;
9659 }
9660
9661 /// Check the validity of a new function declaration being added to an existing
9662 /// multiversioned declaration collection.
9663 static bool CheckMultiVersionAdditionalDecl(
9664     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
9665     MultiVersioning::Type NewMVType, const TargetAttr *NewTA,
9666     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
9667     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9668     LookupResult &Previous) {
9669
9670   MultiVersioning::Type OldMVType = getMultiVersionType(OldFD);
9671   // Disallow mixing of multiversioning types.
9672   if ((OldMVType == MultiVersioning::Target &&
9673        NewMVType != MultiVersioning::Target) ||
9674       (NewMVType == MultiVersioning::Target &&
9675        OldMVType != MultiVersioning::Target)) {
9676     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9677     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9678     NewFD->setInvalidDecl();
9679     return true;
9680   }
9681
9682   TargetAttr::ParsedTargetAttr NewParsed;
9683   if (NewTA) {
9684     NewParsed = NewTA->parse();
9685     llvm::sort(NewParsed.Features.begin(), NewParsed.Features.end());
9686   }
9687
9688   bool UseMemberUsingDeclRules =
9689       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
9690
9691   // Next, check ALL non-overloads to see if this is a redeclaration of a
9692   // previous member of the MultiVersion set.
9693   for (NamedDecl *ND : Previous) {
9694     FunctionDecl *CurFD = ND->getAsFunction();
9695     if (!CurFD)
9696       continue;
9697     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
9698       continue;
9699
9700     if (NewMVType == MultiVersioning::Target) {
9701       const auto *CurTA = CurFD->getAttr<TargetAttr>();
9702       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
9703         NewFD->setIsMultiVersion();
9704         Redeclaration = true;
9705         OldDecl = ND;
9706         return false;
9707       }
9708
9709       TargetAttr::ParsedTargetAttr CurParsed =
9710           CurTA->parse(std::less<std::string>());
9711       if (CurParsed == NewParsed) {
9712         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9713         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9714         NewFD->setInvalidDecl();
9715         return true;
9716       }
9717     } else {
9718       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
9719       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
9720       // Handle CPUDispatch/CPUSpecific versions.
9721       // Only 1 CPUDispatch function is allowed, this will make it go through
9722       // the redeclaration errors.
9723       if (NewMVType == MultiVersioning::CPUDispatch &&
9724           CurFD->hasAttr<CPUDispatchAttr>()) {
9725         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
9726             std::equal(
9727                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
9728                 NewCPUDisp->cpus_begin(),
9729                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9730                   return Cur->getName() == New->getName();
9731                 })) {
9732           NewFD->setIsMultiVersion();
9733           Redeclaration = true;
9734           OldDecl = ND;
9735           return false;
9736         }
9737
9738         // If the declarations don't match, this is an error condition.
9739         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
9740         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9741         NewFD->setInvalidDecl();
9742         return true;
9743       }
9744       if (NewMVType == MultiVersioning::CPUSpecific && CurCPUSpec) {
9745
9746         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
9747             std::equal(
9748                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
9749                 NewCPUSpec->cpus_begin(),
9750                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9751                   return Cur->getName() == New->getName();
9752                 })) {
9753           NewFD->setIsMultiVersion();
9754           Redeclaration = true;
9755           OldDecl = ND;
9756           return false;
9757         }
9758
9759         // Only 1 version of CPUSpecific is allowed for each CPU.
9760         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
9761           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
9762             if (CurII == NewII) {
9763               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
9764                   << NewII;
9765               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9766               NewFD->setInvalidDecl();
9767               return true;
9768             }
9769           }
9770         }
9771       }
9772       // If the two decls aren't the same MVType, there is no possible error
9773       // condition.
9774     }
9775   }
9776
9777   // Else, this is simply a non-redecl case.  Checking the 'value' is only
9778   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
9779   // handled in the attribute adding step.
9780   if (NewMVType == MultiVersioning::Target &&
9781       CheckMultiVersionValue(S, NewFD)) {
9782     NewFD->setInvalidDecl();
9783     return true;
9784   }
9785
9786   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, false, NewMVType)) {
9787     NewFD->setInvalidDecl();
9788     return true;
9789   }
9790
9791   NewFD->setIsMultiVersion();
9792   Redeclaration = false;
9793   MergeTypeWithPrevious = false;
9794   OldDecl = nullptr;
9795   Previous.clear();
9796   return false;
9797 }
9798
9799
9800 /// Check the validity of a mulitversion function declaration.
9801 /// Also sets the multiversion'ness' of the function itself.
9802 ///
9803 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9804 ///
9805 /// Returns true if there was an error, false otherwise.
9806 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
9807                                       bool &Redeclaration, NamedDecl *&OldDecl,
9808                                       bool &MergeTypeWithPrevious,
9809                                       LookupResult &Previous) {
9810   const auto *NewTA = NewFD->getAttr<TargetAttr>();
9811   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
9812   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
9813
9814   // Mixing Multiversioning types is prohibited.
9815   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
9816       (NewCPUDisp && NewCPUSpec)) {
9817     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9818     NewFD->setInvalidDecl();
9819     return true;
9820   }
9821
9822   MultiVersioning::Type MVType = getMultiVersionType(NewFD);
9823
9824   // Main isn't allowed to become a multiversion function, however it IS
9825   // permitted to have 'main' be marked with the 'target' optimization hint.
9826   if (NewFD->isMain()) {
9827     if ((MVType == MultiVersioning::Target && NewTA->isDefaultVersion()) ||
9828         MVType == MultiVersioning::CPUDispatch ||
9829         MVType == MultiVersioning::CPUSpecific) {
9830       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
9831       NewFD->setInvalidDecl();
9832       return true;
9833     }
9834     return false;
9835   }
9836
9837   if (!OldDecl || !OldDecl->getAsFunction() ||
9838       OldDecl->getDeclContext()->getRedeclContext() !=
9839           NewFD->getDeclContext()->getRedeclContext()) {
9840     // If there's no previous declaration, AND this isn't attempting to cause
9841     // multiversioning, this isn't an error condition.
9842     if (MVType == MultiVersioning::None)
9843       return false;
9844     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA, NewCPUDisp,
9845                                           NewCPUSpec);
9846   }
9847
9848   FunctionDecl *OldFD = OldDecl->getAsFunction();
9849
9850   if (!OldFD->isMultiVersion() && MVType == MultiVersioning::None)
9851     return false;
9852
9853   if (OldFD->isMultiVersion() && MVType == MultiVersioning::None) {
9854     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
9855         << (getMultiVersionType(OldFD) != MultiVersioning::Target);
9856     NewFD->setInvalidDecl();
9857     return true;
9858   }
9859
9860   // Handle the target potentially causes multiversioning case.
9861   if (!OldFD->isMultiVersion() && MVType == MultiVersioning::Target)
9862     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
9863                                             Redeclaration, OldDecl,
9864                                             MergeTypeWithPrevious, Previous);
9865   // Previous declarations lack CPUDispatch/CPUSpecific.
9866   if (!OldFD->isMultiVersion()) {
9867     S.Diag(OldFD->getLocation(), diag::err_multiversion_required_in_redecl)
9868         << 1;
9869     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9870     NewFD->setInvalidDecl();
9871     return true;
9872   }
9873
9874   // At this point, we have a multiversion function decl (in OldFD) AND an
9875   // appropriate attribute in the current function decl.  Resolve that these are
9876   // still compatible with previous declarations.
9877   return CheckMultiVersionAdditionalDecl(
9878       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
9879       OldDecl, MergeTypeWithPrevious, Previous);
9880 }
9881
9882 /// Perform semantic checking of a new function declaration.
9883 ///
9884 /// Performs semantic analysis of the new function declaration
9885 /// NewFD. This routine performs all semantic checking that does not
9886 /// require the actual declarator involved in the declaration, and is
9887 /// used both for the declaration of functions as they are parsed
9888 /// (called via ActOnDeclarator) and for the declaration of functions
9889 /// that have been instantiated via C++ template instantiation (called
9890 /// via InstantiateDecl).
9891 ///
9892 /// \param IsMemberSpecialization whether this new function declaration is
9893 /// a member specialization (that replaces any definition provided by the
9894 /// previous declaration).
9895 ///
9896 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9897 ///
9898 /// \returns true if the function declaration is a redeclaration.
9899 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9900                                     LookupResult &Previous,
9901                                     bool IsMemberSpecialization) {
9902   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9903          "Variably modified return types are not handled here");
9904
9905   // Determine whether the type of this function should be merged with
9906   // a previous visible declaration. This never happens for functions in C++,
9907   // and always happens in C if the previous declaration was visible.
9908   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9909                                !Previous.isShadowed();
9910
9911   bool Redeclaration = false;
9912   NamedDecl *OldDecl = nullptr;
9913   bool MayNeedOverloadableChecks = false;
9914
9915   // Merge or overload the declaration with an existing declaration of
9916   // the same name, if appropriate.
9917   if (!Previous.empty()) {
9918     // Determine whether NewFD is an overload of PrevDecl or
9919     // a declaration that requires merging. If it's an overload,
9920     // there's no more work to do here; we'll just add the new
9921     // function to the scope.
9922     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
9923       NamedDecl *Candidate = Previous.getRepresentativeDecl();
9924       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9925         Redeclaration = true;
9926         OldDecl = Candidate;
9927       }
9928     } else {
9929       MayNeedOverloadableChecks = true;
9930       switch (CheckOverload(S, NewFD, Previous, OldDecl,
9931                             /*NewIsUsingDecl*/ false)) {
9932       case Ovl_Match:
9933         Redeclaration = true;
9934         break;
9935
9936       case Ovl_NonFunction:
9937         Redeclaration = true;
9938         break;
9939
9940       case Ovl_Overload:
9941         Redeclaration = false;
9942         break;
9943       }
9944     }
9945   }
9946
9947   // Check for a previous extern "C" declaration with this name.
9948   if (!Redeclaration &&
9949       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9950     if (!Previous.empty()) {
9951       // This is an extern "C" declaration with the same name as a previous
9952       // declaration, and thus redeclares that entity...
9953       Redeclaration = true;
9954       OldDecl = Previous.getFoundDecl();
9955       MergeTypeWithPrevious = false;
9956
9957       // ... except in the presence of __attribute__((overloadable)).
9958       if (OldDecl->hasAttr<OverloadableAttr>() ||
9959           NewFD->hasAttr<OverloadableAttr>()) {
9960         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9961           MayNeedOverloadableChecks = true;
9962           Redeclaration = false;
9963           OldDecl = nullptr;
9964         }
9965       }
9966     }
9967   }
9968
9969   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
9970                                 MergeTypeWithPrevious, Previous))
9971     return Redeclaration;
9972
9973   // C++11 [dcl.constexpr]p8:
9974   //   A constexpr specifier for a non-static member function that is not
9975   //   a constructor declares that member function to be const.
9976   //
9977   // This needs to be delayed until we know whether this is an out-of-line
9978   // definition of a static member function.
9979   //
9980   // This rule is not present in C++1y, so we produce a backwards
9981   // compatibility warning whenever it happens in C++11.
9982   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9983   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9984       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9985       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9986     CXXMethodDecl *OldMD = nullptr;
9987     if (OldDecl)
9988       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9989     if (!OldMD || !OldMD->isStatic()) {
9990       const FunctionProtoType *FPT =
9991         MD->getType()->castAs<FunctionProtoType>();
9992       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9993       EPI.TypeQuals |= Qualifiers::Const;
9994       MD->setType(Context.getFunctionType(FPT->getReturnType(),
9995                                           FPT->getParamTypes(), EPI));
9996
9997       // Warn that we did this, if we're not performing template instantiation.
9998       // In that case, we'll have warned already when the template was defined.
9999       if (!inTemplateInstantiation()) {
10000         SourceLocation AddConstLoc;
10001         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10002                 .IgnoreParens().getAs<FunctionTypeLoc>())
10003           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10004
10005         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10006           << FixItHint::CreateInsertion(AddConstLoc, " const");
10007       }
10008     }
10009   }
10010
10011   if (Redeclaration) {
10012     // NewFD and OldDecl represent declarations that need to be
10013     // merged.
10014     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10015       NewFD->setInvalidDecl();
10016       return Redeclaration;
10017     }
10018
10019     Previous.clear();
10020     Previous.addDecl(OldDecl);
10021
10022     if (FunctionTemplateDecl *OldTemplateDecl =
10023             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10024       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10025       NewFD->setPreviousDeclaration(OldFD);
10026       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10027       FunctionTemplateDecl *NewTemplateDecl
10028         = NewFD->getDescribedFunctionTemplate();
10029       assert(NewTemplateDecl && "Template/non-template mismatch");
10030       if (NewFD->isCXXClassMember()) {
10031         NewFD->setAccess(OldTemplateDecl->getAccess());
10032         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10033       }
10034
10035       // If this is an explicit specialization of a member that is a function
10036       // template, mark it as a member specialization.
10037       if (IsMemberSpecialization &&
10038           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10039         NewTemplateDecl->setMemberSpecialization();
10040         assert(OldTemplateDecl->isMemberSpecialization());
10041         // Explicit specializations of a member template do not inherit deleted
10042         // status from the parent member template that they are specializing.
10043         if (OldFD->isDeleted()) {
10044           // FIXME: This assert will not hold in the presence of modules.
10045           assert(OldFD->getCanonicalDecl() == OldFD);
10046           // FIXME: We need an update record for this AST mutation.
10047           OldFD->setDeletedAsWritten(false);
10048         }
10049       }
10050
10051     } else {
10052       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10053         auto *OldFD = cast<FunctionDecl>(OldDecl);
10054         // This needs to happen first so that 'inline' propagates.
10055         NewFD->setPreviousDeclaration(OldFD);
10056         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10057         if (NewFD->isCXXClassMember())
10058           NewFD->setAccess(OldFD->getAccess());
10059       }
10060     }
10061   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10062              !NewFD->getAttr<OverloadableAttr>()) {
10063     assert((Previous.empty() ||
10064             llvm::any_of(Previous,
10065                          [](const NamedDecl *ND) {
10066                            return ND->hasAttr<OverloadableAttr>();
10067                          })) &&
10068            "Non-redecls shouldn't happen without overloadable present");
10069
10070     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10071       const auto *FD = dyn_cast<FunctionDecl>(ND);
10072       return FD && !FD->hasAttr<OverloadableAttr>();
10073     });
10074
10075     if (OtherUnmarkedIter != Previous.end()) {
10076       Diag(NewFD->getLocation(),
10077            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10078       Diag((*OtherUnmarkedIter)->getLocation(),
10079            diag::note_attribute_overloadable_prev_overload)
10080           << false;
10081
10082       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10083     }
10084   }
10085
10086   // Semantic checking for this function declaration (in isolation).
10087
10088   if (getLangOpts().CPlusPlus) {
10089     // C++-specific checks.
10090     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10091       CheckConstructor(Constructor);
10092     } else if (CXXDestructorDecl *Destructor =
10093                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10094       CXXRecordDecl *Record = Destructor->getParent();
10095       QualType ClassType = Context.getTypeDeclType(Record);
10096
10097       // FIXME: Shouldn't we be able to perform this check even when the class
10098       // type is dependent? Both gcc and edg can handle that.
10099       if (!ClassType->isDependentType()) {
10100         DeclarationName Name
10101           = Context.DeclarationNames.getCXXDestructorName(
10102                                         Context.getCanonicalType(ClassType));
10103         if (NewFD->getDeclName() != Name) {
10104           Diag(NewFD->getLocation(), diag::err_destructor_name);
10105           NewFD->setInvalidDecl();
10106           return Redeclaration;
10107         }
10108       }
10109     } else if (CXXConversionDecl *Conversion
10110                = dyn_cast<CXXConversionDecl>(NewFD)) {
10111       ActOnConversionDeclarator(Conversion);
10112     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10113       if (auto *TD = Guide->getDescribedFunctionTemplate())
10114         CheckDeductionGuideTemplate(TD);
10115
10116       // A deduction guide is not on the list of entities that can be
10117       // explicitly specialized.
10118       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10119         Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
10120             << /*explicit specialization*/ 1;
10121     }
10122
10123     // Find any virtual functions that this function overrides.
10124     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10125       if (!Method->isFunctionTemplateSpecialization() &&
10126           !Method->getDescribedFunctionTemplate() &&
10127           Method->isCanonicalDecl()) {
10128         if (AddOverriddenMethods(Method->getParent(), Method)) {
10129           // If the function was marked as "static", we have a problem.
10130           if (NewFD->getStorageClass() == SC_Static) {
10131             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10132           }
10133         }
10134       }
10135
10136       if (Method->isStatic())
10137         checkThisInStaticMemberFunctionType(Method);
10138     }
10139
10140     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10141     if (NewFD->isOverloadedOperator() &&
10142         CheckOverloadedOperatorDeclaration(NewFD)) {
10143       NewFD->setInvalidDecl();
10144       return Redeclaration;
10145     }
10146
10147     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10148     if (NewFD->getLiteralIdentifier() &&
10149         CheckLiteralOperatorDeclaration(NewFD)) {
10150       NewFD->setInvalidDecl();
10151       return Redeclaration;
10152     }
10153
10154     // In C++, check default arguments now that we have merged decls. Unless
10155     // the lexical context is the class, because in this case this is done
10156     // during delayed parsing anyway.
10157     if (!CurContext->isRecord())
10158       CheckCXXDefaultArguments(NewFD);
10159
10160     // If this function declares a builtin function, check the type of this
10161     // declaration against the expected type for the builtin.
10162     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10163       ASTContext::GetBuiltinTypeError Error;
10164       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10165       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10166       // If the type of the builtin differs only in its exception
10167       // specification, that's OK.
10168       // FIXME: If the types do differ in this way, it would be better to
10169       // retain the 'noexcept' form of the type.
10170       if (!T.isNull() &&
10171           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10172                                                             NewFD->getType()))
10173         // The type of this function differs from the type of the builtin,
10174         // so forget about the builtin entirely.
10175         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10176     }
10177
10178     // If this function is declared as being extern "C", then check to see if
10179     // the function returns a UDT (class, struct, or union type) that is not C
10180     // compatible, and if it does, warn the user.
10181     // But, issue any diagnostic on the first declaration only.
10182     if (Previous.empty() && NewFD->isExternC()) {
10183       QualType R = NewFD->getReturnType();
10184       if (R->isIncompleteType() && !R->isVoidType())
10185         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10186             << NewFD << R;
10187       else if (!R.isPODType(Context) && !R->isVoidType() &&
10188                !R->isObjCObjectPointerType())
10189         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10190     }
10191
10192     // C++1z [dcl.fct]p6:
10193     //   [...] whether the function has a non-throwing exception-specification
10194     //   [is] part of the function type
10195     //
10196     // This results in an ABI break between C++14 and C++17 for functions whose
10197     // declared type includes an exception-specification in a parameter or
10198     // return type. (Exception specifications on the function itself are OK in
10199     // most cases, and exception specifications are not permitted in most other
10200     // contexts where they could make it into a mangling.)
10201     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10202       auto HasNoexcept = [&](QualType T) -> bool {
10203         // Strip off declarator chunks that could be between us and a function
10204         // type. We don't need to look far, exception specifications are very
10205         // restricted prior to C++17.
10206         if (auto *RT = T->getAs<ReferenceType>())
10207           T = RT->getPointeeType();
10208         else if (T->isAnyPointerType())
10209           T = T->getPointeeType();
10210         else if (auto *MPT = T->getAs<MemberPointerType>())
10211           T = MPT->getPointeeType();
10212         if (auto *FPT = T->getAs<FunctionProtoType>())
10213           if (FPT->isNothrow())
10214             return true;
10215         return false;
10216       };
10217
10218       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10219       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10220       for (QualType T : FPT->param_types())
10221         AnyNoexcept |= HasNoexcept(T);
10222       if (AnyNoexcept)
10223         Diag(NewFD->getLocation(),
10224              diag::warn_cxx17_compat_exception_spec_in_signature)
10225             << NewFD;
10226     }
10227
10228     if (!Redeclaration && LangOpts.CUDA)
10229       checkCUDATargetOverload(NewFD, Previous);
10230   }
10231   return Redeclaration;
10232 }
10233
10234 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10235   // C++11 [basic.start.main]p3:
10236   //   A program that [...] declares main to be inline, static or
10237   //   constexpr is ill-formed.
10238   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10239   //   appear in a declaration of main.
10240   // static main is not an error under C99, but we should warn about it.
10241   // We accept _Noreturn main as an extension.
10242   if (FD->getStorageClass() == SC_Static)
10243     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10244          ? diag::err_static_main : diag::warn_static_main)
10245       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10246   if (FD->isInlineSpecified())
10247     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10248       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10249   if (DS.isNoreturnSpecified()) {
10250     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10251     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10252     Diag(NoreturnLoc, diag::ext_noreturn_main);
10253     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10254       << FixItHint::CreateRemoval(NoreturnRange);
10255   }
10256   if (FD->isConstexpr()) {
10257     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10258       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10259     FD->setConstexpr(false);
10260   }
10261
10262   if (getLangOpts().OpenCL) {
10263     Diag(FD->getLocation(), diag::err_opencl_no_main)
10264         << FD->hasAttr<OpenCLKernelAttr>();
10265     FD->setInvalidDecl();
10266     return;
10267   }
10268
10269   QualType T = FD->getType();
10270   assert(T->isFunctionType() && "function decl is not of function type");
10271   const FunctionType* FT = T->castAs<FunctionType>();
10272
10273   // Set default calling convention for main()
10274   if (FT->getCallConv() != CC_C) {
10275     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10276     FD->setType(QualType(FT, 0));
10277     T = Context.getCanonicalType(FD->getType());
10278   }
10279
10280   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10281     // In C with GNU extensions we allow main() to have non-integer return
10282     // type, but we should warn about the extension, and we disable the
10283     // implicit-return-zero rule.
10284
10285     // GCC in C mode accepts qualified 'int'.
10286     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10287       FD->setHasImplicitReturnZero(true);
10288     else {
10289       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10290       SourceRange RTRange = FD->getReturnTypeSourceRange();
10291       if (RTRange.isValid())
10292         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10293             << FixItHint::CreateReplacement(RTRange, "int");
10294     }
10295   } else {
10296     // In C and C++, main magically returns 0 if you fall off the end;
10297     // set the flag which tells us that.
10298     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10299
10300     // All the standards say that main() should return 'int'.
10301     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10302       FD->setHasImplicitReturnZero(true);
10303     else {
10304       // Otherwise, this is just a flat-out error.
10305       SourceRange RTRange = FD->getReturnTypeSourceRange();
10306       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10307           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10308                                 : FixItHint());
10309       FD->setInvalidDecl(true);
10310     }
10311   }
10312
10313   // Treat protoless main() as nullary.
10314   if (isa<FunctionNoProtoType>(FT)) return;
10315
10316   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10317   unsigned nparams = FTP->getNumParams();
10318   assert(FD->getNumParams() == nparams);
10319
10320   bool HasExtraParameters = (nparams > 3);
10321
10322   if (FTP->isVariadic()) {
10323     Diag(FD->getLocation(), diag::ext_variadic_main);
10324     // FIXME: if we had information about the location of the ellipsis, we
10325     // could add a FixIt hint to remove it as a parameter.
10326   }
10327
10328   // Darwin passes an undocumented fourth argument of type char**.  If
10329   // other platforms start sprouting these, the logic below will start
10330   // getting shifty.
10331   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10332     HasExtraParameters = false;
10333
10334   if (HasExtraParameters) {
10335     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10336     FD->setInvalidDecl(true);
10337     nparams = 3;
10338   }
10339
10340   // FIXME: a lot of the following diagnostics would be improved
10341   // if we had some location information about types.
10342
10343   QualType CharPP =
10344     Context.getPointerType(Context.getPointerType(Context.CharTy));
10345   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10346
10347   for (unsigned i = 0; i < nparams; ++i) {
10348     QualType AT = FTP->getParamType(i);
10349
10350     bool mismatch = true;
10351
10352     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10353       mismatch = false;
10354     else if (Expected[i] == CharPP) {
10355       // As an extension, the following forms are okay:
10356       //   char const **
10357       //   char const * const *
10358       //   char * const *
10359
10360       QualifierCollector qs;
10361       const PointerType* PT;
10362       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10363           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10364           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10365                               Context.CharTy)) {
10366         qs.removeConst();
10367         mismatch = !qs.empty();
10368       }
10369     }
10370
10371     if (mismatch) {
10372       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10373       // TODO: suggest replacing given type with expected type
10374       FD->setInvalidDecl(true);
10375     }
10376   }
10377
10378   if (nparams == 1 && !FD->isInvalidDecl()) {
10379     Diag(FD->getLocation(), diag::warn_main_one_arg);
10380   }
10381
10382   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10383     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10384     FD->setInvalidDecl();
10385   }
10386 }
10387
10388 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10389   QualType T = FD->getType();
10390   assert(T->isFunctionType() && "function decl is not of function type");
10391   const FunctionType *FT = T->castAs<FunctionType>();
10392
10393   // Set an implicit return of 'zero' if the function can return some integral,
10394   // enumeration, pointer or nullptr type.
10395   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10396       FT->getReturnType()->isAnyPointerType() ||
10397       FT->getReturnType()->isNullPtrType())
10398     // DllMain is exempt because a return value of zero means it failed.
10399     if (FD->getName() != "DllMain")
10400       FD->setHasImplicitReturnZero(true);
10401
10402   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10403     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10404     FD->setInvalidDecl();
10405   }
10406 }
10407
10408 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10409   // FIXME: Need strict checking.  In C89, we need to check for
10410   // any assignment, increment, decrement, function-calls, or
10411   // commas outside of a sizeof.  In C99, it's the same list,
10412   // except that the aforementioned are allowed in unevaluated
10413   // expressions.  Everything else falls under the
10414   // "may accept other forms of constant expressions" exception.
10415   // (We never end up here for C++, so the constant expression
10416   // rules there don't matter.)
10417   const Expr *Culprit;
10418   if (Init->isConstantInitializer(Context, false, &Culprit))
10419     return false;
10420   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10421     << Culprit->getSourceRange();
10422   return true;
10423 }
10424
10425 namespace {
10426   // Visits an initialization expression to see if OrigDecl is evaluated in
10427   // its own initialization and throws a warning if it does.
10428   class SelfReferenceChecker
10429       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10430     Sema &S;
10431     Decl *OrigDecl;
10432     bool isRecordType;
10433     bool isPODType;
10434     bool isReferenceType;
10435
10436     bool isInitList;
10437     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10438
10439   public:
10440     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10441
10442     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10443                                                     S(S), OrigDecl(OrigDecl) {
10444       isPODType = false;
10445       isRecordType = false;
10446       isReferenceType = false;
10447       isInitList = false;
10448       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10449         isPODType = VD->getType().isPODType(S.Context);
10450         isRecordType = VD->getType()->isRecordType();
10451         isReferenceType = VD->getType()->isReferenceType();
10452       }
10453     }
10454
10455     // For most expressions, just call the visitor.  For initializer lists,
10456     // track the index of the field being initialized since fields are
10457     // initialized in order allowing use of previously initialized fields.
10458     void CheckExpr(Expr *E) {
10459       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10460       if (!InitList) {
10461         Visit(E);
10462         return;
10463       }
10464
10465       // Track and increment the index here.
10466       isInitList = true;
10467       InitFieldIndex.push_back(0);
10468       for (auto Child : InitList->children()) {
10469         CheckExpr(cast<Expr>(Child));
10470         ++InitFieldIndex.back();
10471       }
10472       InitFieldIndex.pop_back();
10473     }
10474
10475     // Returns true if MemberExpr is checked and no further checking is needed.
10476     // Returns false if additional checking is required.
10477     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10478       llvm::SmallVector<FieldDecl*, 4> Fields;
10479       Expr *Base = E;
10480       bool ReferenceField = false;
10481
10482       // Get the field memebers used.
10483       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10484         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10485         if (!FD)
10486           return false;
10487         Fields.push_back(FD);
10488         if (FD->getType()->isReferenceType())
10489           ReferenceField = true;
10490         Base = ME->getBase()->IgnoreParenImpCasts();
10491       }
10492
10493       // Keep checking only if the base Decl is the same.
10494       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10495       if (!DRE || DRE->getDecl() != OrigDecl)
10496         return false;
10497
10498       // A reference field can be bound to an unininitialized field.
10499       if (CheckReference && !ReferenceField)
10500         return true;
10501
10502       // Convert FieldDecls to their index number.
10503       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10504       for (const FieldDecl *I : llvm::reverse(Fields))
10505         UsedFieldIndex.push_back(I->getFieldIndex());
10506
10507       // See if a warning is needed by checking the first difference in index
10508       // numbers.  If field being used has index less than the field being
10509       // initialized, then the use is safe.
10510       for (auto UsedIter = UsedFieldIndex.begin(),
10511                 UsedEnd = UsedFieldIndex.end(),
10512                 OrigIter = InitFieldIndex.begin(),
10513                 OrigEnd = InitFieldIndex.end();
10514            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10515         if (*UsedIter < *OrigIter)
10516           return true;
10517         if (*UsedIter > *OrigIter)
10518           break;
10519       }
10520
10521       // TODO: Add a different warning which will print the field names.
10522       HandleDeclRefExpr(DRE);
10523       return true;
10524     }
10525
10526     // For most expressions, the cast is directly above the DeclRefExpr.
10527     // For conditional operators, the cast can be outside the conditional
10528     // operator if both expressions are DeclRefExpr's.
10529     void HandleValue(Expr *E) {
10530       E = E->IgnoreParens();
10531       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10532         HandleDeclRefExpr(DRE);
10533         return;
10534       }
10535
10536       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10537         Visit(CO->getCond());
10538         HandleValue(CO->getTrueExpr());
10539         HandleValue(CO->getFalseExpr());
10540         return;
10541       }
10542
10543       if (BinaryConditionalOperator *BCO =
10544               dyn_cast<BinaryConditionalOperator>(E)) {
10545         Visit(BCO->getCond());
10546         HandleValue(BCO->getFalseExpr());
10547         return;
10548       }
10549
10550       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10551         HandleValue(OVE->getSourceExpr());
10552         return;
10553       }
10554
10555       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10556         if (BO->getOpcode() == BO_Comma) {
10557           Visit(BO->getLHS());
10558           HandleValue(BO->getRHS());
10559           return;
10560         }
10561       }
10562
10563       if (isa<MemberExpr>(E)) {
10564         if (isInitList) {
10565           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10566                                       false /*CheckReference*/))
10567             return;
10568         }
10569
10570         Expr *Base = E->IgnoreParenImpCasts();
10571         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10572           // Check for static member variables and don't warn on them.
10573           if (!isa<FieldDecl>(ME->getMemberDecl()))
10574             return;
10575           Base = ME->getBase()->IgnoreParenImpCasts();
10576         }
10577         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10578           HandleDeclRefExpr(DRE);
10579         return;
10580       }
10581
10582       Visit(E);
10583     }
10584
10585     // Reference types not handled in HandleValue are handled here since all
10586     // uses of references are bad, not just r-value uses.
10587     void VisitDeclRefExpr(DeclRefExpr *E) {
10588       if (isReferenceType)
10589         HandleDeclRefExpr(E);
10590     }
10591
10592     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10593       if (E->getCastKind() == CK_LValueToRValue) {
10594         HandleValue(E->getSubExpr());
10595         return;
10596       }
10597
10598       Inherited::VisitImplicitCastExpr(E);
10599     }
10600
10601     void VisitMemberExpr(MemberExpr *E) {
10602       if (isInitList) {
10603         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
10604           return;
10605       }
10606
10607       // Don't warn on arrays since they can be treated as pointers.
10608       if (E->getType()->canDecayToPointerType()) return;
10609
10610       // Warn when a non-static method call is followed by non-static member
10611       // field accesses, which is followed by a DeclRefExpr.
10612       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10613       bool Warn = (MD && !MD->isStatic());
10614       Expr *Base = E->getBase()->IgnoreParenImpCasts();
10615       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10616         if (!isa<FieldDecl>(ME->getMemberDecl()))
10617           Warn = false;
10618         Base = ME->getBase()->IgnoreParenImpCasts();
10619       }
10620
10621       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10622         if (Warn)
10623           HandleDeclRefExpr(DRE);
10624         return;
10625       }
10626
10627       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10628       // Visit that expression.
10629       Visit(Base);
10630     }
10631
10632     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10633       Expr *Callee = E->getCallee();
10634
10635       if (isa<UnresolvedLookupExpr>(Callee))
10636         return Inherited::VisitCXXOperatorCallExpr(E);
10637
10638       Visit(Callee);
10639       for (auto Arg: E->arguments())
10640         HandleValue(Arg->IgnoreParenImpCasts());
10641     }
10642
10643     void VisitUnaryOperator(UnaryOperator *E) {
10644       // For POD record types, addresses of its own members are well-defined.
10645       if (E->getOpcode() == UO_AddrOf && isRecordType &&
10646           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
10647         if (!isPODType)
10648           HandleValue(E->getSubExpr());
10649         return;
10650       }
10651
10652       if (E->isIncrementDecrementOp()) {
10653         HandleValue(E->getSubExpr());
10654         return;
10655       }
10656
10657       Inherited::VisitUnaryOperator(E);
10658     }
10659
10660     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
10661
10662     void VisitCXXConstructExpr(CXXConstructExpr *E) {
10663       if (E->getConstructor()->isCopyConstructor()) {
10664         Expr *ArgExpr = E->getArg(0);
10665         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
10666           if (ILE->getNumInits() == 1)
10667             ArgExpr = ILE->getInit(0);
10668         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
10669           if (ICE->getCastKind() == CK_NoOp)
10670             ArgExpr = ICE->getSubExpr();
10671         HandleValue(ArgExpr);
10672         return;
10673       }
10674       Inherited::VisitCXXConstructExpr(E);
10675     }
10676
10677     void VisitCallExpr(CallExpr *E) {
10678       // Treat std::move as a use.
10679       if (E->isCallToStdMove()) {
10680         HandleValue(E->getArg(0));
10681         return;
10682       }
10683
10684       Inherited::VisitCallExpr(E);
10685     }
10686
10687     void VisitBinaryOperator(BinaryOperator *E) {
10688       if (E->isCompoundAssignmentOp()) {
10689         HandleValue(E->getLHS());
10690         Visit(E->getRHS());
10691         return;
10692       }
10693
10694       Inherited::VisitBinaryOperator(E);
10695     }
10696
10697     // A custom visitor for BinaryConditionalOperator is needed because the
10698     // regular visitor would check the condition and true expression separately
10699     // but both point to the same place giving duplicate diagnostics.
10700     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10701       Visit(E->getCond());
10702       Visit(E->getFalseExpr());
10703     }
10704
10705     void HandleDeclRefExpr(DeclRefExpr *DRE) {
10706       Decl* ReferenceDecl = DRE->getDecl();
10707       if (OrigDecl != ReferenceDecl) return;
10708       unsigned diag;
10709       if (isReferenceType) {
10710         diag = diag::warn_uninit_self_reference_in_reference_init;
10711       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10712         diag = diag::warn_static_self_reference_in_init;
10713       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10714                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10715                  DRE->getDecl()->getType()->isRecordType()) {
10716         diag = diag::warn_uninit_self_reference_in_init;
10717       } else {
10718         // Local variables will be handled by the CFG analysis.
10719         return;
10720       }
10721
10722       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
10723                             S.PDiag(diag)
10724                               << DRE->getDecl()
10725                               << OrigDecl->getLocation()
10726                               << DRE->getSourceRange());
10727     }
10728   };
10729
10730   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10731   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10732                                  bool DirectInit) {
10733     // Parameters arguments are occassionially constructed with itself,
10734     // for instance, in recursive functions.  Skip them.
10735     if (isa<ParmVarDecl>(OrigDecl))
10736       return;
10737
10738     E = E->IgnoreParens();
10739
10740     // Skip checking T a = a where T is not a record or reference type.
10741     // Doing so is a way to silence uninitialized warnings.
10742     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10743       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10744         if (ICE->getCastKind() == CK_LValueToRValue)
10745           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10746             if (DRE->getDecl() == OrigDecl)
10747               return;
10748
10749     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10750   }
10751 } // end anonymous namespace
10752
10753 namespace {
10754   // Simple wrapper to add the name of a variable or (if no variable is
10755   // available) a DeclarationName into a diagnostic.
10756   struct VarDeclOrName {
10757     VarDecl *VDecl;
10758     DeclarationName Name;
10759
10760     friend const Sema::SemaDiagnosticBuilder &
10761     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10762       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10763     }
10764   };
10765 } // end anonymous namespace
10766
10767 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10768                                             DeclarationName Name, QualType Type,
10769                                             TypeSourceInfo *TSI,
10770                                             SourceRange Range, bool DirectInit,
10771                                             Expr *Init) {
10772   bool IsInitCapture = !VDecl;
10773   assert((!VDecl || !VDecl->isInitCapture()) &&
10774          "init captures are expected to be deduced prior to initialization");
10775
10776   VarDeclOrName VN{VDecl, Name};
10777
10778   DeducedType *Deduced = Type->getContainedDeducedType();
10779   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10780
10781   // C++11 [dcl.spec.auto]p3
10782   if (!Init) {
10783     assert(VDecl && "no init for init capture deduction?");
10784
10785     // Except for class argument deduction, and then for an initializing
10786     // declaration only, i.e. no static at class scope or extern.
10787     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
10788         VDecl->hasExternalStorage() ||
10789         VDecl->isStaticDataMember()) {
10790       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10791         << VDecl->getDeclName() << Type;
10792       return QualType();
10793     }
10794   }
10795
10796   ArrayRef<Expr*> DeduceInits;
10797   if (Init)
10798     DeduceInits = Init;
10799
10800   if (DirectInit) {
10801     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10802       DeduceInits = PL->exprs();
10803   }
10804
10805   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10806     assert(VDecl && "non-auto type for init capture deduction?");
10807     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10808     InitializationKind Kind = InitializationKind::CreateForInit(
10809         VDecl->getLocation(), DirectInit, Init);
10810     // FIXME: Initialization should not be taking a mutable list of inits.
10811     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10812     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10813                                                        InitsCopy);
10814   }
10815
10816   if (DirectInit) {
10817     if (auto *IL = dyn_cast<InitListExpr>(Init))
10818       DeduceInits = IL->inits();
10819   }
10820
10821   // Deduction only works if we have exactly one source expression.
10822   if (DeduceInits.empty()) {
10823     // It isn't possible to write this directly, but it is possible to
10824     // end up in this situation with "auto x(some_pack...);"
10825     Diag(Init->getLocStart(), IsInitCapture
10826                                   ? diag::err_init_capture_no_expression
10827                                   : diag::err_auto_var_init_no_expression)
10828         << VN << Type << Range;
10829     return QualType();
10830   }
10831
10832   if (DeduceInits.size() > 1) {
10833     Diag(DeduceInits[1]->getLocStart(),
10834          IsInitCapture ? diag::err_init_capture_multiple_expressions
10835                        : diag::err_auto_var_init_multiple_expressions)
10836         << VN << Type << Range;
10837     return QualType();
10838   }
10839
10840   Expr *DeduceInit = DeduceInits[0];
10841   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10842     Diag(Init->getLocStart(), IsInitCapture
10843                                   ? diag::err_init_capture_paren_braces
10844                                   : diag::err_auto_var_init_paren_braces)
10845         << isa<InitListExpr>(Init) << VN << Type << Range;
10846     return QualType();
10847   }
10848
10849   // Expressions default to 'id' when we're in a debugger.
10850   bool DefaultedAnyToId = false;
10851   if (getLangOpts().DebuggerCastResultToId &&
10852       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10853     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10854     if (Result.isInvalid()) {
10855       return QualType();
10856     }
10857     Init = Result.get();
10858     DefaultedAnyToId = true;
10859   }
10860
10861   // C++ [dcl.decomp]p1:
10862   //   If the assignment-expression [...] has array type A and no ref-qualifier
10863   //   is present, e has type cv A
10864   if (VDecl && isa<DecompositionDecl>(VDecl) &&
10865       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10866       DeduceInit->getType()->isConstantArrayType())
10867     return Context.getQualifiedType(DeduceInit->getType(),
10868                                     Type.getQualifiers());
10869
10870   QualType DeducedType;
10871   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
10872     if (!IsInitCapture)
10873       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
10874     else if (isa<InitListExpr>(Init))
10875       Diag(Range.getBegin(),
10876            diag::err_init_capture_deduction_failure_from_init_list)
10877           << VN
10878           << (DeduceInit->getType().isNull() ? TSI->getType()
10879                                              : DeduceInit->getType())
10880           << DeduceInit->getSourceRange();
10881     else
10882       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10883           << VN << TSI->getType()
10884           << (DeduceInit->getType().isNull() ? TSI->getType()
10885                                              : DeduceInit->getType())
10886           << DeduceInit->getSourceRange();
10887   }
10888
10889   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10890   // 'id' instead of a specific object type prevents most of our usual
10891   // checks.
10892   // We only want to warn outside of template instantiations, though:
10893   // inside a template, the 'id' could have come from a parameter.
10894   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10895       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10896     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10897     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10898   }
10899
10900   return DeducedType;
10901 }
10902
10903 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
10904                                          Expr *Init) {
10905   QualType DeducedType = deduceVarTypeFromInitializer(
10906       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10907       VDecl->getSourceRange(), DirectInit, Init);
10908   if (DeducedType.isNull()) {
10909     VDecl->setInvalidDecl();
10910     return true;
10911   }
10912
10913   VDecl->setType(DeducedType);
10914   assert(VDecl->isLinkageValid());
10915
10916   // In ARC, infer lifetime.
10917   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10918     VDecl->setInvalidDecl();
10919
10920   // If this is a redeclaration, check that the type we just deduced matches
10921   // the previously declared type.
10922   if (VarDecl *Old = VDecl->getPreviousDecl()) {
10923     // We never need to merge the type, because we cannot form an incomplete
10924     // array of auto, nor deduce such a type.
10925     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
10926   }
10927
10928   // Check the deduced type is valid for a variable declaration.
10929   CheckVariableDeclarationType(VDecl);
10930   return VDecl->isInvalidDecl();
10931 }
10932
10933 /// AddInitializerToDecl - Adds the initializer Init to the
10934 /// declaration dcl. If DirectInit is true, this is C++ direct
10935 /// initialization rather than copy initialization.
10936 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10937   // If there is no declaration, there was an error parsing it.  Just ignore
10938   // the initializer.
10939   if (!RealDecl || RealDecl->isInvalidDecl()) {
10940     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10941     return;
10942   }
10943
10944   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10945     // Pure-specifiers are handled in ActOnPureSpecifier.
10946     Diag(Method->getLocation(), diag::err_member_function_initialization)
10947       << Method->getDeclName() << Init->getSourceRange();
10948     Method->setInvalidDecl();
10949     return;
10950   }
10951
10952   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
10953   if (!VDecl) {
10954     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
10955     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
10956     RealDecl->setInvalidDecl();
10957     return;
10958   }
10959
10960   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
10961   if (VDecl->getType()->isUndeducedType()) {
10962     // Attempt typo correction early so that the type of the init expression can
10963     // be deduced based on the chosen correction if the original init contains a
10964     // TypoExpr.
10965     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
10966     if (!Res.isUsable()) {
10967       RealDecl->setInvalidDecl();
10968       return;
10969     }
10970     Init = Res.get();
10971
10972     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
10973       return;
10974   }
10975
10976   // dllimport cannot be used on variable definitions.
10977   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
10978     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
10979     VDecl->setInvalidDecl();
10980     return;
10981   }
10982
10983   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
10984     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
10985     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
10986     VDecl->setInvalidDecl();
10987     return;
10988   }
10989
10990   if (!VDecl->getType()->isDependentType()) {
10991     // A definition must end up with a complete type, which means it must be
10992     // complete with the restriction that an array type might be completed by
10993     // the initializer; note that later code assumes this restriction.
10994     QualType BaseDeclType = VDecl->getType();
10995     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
10996       BaseDeclType = Array->getElementType();
10997     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
10998                             diag::err_typecheck_decl_incomplete_type)) {
10999       RealDecl->setInvalidDecl();
11000       return;
11001     }
11002
11003     // The variable can not have an abstract class type.
11004     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11005                                diag::err_abstract_type_in_decl,
11006                                AbstractVariableType))
11007       VDecl->setInvalidDecl();
11008   }
11009
11010   // If adding the initializer will turn this declaration into a definition,
11011   // and we already have a definition for this variable, diagnose or otherwise
11012   // handle the situation.
11013   VarDecl *Def;
11014   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11015       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11016       !VDecl->isThisDeclarationADemotedDefinition() &&
11017       checkVarDeclRedefinition(Def, VDecl))
11018     return;
11019
11020   if (getLangOpts().CPlusPlus) {
11021     // C++ [class.static.data]p4
11022     //   If a static data member is of const integral or const
11023     //   enumeration type, its declaration in the class definition can
11024     //   specify a constant-initializer which shall be an integral
11025     //   constant expression (5.19). In that case, the member can appear
11026     //   in integral constant expressions. The member shall still be
11027     //   defined in a namespace scope if it is used in the program and the
11028     //   namespace scope definition shall not contain an initializer.
11029     //
11030     // We already performed a redefinition check above, but for static
11031     // data members we also need to check whether there was an in-class
11032     // declaration with an initializer.
11033     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11034       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11035           << VDecl->getDeclName();
11036       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11037            diag::note_previous_initializer)
11038           << 0;
11039       return;
11040     }
11041
11042     if (VDecl->hasLocalStorage())
11043       setFunctionHasBranchProtectedScope();
11044
11045     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11046       VDecl->setInvalidDecl();
11047       return;
11048     }
11049   }
11050
11051   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11052   // a kernel function cannot be initialized."
11053   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11054     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11055     VDecl->setInvalidDecl();
11056     return;
11057   }
11058
11059   // Get the decls type and save a reference for later, since
11060   // CheckInitializerTypes may change it.
11061   QualType DclT = VDecl->getType(), SavT = DclT;
11062
11063   // Expressions default to 'id' when we're in a debugger
11064   // and we are assigning it to a variable of Objective-C pointer type.
11065   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11066       Init->getType() == Context.UnknownAnyTy) {
11067     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11068     if (Result.isInvalid()) {
11069       VDecl->setInvalidDecl();
11070       return;
11071     }
11072     Init = Result.get();
11073   }
11074
11075   // Perform the initialization.
11076   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11077   if (!VDecl->isInvalidDecl()) {
11078     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11079     InitializationKind Kind = InitializationKind::CreateForInit(
11080         VDecl->getLocation(), DirectInit, Init);
11081
11082     MultiExprArg Args = Init;
11083     if (CXXDirectInit)
11084       Args = MultiExprArg(CXXDirectInit->getExprs(),
11085                           CXXDirectInit->getNumExprs());
11086
11087     // Try to correct any TypoExprs in the initialization arguments.
11088     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11089       ExprResult Res = CorrectDelayedTyposInExpr(
11090           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11091             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11092             return Init.Failed() ? ExprError() : E;
11093           });
11094       if (Res.isInvalid()) {
11095         VDecl->setInvalidDecl();
11096       } else if (Res.get() != Args[Idx]) {
11097         Args[Idx] = Res.get();
11098       }
11099     }
11100     if (VDecl->isInvalidDecl())
11101       return;
11102
11103     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11104                                    /*TopLevelOfInitList=*/false,
11105                                    /*TreatUnavailableAsInvalid=*/false);
11106     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11107     if (Result.isInvalid()) {
11108       VDecl->setInvalidDecl();
11109       return;
11110     }
11111
11112     Init = Result.getAs<Expr>();
11113   }
11114
11115   // Check for self-references within variable initializers.
11116   // Variables declared within a function/method body (except for references)
11117   // are handled by a dataflow analysis.
11118   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11119       VDecl->getType()->isReferenceType()) {
11120     CheckSelfReference(*this, RealDecl, Init, DirectInit);
11121   }
11122
11123   // If the type changed, it means we had an incomplete type that was
11124   // completed by the initializer. For example:
11125   //   int ary[] = { 1, 3, 5 };
11126   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11127   if (!VDecl->isInvalidDecl() && (DclT != SavT))
11128     VDecl->setType(DclT);
11129
11130   if (!VDecl->isInvalidDecl()) {
11131     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11132
11133     if (VDecl->hasAttr<BlocksAttr>())
11134       checkRetainCycles(VDecl, Init);
11135
11136     // It is safe to assign a weak reference into a strong variable.
11137     // Although this code can still have problems:
11138     //   id x = self.weakProp;
11139     //   id y = self.weakProp;
11140     // we do not warn to warn spuriously when 'x' and 'y' are on separate
11141     // paths through the function. This should be revisited if
11142     // -Wrepeated-use-of-weak is made flow-sensitive.
11143     if (FunctionScopeInfo *FSI = getCurFunction())
11144       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11145            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11146           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11147                            Init->getLocStart()))
11148         FSI->markSafeWeakUse(Init);
11149   }
11150
11151   // The initialization is usually a full-expression.
11152   //
11153   // FIXME: If this is a braced initialization of an aggregate, it is not
11154   // an expression, and each individual field initializer is a separate
11155   // full-expression. For instance, in:
11156   //
11157   //   struct Temp { ~Temp(); };
11158   //   struct S { S(Temp); };
11159   //   struct T { S a, b; } t = { Temp(), Temp() }
11160   //
11161   // we should destroy the first Temp before constructing the second.
11162   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
11163                                           false,
11164                                           VDecl->isConstexpr());
11165   if (Result.isInvalid()) {
11166     VDecl->setInvalidDecl();
11167     return;
11168   }
11169   Init = Result.get();
11170
11171   // Attach the initializer to the decl.
11172   VDecl->setInit(Init);
11173
11174   if (VDecl->isLocalVarDecl()) {
11175     // Don't check the initializer if the declaration is malformed.
11176     if (VDecl->isInvalidDecl()) {
11177       // do nothing
11178
11179     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11180     // This is true even in OpenCL C++.
11181     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11182       CheckForConstantInitializer(Init, DclT);
11183
11184     // Otherwise, C++ does not restrict the initializer.
11185     } else if (getLangOpts().CPlusPlus) {
11186       // do nothing
11187
11188     // C99 6.7.8p4: All the expressions in an initializer for an object that has
11189     // static storage duration shall be constant expressions or string literals.
11190     } else if (VDecl->getStorageClass() == SC_Static) {
11191       CheckForConstantInitializer(Init, DclT);
11192
11193     // C89 is stricter than C99 for aggregate initializers.
11194     // C89 6.5.7p3: All the expressions [...] in an initializer list
11195     // for an object that has aggregate or union type shall be
11196     // constant expressions.
11197     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11198                isa<InitListExpr>(Init)) {
11199       const Expr *Culprit;
11200       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11201         Diag(Culprit->getExprLoc(),
11202              diag::ext_aggregate_init_not_constant)
11203           << Culprit->getSourceRange();
11204       }
11205     }
11206   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11207              VDecl->getLexicalDeclContext()->isRecord()) {
11208     // This is an in-class initialization for a static data member, e.g.,
11209     //
11210     // struct S {
11211     //   static const int value = 17;
11212     // };
11213
11214     // C++ [class.mem]p4:
11215     //   A member-declarator can contain a constant-initializer only
11216     //   if it declares a static member (9.4) of const integral or
11217     //   const enumeration type, see 9.4.2.
11218     //
11219     // C++11 [class.static.data]p3:
11220     //   If a non-volatile non-inline const static data member is of integral
11221     //   or enumeration type, its declaration in the class definition can
11222     //   specify a brace-or-equal-initializer in which every initializer-clause
11223     //   that is an assignment-expression is a constant expression. A static
11224     //   data member of literal type can be declared in the class definition
11225     //   with the constexpr specifier; if so, its declaration shall specify a
11226     //   brace-or-equal-initializer in which every initializer-clause that is
11227     //   an assignment-expression is a constant expression.
11228
11229     // Do nothing on dependent types.
11230     if (DclT->isDependentType()) {
11231
11232     // Allow any 'static constexpr' members, whether or not they are of literal
11233     // type. We separately check that every constexpr variable is of literal
11234     // type.
11235     } else if (VDecl->isConstexpr()) {
11236
11237     // Require constness.
11238     } else if (!DclT.isConstQualified()) {
11239       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11240         << Init->getSourceRange();
11241       VDecl->setInvalidDecl();
11242
11243     // We allow integer constant expressions in all cases.
11244     } else if (DclT->isIntegralOrEnumerationType()) {
11245       // Check whether the expression is a constant expression.
11246       SourceLocation Loc;
11247       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11248         // In C++11, a non-constexpr const static data member with an
11249         // in-class initializer cannot be volatile.
11250         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11251       else if (Init->isValueDependent())
11252         ; // Nothing to check.
11253       else if (Init->isIntegerConstantExpr(Context, &Loc))
11254         ; // Ok, it's an ICE!
11255       else if (Init->getType()->isScopedEnumeralType() &&
11256                Init->isCXX11ConstantExpr(Context))
11257         ; // Ok, it is a scoped-enum constant expression.
11258       else if (Init->isEvaluatable(Context)) {
11259         // If we can constant fold the initializer through heroics, accept it,
11260         // but report this as a use of an extension for -pedantic.
11261         Diag(Loc, diag::ext_in_class_initializer_non_constant)
11262           << Init->getSourceRange();
11263       } else {
11264         // Otherwise, this is some crazy unknown case.  Report the issue at the
11265         // location provided by the isIntegerConstantExpr failed check.
11266         Diag(Loc, diag::err_in_class_initializer_non_constant)
11267           << Init->getSourceRange();
11268         VDecl->setInvalidDecl();
11269       }
11270
11271     // We allow foldable floating-point constants as an extension.
11272     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
11273       // In C++98, this is a GNU extension. In C++11, it is not, but we support
11274       // it anyway and provide a fixit to add the 'constexpr'.
11275       if (getLangOpts().CPlusPlus11) {
11276         Diag(VDecl->getLocation(),
11277              diag::ext_in_class_initializer_float_type_cxx11)
11278             << DclT << Init->getSourceRange();
11279         Diag(VDecl->getLocStart(),
11280              diag::note_in_class_initializer_float_type_cxx11)
11281             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
11282       } else {
11283         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
11284           << DclT << Init->getSourceRange();
11285
11286         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
11287           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
11288             << Init->getSourceRange();
11289           VDecl->setInvalidDecl();
11290         }
11291       }
11292
11293     // Suggest adding 'constexpr' in C++11 for literal types.
11294     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
11295       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
11296         << DclT << Init->getSourceRange()
11297         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
11298       VDecl->setConstexpr(true);
11299
11300     } else {
11301       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
11302         << DclT << Init->getSourceRange();
11303       VDecl->setInvalidDecl();
11304     }
11305   } else if (VDecl->isFileVarDecl()) {
11306     // In C, extern is typically used to avoid tentative definitions when
11307     // declaring variables in headers, but adding an intializer makes it a
11308     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
11309     // In C++, extern is often used to give implictly static const variables
11310     // external linkage, so don't warn in that case. If selectany is present,
11311     // this might be header code intended for C and C++ inclusion, so apply the
11312     // C++ rules.
11313     if (VDecl->getStorageClass() == SC_Extern &&
11314         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
11315          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
11316         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
11317         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
11318       Diag(VDecl->getLocation(), diag::warn_extern_init);
11319
11320     // C99 6.7.8p4. All file scoped initializers need to be constant.
11321     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
11322       CheckForConstantInitializer(Init, DclT);
11323   }
11324
11325   // We will represent direct-initialization similarly to copy-initialization:
11326   //    int x(1);  -as-> int x = 1;
11327   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
11328   //
11329   // Clients that want to distinguish between the two forms, can check for
11330   // direct initializer using VarDecl::getInitStyle().
11331   // A major benefit is that clients that don't particularly care about which
11332   // exactly form was it (like the CodeGen) can handle both cases without
11333   // special case code.
11334
11335   // C++ 8.5p11:
11336   // The form of initialization (using parentheses or '=') is generally
11337   // insignificant, but does matter when the entity being initialized has a
11338   // class type.
11339   if (CXXDirectInit) {
11340     assert(DirectInit && "Call-style initializer must be direct init.");
11341     VDecl->setInitStyle(VarDecl::CallInit);
11342   } else if (DirectInit) {
11343     // This must be list-initialization. No other way is direct-initialization.
11344     VDecl->setInitStyle(VarDecl::ListInit);
11345   }
11346
11347   CheckCompleteVariableDeclaration(VDecl);
11348 }
11349
11350 /// ActOnInitializerError - Given that there was an error parsing an
11351 /// initializer for the given declaration, try to return to some form
11352 /// of sanity.
11353 void Sema::ActOnInitializerError(Decl *D) {
11354   // Our main concern here is re-establishing invariants like "a
11355   // variable's type is either dependent or complete".
11356   if (!D || D->isInvalidDecl()) return;
11357
11358   VarDecl *VD = dyn_cast<VarDecl>(D);
11359   if (!VD) return;
11360
11361   // Bindings are not usable if we can't make sense of the initializer.
11362   if (auto *DD = dyn_cast<DecompositionDecl>(D))
11363     for (auto *BD : DD->bindings())
11364       BD->setInvalidDecl();
11365
11366   // Auto types are meaningless if we can't make sense of the initializer.
11367   if (ParsingInitForAutoVars.count(D)) {
11368     D->setInvalidDecl();
11369     return;
11370   }
11371
11372   QualType Ty = VD->getType();
11373   if (Ty->isDependentType()) return;
11374
11375   // Require a complete type.
11376   if (RequireCompleteType(VD->getLocation(),
11377                           Context.getBaseElementType(Ty),
11378                           diag::err_typecheck_decl_incomplete_type)) {
11379     VD->setInvalidDecl();
11380     return;
11381   }
11382
11383   // Require a non-abstract type.
11384   if (RequireNonAbstractType(VD->getLocation(), Ty,
11385                              diag::err_abstract_type_in_decl,
11386                              AbstractVariableType)) {
11387     VD->setInvalidDecl();
11388     return;
11389   }
11390
11391   // Don't bother complaining about constructors or destructors,
11392   // though.
11393 }
11394
11395 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
11396   // If there is no declaration, there was an error parsing it. Just ignore it.
11397   if (!RealDecl)
11398     return;
11399
11400   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
11401     QualType Type = Var->getType();
11402
11403     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
11404     if (isa<DecompositionDecl>(RealDecl)) {
11405       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
11406       Var->setInvalidDecl();
11407       return;
11408     }
11409
11410     if (Type->isUndeducedType() &&
11411         DeduceVariableDeclarationType(Var, false, nullptr))
11412       return;
11413
11414     // C++11 [class.static.data]p3: A static data member can be declared with
11415     // the constexpr specifier; if so, its declaration shall specify
11416     // a brace-or-equal-initializer.
11417     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
11418     // the definition of a variable [...] or the declaration of a static data
11419     // member.
11420     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
11421         !Var->isThisDeclarationADemotedDefinition()) {
11422       if (Var->isStaticDataMember()) {
11423         // C++1z removes the relevant rule; the in-class declaration is always
11424         // a definition there.
11425         if (!getLangOpts().CPlusPlus17) {
11426           Diag(Var->getLocation(),
11427                diag::err_constexpr_static_mem_var_requires_init)
11428             << Var->getDeclName();
11429           Var->setInvalidDecl();
11430           return;
11431         }
11432       } else {
11433         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
11434         Var->setInvalidDecl();
11435         return;
11436       }
11437     }
11438
11439     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
11440     // be initialized.
11441     if (!Var->isInvalidDecl() &&
11442         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
11443         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
11444       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
11445       Var->setInvalidDecl();
11446       return;
11447     }
11448
11449     switch (Var->isThisDeclarationADefinition()) {
11450     case VarDecl::Definition:
11451       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
11452         break;
11453
11454       // We have an out-of-line definition of a static data member
11455       // that has an in-class initializer, so we type-check this like
11456       // a declaration.
11457       //
11458       LLVM_FALLTHROUGH;
11459
11460     case VarDecl::DeclarationOnly:
11461       // It's only a declaration.
11462
11463       // Block scope. C99 6.7p7: If an identifier for an object is
11464       // declared with no linkage (C99 6.2.2p6), the type for the
11465       // object shall be complete.
11466       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
11467           !Var->hasLinkage() && !Var->isInvalidDecl() &&
11468           RequireCompleteType(Var->getLocation(), Type,
11469                               diag::err_typecheck_decl_incomplete_type))
11470         Var->setInvalidDecl();
11471
11472       // Make sure that the type is not abstract.
11473       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11474           RequireNonAbstractType(Var->getLocation(), Type,
11475                                  diag::err_abstract_type_in_decl,
11476                                  AbstractVariableType))
11477         Var->setInvalidDecl();
11478       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11479           Var->getStorageClass() == SC_PrivateExtern) {
11480         Diag(Var->getLocation(), diag::warn_private_extern);
11481         Diag(Var->getLocation(), diag::note_private_extern);
11482       }
11483
11484       return;
11485
11486     case VarDecl::TentativeDefinition:
11487       // File scope. C99 6.9.2p2: A declaration of an identifier for an
11488       // object that has file scope without an initializer, and without a
11489       // storage-class specifier or with the storage-class specifier "static",
11490       // constitutes a tentative definition. Note: A tentative definition with
11491       // external linkage is valid (C99 6.2.2p5).
11492       if (!Var->isInvalidDecl()) {
11493         if (const IncompleteArrayType *ArrayT
11494                                     = Context.getAsIncompleteArrayType(Type)) {
11495           if (RequireCompleteType(Var->getLocation(),
11496                                   ArrayT->getElementType(),
11497                                   diag::err_illegal_decl_array_incomplete_type))
11498             Var->setInvalidDecl();
11499         } else if (Var->getStorageClass() == SC_Static) {
11500           // C99 6.9.2p3: If the declaration of an identifier for an object is
11501           // a tentative definition and has internal linkage (C99 6.2.2p3), the
11502           // declared type shall not be an incomplete type.
11503           // NOTE: code such as the following
11504           //     static struct s;
11505           //     struct s { int a; };
11506           // is accepted by gcc. Hence here we issue a warning instead of
11507           // an error and we do not invalidate the static declaration.
11508           // NOTE: to avoid multiple warnings, only check the first declaration.
11509           if (Var->isFirstDecl())
11510             RequireCompleteType(Var->getLocation(), Type,
11511                                 diag::ext_typecheck_decl_incomplete_type);
11512         }
11513       }
11514
11515       // Record the tentative definition; we're done.
11516       if (!Var->isInvalidDecl())
11517         TentativeDefinitions.push_back(Var);
11518       return;
11519     }
11520
11521     // Provide a specific diagnostic for uninitialized variable
11522     // definitions with incomplete array type.
11523     if (Type->isIncompleteArrayType()) {
11524       Diag(Var->getLocation(),
11525            diag::err_typecheck_incomplete_array_needs_initializer);
11526       Var->setInvalidDecl();
11527       return;
11528     }
11529
11530     // Provide a specific diagnostic for uninitialized variable
11531     // definitions with reference type.
11532     if (Type->isReferenceType()) {
11533       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
11534         << Var->getDeclName()
11535         << SourceRange(Var->getLocation(), Var->getLocation());
11536       Var->setInvalidDecl();
11537       return;
11538     }
11539
11540     // Do not attempt to type-check the default initializer for a
11541     // variable with dependent type.
11542     if (Type->isDependentType())
11543       return;
11544
11545     if (Var->isInvalidDecl())
11546       return;
11547
11548     if (!Var->hasAttr<AliasAttr>()) {
11549       if (RequireCompleteType(Var->getLocation(),
11550                               Context.getBaseElementType(Type),
11551                               diag::err_typecheck_decl_incomplete_type)) {
11552         Var->setInvalidDecl();
11553         return;
11554       }
11555     } else {
11556       return;
11557     }
11558
11559     // The variable can not have an abstract class type.
11560     if (RequireNonAbstractType(Var->getLocation(), Type,
11561                                diag::err_abstract_type_in_decl,
11562                                AbstractVariableType)) {
11563       Var->setInvalidDecl();
11564       return;
11565     }
11566
11567     // Check for jumps past the implicit initializer.  C++0x
11568     // clarifies that this applies to a "variable with automatic
11569     // storage duration", not a "local variable".
11570     // C++11 [stmt.dcl]p3
11571     //   A program that jumps from a point where a variable with automatic
11572     //   storage duration is not in scope to a point where it is in scope is
11573     //   ill-formed unless the variable has scalar type, class type with a
11574     //   trivial default constructor and a trivial destructor, a cv-qualified
11575     //   version of one of these types, or an array of one of the preceding
11576     //   types and is declared without an initializer.
11577     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
11578       if (const RecordType *Record
11579             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
11580         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
11581         // Mark the function (if we're in one) for further checking even if the
11582         // looser rules of C++11 do not require such checks, so that we can
11583         // diagnose incompatibilities with C++98.
11584         if (!CXXRecord->isPOD())
11585           setFunctionHasBranchProtectedScope();
11586       }
11587     }
11588
11589     // C++03 [dcl.init]p9:
11590     //   If no initializer is specified for an object, and the
11591     //   object is of (possibly cv-qualified) non-POD class type (or
11592     //   array thereof), the object shall be default-initialized; if
11593     //   the object is of const-qualified type, the underlying class
11594     //   type shall have a user-declared default
11595     //   constructor. Otherwise, if no initializer is specified for
11596     //   a non- static object, the object and its subobjects, if
11597     //   any, have an indeterminate initial value); if the object
11598     //   or any of its subobjects are of const-qualified type, the
11599     //   program is ill-formed.
11600     // C++0x [dcl.init]p11:
11601     //   If no initializer is specified for an object, the object is
11602     //   default-initialized; [...].
11603     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
11604     InitializationKind Kind
11605       = InitializationKind::CreateDefault(Var->getLocation());
11606
11607     InitializationSequence InitSeq(*this, Entity, Kind, None);
11608     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
11609     if (Init.isInvalid())
11610       Var->setInvalidDecl();
11611     else if (Init.get()) {
11612       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
11613       // This is important for template substitution.
11614       Var->setInitStyle(VarDecl::CallInit);
11615     }
11616
11617     CheckCompleteVariableDeclaration(Var);
11618   }
11619 }
11620
11621 void Sema::ActOnCXXForRangeDecl(Decl *D) {
11622   // If there is no declaration, there was an error parsing it. Ignore it.
11623   if (!D)
11624     return;
11625
11626   VarDecl *VD = dyn_cast<VarDecl>(D);
11627   if (!VD) {
11628     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
11629     D->setInvalidDecl();
11630     return;
11631   }
11632
11633   VD->setCXXForRangeDecl(true);
11634
11635   // for-range-declaration cannot be given a storage class specifier.
11636   int Error = -1;
11637   switch (VD->getStorageClass()) {
11638   case SC_None:
11639     break;
11640   case SC_Extern:
11641     Error = 0;
11642     break;
11643   case SC_Static:
11644     Error = 1;
11645     break;
11646   case SC_PrivateExtern:
11647     Error = 2;
11648     break;
11649   case SC_Auto:
11650     Error = 3;
11651     break;
11652   case SC_Register:
11653     Error = 4;
11654     break;
11655   }
11656   if (Error != -1) {
11657     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
11658       << VD->getDeclName() << Error;
11659     D->setInvalidDecl();
11660   }
11661 }
11662
11663 StmtResult
11664 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
11665                                  IdentifierInfo *Ident,
11666                                  ParsedAttributes &Attrs,
11667                                  SourceLocation AttrEnd) {
11668   // C++1y [stmt.iter]p1:
11669   //   A range-based for statement of the form
11670   //      for ( for-range-identifier : for-range-initializer ) statement
11671   //   is equivalent to
11672   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
11673   DeclSpec DS(Attrs.getPool().getFactory());
11674
11675   const char *PrevSpec;
11676   unsigned DiagID;
11677   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
11678                      getPrintingPolicy());
11679
11680   Declarator D(DS, DeclaratorContext::ForContext);
11681   D.SetIdentifier(Ident, IdentLoc);
11682   D.takeAttributes(Attrs, AttrEnd);
11683
11684   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
11685   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
11686                 IdentLoc);
11687   Decl *Var = ActOnDeclarator(S, D);
11688   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
11689   FinalizeDeclaration(Var);
11690   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
11691                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
11692 }
11693
11694 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
11695   if (var->isInvalidDecl()) return;
11696
11697   if (getLangOpts().OpenCL) {
11698     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
11699     // initialiser
11700     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
11701         !var->hasInit()) {
11702       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
11703           << 1 /*Init*/;
11704       var->setInvalidDecl();
11705       return;
11706     }
11707   }
11708
11709   // In Objective-C, don't allow jumps past the implicit initialization of a
11710   // local retaining variable.
11711   if (getLangOpts().ObjC1 &&
11712       var->hasLocalStorage()) {
11713     switch (var->getType().getObjCLifetime()) {
11714     case Qualifiers::OCL_None:
11715     case Qualifiers::OCL_ExplicitNone:
11716     case Qualifiers::OCL_Autoreleasing:
11717       break;
11718
11719     case Qualifiers::OCL_Weak:
11720     case Qualifiers::OCL_Strong:
11721       setFunctionHasBranchProtectedScope();
11722       break;
11723     }
11724   }
11725
11726   if (var->hasLocalStorage() &&
11727       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
11728     setFunctionHasBranchProtectedScope();
11729
11730   // Warn about externally-visible variables being defined without a
11731   // prior declaration.  We only want to do this for global
11732   // declarations, but we also specifically need to avoid doing it for
11733   // class members because the linkage of an anonymous class can
11734   // change if it's later given a typedef name.
11735   if (var->isThisDeclarationADefinition() &&
11736       var->getDeclContext()->getRedeclContext()->isFileContext() &&
11737       var->isExternallyVisible() && var->hasLinkage() &&
11738       !var->isInline() && !var->getDescribedVarTemplate() &&
11739       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
11740       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11741                                   var->getLocation())) {
11742     // Find a previous declaration that's not a definition.
11743     VarDecl *prev = var->getPreviousDecl();
11744     while (prev && prev->isThisDeclarationADefinition())
11745       prev = prev->getPreviousDecl();
11746
11747     if (!prev)
11748       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11749   }
11750
11751   // Cache the result of checking for constant initialization.
11752   Optional<bool> CacheHasConstInit;
11753   const Expr *CacheCulprit;
11754   auto checkConstInit = [&]() mutable {
11755     if (!CacheHasConstInit)
11756       CacheHasConstInit = var->getInit()->isConstantInitializer(
11757             Context, var->getType()->isReferenceType(), &CacheCulprit);
11758     return *CacheHasConstInit;
11759   };
11760
11761   if (var->getTLSKind() == VarDecl::TLS_Static) {
11762     if (var->getType().isDestructedType()) {
11763       // GNU C++98 edits for __thread, [basic.start.term]p3:
11764       //   The type of an object with thread storage duration shall not
11765       //   have a non-trivial destructor.
11766       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11767       if (getLangOpts().CPlusPlus11)
11768         Diag(var->getLocation(), diag::note_use_thread_local);
11769     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11770       if (!checkConstInit()) {
11771         // GNU C++98 edits for __thread, [basic.start.init]p4:
11772         //   An object of thread storage duration shall not require dynamic
11773         //   initialization.
11774         // FIXME: Need strict checking here.
11775         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11776           << CacheCulprit->getSourceRange();
11777         if (getLangOpts().CPlusPlus11)
11778           Diag(var->getLocation(), diag::note_use_thread_local);
11779       }
11780     }
11781   }
11782
11783   // Apply section attributes and pragmas to global variables.
11784   bool GlobalStorage = var->hasGlobalStorage();
11785   if (GlobalStorage && var->isThisDeclarationADefinition() &&
11786       !inTemplateInstantiation()) {
11787     PragmaStack<StringLiteral *> *Stack = nullptr;
11788     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11789     if (var->getType().isConstQualified())
11790       Stack = &ConstSegStack;
11791     else if (!var->getInit()) {
11792       Stack = &BSSSegStack;
11793       SectionFlags |= ASTContext::PSF_Write;
11794     } else {
11795       Stack = &DataSegStack;
11796       SectionFlags |= ASTContext::PSF_Write;
11797     }
11798     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11799       var->addAttr(SectionAttr::CreateImplicit(
11800           Context, SectionAttr::Declspec_allocate,
11801           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11802     }
11803     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11804       if (UnifySection(SA->getName(), SectionFlags, var))
11805         var->dropAttr<SectionAttr>();
11806
11807     // Apply the init_seg attribute if this has an initializer.  If the
11808     // initializer turns out to not be dynamic, we'll end up ignoring this
11809     // attribute.
11810     if (CurInitSeg && var->getInit())
11811       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11812                                                CurInitSegLoc));
11813   }
11814
11815   // All the following checks are C++ only.
11816   if (!getLangOpts().CPlusPlus) {
11817       // If this variable must be emitted, add it as an initializer for the
11818       // current module.
11819      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11820        Context.addModuleInitializer(ModuleScopes.back().Module, var);
11821      return;
11822   }
11823
11824   if (auto *DD = dyn_cast<DecompositionDecl>(var))
11825     CheckCompleteDecompositionDeclaration(DD);
11826
11827   QualType type = var->getType();
11828   if (type->isDependentType()) return;
11829
11830   // __block variables might require us to capture a copy-initializer.
11831   if (var->hasAttr<BlocksAttr>()) {
11832     // It's currently invalid to ever have a __block variable with an
11833     // array type; should we diagnose that here?
11834
11835     // Regardless, we don't want to ignore array nesting when
11836     // constructing this copy.
11837     if (type->isStructureOrClassType()) {
11838       EnterExpressionEvaluationContext scope(
11839           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
11840       SourceLocation poi = var->getLocation();
11841       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
11842       ExprResult result
11843         = PerformMoveOrCopyInitialization(
11844             InitializedEntity::InitializeBlock(poi, type, false),
11845             var, var->getType(), varRef, /*AllowNRVO=*/true);
11846       if (!result.isInvalid()) {
11847         result = MaybeCreateExprWithCleanups(result);
11848         Expr *init = result.getAs<Expr>();
11849         Context.setBlockVarCopyInits(var, init);
11850       }
11851     }
11852   }
11853
11854   Expr *Init = var->getInit();
11855   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11856   QualType baseType = Context.getBaseElementType(type);
11857
11858   if (Init && !Init->isValueDependent()) {
11859     if (var->isConstexpr()) {
11860       SmallVector<PartialDiagnosticAt, 8> Notes;
11861       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11862         SourceLocation DiagLoc = var->getLocation();
11863         // If the note doesn't add any useful information other than a source
11864         // location, fold it into the primary diagnostic.
11865         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11866               diag::note_invalid_subexpr_in_const_expr) {
11867           DiagLoc = Notes[0].first;
11868           Notes.clear();
11869         }
11870         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11871           << var << Init->getSourceRange();
11872         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11873           Diag(Notes[I].first, Notes[I].second);
11874       }
11875     } else if (var->isUsableInConstantExpressions(Context)) {
11876       // Check whether the initializer of a const variable of integral or
11877       // enumeration type is an ICE now, since we can't tell whether it was
11878       // initialized by a constant expression if we check later.
11879       var->checkInitIsICE();
11880     }
11881
11882     // Don't emit further diagnostics about constexpr globals since they
11883     // were just diagnosed.
11884     if (!var->isConstexpr() && GlobalStorage &&
11885             var->hasAttr<RequireConstantInitAttr>()) {
11886       // FIXME: Need strict checking in C++03 here.
11887       bool DiagErr = getLangOpts().CPlusPlus11
11888           ? !var->checkInitIsICE() : !checkConstInit();
11889       if (DiagErr) {
11890         auto attr = var->getAttr<RequireConstantInitAttr>();
11891         Diag(var->getLocation(), diag::err_require_constant_init_failed)
11892           << Init->getSourceRange();
11893         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11894           << attr->getRange();
11895         if (getLangOpts().CPlusPlus11) {
11896           APValue Value;
11897           SmallVector<PartialDiagnosticAt, 8> Notes;
11898           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11899           for (auto &it : Notes)
11900             Diag(it.first, it.second);
11901         } else {
11902           Diag(CacheCulprit->getExprLoc(),
11903                diag::note_invalid_subexpr_in_const_expr)
11904               << CacheCulprit->getSourceRange();
11905         }
11906       }
11907     }
11908     else if (!var->isConstexpr() && IsGlobal &&
11909              !getDiagnostics().isIgnored(diag::warn_global_constructor,
11910                                     var->getLocation())) {
11911       // Warn about globals which don't have a constant initializer.  Don't
11912       // warn about globals with a non-trivial destructor because we already
11913       // warned about them.
11914       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11915       if (!(RD && !RD->hasTrivialDestructor())) {
11916         if (!checkConstInit())
11917           Diag(var->getLocation(), diag::warn_global_constructor)
11918             << Init->getSourceRange();
11919       }
11920     }
11921   }
11922
11923   // Require the destructor.
11924   if (const RecordType *recordType = baseType->getAs<RecordType>())
11925     FinalizeVarWithDestructor(var, recordType);
11926
11927   // If this variable must be emitted, add it as an initializer for the current
11928   // module.
11929   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11930     Context.addModuleInitializer(ModuleScopes.back().Module, var);
11931 }
11932
11933 /// Determines if a variable's alignment is dependent.
11934 static bool hasDependentAlignment(VarDecl *VD) {
11935   if (VD->getType()->isDependentType())
11936     return true;
11937   for (auto *I : VD->specific_attrs<AlignedAttr>())
11938     if (I->isAlignmentDependent())
11939       return true;
11940   return false;
11941 }
11942
11943 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
11944 /// any semantic actions necessary after any initializer has been attached.
11945 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
11946   // Note that we are no longer parsing the initializer for this declaration.
11947   ParsingInitForAutoVars.erase(ThisDecl);
11948
11949   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
11950   if (!VD)
11951     return;
11952
11953   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
11954   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
11955       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
11956     if (PragmaClangBSSSection.Valid)
11957       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
11958                                                             PragmaClangBSSSection.SectionName,
11959                                                             PragmaClangBSSSection.PragmaLocation));
11960     if (PragmaClangDataSection.Valid)
11961       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
11962                                                              PragmaClangDataSection.SectionName,
11963                                                              PragmaClangDataSection.PragmaLocation));
11964     if (PragmaClangRodataSection.Valid)
11965       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
11966                                                                PragmaClangRodataSection.SectionName,
11967                                                                PragmaClangRodataSection.PragmaLocation));
11968   }
11969
11970   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
11971     for (auto *BD : DD->bindings()) {
11972       FinalizeDeclaration(BD);
11973     }
11974   }
11975
11976   checkAttributesAfterMerging(*this, *VD);
11977
11978   // Perform TLS alignment check here after attributes attached to the variable
11979   // which may affect the alignment have been processed. Only perform the check
11980   // if the target has a maximum TLS alignment (zero means no constraints).
11981   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
11982     // Protect the check so that it's not performed on dependent types and
11983     // dependent alignments (we can't determine the alignment in that case).
11984     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
11985         !VD->isInvalidDecl()) {
11986       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
11987       if (Context.getDeclAlign(VD) > MaxAlignChars) {
11988         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
11989           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
11990           << (unsigned)MaxAlignChars.getQuantity();
11991       }
11992     }
11993   }
11994
11995   if (VD->isStaticLocal()) {
11996     if (FunctionDecl *FD =
11997             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
11998       // Static locals inherit dll attributes from their function.
11999       if (Attr *A = getDLLAttr(FD)) {
12000         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12001         NewAttr->setInherited(true);
12002         VD->addAttr(NewAttr);
12003       }
12004       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12005       // function, only __shared__ variables or variables without any device
12006       // memory qualifiers may be declared with static storage class.
12007       // Note: It is unclear how a function-scope non-const static variable
12008       // without device memory qualifier is implemented, therefore only static
12009       // const variable without device memory qualifier is allowed.
12010       [&]() {
12011         if (!getLangOpts().CUDA)
12012           return;
12013         if (VD->hasAttr<CUDASharedAttr>())
12014           return;
12015         if (VD->getType().isConstQualified() &&
12016             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12017           return;
12018         if (CUDADiagIfDeviceCode(VD->getLocation(),
12019                                  diag::err_device_static_local_var)
12020             << CurrentCUDATarget())
12021           VD->setInvalidDecl();
12022       }();
12023     }
12024   }
12025
12026   // Perform check for initializers of device-side global variables.
12027   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12028   // 7.5). We must also apply the same checks to all __shared__
12029   // variables whether they are local or not. CUDA also allows
12030   // constant initializers for __constant__ and __device__ variables.
12031   if (getLangOpts().CUDA)
12032     checkAllowedCUDAInitializer(VD);
12033
12034   // Grab the dllimport or dllexport attribute off of the VarDecl.
12035   const InheritableAttr *DLLAttr = getDLLAttr(VD);
12036
12037   // Imported static data members cannot be defined out-of-line.
12038   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12039     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12040         VD->isThisDeclarationADefinition()) {
12041       // We allow definitions of dllimport class template static data members
12042       // with a warning.
12043       CXXRecordDecl *Context =
12044         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12045       bool IsClassTemplateMember =
12046           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12047           Context->getDescribedClassTemplate();
12048
12049       Diag(VD->getLocation(),
12050            IsClassTemplateMember
12051                ? diag::warn_attribute_dllimport_static_field_definition
12052                : diag::err_attribute_dllimport_static_field_definition);
12053       Diag(IA->getLocation(), diag::note_attribute);
12054       if (!IsClassTemplateMember)
12055         VD->setInvalidDecl();
12056     }
12057   }
12058
12059   // dllimport/dllexport variables cannot be thread local, their TLS index
12060   // isn't exported with the variable.
12061   if (DLLAttr && VD->getTLSKind()) {
12062     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12063     if (F && getDLLAttr(F)) {
12064       assert(VD->isStaticLocal());
12065       // But if this is a static local in a dlimport/dllexport function, the
12066       // function will never be inlined, which means the var would never be
12067       // imported, so having it marked import/export is safe.
12068     } else {
12069       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12070                                                                     << DLLAttr;
12071       VD->setInvalidDecl();
12072     }
12073   }
12074
12075   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12076     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12077       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12078       VD->dropAttr<UsedAttr>();
12079     }
12080   }
12081
12082   const DeclContext *DC = VD->getDeclContext();
12083   // If there's a #pragma GCC visibility in scope, and this isn't a class
12084   // member, set the visibility of this variable.
12085   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12086     AddPushedVisibilityAttribute(VD);
12087
12088   // FIXME: Warn on unused var template partial specializations.
12089   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12090     MarkUnusedFileScopedDecl(VD);
12091
12092   // Now we have parsed the initializer and can update the table of magic
12093   // tag values.
12094   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12095       !VD->getType()->isIntegralOrEnumerationType())
12096     return;
12097
12098   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12099     const Expr *MagicValueExpr = VD->getInit();
12100     if (!MagicValueExpr) {
12101       continue;
12102     }
12103     llvm::APSInt MagicValueInt;
12104     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12105       Diag(I->getRange().getBegin(),
12106            diag::err_type_tag_for_datatype_not_ice)
12107         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12108       continue;
12109     }
12110     if (MagicValueInt.getActiveBits() > 64) {
12111       Diag(I->getRange().getBegin(),
12112            diag::err_type_tag_for_datatype_too_large)
12113         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12114       continue;
12115     }
12116     uint64_t MagicValue = MagicValueInt.getZExtValue();
12117     RegisterTypeTagForDatatype(I->getArgumentKind(),
12118                                MagicValue,
12119                                I->getMatchingCType(),
12120                                I->getLayoutCompatible(),
12121                                I->getMustBeNull());
12122   }
12123 }
12124
12125 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12126   auto *VD = dyn_cast<VarDecl>(DD);
12127   return VD && !VD->getType()->hasAutoForTrailingReturnType();
12128 }
12129
12130 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12131                                                    ArrayRef<Decl *> Group) {
12132   SmallVector<Decl*, 8> Decls;
12133
12134   if (DS.isTypeSpecOwned())
12135     Decls.push_back(DS.getRepAsDecl());
12136
12137   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12138   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12139   bool DiagnosedMultipleDecomps = false;
12140   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12141   bool DiagnosedNonDeducedAuto = false;
12142
12143   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12144     if (Decl *D = Group[i]) {
12145       // For declarators, there are some additional syntactic-ish checks we need
12146       // to perform.
12147       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12148         if (!FirstDeclaratorInGroup)
12149           FirstDeclaratorInGroup = DD;
12150         if (!FirstDecompDeclaratorInGroup)
12151           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12152         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12153             !hasDeducedAuto(DD))
12154           FirstNonDeducedAutoInGroup = DD;
12155
12156         if (FirstDeclaratorInGroup != DD) {
12157           // A decomposition declaration cannot be combined with any other
12158           // declaration in the same group.
12159           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12160             Diag(FirstDecompDeclaratorInGroup->getLocation(),
12161                  diag::err_decomp_decl_not_alone)
12162                 << FirstDeclaratorInGroup->getSourceRange()
12163                 << DD->getSourceRange();
12164             DiagnosedMultipleDecomps = true;
12165           }
12166
12167           // A declarator that uses 'auto' in any way other than to declare a
12168           // variable with a deduced type cannot be combined with any other
12169           // declarator in the same group.
12170           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12171             Diag(FirstNonDeducedAutoInGroup->getLocation(),
12172                  diag::err_auto_non_deduced_not_alone)
12173                 << FirstNonDeducedAutoInGroup->getType()
12174                        ->hasAutoForTrailingReturnType()
12175                 << FirstDeclaratorInGroup->getSourceRange()
12176                 << DD->getSourceRange();
12177             DiagnosedNonDeducedAuto = true;
12178           }
12179         }
12180       }
12181
12182       Decls.push_back(D);
12183     }
12184   }
12185
12186   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12187     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12188       handleTagNumbering(Tag, S);
12189       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12190           getLangOpts().CPlusPlus)
12191         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
12192     }
12193   }
12194
12195   return BuildDeclaratorGroup(Decls);
12196 }
12197
12198 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
12199 /// group, performing any necessary semantic checking.
12200 Sema::DeclGroupPtrTy
12201 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
12202   // C++14 [dcl.spec.auto]p7: (DR1347)
12203   //   If the type that replaces the placeholder type is not the same in each
12204   //   deduction, the program is ill-formed.
12205   if (Group.size() > 1) {
12206     QualType Deduced;
12207     VarDecl *DeducedDecl = nullptr;
12208     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12209       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
12210       if (!D || D->isInvalidDecl())
12211         break;
12212       DeducedType *DT = D->getType()->getContainedDeducedType();
12213       if (!DT || DT->getDeducedType().isNull())
12214         continue;
12215       if (Deduced.isNull()) {
12216         Deduced = DT->getDeducedType();
12217         DeducedDecl = D;
12218       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
12219         auto *AT = dyn_cast<AutoType>(DT);
12220         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
12221              diag::err_auto_different_deductions)
12222           << (AT ? (unsigned)AT->getKeyword() : 3)
12223           << Deduced << DeducedDecl->getDeclName()
12224           << DT->getDeducedType() << D->getDeclName()
12225           << DeducedDecl->getInit()->getSourceRange()
12226           << D->getInit()->getSourceRange();
12227         D->setInvalidDecl();
12228         break;
12229       }
12230     }
12231   }
12232
12233   ActOnDocumentableDecls(Group);
12234
12235   return DeclGroupPtrTy::make(
12236       DeclGroupRef::Create(Context, Group.data(), Group.size()));
12237 }
12238
12239 void Sema::ActOnDocumentableDecl(Decl *D) {
12240   ActOnDocumentableDecls(D);
12241 }
12242
12243 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
12244   // Don't parse the comment if Doxygen diagnostics are ignored.
12245   if (Group.empty() || !Group[0])
12246     return;
12247
12248   if (Diags.isIgnored(diag::warn_doc_param_not_found,
12249                       Group[0]->getLocation()) &&
12250       Diags.isIgnored(diag::warn_unknown_comment_command_name,
12251                       Group[0]->getLocation()))
12252     return;
12253
12254   if (Group.size() >= 2) {
12255     // This is a decl group.  Normally it will contain only declarations
12256     // produced from declarator list.  But in case we have any definitions or
12257     // additional declaration references:
12258     //   'typedef struct S {} S;'
12259     //   'typedef struct S *S;'
12260     //   'struct S *pS;'
12261     // FinalizeDeclaratorGroup adds these as separate declarations.
12262     Decl *MaybeTagDecl = Group[0];
12263     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
12264       Group = Group.slice(1);
12265     }
12266   }
12267
12268   // See if there are any new comments that are not attached to a decl.
12269   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
12270   if (!Comments.empty() &&
12271       !Comments.back()->isAttached()) {
12272     // There is at least one comment that not attached to a decl.
12273     // Maybe it should be attached to one of these decls?
12274     //
12275     // Note that this way we pick up not only comments that precede the
12276     // declaration, but also comments that *follow* the declaration -- thanks to
12277     // the lookahead in the lexer: we've consumed the semicolon and looked
12278     // ahead through comments.
12279     for (unsigned i = 0, e = Group.size(); i != e; ++i)
12280       Context.getCommentForDecl(Group[i], &PP);
12281   }
12282 }
12283
12284 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
12285 /// to introduce parameters into function prototype scope.
12286 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
12287   const DeclSpec &DS = D.getDeclSpec();
12288
12289   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
12290
12291   // C++03 [dcl.stc]p2 also permits 'auto'.
12292   StorageClass SC = SC_None;
12293   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
12294     SC = SC_Register;
12295     // In C++11, the 'register' storage class specifier is deprecated.
12296     // In C++17, it is not allowed, but we tolerate it as an extension.
12297     if (getLangOpts().CPlusPlus11) {
12298       Diag(DS.getStorageClassSpecLoc(),
12299            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
12300                                      : diag::warn_deprecated_register)
12301         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12302     }
12303   } else if (getLangOpts().CPlusPlus &&
12304              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
12305     SC = SC_Auto;
12306   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
12307     Diag(DS.getStorageClassSpecLoc(),
12308          diag::err_invalid_storage_class_in_func_decl);
12309     D.getMutableDeclSpec().ClearStorageClassSpecs();
12310   }
12311
12312   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
12313     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
12314       << DeclSpec::getSpecifierName(TSCS);
12315   if (DS.isInlineSpecified())
12316     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
12317         << getLangOpts().CPlusPlus17;
12318   if (DS.isConstexprSpecified())
12319     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
12320       << 0;
12321
12322   DiagnoseFunctionSpecifiers(DS);
12323
12324   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12325   QualType parmDeclType = TInfo->getType();
12326
12327   if (getLangOpts().CPlusPlus) {
12328     // Check that there are no default arguments inside the type of this
12329     // parameter.
12330     CheckExtraCXXDefaultArguments(D);
12331
12332     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
12333     if (D.getCXXScopeSpec().isSet()) {
12334       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
12335         << D.getCXXScopeSpec().getRange();
12336       D.getCXXScopeSpec().clear();
12337     }
12338   }
12339
12340   // Ensure we have a valid name
12341   IdentifierInfo *II = nullptr;
12342   if (D.hasName()) {
12343     II = D.getIdentifier();
12344     if (!II) {
12345       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
12346         << GetNameForDeclarator(D).getName();
12347       D.setInvalidType(true);
12348     }
12349   }
12350
12351   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
12352   if (II) {
12353     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
12354                    ForVisibleRedeclaration);
12355     LookupName(R, S);
12356     if (R.isSingleResult()) {
12357       NamedDecl *PrevDecl = R.getFoundDecl();
12358       if (PrevDecl->isTemplateParameter()) {
12359         // Maybe we will complain about the shadowed template parameter.
12360         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12361         // Just pretend that we didn't see the previous declaration.
12362         PrevDecl = nullptr;
12363       } else if (S->isDeclScope(PrevDecl)) {
12364         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
12365         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12366
12367         // Recover by removing the name
12368         II = nullptr;
12369         D.SetIdentifier(nullptr, D.getIdentifierLoc());
12370         D.setInvalidType(true);
12371       }
12372     }
12373   }
12374
12375   // Temporarily put parameter variables in the translation unit, not
12376   // the enclosing context.  This prevents them from accidentally
12377   // looking like class members in C++.
12378   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
12379                                     D.getLocStart(),
12380                                     D.getIdentifierLoc(), II,
12381                                     parmDeclType, TInfo,
12382                                     SC);
12383
12384   if (D.isInvalidType())
12385     New->setInvalidDecl();
12386
12387   assert(S->isFunctionPrototypeScope());
12388   assert(S->getFunctionPrototypeDepth() >= 1);
12389   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
12390                     S->getNextFunctionPrototypeIndex());
12391
12392   // Add the parameter declaration into this scope.
12393   S->AddDecl(New);
12394   if (II)
12395     IdResolver.AddDecl(New);
12396
12397   ProcessDeclAttributes(S, New, D);
12398
12399   if (D.getDeclSpec().isModulePrivateSpecified())
12400     Diag(New->getLocation(), diag::err_module_private_local)
12401       << 1 << New->getDeclName()
12402       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12403       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12404
12405   if (New->hasAttr<BlocksAttr>()) {
12406     Diag(New->getLocation(), diag::err_block_on_nonlocal);
12407   }
12408   return New;
12409 }
12410
12411 /// Synthesizes a variable for a parameter arising from a
12412 /// typedef.
12413 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
12414                                               SourceLocation Loc,
12415                                               QualType T) {
12416   /* FIXME: setting StartLoc == Loc.
12417      Would it be worth to modify callers so as to provide proper source
12418      location for the unnamed parameters, embedding the parameter's type? */
12419   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
12420                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
12421                                            SC_None, nullptr);
12422   Param->setImplicit();
12423   return Param;
12424 }
12425
12426 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
12427   // Don't diagnose unused-parameter errors in template instantiations; we
12428   // will already have done so in the template itself.
12429   if (inTemplateInstantiation())
12430     return;
12431
12432   for (const ParmVarDecl *Parameter : Parameters) {
12433     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
12434         !Parameter->hasAttr<UnusedAttr>()) {
12435       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
12436         << Parameter->getDeclName();
12437     }
12438   }
12439 }
12440
12441 void Sema::DiagnoseSizeOfParametersAndReturnValue(
12442     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
12443   if (LangOpts.NumLargeByValueCopy == 0) // No check.
12444     return;
12445
12446   // Warn if the return value is pass-by-value and larger than the specified
12447   // threshold.
12448   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
12449     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
12450     if (Size > LangOpts.NumLargeByValueCopy)
12451       Diag(D->getLocation(), diag::warn_return_value_size)
12452           << D->getDeclName() << Size;
12453   }
12454
12455   // Warn if any parameter is pass-by-value and larger than the specified
12456   // threshold.
12457   for (const ParmVarDecl *Parameter : Parameters) {
12458     QualType T = Parameter->getType();
12459     if (T->isDependentType() || !T.isPODType(Context))
12460       continue;
12461     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
12462     if (Size > LangOpts.NumLargeByValueCopy)
12463       Diag(Parameter->getLocation(), diag::warn_parameter_size)
12464           << Parameter->getDeclName() << Size;
12465   }
12466 }
12467
12468 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
12469                                   SourceLocation NameLoc, IdentifierInfo *Name,
12470                                   QualType T, TypeSourceInfo *TSInfo,
12471                                   StorageClass SC) {
12472   // In ARC, infer a lifetime qualifier for appropriate parameter types.
12473   if (getLangOpts().ObjCAutoRefCount &&
12474       T.getObjCLifetime() == Qualifiers::OCL_None &&
12475       T->isObjCLifetimeType()) {
12476
12477     Qualifiers::ObjCLifetime lifetime;
12478
12479     // Special cases for arrays:
12480     //   - if it's const, use __unsafe_unretained
12481     //   - otherwise, it's an error
12482     if (T->isArrayType()) {
12483       if (!T.isConstQualified()) {
12484         DelayedDiagnostics.add(
12485             sema::DelayedDiagnostic::makeForbiddenType(
12486             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
12487       }
12488       lifetime = Qualifiers::OCL_ExplicitNone;
12489     } else {
12490       lifetime = T->getObjCARCImplicitLifetime();
12491     }
12492     T = Context.getLifetimeQualifiedType(T, lifetime);
12493   }
12494
12495   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
12496                                          Context.getAdjustedParameterType(T),
12497                                          TSInfo, SC, nullptr);
12498
12499   // Parameters can not be abstract class types.
12500   // For record types, this is done by the AbstractClassUsageDiagnoser once
12501   // the class has been completely parsed.
12502   if (!CurContext->isRecord() &&
12503       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
12504                              AbstractParamType))
12505     New->setInvalidDecl();
12506
12507   // Parameter declarators cannot be interface types. All ObjC objects are
12508   // passed by reference.
12509   if (T->isObjCObjectType()) {
12510     SourceLocation TypeEndLoc =
12511         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
12512     Diag(NameLoc,
12513          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
12514       << FixItHint::CreateInsertion(TypeEndLoc, "*");
12515     T = Context.getObjCObjectPointerType(T);
12516     New->setType(T);
12517   }
12518
12519   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
12520   // duration shall not be qualified by an address-space qualifier."
12521   // Since all parameters have automatic store duration, they can not have
12522   // an address space.
12523   if (T.getAddressSpace() != LangAS::Default &&
12524       // OpenCL allows function arguments declared to be an array of a type
12525       // to be qualified with an address space.
12526       !(getLangOpts().OpenCL &&
12527         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
12528     Diag(NameLoc, diag::err_arg_with_address_space);
12529     New->setInvalidDecl();
12530   }
12531
12532   return New;
12533 }
12534
12535 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
12536                                            SourceLocation LocAfterDecls) {
12537   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
12538
12539   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
12540   // for a K&R function.
12541   if (!FTI.hasPrototype) {
12542     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
12543       --i;
12544       if (FTI.Params[i].Param == nullptr) {
12545         SmallString<256> Code;
12546         llvm::raw_svector_ostream(Code)
12547             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
12548         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
12549             << FTI.Params[i].Ident
12550             << FixItHint::CreateInsertion(LocAfterDecls, Code);
12551
12552         // Implicitly declare the argument as type 'int' for lack of a better
12553         // type.
12554         AttributeFactory attrs;
12555         DeclSpec DS(attrs);
12556         const char* PrevSpec; // unused
12557         unsigned DiagID; // unused
12558         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
12559                            DiagID, Context.getPrintingPolicy());
12560         // Use the identifier location for the type source range.
12561         DS.SetRangeStart(FTI.Params[i].IdentLoc);
12562         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
12563         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
12564         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
12565         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
12566       }
12567     }
12568   }
12569 }
12570
12571 Decl *
12572 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
12573                               MultiTemplateParamsArg TemplateParameterLists,
12574                               SkipBodyInfo *SkipBody) {
12575   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
12576   assert(D.isFunctionDeclarator() && "Not a function declarator!");
12577   Scope *ParentScope = FnBodyScope->getParent();
12578
12579   D.setFunctionDefinitionKind(FDK_Definition);
12580   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
12581   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
12582 }
12583
12584 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
12585   Consumer.HandleInlineFunctionDefinition(D);
12586 }
12587
12588 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
12589                              const FunctionDecl*& PossibleZeroParamPrototype) {
12590   // Don't warn about invalid declarations.
12591   if (FD->isInvalidDecl())
12592     return false;
12593
12594   // Or declarations that aren't global.
12595   if (!FD->isGlobal())
12596     return false;
12597
12598   // Don't warn about C++ member functions.
12599   if (isa<CXXMethodDecl>(FD))
12600     return false;
12601
12602   // Don't warn about 'main'.
12603   if (FD->isMain())
12604     return false;
12605
12606   // Don't warn about inline functions.
12607   if (FD->isInlined())
12608     return false;
12609
12610   // Don't warn about function templates.
12611   if (FD->getDescribedFunctionTemplate())
12612     return false;
12613
12614   // Don't warn about function template specializations.
12615   if (FD->isFunctionTemplateSpecialization())
12616     return false;
12617
12618   // Don't warn for OpenCL kernels.
12619   if (FD->hasAttr<OpenCLKernelAttr>())
12620     return false;
12621
12622   // Don't warn on explicitly deleted functions.
12623   if (FD->isDeleted())
12624     return false;
12625
12626   bool MissingPrototype = true;
12627   for (const FunctionDecl *Prev = FD->getPreviousDecl();
12628        Prev; Prev = Prev->getPreviousDecl()) {
12629     // Ignore any declarations that occur in function or method
12630     // scope, because they aren't visible from the header.
12631     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
12632       continue;
12633
12634     MissingPrototype = !Prev->getType()->isFunctionProtoType();
12635     if (FD->getNumParams() == 0)
12636       PossibleZeroParamPrototype = Prev;
12637     break;
12638   }
12639
12640   return MissingPrototype;
12641 }
12642
12643 void
12644 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
12645                                    const FunctionDecl *EffectiveDefinition,
12646                                    SkipBodyInfo *SkipBody) {
12647   const FunctionDecl *Definition = EffectiveDefinition;
12648   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
12649     // If this is a friend function defined in a class template, it does not
12650     // have a body until it is used, nevertheless it is a definition, see
12651     // [temp.inst]p2:
12652     //
12653     // ... for the purpose of determining whether an instantiated redeclaration
12654     // is valid according to [basic.def.odr] and [class.mem], a declaration that
12655     // corresponds to a definition in the template is considered to be a
12656     // definition.
12657     //
12658     // The following code must produce redefinition error:
12659     //
12660     //     template<typename T> struct C20 { friend void func_20() {} };
12661     //     C20<int> c20i;
12662     //     void func_20() {}
12663     //
12664     for (auto I : FD->redecls()) {
12665       if (I != FD && !I->isInvalidDecl() &&
12666           I->getFriendObjectKind() != Decl::FOK_None) {
12667         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
12668           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
12669             // A merged copy of the same function, instantiated as a member of
12670             // the same class, is OK.
12671             if (declaresSameEntity(OrigFD, Original) &&
12672                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
12673                                    cast<Decl>(FD->getLexicalDeclContext())))
12674               continue;
12675           }
12676
12677           if (Original->isThisDeclarationADefinition()) {
12678             Definition = I;
12679             break;
12680           }
12681         }
12682       }
12683     }
12684   }
12685   if (!Definition)
12686     return;
12687
12688   if (canRedefineFunction(Definition, getLangOpts()))
12689     return;
12690
12691   // Don't emit an error when this is redefinition of a typo-corrected
12692   // definition.
12693   if (TypoCorrectedFunctionDefinitions.count(Definition))
12694     return;
12695
12696   // If we don't have a visible definition of the function, and it's inline or
12697   // a template, skip the new definition.
12698   if (SkipBody && !hasVisibleDefinition(Definition) &&
12699       (Definition->getFormalLinkage() == InternalLinkage ||
12700        Definition->isInlined() ||
12701        Definition->getDescribedFunctionTemplate() ||
12702        Definition->getNumTemplateParameterLists())) {
12703     SkipBody->ShouldSkip = true;
12704     if (auto *TD = Definition->getDescribedFunctionTemplate())
12705       makeMergedDefinitionVisible(TD);
12706     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
12707     return;
12708   }
12709
12710   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
12711       Definition->getStorageClass() == SC_Extern)
12712     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
12713         << FD->getDeclName() << getLangOpts().CPlusPlus;
12714   else
12715     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12716
12717   Diag(Definition->getLocation(), diag::note_previous_definition);
12718   FD->setInvalidDecl();
12719 }
12720
12721 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12722                                    Sema &S) {
12723   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12724
12725   LambdaScopeInfo *LSI = S.PushLambdaScope();
12726   LSI->CallOperator = CallOperator;
12727   LSI->Lambda = LambdaClass;
12728   LSI->ReturnType = CallOperator->getReturnType();
12729   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12730
12731   if (LCD == LCD_None)
12732     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12733   else if (LCD == LCD_ByCopy)
12734     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12735   else if (LCD == LCD_ByRef)
12736     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12737   DeclarationNameInfo DNI = CallOperator->getNameInfo();
12738
12739   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12740   LSI->Mutable = !CallOperator->isConst();
12741
12742   // Add the captures to the LSI so they can be noted as already
12743   // captured within tryCaptureVar.
12744   auto I = LambdaClass->field_begin();
12745   for (const auto &C : LambdaClass->captures()) {
12746     if (C.capturesVariable()) {
12747       VarDecl *VD = C.getCapturedVar();
12748       if (VD->isInitCapture())
12749         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12750       QualType CaptureType = VD->getType();
12751       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12752       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12753           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12754           /*EllipsisLoc*/C.isPackExpansion()
12755                          ? C.getEllipsisLoc() : SourceLocation(),
12756           CaptureType, /*Expr*/ nullptr);
12757
12758     } else if (C.capturesThis()) {
12759       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
12760                               /*Expr*/ nullptr,
12761                               C.getCaptureKind() == LCK_StarThis);
12762     } else {
12763       LSI->addVLATypeCapture(C.getLocation(), I->getType());
12764     }
12765     ++I;
12766   }
12767 }
12768
12769 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12770                                     SkipBodyInfo *SkipBody) {
12771   if (!D) {
12772     // Parsing the function declaration failed in some way. Push on a fake scope
12773     // anyway so we can try to parse the function body.
12774     PushFunctionScope();
12775     return D;
12776   }
12777
12778   FunctionDecl *FD = nullptr;
12779
12780   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
12781     FD = FunTmpl->getTemplatedDecl();
12782   else
12783     FD = cast<FunctionDecl>(D);
12784
12785   // Check for defining attributes before the check for redefinition.
12786   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
12787     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
12788     FD->dropAttr<AliasAttr>();
12789     FD->setInvalidDecl();
12790   }
12791   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12792     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12793     FD->dropAttr<IFuncAttr>();
12794     FD->setInvalidDecl();
12795   }
12796
12797   // See if this is a redefinition. If 'will have body' is already set, then
12798   // these checks were already performed when it was set.
12799   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
12800     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
12801
12802     // If we're skipping the body, we're done. Don't enter the scope.
12803     if (SkipBody && SkipBody->ShouldSkip)
12804       return D;
12805   }
12806
12807   // Mark this function as "will have a body eventually".  This lets users to
12808   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12809   // this function.
12810   FD->setWillHaveBody();
12811
12812   // If we are instantiating a generic lambda call operator, push
12813   // a LambdaScopeInfo onto the function stack.  But use the information
12814   // that's already been calculated (ActOnLambdaExpr) to prime the current
12815   // LambdaScopeInfo.
12816   // When the template operator is being specialized, the LambdaScopeInfo,
12817   // has to be properly restored so that tryCaptureVariable doesn't try
12818   // and capture any new variables. In addition when calculating potential
12819   // captures during transformation of nested lambdas, it is necessary to
12820   // have the LSI properly restored.
12821   if (isGenericLambdaCallOperatorSpecialization(FD)) {
12822     assert(inTemplateInstantiation() &&
12823            "There should be an active template instantiation on the stack "
12824            "when instantiating a generic lambda!");
12825     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12826   } else {
12827     // Enter a new function scope
12828     PushFunctionScope();
12829   }
12830
12831   // Builtin functions cannot be defined.
12832   if (unsigned BuiltinID = FD->getBuiltinID()) {
12833     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12834         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12835       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12836       FD->setInvalidDecl();
12837     }
12838   }
12839
12840   // The return type of a function definition must be complete
12841   // (C99 6.9.1p3, C++ [dcl.fct]p6).
12842   QualType ResultType = FD->getReturnType();
12843   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12844       !FD->isInvalidDecl() &&
12845       RequireCompleteType(FD->getLocation(), ResultType,
12846                           diag::err_func_def_incomplete_result))
12847     FD->setInvalidDecl();
12848
12849   if (FnBodyScope)
12850     PushDeclContext(FnBodyScope, FD);
12851
12852   // Check the validity of our function parameters
12853   CheckParmsForFunctionDef(FD->parameters(),
12854                            /*CheckParameterNames=*/true);
12855
12856   // Add non-parameter declarations already in the function to the current
12857   // scope.
12858   if (FnBodyScope) {
12859     for (Decl *NPD : FD->decls()) {
12860       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
12861       if (!NonParmDecl)
12862         continue;
12863       assert(!isa<ParmVarDecl>(NonParmDecl) &&
12864              "parameters should not be in newly created FD yet");
12865
12866       // If the decl has a name, make it accessible in the current scope.
12867       if (NonParmDecl->getDeclName())
12868         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
12869
12870       // Similarly, dive into enums and fish their constants out, making them
12871       // accessible in this scope.
12872       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
12873         for (auto *EI : ED->enumerators())
12874           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
12875       }
12876     }
12877   }
12878
12879   // Introduce our parameters into the function scope
12880   for (auto Param : FD->parameters()) {
12881     Param->setOwningFunction(FD);
12882
12883     // If this has an identifier, add it to the scope stack.
12884     if (Param->getIdentifier() && FnBodyScope) {
12885       CheckShadow(FnBodyScope, Param);
12886
12887       PushOnScopeChains(Param, FnBodyScope);
12888     }
12889   }
12890
12891   // Ensure that the function's exception specification is instantiated.
12892   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
12893     ResolveExceptionSpec(D->getLocation(), FPT);
12894
12895   // dllimport cannot be applied to non-inline function definitions.
12896   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
12897       !FD->isTemplateInstantiation()) {
12898     assert(!FD->hasAttr<DLLExportAttr>());
12899     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
12900     FD->setInvalidDecl();
12901     return D;
12902   }
12903   // We want to attach documentation to original Decl (which might be
12904   // a function template).
12905   ActOnDocumentableDecl(D);
12906   if (getCurLexicalContext()->isObjCContainer() &&
12907       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
12908       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
12909     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
12910
12911   return D;
12912 }
12913
12914 /// Given the set of return statements within a function body,
12915 /// compute the variables that are subject to the named return value
12916 /// optimization.
12917 ///
12918 /// Each of the variables that is subject to the named return value
12919 /// optimization will be marked as NRVO variables in the AST, and any
12920 /// return statement that has a marked NRVO variable as its NRVO candidate can
12921 /// use the named return value optimization.
12922 ///
12923 /// This function applies a very simplistic algorithm for NRVO: if every return
12924 /// statement in the scope of a variable has the same NRVO candidate, that
12925 /// candidate is an NRVO variable.
12926 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
12927   ReturnStmt **Returns = Scope->Returns.data();
12928
12929   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
12930     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
12931       if (!NRVOCandidate->isNRVOVariable())
12932         Returns[I]->setNRVOCandidate(nullptr);
12933     }
12934   }
12935 }
12936
12937 bool Sema::canDelayFunctionBody(const Declarator &D) {
12938   // We can't delay parsing the body of a constexpr function template (yet).
12939   if (D.getDeclSpec().isConstexprSpecified())
12940     return false;
12941
12942   // We can't delay parsing the body of a function template with a deduced
12943   // return type (yet).
12944   if (D.getDeclSpec().hasAutoTypeSpec()) {
12945     // If the placeholder introduces a non-deduced trailing return type,
12946     // we can still delay parsing it.
12947     if (D.getNumTypeObjects()) {
12948       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
12949       if (Outer.Kind == DeclaratorChunk::Function &&
12950           Outer.Fun.hasTrailingReturnType()) {
12951         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
12952         return Ty.isNull() || !Ty->isUndeducedType();
12953       }
12954     }
12955     return false;
12956   }
12957
12958   return true;
12959 }
12960
12961 bool Sema::canSkipFunctionBody(Decl *D) {
12962   // We cannot skip the body of a function (or function template) which is
12963   // constexpr, since we may need to evaluate its body in order to parse the
12964   // rest of the file.
12965   // We cannot skip the body of a function with an undeduced return type,
12966   // because any callers of that function need to know the type.
12967   if (const FunctionDecl *FD = D->getAsFunction()) {
12968     if (FD->isConstexpr())
12969       return false;
12970     // We can't simply call Type::isUndeducedType here, because inside template
12971     // auto can be deduced to a dependent type, which is not considered
12972     // "undeduced".
12973     if (FD->getReturnType()->getContainedDeducedType())
12974       return false;
12975   }
12976   return Consumer.shouldSkipFunctionBody(D);
12977 }
12978
12979 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
12980   if (!Decl)
12981     return nullptr;
12982   if (FunctionDecl *FD = Decl->getAsFunction())
12983     FD->setHasSkippedBody();
12984   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
12985     MD->setHasSkippedBody();
12986   return Decl;
12987 }
12988
12989 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
12990   return ActOnFinishFunctionBody(D, BodyArg, false);
12991 }
12992
12993 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
12994                                     bool IsInstantiation) {
12995   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
12996
12997   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12998   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
12999
13000   if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
13001     CheckCompletedCoroutineBody(FD, Body);
13002
13003   if (FD) {
13004     FD->setBody(Body);
13005     FD->setWillHaveBody(false);
13006
13007     if (getLangOpts().CPlusPlus14) {
13008       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13009           FD->getReturnType()->isUndeducedType()) {
13010         // If the function has a deduced result type but contains no 'return'
13011         // statements, the result type as written must be exactly 'auto', and
13012         // the deduced result type is 'void'.
13013         if (!FD->getReturnType()->getAs<AutoType>()) {
13014           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13015               << FD->getReturnType();
13016           FD->setInvalidDecl();
13017         } else {
13018           // Substitute 'void' for the 'auto' in the type.
13019           TypeLoc ResultType = getReturnTypeLoc(FD);
13020           Context.adjustDeducedFunctionResultType(
13021               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13022         }
13023       }
13024     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13025       // In C++11, we don't use 'auto' deduction rules for lambda call
13026       // operators because we don't support return type deduction.
13027       auto *LSI = getCurLambda();
13028       if (LSI->HasImplicitReturnType) {
13029         deduceClosureReturnType(*LSI);
13030
13031         // C++11 [expr.prim.lambda]p4:
13032         //   [...] if there are no return statements in the compound-statement
13033         //   [the deduced type is] the type void
13034         QualType RetType =
13035             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13036
13037         // Update the return type to the deduced type.
13038         const FunctionProtoType *Proto =
13039             FD->getType()->getAs<FunctionProtoType>();
13040         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13041                                             Proto->getExtProtoInfo()));
13042       }
13043     }
13044
13045     // If the function implicitly returns zero (like 'main') or is naked,
13046     // don't complain about missing return statements.
13047     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13048       WP.disableCheckFallThrough();
13049
13050     // MSVC permits the use of pure specifier (=0) on function definition,
13051     // defined at class scope, warn about this non-standard construct.
13052     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
13053       Diag(FD->getLocation(), diag::ext_pure_function_definition);
13054
13055     if (!FD->isInvalidDecl()) {
13056       // Don't diagnose unused parameters of defaulted or deleted functions.
13057       if (!FD->isDeleted() && !FD->isDefaulted())
13058         DiagnoseUnusedParameters(FD->parameters());
13059       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13060                                              FD->getReturnType(), FD);
13061
13062       // If this is a structor, we need a vtable.
13063       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13064         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13065       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13066         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13067
13068       // Try to apply the named return value optimization. We have to check
13069       // if we can do this here because lambdas keep return statements around
13070       // to deduce an implicit return type.
13071       if (FD->getReturnType()->isRecordType() &&
13072           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13073         computeNRVO(Body, getCurFunction());
13074     }
13075
13076     // GNU warning -Wmissing-prototypes:
13077     //   Warn if a global function is defined without a previous
13078     //   prototype declaration. This warning is issued even if the
13079     //   definition itself provides a prototype. The aim is to detect
13080     //   global functions that fail to be declared in header files.
13081     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
13082     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
13083       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
13084
13085       if (PossibleZeroParamPrototype) {
13086         // We found a declaration that is not a prototype,
13087         // but that could be a zero-parameter prototype
13088         if (TypeSourceInfo *TI =
13089                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
13090           TypeLoc TL = TI->getTypeLoc();
13091           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
13092             Diag(PossibleZeroParamPrototype->getLocation(),
13093                  diag::note_declaration_not_a_prototype)
13094                 << PossibleZeroParamPrototype
13095                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
13096         }
13097       }
13098
13099       // GNU warning -Wstrict-prototypes
13100       //   Warn if K&R function is defined without a previous declaration.
13101       //   This warning is issued only if the definition itself does not provide
13102       //   a prototype. Only K&R definitions do not provide a prototype.
13103       //   An empty list in a function declarator that is part of a definition
13104       //   of that function specifies that the function has no parameters
13105       //   (C99 6.7.5.3p14)
13106       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
13107           !LangOpts.CPlusPlus) {
13108         TypeSourceInfo *TI = FD->getTypeSourceInfo();
13109         TypeLoc TL = TI->getTypeLoc();
13110         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
13111         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
13112       }
13113     }
13114
13115     // Warn on CPUDispatch with an actual body.
13116     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
13117       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
13118         if (!CmpndBody->body_empty())
13119           Diag(CmpndBody->body_front()->getLocStart(),
13120                diag::warn_dispatch_body_ignored);
13121
13122     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13123       const CXXMethodDecl *KeyFunction;
13124       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
13125           MD->isVirtual() &&
13126           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
13127           MD == KeyFunction->getCanonicalDecl()) {
13128         // Update the key-function state if necessary for this ABI.
13129         if (FD->isInlined() &&
13130             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13131           Context.setNonKeyFunction(MD);
13132
13133           // If the newly-chosen key function is already defined, then we
13134           // need to mark the vtable as used retroactively.
13135           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
13136           const FunctionDecl *Definition;
13137           if (KeyFunction && KeyFunction->isDefined(Definition))
13138             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
13139         } else {
13140           // We just defined they key function; mark the vtable as used.
13141           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
13142         }
13143       }
13144     }
13145
13146     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
13147            "Function parsing confused");
13148   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
13149     assert(MD == getCurMethodDecl() && "Method parsing confused");
13150     MD->setBody(Body);
13151     if (!MD->isInvalidDecl()) {
13152       DiagnoseUnusedParameters(MD->parameters());
13153       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
13154                                              MD->getReturnType(), MD);
13155
13156       if (Body)
13157         computeNRVO(Body, getCurFunction());
13158     }
13159     if (getCurFunction()->ObjCShouldCallSuper) {
13160       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
13161         << MD->getSelector().getAsString();
13162       getCurFunction()->ObjCShouldCallSuper = false;
13163     }
13164     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
13165       const ObjCMethodDecl *InitMethod = nullptr;
13166       bool isDesignated =
13167           MD->isDesignatedInitializerForTheInterface(&InitMethod);
13168       assert(isDesignated && InitMethod);
13169       (void)isDesignated;
13170
13171       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
13172         auto IFace = MD->getClassInterface();
13173         if (!IFace)
13174           return false;
13175         auto SuperD = IFace->getSuperClass();
13176         if (!SuperD)
13177           return false;
13178         return SuperD->getIdentifier() ==
13179             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
13180       };
13181       // Don't issue this warning for unavailable inits or direct subclasses
13182       // of NSObject.
13183       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
13184         Diag(MD->getLocation(),
13185              diag::warn_objc_designated_init_missing_super_call);
13186         Diag(InitMethod->getLocation(),
13187              diag::note_objc_designated_init_marked_here);
13188       }
13189       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
13190     }
13191     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
13192       // Don't issue this warning for unavaialable inits.
13193       if (!MD->isUnavailable())
13194         Diag(MD->getLocation(),
13195              diag::warn_objc_secondary_init_missing_init_call);
13196       getCurFunction()->ObjCWarnForNoInitDelegation = false;
13197     }
13198   } else {
13199     // Parsing the function declaration failed in some way. Pop the fake scope
13200     // we pushed on.
13201     PopFunctionScopeInfo(ActivePolicy, dcl);
13202     return nullptr;
13203   }
13204
13205   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13206     DiagnoseUnguardedAvailabilityViolations(dcl);
13207
13208   assert(!getCurFunction()->ObjCShouldCallSuper &&
13209          "This should only be set for ObjC methods, which should have been "
13210          "handled in the block above.");
13211
13212   // Verify and clean out per-function state.
13213   if (Body && (!FD || !FD->isDefaulted())) {
13214     // C++ constructors that have function-try-blocks can't have return
13215     // statements in the handlers of that block. (C++ [except.handle]p14)
13216     // Verify this.
13217     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
13218       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
13219
13220     // Verify that gotos and switch cases don't jump into scopes illegally.
13221     if (getCurFunction()->NeedsScopeChecking() &&
13222         !PP.isCodeCompletionEnabled())
13223       DiagnoseInvalidJumps(Body);
13224
13225     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
13226       if (!Destructor->getParent()->isDependentType())
13227         CheckDestructor(Destructor);
13228
13229       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13230                                              Destructor->getParent());
13231     }
13232
13233     // If any errors have occurred, clear out any temporaries that may have
13234     // been leftover. This ensures that these temporaries won't be picked up for
13235     // deletion in some later function.
13236     if (getDiagnostics().hasErrorOccurred() ||
13237         getDiagnostics().getSuppressAllDiagnostics()) {
13238       DiscardCleanupsInEvaluationContext();
13239     }
13240     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
13241         !isa<FunctionTemplateDecl>(dcl)) {
13242       // Since the body is valid, issue any analysis-based warnings that are
13243       // enabled.
13244       ActivePolicy = &WP;
13245     }
13246
13247     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
13248         (!CheckConstexprFunctionDecl(FD) ||
13249          !CheckConstexprFunctionBody(FD, Body)))
13250       FD->setInvalidDecl();
13251
13252     if (FD && FD->hasAttr<NakedAttr>()) {
13253       for (const Stmt *S : Body->children()) {
13254         // Allow local register variables without initializer as they don't
13255         // require prologue.
13256         bool RegisterVariables = false;
13257         if (auto *DS = dyn_cast<DeclStmt>(S)) {
13258           for (const auto *Decl : DS->decls()) {
13259             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
13260               RegisterVariables =
13261                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
13262               if (!RegisterVariables)
13263                 break;
13264             }
13265           }
13266         }
13267         if (RegisterVariables)
13268           continue;
13269         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
13270           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
13271           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
13272           FD->setInvalidDecl();
13273           break;
13274         }
13275       }
13276     }
13277
13278     assert(ExprCleanupObjects.size() ==
13279                ExprEvalContexts.back().NumCleanupObjects &&
13280            "Leftover temporaries in function");
13281     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
13282     assert(MaybeODRUseExprs.empty() &&
13283            "Leftover expressions for odr-use checking");
13284   }
13285
13286   if (!IsInstantiation)
13287     PopDeclContext();
13288
13289   PopFunctionScopeInfo(ActivePolicy, dcl);
13290   // If any errors have occurred, clear out any temporaries that may have
13291   // been leftover. This ensures that these temporaries won't be picked up for
13292   // deletion in some later function.
13293   if (getDiagnostics().hasErrorOccurred()) {
13294     DiscardCleanupsInEvaluationContext();
13295   }
13296
13297   return dcl;
13298 }
13299
13300 /// When we finish delayed parsing of an attribute, we must attach it to the
13301 /// relevant Decl.
13302 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
13303                                        ParsedAttributes &Attrs) {
13304   // Always attach attributes to the underlying decl.
13305   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
13306     D = TD->getTemplatedDecl();
13307   ProcessDeclAttributeList(S, D, Attrs);
13308
13309   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
13310     if (Method->isStatic())
13311       checkThisInStaticMemberFunctionAttributes(Method);
13312 }
13313
13314 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
13315 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
13316 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
13317                                           IdentifierInfo &II, Scope *S) {
13318   // Find the scope in which the identifier is injected and the corresponding
13319   // DeclContext.
13320   // FIXME: C89 does not say what happens if there is no enclosing block scope.
13321   // In that case, we inject the declaration into the translation unit scope
13322   // instead.
13323   Scope *BlockScope = S;
13324   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
13325     BlockScope = BlockScope->getParent();
13326
13327   Scope *ContextScope = BlockScope;
13328   while (!ContextScope->getEntity())
13329     ContextScope = ContextScope->getParent();
13330   ContextRAII SavedContext(*this, ContextScope->getEntity());
13331
13332   // Before we produce a declaration for an implicitly defined
13333   // function, see whether there was a locally-scoped declaration of
13334   // this name as a function or variable. If so, use that
13335   // (non-visible) declaration, and complain about it.
13336   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
13337   if (ExternCPrev) {
13338     // We still need to inject the function into the enclosing block scope so
13339     // that later (non-call) uses can see it.
13340     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
13341
13342     // C89 footnote 38:
13343     //   If in fact it is not defined as having type "function returning int",
13344     //   the behavior is undefined.
13345     if (!isa<FunctionDecl>(ExternCPrev) ||
13346         !Context.typesAreCompatible(
13347             cast<FunctionDecl>(ExternCPrev)->getType(),
13348             Context.getFunctionNoProtoType(Context.IntTy))) {
13349       Diag(Loc, diag::ext_use_out_of_scope_declaration)
13350           << ExternCPrev << !getLangOpts().C99;
13351       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
13352       return ExternCPrev;
13353     }
13354   }
13355
13356   // Extension in C99.  Legal in C90, but warn about it.
13357   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
13358   unsigned diag_id;
13359   if (II.getName().startswith("__builtin_"))
13360     diag_id = diag::warn_builtin_unknown;
13361   else if (getLangOpts().C99 || getLangOpts().OpenCL)
13362     diag_id = diag::ext_implicit_function_decl;
13363   else
13364     diag_id = diag::warn_implicit_function_decl;
13365   Diag(Loc, diag_id) << &II << getLangOpts().OpenCL;
13366
13367   // If we found a prior declaration of this function, don't bother building
13368   // another one. We've already pushed that one into scope, so there's nothing
13369   // more to do.
13370   if (ExternCPrev)
13371     return ExternCPrev;
13372
13373   // Because typo correction is expensive, only do it if the implicit
13374   // function declaration is going to be treated as an error.
13375   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
13376     TypoCorrection Corrected;
13377     if (S &&
13378         (Corrected = CorrectTypo(
13379              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
13380              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
13381       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
13382                    /*ErrorRecovery*/false);
13383   }
13384
13385   // Set a Declarator for the implicit definition: int foo();
13386   const char *Dummy;
13387   AttributeFactory attrFactory;
13388   DeclSpec DS(attrFactory);
13389   unsigned DiagID;
13390   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
13391                                   Context.getPrintingPolicy());
13392   (void)Error; // Silence warning.
13393   assert(!Error && "Error setting up implicit decl!");
13394   SourceLocation NoLoc;
13395   Declarator D(DS, DeclaratorContext::BlockContext);
13396   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
13397                                              /*IsAmbiguous=*/false,
13398                                              /*LParenLoc=*/NoLoc,
13399                                              /*Params=*/nullptr,
13400                                              /*NumParams=*/0,
13401                                              /*EllipsisLoc=*/NoLoc,
13402                                              /*RParenLoc=*/NoLoc,
13403                                              /*TypeQuals=*/0,
13404                                              /*RefQualifierIsLvalueRef=*/true,
13405                                              /*RefQualifierLoc=*/NoLoc,
13406                                              /*ConstQualifierLoc=*/NoLoc,
13407                                              /*VolatileQualifierLoc=*/NoLoc,
13408                                              /*RestrictQualifierLoc=*/NoLoc,
13409                                              /*MutableLoc=*/NoLoc, EST_None,
13410                                              /*ESpecRange=*/SourceRange(),
13411                                              /*Exceptions=*/nullptr,
13412                                              /*ExceptionRanges=*/nullptr,
13413                                              /*NumExceptions=*/0,
13414                                              /*NoexceptExpr=*/nullptr,
13415                                              /*ExceptionSpecTokens=*/nullptr,
13416                                              /*DeclsInPrototype=*/None, Loc,
13417                                              Loc, D),
13418                 std::move(DS.getAttributes()), SourceLocation());
13419   D.SetIdentifier(&II, Loc);
13420
13421   // Insert this function into the enclosing block scope.
13422   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
13423   FD->setImplicit();
13424
13425   AddKnownFunctionAttributes(FD);
13426
13427   return FD;
13428 }
13429
13430 /// Adds any function attributes that we know a priori based on
13431 /// the declaration of this function.
13432 ///
13433 /// These attributes can apply both to implicitly-declared builtins
13434 /// (like __builtin___printf_chk) or to library-declared functions
13435 /// like NSLog or printf.
13436 ///
13437 /// We need to check for duplicate attributes both here and where user-written
13438 /// attributes are applied to declarations.
13439 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
13440   if (FD->isInvalidDecl())
13441     return;
13442
13443   // If this is a built-in function, map its builtin attributes to
13444   // actual attributes.
13445   if (unsigned BuiltinID = FD->getBuiltinID()) {
13446     // Handle printf-formatting attributes.
13447     unsigned FormatIdx;
13448     bool HasVAListArg;
13449     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
13450       if (!FD->hasAttr<FormatAttr>()) {
13451         const char *fmt = "printf";
13452         unsigned int NumParams = FD->getNumParams();
13453         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
13454             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
13455           fmt = "NSString";
13456         FD->addAttr(FormatAttr::CreateImplicit(Context,
13457                                                &Context.Idents.get(fmt),
13458                                                FormatIdx+1,
13459                                                HasVAListArg ? 0 : FormatIdx+2,
13460                                                FD->getLocation()));
13461       }
13462     }
13463     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
13464                                              HasVAListArg)) {
13465      if (!FD->hasAttr<FormatAttr>())
13466        FD->addAttr(FormatAttr::CreateImplicit(Context,
13467                                               &Context.Idents.get("scanf"),
13468                                               FormatIdx+1,
13469                                               HasVAListArg ? 0 : FormatIdx+2,
13470                                               FD->getLocation()));
13471     }
13472
13473     // Mark const if we don't care about errno and that is the only thing
13474     // preventing the function from being const. This allows IRgen to use LLVM
13475     // intrinsics for such functions.
13476     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
13477         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
13478       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13479
13480     // We make "fma" on some platforms const because we know it does not set
13481     // errno in those environments even though it could set errno based on the
13482     // C standard.
13483     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
13484     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
13485         !FD->hasAttr<ConstAttr>()) {
13486       switch (BuiltinID) {
13487       case Builtin::BI__builtin_fma:
13488       case Builtin::BI__builtin_fmaf:
13489       case Builtin::BI__builtin_fmal:
13490       case Builtin::BIfma:
13491       case Builtin::BIfmaf:
13492       case Builtin::BIfmal:
13493         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13494         break;
13495       default:
13496         break;
13497       }
13498     }
13499
13500     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
13501         !FD->hasAttr<ReturnsTwiceAttr>())
13502       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
13503                                          FD->getLocation()));
13504     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
13505       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13506     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
13507       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
13508     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
13509       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13510     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
13511         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
13512       // Add the appropriate attribute, depending on the CUDA compilation mode
13513       // and which target the builtin belongs to. For example, during host
13514       // compilation, aux builtins are __device__, while the rest are __host__.
13515       if (getLangOpts().CUDAIsDevice !=
13516           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
13517         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
13518       else
13519         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
13520     }
13521   }
13522
13523   // If C++ exceptions are enabled but we are told extern "C" functions cannot
13524   // throw, add an implicit nothrow attribute to any extern "C" function we come
13525   // across.
13526   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
13527       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
13528     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
13529     if (!FPT || FPT->getExceptionSpecType() == EST_None)
13530       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13531   }
13532
13533   IdentifierInfo *Name = FD->getIdentifier();
13534   if (!Name)
13535     return;
13536   if ((!getLangOpts().CPlusPlus &&
13537        FD->getDeclContext()->isTranslationUnit()) ||
13538       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
13539        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
13540        LinkageSpecDecl::lang_c)) {
13541     // Okay: this could be a libc/libm/Objective-C function we know
13542     // about.
13543   } else
13544     return;
13545
13546   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
13547     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
13548     // target-specific builtins, perhaps?
13549     if (!FD->hasAttr<FormatAttr>())
13550       FD->addAttr(FormatAttr::CreateImplicit(Context,
13551                                              &Context.Idents.get("printf"), 2,
13552                                              Name->isStr("vasprintf") ? 0 : 3,
13553                                              FD->getLocation()));
13554   }
13555
13556   if (Name->isStr("__CFStringMakeConstantString")) {
13557     // We already have a __builtin___CFStringMakeConstantString,
13558     // but builds that use -fno-constant-cfstrings don't go through that.
13559     if (!FD->hasAttr<FormatArgAttr>())
13560       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
13561                                                 FD->getLocation()));
13562   }
13563 }
13564
13565 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
13566                                     TypeSourceInfo *TInfo) {
13567   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
13568   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
13569
13570   if (!TInfo) {
13571     assert(D.isInvalidType() && "no declarator info for valid type");
13572     TInfo = Context.getTrivialTypeSourceInfo(T);
13573   }
13574
13575   // Scope manipulation handled by caller.
13576   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
13577                                            D.getLocStart(),
13578                                            D.getIdentifierLoc(),
13579                                            D.getIdentifier(),
13580                                            TInfo);
13581
13582   // Bail out immediately if we have an invalid declaration.
13583   if (D.isInvalidType()) {
13584     NewTD->setInvalidDecl();
13585     return NewTD;
13586   }
13587
13588   if (D.getDeclSpec().isModulePrivateSpecified()) {
13589     if (CurContext->isFunctionOrMethod())
13590       Diag(NewTD->getLocation(), diag::err_module_private_local)
13591         << 2 << NewTD->getDeclName()
13592         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13593         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13594     else
13595       NewTD->setModulePrivate();
13596   }
13597
13598   // C++ [dcl.typedef]p8:
13599   //   If the typedef declaration defines an unnamed class (or
13600   //   enum), the first typedef-name declared by the declaration
13601   //   to be that class type (or enum type) is used to denote the
13602   //   class type (or enum type) for linkage purposes only.
13603   // We need to check whether the type was declared in the declaration.
13604   switch (D.getDeclSpec().getTypeSpecType()) {
13605   case TST_enum:
13606   case TST_struct:
13607   case TST_interface:
13608   case TST_union:
13609   case TST_class: {
13610     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
13611     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
13612     break;
13613   }
13614
13615   default:
13616     break;
13617   }
13618
13619   return NewTD;
13620 }
13621
13622 /// Check that this is a valid underlying type for an enum declaration.
13623 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
13624   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
13625   QualType T = TI->getType();
13626
13627   if (T->isDependentType())
13628     return false;
13629
13630   if (const BuiltinType *BT = T->getAs<BuiltinType>())
13631     if (BT->isInteger())
13632       return false;
13633
13634   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
13635   return true;
13636 }
13637
13638 /// Check whether this is a valid redeclaration of a previous enumeration.
13639 /// \return true if the redeclaration was invalid.
13640 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
13641                                   QualType EnumUnderlyingTy, bool IsFixed,
13642                                   const EnumDecl *Prev) {
13643   if (IsScoped != Prev->isScoped()) {
13644     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
13645       << Prev->isScoped();
13646     Diag(Prev->getLocation(), diag::note_previous_declaration);
13647     return true;
13648   }
13649
13650   if (IsFixed && Prev->isFixed()) {
13651     if (!EnumUnderlyingTy->isDependentType() &&
13652         !Prev->getIntegerType()->isDependentType() &&
13653         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
13654                                         Prev->getIntegerType())) {
13655       // TODO: Highlight the underlying type of the redeclaration.
13656       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
13657         << EnumUnderlyingTy << Prev->getIntegerType();
13658       Diag(Prev->getLocation(), diag::note_previous_declaration)
13659           << Prev->getIntegerTypeRange();
13660       return true;
13661     }
13662   } else if (IsFixed != Prev->isFixed()) {
13663     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
13664       << Prev->isFixed();
13665     Diag(Prev->getLocation(), diag::note_previous_declaration);
13666     return true;
13667   }
13668
13669   return false;
13670 }
13671
13672 /// Get diagnostic %select index for tag kind for
13673 /// redeclaration diagnostic message.
13674 /// WARNING: Indexes apply to particular diagnostics only!
13675 ///
13676 /// \returns diagnostic %select index.
13677 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
13678   switch (Tag) {
13679   case TTK_Struct: return 0;
13680   case TTK_Interface: return 1;
13681   case TTK_Class:  return 2;
13682   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
13683   }
13684 }
13685
13686 /// Determine if tag kind is a class-key compatible with
13687 /// class for redeclaration (class, struct, or __interface).
13688 ///
13689 /// \returns true iff the tag kind is compatible.
13690 static bool isClassCompatTagKind(TagTypeKind Tag)
13691 {
13692   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
13693 }
13694
13695 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
13696                                              TagTypeKind TTK) {
13697   if (isa<TypedefDecl>(PrevDecl))
13698     return NTK_Typedef;
13699   else if (isa<TypeAliasDecl>(PrevDecl))
13700     return NTK_TypeAlias;
13701   else if (isa<ClassTemplateDecl>(PrevDecl))
13702     return NTK_Template;
13703   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
13704     return NTK_TypeAliasTemplate;
13705   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
13706     return NTK_TemplateTemplateArgument;
13707   switch (TTK) {
13708   case TTK_Struct:
13709   case TTK_Interface:
13710   case TTK_Class:
13711     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
13712   case TTK_Union:
13713     return NTK_NonUnion;
13714   case TTK_Enum:
13715     return NTK_NonEnum;
13716   }
13717   llvm_unreachable("invalid TTK");
13718 }
13719
13720 /// Determine whether a tag with a given kind is acceptable
13721 /// as a redeclaration of the given tag declaration.
13722 ///
13723 /// \returns true if the new tag kind is acceptable, false otherwise.
13724 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
13725                                         TagTypeKind NewTag, bool isDefinition,
13726                                         SourceLocation NewTagLoc,
13727                                         const IdentifierInfo *Name) {
13728   // C++ [dcl.type.elab]p3:
13729   //   The class-key or enum keyword present in the
13730   //   elaborated-type-specifier shall agree in kind with the
13731   //   declaration to which the name in the elaborated-type-specifier
13732   //   refers. This rule also applies to the form of
13733   //   elaborated-type-specifier that declares a class-name or
13734   //   friend class since it can be construed as referring to the
13735   //   definition of the class. Thus, in any
13736   //   elaborated-type-specifier, the enum keyword shall be used to
13737   //   refer to an enumeration (7.2), the union class-key shall be
13738   //   used to refer to a union (clause 9), and either the class or
13739   //   struct class-key shall be used to refer to a class (clause 9)
13740   //   declared using the class or struct class-key.
13741   TagTypeKind OldTag = Previous->getTagKind();
13742   if (!isDefinition || !isClassCompatTagKind(NewTag))
13743     if (OldTag == NewTag)
13744       return true;
13745
13746   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
13747     // Warn about the struct/class tag mismatch.
13748     bool isTemplate = false;
13749     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
13750       isTemplate = Record->getDescribedClassTemplate();
13751
13752     if (inTemplateInstantiation()) {
13753       // In a template instantiation, do not offer fix-its for tag mismatches
13754       // since they usually mess up the template instead of fixing the problem.
13755       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13756         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13757         << getRedeclDiagFromTagKind(OldTag);
13758       return true;
13759     }
13760
13761     if (isDefinition) {
13762       // On definitions, check previous tags and issue a fix-it for each
13763       // one that doesn't match the current tag.
13764       if (Previous->getDefinition()) {
13765         // Don't suggest fix-its for redefinitions.
13766         return true;
13767       }
13768
13769       bool previousMismatch = false;
13770       for (auto I : Previous->redecls()) {
13771         if (I->getTagKind() != NewTag) {
13772           if (!previousMismatch) {
13773             previousMismatch = true;
13774             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
13775               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13776               << getRedeclDiagFromTagKind(I->getTagKind());
13777           }
13778           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
13779             << getRedeclDiagFromTagKind(NewTag)
13780             << FixItHint::CreateReplacement(I->getInnerLocStart(),
13781                  TypeWithKeyword::getTagTypeKindName(NewTag));
13782         }
13783       }
13784       return true;
13785     }
13786
13787     // Check for a previous definition.  If current tag and definition
13788     // are same type, do nothing.  If no definition, but disagree with
13789     // with previous tag type, give a warning, but no fix-it.
13790     const TagDecl *Redecl = Previous->getDefinition() ?
13791                             Previous->getDefinition() : Previous;
13792     if (Redecl->getTagKind() == NewTag) {
13793       return true;
13794     }
13795
13796     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13797       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13798       << getRedeclDiagFromTagKind(OldTag);
13799     Diag(Redecl->getLocation(), diag::note_previous_use);
13800
13801     // If there is a previous definition, suggest a fix-it.
13802     if (Previous->getDefinition()) {
13803         Diag(NewTagLoc, diag::note_struct_class_suggestion)
13804           << getRedeclDiagFromTagKind(Redecl->getTagKind())
13805           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
13806                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
13807     }
13808
13809     return true;
13810   }
13811   return false;
13812 }
13813
13814 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
13815 /// from an outer enclosing namespace or file scope inside a friend declaration.
13816 /// This should provide the commented out code in the following snippet:
13817 ///   namespace N {
13818 ///     struct X;
13819 ///     namespace M {
13820 ///       struct Y { friend struct /*N::*/ X; };
13821 ///     }
13822 ///   }
13823 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
13824                                          SourceLocation NameLoc) {
13825   // While the decl is in a namespace, do repeated lookup of that name and see
13826   // if we get the same namespace back.  If we do not, continue until
13827   // translation unit scope, at which point we have a fully qualified NNS.
13828   SmallVector<IdentifierInfo *, 4> Namespaces;
13829   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13830   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
13831     // This tag should be declared in a namespace, which can only be enclosed by
13832     // other namespaces.  Bail if there's an anonymous namespace in the chain.
13833     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
13834     if (!Namespace || Namespace->isAnonymousNamespace())
13835       return FixItHint();
13836     IdentifierInfo *II = Namespace->getIdentifier();
13837     Namespaces.push_back(II);
13838     NamedDecl *Lookup = SemaRef.LookupSingleName(
13839         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
13840     if (Lookup == Namespace)
13841       break;
13842   }
13843
13844   // Once we have all the namespaces, reverse them to go outermost first, and
13845   // build an NNS.
13846   SmallString<64> Insertion;
13847   llvm::raw_svector_ostream OS(Insertion);
13848   if (DC->isTranslationUnit())
13849     OS << "::";
13850   std::reverse(Namespaces.begin(), Namespaces.end());
13851   for (auto *II : Namespaces)
13852     OS << II->getName() << "::";
13853   return FixItHint::CreateInsertion(NameLoc, Insertion);
13854 }
13855
13856 /// Determine whether a tag originally declared in context \p OldDC can
13857 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
13858 /// found a declaration in \p OldDC as a previous decl, perhaps through a
13859 /// using-declaration).
13860 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
13861                                          DeclContext *NewDC) {
13862   OldDC = OldDC->getRedeclContext();
13863   NewDC = NewDC->getRedeclContext();
13864
13865   if (OldDC->Equals(NewDC))
13866     return true;
13867
13868   // In MSVC mode, we allow a redeclaration if the contexts are related (either
13869   // encloses the other).
13870   if (S.getLangOpts().MSVCCompat &&
13871       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
13872     return true;
13873
13874   return false;
13875 }
13876
13877 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
13878 /// former case, Name will be non-null.  In the later case, Name will be null.
13879 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
13880 /// reference/declaration/definition of a tag.
13881 ///
13882 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
13883 /// trailing-type-specifier) other than one in an alias-declaration.
13884 ///
13885 /// \param SkipBody If non-null, will be set to indicate if the caller should
13886 /// skip the definition of this tag and treat it as if it were a declaration.
13887 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
13888                      SourceLocation KWLoc, CXXScopeSpec &SS,
13889                      IdentifierInfo *Name, SourceLocation NameLoc,
13890                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
13891                      SourceLocation ModulePrivateLoc,
13892                      MultiTemplateParamsArg TemplateParameterLists,
13893                      bool &OwnedDecl, bool &IsDependent,
13894                      SourceLocation ScopedEnumKWLoc,
13895                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
13896                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
13897                      SkipBodyInfo *SkipBody) {
13898   // If this is not a definition, it must have a name.
13899   IdentifierInfo *OrigName = Name;
13900   assert((Name != nullptr || TUK == TUK_Definition) &&
13901          "Nameless record must be a definition!");
13902   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
13903
13904   OwnedDecl = false;
13905   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13906   bool ScopedEnum = ScopedEnumKWLoc.isValid();
13907
13908   // FIXME: Check member specializations more carefully.
13909   bool isMemberSpecialization = false;
13910   bool Invalid = false;
13911
13912   // We only need to do this matching if we have template parameters
13913   // or a scope specifier, which also conveniently avoids this work
13914   // for non-C++ cases.
13915   if (TemplateParameterLists.size() > 0 ||
13916       (SS.isNotEmpty() && TUK != TUK_Reference)) {
13917     if (TemplateParameterList *TemplateParams =
13918             MatchTemplateParametersToScopeSpecifier(
13919                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
13920                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
13921       if (Kind == TTK_Enum) {
13922         Diag(KWLoc, diag::err_enum_template);
13923         return nullptr;
13924       }
13925
13926       if (TemplateParams->size() > 0) {
13927         // This is a declaration or definition of a class template (which may
13928         // be a member of another template).
13929
13930         if (Invalid)
13931           return nullptr;
13932
13933         OwnedDecl = false;
13934         DeclResult Result = CheckClassTemplate(
13935             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
13936             AS, ModulePrivateLoc,
13937             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
13938             TemplateParameterLists.data(), SkipBody);
13939         return Result.get();
13940       } else {
13941         // The "template<>" header is extraneous.
13942         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13943           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13944         isMemberSpecialization = true;
13945       }
13946     }
13947   }
13948
13949   // Figure out the underlying type if this a enum declaration. We need to do
13950   // this early, because it's needed to detect if this is an incompatible
13951   // redeclaration.
13952   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
13953   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
13954
13955   if (Kind == TTK_Enum) {
13956     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
13957       // No underlying type explicitly specified, or we failed to parse the
13958       // type, default to int.
13959       EnumUnderlying = Context.IntTy.getTypePtr();
13960     } else if (UnderlyingType.get()) {
13961       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
13962       // integral type; any cv-qualification is ignored.
13963       TypeSourceInfo *TI = nullptr;
13964       GetTypeFromParser(UnderlyingType.get(), &TI);
13965       EnumUnderlying = TI;
13966
13967       if (CheckEnumUnderlyingType(TI))
13968         // Recover by falling back to int.
13969         EnumUnderlying = Context.IntTy.getTypePtr();
13970
13971       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
13972                                           UPPC_FixedUnderlyingType))
13973         EnumUnderlying = Context.IntTy.getTypePtr();
13974
13975     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13976       // For MSVC ABI compatibility, unfixed enums must use an underlying type
13977       // of 'int'. However, if this is an unfixed forward declaration, don't set
13978       // the underlying type unless the user enables -fms-compatibility. This
13979       // makes unfixed forward declared enums incomplete and is more conforming.
13980       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
13981         EnumUnderlying = Context.IntTy.getTypePtr();
13982     }
13983   }
13984
13985   DeclContext *SearchDC = CurContext;
13986   DeclContext *DC = CurContext;
13987   bool isStdBadAlloc = false;
13988   bool isStdAlignValT = false;
13989
13990   RedeclarationKind Redecl = forRedeclarationInCurContext();
13991   if (TUK == TUK_Friend || TUK == TUK_Reference)
13992     Redecl = NotForRedeclaration;
13993
13994   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
13995   /// implemented asks for structural equivalence checking, the returned decl
13996   /// here is passed back to the parser, allowing the tag body to be parsed.
13997   auto createTagFromNewDecl = [&]() -> TagDecl * {
13998     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
13999     // If there is an identifier, use the location of the identifier as the
14000     // location of the decl, otherwise use the location of the struct/union
14001     // keyword.
14002     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14003     TagDecl *New = nullptr;
14004
14005     if (Kind == TTK_Enum) {
14006       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14007                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14008       // If this is an undefined enum, bail.
14009       if (TUK != TUK_Definition && !Invalid)
14010         return nullptr;
14011       if (EnumUnderlying) {
14012         EnumDecl *ED = cast<EnumDecl>(New);
14013         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14014           ED->setIntegerTypeSourceInfo(TI);
14015         else
14016           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14017         ED->setPromotionType(ED->getIntegerType());
14018       }
14019     } else { // struct/union
14020       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14021                                nullptr);
14022     }
14023
14024     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14025       // Add alignment attributes if necessary; these attributes are checked
14026       // when the ASTContext lays out the structure.
14027       //
14028       // It is important for implementing the correct semantics that this
14029       // happen here (in ActOnTag). The #pragma pack stack is
14030       // maintained as a result of parser callbacks which can occur at
14031       // many points during the parsing of a struct declaration (because
14032       // the #pragma tokens are effectively skipped over during the
14033       // parsing of the struct).
14034       if (TUK == TUK_Definition) {
14035         AddAlignmentAttributesForRecord(RD);
14036         AddMsStructLayoutForRecord(RD);
14037       }
14038     }
14039     New->setLexicalDeclContext(CurContext);
14040     return New;
14041   };
14042
14043   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
14044   if (Name && SS.isNotEmpty()) {
14045     // We have a nested-name tag ('struct foo::bar').
14046
14047     // Check for invalid 'foo::'.
14048     if (SS.isInvalid()) {
14049       Name = nullptr;
14050       goto CreateNewDecl;
14051     }
14052
14053     // If this is a friend or a reference to a class in a dependent
14054     // context, don't try to make a decl for it.
14055     if (TUK == TUK_Friend || TUK == TUK_Reference) {
14056       DC = computeDeclContext(SS, false);
14057       if (!DC) {
14058         IsDependent = true;
14059         return nullptr;
14060       }
14061     } else {
14062       DC = computeDeclContext(SS, true);
14063       if (!DC) {
14064         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
14065           << SS.getRange();
14066         return nullptr;
14067       }
14068     }
14069
14070     if (RequireCompleteDeclContext(SS, DC))
14071       return nullptr;
14072
14073     SearchDC = DC;
14074     // Look-up name inside 'foo::'.
14075     LookupQualifiedName(Previous, DC);
14076
14077     if (Previous.isAmbiguous())
14078       return nullptr;
14079
14080     if (Previous.empty()) {
14081       // Name lookup did not find anything. However, if the
14082       // nested-name-specifier refers to the current instantiation,
14083       // and that current instantiation has any dependent base
14084       // classes, we might find something at instantiation time: treat
14085       // this as a dependent elaborated-type-specifier.
14086       // But this only makes any sense for reference-like lookups.
14087       if (Previous.wasNotFoundInCurrentInstantiation() &&
14088           (TUK == TUK_Reference || TUK == TUK_Friend)) {
14089         IsDependent = true;
14090         return nullptr;
14091       }
14092
14093       // A tag 'foo::bar' must already exist.
14094       Diag(NameLoc, diag::err_not_tag_in_scope)
14095         << Kind << Name << DC << SS.getRange();
14096       Name = nullptr;
14097       Invalid = true;
14098       goto CreateNewDecl;
14099     }
14100   } else if (Name) {
14101     // C++14 [class.mem]p14:
14102     //   If T is the name of a class, then each of the following shall have a
14103     //   name different from T:
14104     //    -- every member of class T that is itself a type
14105     if (TUK != TUK_Reference && TUK != TUK_Friend &&
14106         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
14107       return nullptr;
14108
14109     // If this is a named struct, check to see if there was a previous forward
14110     // declaration or definition.
14111     // FIXME: We're looking into outer scopes here, even when we
14112     // shouldn't be. Doing so can result in ambiguities that we
14113     // shouldn't be diagnosing.
14114     LookupName(Previous, S);
14115
14116     // When declaring or defining a tag, ignore ambiguities introduced
14117     // by types using'ed into this scope.
14118     if (Previous.isAmbiguous() &&
14119         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
14120       LookupResult::Filter F = Previous.makeFilter();
14121       while (F.hasNext()) {
14122         NamedDecl *ND = F.next();
14123         if (!ND->getDeclContext()->getRedeclContext()->Equals(
14124                 SearchDC->getRedeclContext()))
14125           F.erase();
14126       }
14127       F.done();
14128     }
14129
14130     // C++11 [namespace.memdef]p3:
14131     //   If the name in a friend declaration is neither qualified nor
14132     //   a template-id and the declaration is a function or an
14133     //   elaborated-type-specifier, the lookup to determine whether
14134     //   the entity has been previously declared shall not consider
14135     //   any scopes outside the innermost enclosing namespace.
14136     //
14137     // MSVC doesn't implement the above rule for types, so a friend tag
14138     // declaration may be a redeclaration of a type declared in an enclosing
14139     // scope.  They do implement this rule for friend functions.
14140     //
14141     // Does it matter that this should be by scope instead of by
14142     // semantic context?
14143     if (!Previous.empty() && TUK == TUK_Friend) {
14144       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
14145       LookupResult::Filter F = Previous.makeFilter();
14146       bool FriendSawTagOutsideEnclosingNamespace = false;
14147       while (F.hasNext()) {
14148         NamedDecl *ND = F.next();
14149         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14150         if (DC->isFileContext() &&
14151             !EnclosingNS->Encloses(ND->getDeclContext())) {
14152           if (getLangOpts().MSVCCompat)
14153             FriendSawTagOutsideEnclosingNamespace = true;
14154           else
14155             F.erase();
14156         }
14157       }
14158       F.done();
14159
14160       // Diagnose this MSVC extension in the easy case where lookup would have
14161       // unambiguously found something outside the enclosing namespace.
14162       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
14163         NamedDecl *ND = Previous.getFoundDecl();
14164         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
14165             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
14166       }
14167     }
14168
14169     // Note:  there used to be some attempt at recovery here.
14170     if (Previous.isAmbiguous())
14171       return nullptr;
14172
14173     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
14174       // FIXME: This makes sure that we ignore the contexts associated
14175       // with C structs, unions, and enums when looking for a matching
14176       // tag declaration or definition. See the similar lookup tweak
14177       // in Sema::LookupName; is there a better way to deal with this?
14178       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
14179         SearchDC = SearchDC->getParent();
14180     }
14181   }
14182
14183   if (Previous.isSingleResult() &&
14184       Previous.getFoundDecl()->isTemplateParameter()) {
14185     // Maybe we will complain about the shadowed template parameter.
14186     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
14187     // Just pretend that we didn't see the previous declaration.
14188     Previous.clear();
14189   }
14190
14191   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
14192       DC->Equals(getStdNamespace())) {
14193     if (Name->isStr("bad_alloc")) {
14194       // This is a declaration of or a reference to "std::bad_alloc".
14195       isStdBadAlloc = true;
14196
14197       // If std::bad_alloc has been implicitly declared (but made invisible to
14198       // name lookup), fill in this implicit declaration as the previous
14199       // declaration, so that the declarations get chained appropriately.
14200       if (Previous.empty() && StdBadAlloc)
14201         Previous.addDecl(getStdBadAlloc());
14202     } else if (Name->isStr("align_val_t")) {
14203       isStdAlignValT = true;
14204       if (Previous.empty() && StdAlignValT)
14205         Previous.addDecl(getStdAlignValT());
14206     }
14207   }
14208
14209   // If we didn't find a previous declaration, and this is a reference
14210   // (or friend reference), move to the correct scope.  In C++, we
14211   // also need to do a redeclaration lookup there, just in case
14212   // there's a shadow friend decl.
14213   if (Name && Previous.empty() &&
14214       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
14215     if (Invalid) goto CreateNewDecl;
14216     assert(SS.isEmpty());
14217
14218     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
14219       // C++ [basic.scope.pdecl]p5:
14220       //   -- for an elaborated-type-specifier of the form
14221       //
14222       //          class-key identifier
14223       //
14224       //      if the elaborated-type-specifier is used in the
14225       //      decl-specifier-seq or parameter-declaration-clause of a
14226       //      function defined in namespace scope, the identifier is
14227       //      declared as a class-name in the namespace that contains
14228       //      the declaration; otherwise, except as a friend
14229       //      declaration, the identifier is declared in the smallest
14230       //      non-class, non-function-prototype scope that contains the
14231       //      declaration.
14232       //
14233       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
14234       // C structs and unions.
14235       //
14236       // It is an error in C++ to declare (rather than define) an enum
14237       // type, including via an elaborated type specifier.  We'll
14238       // diagnose that later; for now, declare the enum in the same
14239       // scope as we would have picked for any other tag type.
14240       //
14241       // GNU C also supports this behavior as part of its incomplete
14242       // enum types extension, while GNU C++ does not.
14243       //
14244       // Find the context where we'll be declaring the tag.
14245       // FIXME: We would like to maintain the current DeclContext as the
14246       // lexical context,
14247       SearchDC = getTagInjectionContext(SearchDC);
14248
14249       // Find the scope where we'll be declaring the tag.
14250       S = getTagInjectionScope(S, getLangOpts());
14251     } else {
14252       assert(TUK == TUK_Friend);
14253       // C++ [namespace.memdef]p3:
14254       //   If a friend declaration in a non-local class first declares a
14255       //   class or function, the friend class or function is a member of
14256       //   the innermost enclosing namespace.
14257       SearchDC = SearchDC->getEnclosingNamespaceContext();
14258     }
14259
14260     // In C++, we need to do a redeclaration lookup to properly
14261     // diagnose some problems.
14262     // FIXME: redeclaration lookup is also used (with and without C++) to find a
14263     // hidden declaration so that we don't get ambiguity errors when using a
14264     // type declared by an elaborated-type-specifier.  In C that is not correct
14265     // and we should instead merge compatible types found by lookup.
14266     if (getLangOpts().CPlusPlus) {
14267       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14268       LookupQualifiedName(Previous, SearchDC);
14269     } else {
14270       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14271       LookupName(Previous, S);
14272     }
14273   }
14274
14275   // If we have a known previous declaration to use, then use it.
14276   if (Previous.empty() && SkipBody && SkipBody->Previous)
14277     Previous.addDecl(SkipBody->Previous);
14278
14279   if (!Previous.empty()) {
14280     NamedDecl *PrevDecl = Previous.getFoundDecl();
14281     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
14282
14283     // It's okay to have a tag decl in the same scope as a typedef
14284     // which hides a tag decl in the same scope.  Finding this
14285     // insanity with a redeclaration lookup can only actually happen
14286     // in C++.
14287     //
14288     // This is also okay for elaborated-type-specifiers, which is
14289     // technically forbidden by the current standard but which is
14290     // okay according to the likely resolution of an open issue;
14291     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
14292     if (getLangOpts().CPlusPlus) {
14293       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14294         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
14295           TagDecl *Tag = TT->getDecl();
14296           if (Tag->getDeclName() == Name &&
14297               Tag->getDeclContext()->getRedeclContext()
14298                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
14299             PrevDecl = Tag;
14300             Previous.clear();
14301             Previous.addDecl(Tag);
14302             Previous.resolveKind();
14303           }
14304         }
14305       }
14306     }
14307
14308     // If this is a redeclaration of a using shadow declaration, it must
14309     // declare a tag in the same context. In MSVC mode, we allow a
14310     // redefinition if either context is within the other.
14311     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
14312       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
14313       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
14314           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
14315           !(OldTag && isAcceptableTagRedeclContext(
14316                           *this, OldTag->getDeclContext(), SearchDC))) {
14317         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
14318         Diag(Shadow->getTargetDecl()->getLocation(),
14319              diag::note_using_decl_target);
14320         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
14321             << 0;
14322         // Recover by ignoring the old declaration.
14323         Previous.clear();
14324         goto CreateNewDecl;
14325       }
14326     }
14327
14328     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
14329       // If this is a use of a previous tag, or if the tag is already declared
14330       // in the same scope (so that the definition/declaration completes or
14331       // rementions the tag), reuse the decl.
14332       if (TUK == TUK_Reference || TUK == TUK_Friend ||
14333           isDeclInScope(DirectPrevDecl, SearchDC, S,
14334                         SS.isNotEmpty() || isMemberSpecialization)) {
14335         // Make sure that this wasn't declared as an enum and now used as a
14336         // struct or something similar.
14337         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
14338                                           TUK == TUK_Definition, KWLoc,
14339                                           Name)) {
14340           bool SafeToContinue
14341             = (PrevTagDecl->getTagKind() != TTK_Enum &&
14342                Kind != TTK_Enum);
14343           if (SafeToContinue)
14344             Diag(KWLoc, diag::err_use_with_wrong_tag)
14345               << Name
14346               << FixItHint::CreateReplacement(SourceRange(KWLoc),
14347                                               PrevTagDecl->getKindName());
14348           else
14349             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
14350           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
14351
14352           if (SafeToContinue)
14353             Kind = PrevTagDecl->getTagKind();
14354           else {
14355             // Recover by making this an anonymous redefinition.
14356             Name = nullptr;
14357             Previous.clear();
14358             Invalid = true;
14359           }
14360         }
14361
14362         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
14363           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
14364
14365           // If this is an elaborated-type-specifier for a scoped enumeration,
14366           // the 'class' keyword is not necessary and not permitted.
14367           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14368             if (ScopedEnum)
14369               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
14370                 << PrevEnum->isScoped()
14371                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
14372             return PrevTagDecl;
14373           }
14374
14375           QualType EnumUnderlyingTy;
14376           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14377             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
14378           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
14379             EnumUnderlyingTy = QualType(T, 0);
14380
14381           // All conflicts with previous declarations are recovered by
14382           // returning the previous declaration, unless this is a definition,
14383           // in which case we want the caller to bail out.
14384           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
14385                                      ScopedEnum, EnumUnderlyingTy,
14386                                      IsFixed, PrevEnum))
14387             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
14388         }
14389
14390         // C++11 [class.mem]p1:
14391         //   A member shall not be declared twice in the member-specification,
14392         //   except that a nested class or member class template can be declared
14393         //   and then later defined.
14394         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
14395             S->isDeclScope(PrevDecl)) {
14396           Diag(NameLoc, diag::ext_member_redeclared);
14397           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
14398         }
14399
14400         if (!Invalid) {
14401           // If this is a use, just return the declaration we found, unless
14402           // we have attributes.
14403           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14404             if (!Attrs.empty()) {
14405               // FIXME: Diagnose these attributes. For now, we create a new
14406               // declaration to hold them.
14407             } else if (TUK == TUK_Reference &&
14408                        (PrevTagDecl->getFriendObjectKind() ==
14409                             Decl::FOK_Undeclared ||
14410                         PrevDecl->getOwningModule() != getCurrentModule()) &&
14411                        SS.isEmpty()) {
14412               // This declaration is a reference to an existing entity, but
14413               // has different visibility from that entity: it either makes
14414               // a friend visible or it makes a type visible in a new module.
14415               // In either case, create a new declaration. We only do this if
14416               // the declaration would have meant the same thing if no prior
14417               // declaration were found, that is, if it was found in the same
14418               // scope where we would have injected a declaration.
14419               if (!getTagInjectionContext(CurContext)->getRedeclContext()
14420                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
14421                 return PrevTagDecl;
14422               // This is in the injected scope, create a new declaration in
14423               // that scope.
14424               S = getTagInjectionScope(S, getLangOpts());
14425             } else {
14426               return PrevTagDecl;
14427             }
14428           }
14429
14430           // Diagnose attempts to redefine a tag.
14431           if (TUK == TUK_Definition) {
14432             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
14433               // If we're defining a specialization and the previous definition
14434               // is from an implicit instantiation, don't emit an error
14435               // here; we'll catch this in the general case below.
14436               bool IsExplicitSpecializationAfterInstantiation = false;
14437               if (isMemberSpecialization) {
14438                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
14439                   IsExplicitSpecializationAfterInstantiation =
14440                     RD->getTemplateSpecializationKind() !=
14441                     TSK_ExplicitSpecialization;
14442                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
14443                   IsExplicitSpecializationAfterInstantiation =
14444                     ED->getTemplateSpecializationKind() !=
14445                     TSK_ExplicitSpecialization;
14446               }
14447
14448               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
14449               // not keep more that one definition around (merge them). However,
14450               // ensure the decl passes the structural compatibility check in
14451               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
14452               NamedDecl *Hidden = nullptr;
14453               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
14454                 // There is a definition of this tag, but it is not visible. We
14455                 // explicitly make use of C++'s one definition rule here, and
14456                 // assume that this definition is identical to the hidden one
14457                 // we already have. Make the existing definition visible and
14458                 // use it in place of this one.
14459                 if (!getLangOpts().CPlusPlus) {
14460                   // Postpone making the old definition visible until after we
14461                   // complete parsing the new one and do the structural
14462                   // comparison.
14463                   SkipBody->CheckSameAsPrevious = true;
14464                   SkipBody->New = createTagFromNewDecl();
14465                   SkipBody->Previous = Hidden;
14466                 } else {
14467                   SkipBody->ShouldSkip = true;
14468                   makeMergedDefinitionVisible(Hidden);
14469                 }
14470                 return Def;
14471               } else if (!IsExplicitSpecializationAfterInstantiation) {
14472                 // A redeclaration in function prototype scope in C isn't
14473                 // visible elsewhere, so merely issue a warning.
14474                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
14475                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
14476                 else
14477                   Diag(NameLoc, diag::err_redefinition) << Name;
14478                 notePreviousDefinition(Def,
14479                                        NameLoc.isValid() ? NameLoc : KWLoc);
14480                 // If this is a redefinition, recover by making this
14481                 // struct be anonymous, which will make any later
14482                 // references get the previous definition.
14483                 Name = nullptr;
14484                 Previous.clear();
14485                 Invalid = true;
14486               }
14487             } else {
14488               // If the type is currently being defined, complain
14489               // about a nested redefinition.
14490               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
14491               if (TD->isBeingDefined()) {
14492                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
14493                 Diag(PrevTagDecl->getLocation(),
14494                      diag::note_previous_definition);
14495                 Name = nullptr;
14496                 Previous.clear();
14497                 Invalid = true;
14498               }
14499             }
14500
14501             // Okay, this is definition of a previously declared or referenced
14502             // tag. We're going to create a new Decl for it.
14503           }
14504
14505           // Okay, we're going to make a redeclaration.  If this is some kind
14506           // of reference, make sure we build the redeclaration in the same DC
14507           // as the original, and ignore the current access specifier.
14508           if (TUK == TUK_Friend || TUK == TUK_Reference) {
14509             SearchDC = PrevTagDecl->getDeclContext();
14510             AS = AS_none;
14511           }
14512         }
14513         // If we get here we have (another) forward declaration or we
14514         // have a definition.  Just create a new decl.
14515
14516       } else {
14517         // If we get here, this is a definition of a new tag type in a nested
14518         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
14519         // new decl/type.  We set PrevDecl to NULL so that the entities
14520         // have distinct types.
14521         Previous.clear();
14522       }
14523       // If we get here, we're going to create a new Decl. If PrevDecl
14524       // is non-NULL, it's a definition of the tag declared by
14525       // PrevDecl. If it's NULL, we have a new definition.
14526
14527     // Otherwise, PrevDecl is not a tag, but was found with tag
14528     // lookup.  This is only actually possible in C++, where a few
14529     // things like templates still live in the tag namespace.
14530     } else {
14531       // Use a better diagnostic if an elaborated-type-specifier
14532       // found the wrong kind of type on the first
14533       // (non-redeclaration) lookup.
14534       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
14535           !Previous.isForRedeclaration()) {
14536         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14537         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
14538                                                        << Kind;
14539         Diag(PrevDecl->getLocation(), diag::note_declared_at);
14540         Invalid = true;
14541
14542       // Otherwise, only diagnose if the declaration is in scope.
14543       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
14544                                 SS.isNotEmpty() || isMemberSpecialization)) {
14545         // do nothing
14546
14547       // Diagnose implicit declarations introduced by elaborated types.
14548       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
14549         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14550         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
14551         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14552         Invalid = true;
14553
14554       // Otherwise it's a declaration.  Call out a particularly common
14555       // case here.
14556       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14557         unsigned Kind = 0;
14558         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
14559         Diag(NameLoc, diag::err_tag_definition_of_typedef)
14560           << Name << Kind << TND->getUnderlyingType();
14561         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14562         Invalid = true;
14563
14564       // Otherwise, diagnose.
14565       } else {
14566         // The tag name clashes with something else in the target scope,
14567         // issue an error and recover by making this tag be anonymous.
14568         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
14569         notePreviousDefinition(PrevDecl, NameLoc);
14570         Name = nullptr;
14571         Invalid = true;
14572       }
14573
14574       // The existing declaration isn't relevant to us; we're in a
14575       // new scope, so clear out the previous declaration.
14576       Previous.clear();
14577     }
14578   }
14579
14580 CreateNewDecl:
14581
14582   TagDecl *PrevDecl = nullptr;
14583   if (Previous.isSingleResult())
14584     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
14585
14586   // If there is an identifier, use the location of the identifier as the
14587   // location of the decl, otherwise use the location of the struct/union
14588   // keyword.
14589   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14590
14591   // Otherwise, create a new declaration. If there is a previous
14592   // declaration of the same entity, the two will be linked via
14593   // PrevDecl.
14594   TagDecl *New;
14595
14596   if (Kind == TTK_Enum) {
14597     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14598     // enum X { A, B, C } D;    D should chain to X.
14599     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
14600                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
14601                            ScopedEnumUsesClassTag, IsFixed);
14602
14603     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
14604       StdAlignValT = cast<EnumDecl>(New);
14605
14606     // If this is an undefined enum, warn.
14607     if (TUK != TUK_Definition && !Invalid) {
14608       TagDecl *Def;
14609       if (IsFixed && (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
14610           cast<EnumDecl>(New)->isFixed()) {
14611         // C++0x: 7.2p2: opaque-enum-declaration.
14612         // Conflicts are diagnosed above. Do nothing.
14613       }
14614       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
14615         Diag(Loc, diag::ext_forward_ref_enum_def)
14616           << New;
14617         Diag(Def->getLocation(), diag::note_previous_definition);
14618       } else {
14619         unsigned DiagID = diag::ext_forward_ref_enum;
14620         if (getLangOpts().MSVCCompat)
14621           DiagID = diag::ext_ms_forward_ref_enum;
14622         else if (getLangOpts().CPlusPlus)
14623           DiagID = diag::err_forward_ref_enum;
14624         Diag(Loc, DiagID);
14625       }
14626     }
14627
14628     if (EnumUnderlying) {
14629       EnumDecl *ED = cast<EnumDecl>(New);
14630       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14631         ED->setIntegerTypeSourceInfo(TI);
14632       else
14633         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
14634       ED->setPromotionType(ED->getIntegerType());
14635       assert(ED->isComplete() && "enum with type should be complete");
14636     }
14637   } else {
14638     // struct/union/class
14639
14640     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14641     // struct X { int A; } D;    D should chain to X.
14642     if (getLangOpts().CPlusPlus) {
14643       // FIXME: Look for a way to use RecordDecl for simple structs.
14644       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14645                                   cast_or_null<CXXRecordDecl>(PrevDecl));
14646
14647       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
14648         StdBadAlloc = cast<CXXRecordDecl>(New);
14649     } else
14650       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14651                                cast_or_null<RecordDecl>(PrevDecl));
14652   }
14653
14654   // C++11 [dcl.type]p3:
14655   //   A type-specifier-seq shall not define a class or enumeration [...].
14656   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
14657       TUK == TUK_Definition) {
14658     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
14659       << Context.getTagDeclType(New);
14660     Invalid = true;
14661   }
14662
14663   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
14664       DC->getDeclKind() == Decl::Enum) {
14665     Diag(New->getLocation(), diag::err_type_defined_in_enum)
14666       << Context.getTagDeclType(New);
14667     Invalid = true;
14668   }
14669
14670   // Maybe add qualifier info.
14671   if (SS.isNotEmpty()) {
14672     if (SS.isSet()) {
14673       // If this is either a declaration or a definition, check the
14674       // nested-name-specifier against the current context.
14675       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
14676           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
14677                                        isMemberSpecialization))
14678         Invalid = true;
14679
14680       New->setQualifierInfo(SS.getWithLocInContext(Context));
14681       if (TemplateParameterLists.size() > 0) {
14682         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
14683       }
14684     }
14685     else
14686       Invalid = true;
14687   }
14688
14689   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14690     // Add alignment attributes if necessary; these attributes are checked when
14691     // the ASTContext lays out the structure.
14692     //
14693     // It is important for implementing the correct semantics that this
14694     // happen here (in ActOnTag). The #pragma pack stack is
14695     // maintained as a result of parser callbacks which can occur at
14696     // many points during the parsing of a struct declaration (because
14697     // the #pragma tokens are effectively skipped over during the
14698     // parsing of the struct).
14699     if (TUK == TUK_Definition) {
14700       AddAlignmentAttributesForRecord(RD);
14701       AddMsStructLayoutForRecord(RD);
14702     }
14703   }
14704
14705   if (ModulePrivateLoc.isValid()) {
14706     if (isMemberSpecialization)
14707       Diag(New->getLocation(), diag::err_module_private_specialization)
14708         << 2
14709         << FixItHint::CreateRemoval(ModulePrivateLoc);
14710     // __module_private__ does not apply to local classes. However, we only
14711     // diagnose this as an error when the declaration specifiers are
14712     // freestanding. Here, we just ignore the __module_private__.
14713     else if (!SearchDC->isFunctionOrMethod())
14714       New->setModulePrivate();
14715   }
14716
14717   // If this is a specialization of a member class (of a class template),
14718   // check the specialization.
14719   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
14720     Invalid = true;
14721
14722   // If we're declaring or defining a tag in function prototype scope in C,
14723   // note that this type can only be used within the function and add it to
14724   // the list of decls to inject into the function definition scope.
14725   if ((Name || Kind == TTK_Enum) &&
14726       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
14727     if (getLangOpts().CPlusPlus) {
14728       // C++ [dcl.fct]p6:
14729       //   Types shall not be defined in return or parameter types.
14730       if (TUK == TUK_Definition && !IsTypeSpecifier) {
14731         Diag(Loc, diag::err_type_defined_in_param_type)
14732             << Name;
14733         Invalid = true;
14734       }
14735     } else if (!PrevDecl) {
14736       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
14737     }
14738   }
14739
14740   if (Invalid)
14741     New->setInvalidDecl();
14742
14743   // Set the lexical context. If the tag has a C++ scope specifier, the
14744   // lexical context will be different from the semantic context.
14745   New->setLexicalDeclContext(CurContext);
14746
14747   // Mark this as a friend decl if applicable.
14748   // In Microsoft mode, a friend declaration also acts as a forward
14749   // declaration so we always pass true to setObjectOfFriendDecl to make
14750   // the tag name visible.
14751   if (TUK == TUK_Friend)
14752     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
14753
14754   // Set the access specifier.
14755   if (!Invalid && SearchDC->isRecord())
14756     SetMemberAccessSpecifier(New, PrevDecl, AS);
14757
14758   if (PrevDecl)
14759     CheckRedeclarationModuleOwnership(New, PrevDecl);
14760
14761   if (TUK == TUK_Definition)
14762     New->startDefinition();
14763
14764   ProcessDeclAttributeList(S, New, Attrs);
14765   AddPragmaAttributes(S, New);
14766
14767   // If this has an identifier, add it to the scope stack.
14768   if (TUK == TUK_Friend) {
14769     // We might be replacing an existing declaration in the lookup tables;
14770     // if so, borrow its access specifier.
14771     if (PrevDecl)
14772       New->setAccess(PrevDecl->getAccess());
14773
14774     DeclContext *DC = New->getDeclContext()->getRedeclContext();
14775     DC->makeDeclVisibleInContext(New);
14776     if (Name) // can be null along some error paths
14777       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14778         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
14779   } else if (Name) {
14780     S = getNonFieldDeclScope(S);
14781     PushOnScopeChains(New, S, true);
14782   } else {
14783     CurContext->addDecl(New);
14784   }
14785
14786   // If this is the C FILE type, notify the AST context.
14787   if (IdentifierInfo *II = New->getIdentifier())
14788     if (!New->isInvalidDecl() &&
14789         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
14790         II->isStr("FILE"))
14791       Context.setFILEDecl(New);
14792
14793   if (PrevDecl)
14794     mergeDeclAttributes(New, PrevDecl);
14795
14796   // If there's a #pragma GCC visibility in scope, set the visibility of this
14797   // record.
14798   AddPushedVisibilityAttribute(New);
14799
14800   if (isMemberSpecialization && !New->isInvalidDecl())
14801     CompleteMemberSpecialization(New, Previous);
14802
14803   OwnedDecl = true;
14804   // In C++, don't return an invalid declaration. We can't recover well from
14805   // the cases where we make the type anonymous.
14806   if (Invalid && getLangOpts().CPlusPlus) {
14807     if (New->isBeingDefined())
14808       if (auto RD = dyn_cast<RecordDecl>(New))
14809         RD->completeDefinition();
14810     return nullptr;
14811   } else {
14812     return New;
14813   }
14814 }
14815
14816 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
14817   AdjustDeclIfTemplate(TagD);
14818   TagDecl *Tag = cast<TagDecl>(TagD);
14819
14820   // Enter the tag context.
14821   PushDeclContext(S, Tag);
14822
14823   ActOnDocumentableDecl(TagD);
14824
14825   // If there's a #pragma GCC visibility in scope, set the visibility of this
14826   // record.
14827   AddPushedVisibilityAttribute(Tag);
14828 }
14829
14830 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
14831                                     SkipBodyInfo &SkipBody) {
14832   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
14833     return false;
14834
14835   // Make the previous decl visible.
14836   makeMergedDefinitionVisible(SkipBody.Previous);
14837   return true;
14838 }
14839
14840 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
14841   assert(isa<ObjCContainerDecl>(IDecl) &&
14842          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
14843   DeclContext *OCD = cast<DeclContext>(IDecl);
14844   assert(getContainingDC(OCD) == CurContext &&
14845       "The next DeclContext should be lexically contained in the current one.");
14846   CurContext = OCD;
14847   return IDecl;
14848 }
14849
14850 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
14851                                            SourceLocation FinalLoc,
14852                                            bool IsFinalSpelledSealed,
14853                                            SourceLocation LBraceLoc) {
14854   AdjustDeclIfTemplate(TagD);
14855   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
14856
14857   FieldCollector->StartClass();
14858
14859   if (!Record->getIdentifier())
14860     return;
14861
14862   if (FinalLoc.isValid())
14863     Record->addAttr(new (Context)
14864                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
14865
14866   // C++ [class]p2:
14867   //   [...] The class-name is also inserted into the scope of the
14868   //   class itself; this is known as the injected-class-name. For
14869   //   purposes of access checking, the injected-class-name is treated
14870   //   as if it were a public member name.
14871   CXXRecordDecl *InjectedClassName
14872     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
14873                             Record->getLocStart(), Record->getLocation(),
14874                             Record->getIdentifier(),
14875                             /*PrevDecl=*/nullptr,
14876                             /*DelayTypeCreation=*/true);
14877   Context.getTypeDeclType(InjectedClassName, Record);
14878   InjectedClassName->setImplicit();
14879   InjectedClassName->setAccess(AS_public);
14880   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
14881       InjectedClassName->setDescribedClassTemplate(Template);
14882   PushOnScopeChains(InjectedClassName, S);
14883   assert(InjectedClassName->isInjectedClassName() &&
14884          "Broken injected-class-name");
14885 }
14886
14887 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
14888                                     SourceRange BraceRange) {
14889   AdjustDeclIfTemplate(TagD);
14890   TagDecl *Tag = cast<TagDecl>(TagD);
14891   Tag->setBraceRange(BraceRange);
14892
14893   // Make sure we "complete" the definition even it is invalid.
14894   if (Tag->isBeingDefined()) {
14895     assert(Tag->isInvalidDecl() && "We should already have completed it");
14896     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14897       RD->completeDefinition();
14898   }
14899
14900   if (isa<CXXRecordDecl>(Tag)) {
14901     FieldCollector->FinishClass();
14902   }
14903
14904   // Exit this scope of this tag's definition.
14905   PopDeclContext();
14906
14907   if (getCurLexicalContext()->isObjCContainer() &&
14908       Tag->getDeclContext()->isFileContext())
14909     Tag->setTopLevelDeclInObjCContainer();
14910
14911   // Notify the consumer that we've defined a tag.
14912   if (!Tag->isInvalidDecl())
14913     Consumer.HandleTagDeclDefinition(Tag);
14914 }
14915
14916 void Sema::ActOnObjCContainerFinishDefinition() {
14917   // Exit this scope of this interface definition.
14918   PopDeclContext();
14919 }
14920
14921 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
14922   assert(DC == CurContext && "Mismatch of container contexts");
14923   OriginalLexicalContext = DC;
14924   ActOnObjCContainerFinishDefinition();
14925 }
14926
14927 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
14928   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
14929   OriginalLexicalContext = nullptr;
14930 }
14931
14932 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
14933   AdjustDeclIfTemplate(TagD);
14934   TagDecl *Tag = cast<TagDecl>(TagD);
14935   Tag->setInvalidDecl();
14936
14937   // Make sure we "complete" the definition even it is invalid.
14938   if (Tag->isBeingDefined()) {
14939     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14940       RD->completeDefinition();
14941   }
14942
14943   // We're undoing ActOnTagStartDefinition here, not
14944   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
14945   // the FieldCollector.
14946
14947   PopDeclContext();
14948 }
14949
14950 // Note that FieldName may be null for anonymous bitfields.
14951 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
14952                                 IdentifierInfo *FieldName,
14953                                 QualType FieldTy, bool IsMsStruct,
14954                                 Expr *BitWidth, bool *ZeroWidth) {
14955   // Default to true; that shouldn't confuse checks for emptiness
14956   if (ZeroWidth)
14957     *ZeroWidth = true;
14958
14959   // C99 6.7.2.1p4 - verify the field type.
14960   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
14961   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
14962     // Handle incomplete types with specific error.
14963     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
14964       return ExprError();
14965     if (FieldName)
14966       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
14967         << FieldName << FieldTy << BitWidth->getSourceRange();
14968     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
14969       << FieldTy << BitWidth->getSourceRange();
14970   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
14971                                              UPPC_BitFieldWidth))
14972     return ExprError();
14973
14974   // If the bit-width is type- or value-dependent, don't try to check
14975   // it now.
14976   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
14977     return BitWidth;
14978
14979   llvm::APSInt Value;
14980   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
14981   if (ICE.isInvalid())
14982     return ICE;
14983   BitWidth = ICE.get();
14984
14985   if (Value != 0 && ZeroWidth)
14986     *ZeroWidth = false;
14987
14988   // Zero-width bitfield is ok for anonymous field.
14989   if (Value == 0 && FieldName)
14990     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
14991
14992   if (Value.isSigned() && Value.isNegative()) {
14993     if (FieldName)
14994       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
14995                << FieldName << Value.toString(10);
14996     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
14997       << Value.toString(10);
14998   }
14999
15000   if (!FieldTy->isDependentType()) {
15001     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15002     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15003     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15004
15005     // Over-wide bitfields are an error in C or when using the MSVC bitfield
15006     // ABI.
15007     bool CStdConstraintViolation =
15008         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15009     bool MSBitfieldViolation =
15010         Value.ugt(TypeStorageSize) &&
15011         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15012     if (CStdConstraintViolation || MSBitfieldViolation) {
15013       unsigned DiagWidth =
15014           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15015       if (FieldName)
15016         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15017                << FieldName << (unsigned)Value.getZExtValue()
15018                << !CStdConstraintViolation << DiagWidth;
15019
15020       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15021              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15022              << DiagWidth;
15023     }
15024
15025     // Warn on types where the user might conceivably expect to get all
15026     // specified bits as value bits: that's all integral types other than
15027     // 'bool'.
15028     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15029       if (FieldName)
15030         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15031             << FieldName << (unsigned)Value.getZExtValue()
15032             << (unsigned)TypeWidth;
15033       else
15034         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15035             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
15036     }
15037   }
15038
15039   return BitWidth;
15040 }
15041
15042 /// ActOnField - Each field of a C struct/union is passed into this in order
15043 /// to create a FieldDecl object for it.
15044 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
15045                        Declarator &D, Expr *BitfieldWidth) {
15046   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
15047                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
15048                                /*InitStyle=*/ICIS_NoInit, AS_public);
15049   return Res;
15050 }
15051
15052 /// HandleField - Analyze a field of a C struct or a C++ data member.
15053 ///
15054 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
15055                              SourceLocation DeclStart,
15056                              Declarator &D, Expr *BitWidth,
15057                              InClassInitStyle InitStyle,
15058                              AccessSpecifier AS) {
15059   if (D.isDecompositionDeclarator()) {
15060     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
15061     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
15062       << Decomp.getSourceRange();
15063     return nullptr;
15064   }
15065
15066   IdentifierInfo *II = D.getIdentifier();
15067   SourceLocation Loc = DeclStart;
15068   if (II) Loc = D.getIdentifierLoc();
15069
15070   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15071   QualType T = TInfo->getType();
15072   if (getLangOpts().CPlusPlus) {
15073     CheckExtraCXXDefaultArguments(D);
15074
15075     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15076                                         UPPC_DataMemberType)) {
15077       D.setInvalidType();
15078       T = Context.IntTy;
15079       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15080     }
15081   }
15082
15083   // TR 18037 does not allow fields to be declared with address spaces.
15084   if (T.getQualifiers().hasAddressSpace() ||
15085       T->isDependentAddressSpaceType() ||
15086       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
15087     Diag(Loc, diag::err_field_with_address_space);
15088     D.setInvalidType();
15089   }
15090
15091   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
15092   // used as structure or union field: image, sampler, event or block types.
15093   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
15094                           T->isSamplerT() || T->isBlockPointerType())) {
15095     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
15096     D.setInvalidType();
15097   }
15098
15099   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15100
15101   if (D.getDeclSpec().isInlineSpecified())
15102     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15103         << getLangOpts().CPlusPlus17;
15104   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15105     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15106          diag::err_invalid_thread)
15107       << DeclSpec::getSpecifierName(TSCS);
15108
15109   // Check to see if this name was declared as a member previously
15110   NamedDecl *PrevDecl = nullptr;
15111   LookupResult Previous(*this, II, Loc, LookupMemberName,
15112                         ForVisibleRedeclaration);
15113   LookupName(Previous, S);
15114   switch (Previous.getResultKind()) {
15115     case LookupResult::Found:
15116     case LookupResult::FoundUnresolvedValue:
15117       PrevDecl = Previous.getAsSingle<NamedDecl>();
15118       break;
15119
15120     case LookupResult::FoundOverloaded:
15121       PrevDecl = Previous.getRepresentativeDecl();
15122       break;
15123
15124     case LookupResult::NotFound:
15125     case LookupResult::NotFoundInCurrentInstantiation:
15126     case LookupResult::Ambiguous:
15127       break;
15128   }
15129   Previous.suppressDiagnostics();
15130
15131   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15132     // Maybe we will complain about the shadowed template parameter.
15133     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15134     // Just pretend that we didn't see the previous declaration.
15135     PrevDecl = nullptr;
15136   }
15137
15138   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15139     PrevDecl = nullptr;
15140
15141   bool Mutable
15142     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
15143   SourceLocation TSSL = D.getLocStart();
15144   FieldDecl *NewFD
15145     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
15146                      TSSL, AS, PrevDecl, &D);
15147
15148   if (NewFD->isInvalidDecl())
15149     Record->setInvalidDecl();
15150
15151   if (D.getDeclSpec().isModulePrivateSpecified())
15152     NewFD->setModulePrivate();
15153
15154   if (NewFD->isInvalidDecl() && PrevDecl) {
15155     // Don't introduce NewFD into scope; there's already something
15156     // with the same name in the same scope.
15157   } else if (II) {
15158     PushOnScopeChains(NewFD, S);
15159   } else
15160     Record->addDecl(NewFD);
15161
15162   return NewFD;
15163 }
15164
15165 /// Build a new FieldDecl and check its well-formedness.
15166 ///
15167 /// This routine builds a new FieldDecl given the fields name, type,
15168 /// record, etc. \p PrevDecl should refer to any previous declaration
15169 /// with the same name and in the same scope as the field to be
15170 /// created.
15171 ///
15172 /// \returns a new FieldDecl.
15173 ///
15174 /// \todo The Declarator argument is a hack. It will be removed once
15175 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
15176                                 TypeSourceInfo *TInfo,
15177                                 RecordDecl *Record, SourceLocation Loc,
15178                                 bool Mutable, Expr *BitWidth,
15179                                 InClassInitStyle InitStyle,
15180                                 SourceLocation TSSL,
15181                                 AccessSpecifier AS, NamedDecl *PrevDecl,
15182                                 Declarator *D) {
15183   IdentifierInfo *II = Name.getAsIdentifierInfo();
15184   bool InvalidDecl = false;
15185   if (D) InvalidDecl = D->isInvalidType();
15186
15187   // If we receive a broken type, recover by assuming 'int' and
15188   // marking this declaration as invalid.
15189   if (T.isNull()) {
15190     InvalidDecl = true;
15191     T = Context.IntTy;
15192   }
15193
15194   QualType EltTy = Context.getBaseElementType(T);
15195   if (!EltTy->isDependentType()) {
15196     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
15197       // Fields of incomplete type force their record to be invalid.
15198       Record->setInvalidDecl();
15199       InvalidDecl = true;
15200     } else {
15201       NamedDecl *Def;
15202       EltTy->isIncompleteType(&Def);
15203       if (Def && Def->isInvalidDecl()) {
15204         Record->setInvalidDecl();
15205         InvalidDecl = true;
15206       }
15207     }
15208   }
15209
15210   // OpenCL v1.2 s6.9.c: bitfields are not supported.
15211   if (BitWidth && getLangOpts().OpenCL) {
15212     Diag(Loc, diag::err_opencl_bitfields);
15213     InvalidDecl = true;
15214   }
15215
15216   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
15217   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
15218       T.hasQualifiers()) {
15219     InvalidDecl = true;
15220     Diag(Loc, diag::err_anon_bitfield_qualifiers);
15221   }
15222
15223   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15224   // than a variably modified type.
15225   if (!InvalidDecl && T->isVariablyModifiedType()) {
15226     bool SizeIsNegative;
15227     llvm::APSInt Oversized;
15228
15229     TypeSourceInfo *FixedTInfo =
15230       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
15231                                                     SizeIsNegative,
15232                                                     Oversized);
15233     if (FixedTInfo) {
15234       Diag(Loc, diag::warn_illegal_constant_array_size);
15235       TInfo = FixedTInfo;
15236       T = FixedTInfo->getType();
15237     } else {
15238       if (SizeIsNegative)
15239         Diag(Loc, diag::err_typecheck_negative_array_size);
15240       else if (Oversized.getBoolValue())
15241         Diag(Loc, diag::err_array_too_large)
15242           << Oversized.toString(10);
15243       else
15244         Diag(Loc, diag::err_typecheck_field_variable_size);
15245       InvalidDecl = true;
15246     }
15247   }
15248
15249   // Fields can not have abstract class types
15250   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
15251                                              diag::err_abstract_type_in_decl,
15252                                              AbstractFieldType))
15253     InvalidDecl = true;
15254
15255   bool ZeroWidth = false;
15256   if (InvalidDecl)
15257     BitWidth = nullptr;
15258   // If this is declared as a bit-field, check the bit-field.
15259   if (BitWidth) {
15260     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
15261                               &ZeroWidth).get();
15262     if (!BitWidth) {
15263       InvalidDecl = true;
15264       BitWidth = nullptr;
15265       ZeroWidth = false;
15266     }
15267   }
15268
15269   // Check that 'mutable' is consistent with the type of the declaration.
15270   if (!InvalidDecl && Mutable) {
15271     unsigned DiagID = 0;
15272     if (T->isReferenceType())
15273       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
15274                                         : diag::err_mutable_reference;
15275     else if (T.isConstQualified())
15276       DiagID = diag::err_mutable_const;
15277
15278     if (DiagID) {
15279       SourceLocation ErrLoc = Loc;
15280       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
15281         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
15282       Diag(ErrLoc, DiagID);
15283       if (DiagID != diag::ext_mutable_reference) {
15284         Mutable = false;
15285         InvalidDecl = true;
15286       }
15287     }
15288   }
15289
15290   // C++11 [class.union]p8 (DR1460):
15291   //   At most one variant member of a union may have a
15292   //   brace-or-equal-initializer.
15293   if (InitStyle != ICIS_NoInit)
15294     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
15295
15296   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
15297                                        BitWidth, Mutable, InitStyle);
15298   if (InvalidDecl)
15299     NewFD->setInvalidDecl();
15300
15301   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
15302     Diag(Loc, diag::err_duplicate_member) << II;
15303     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15304     NewFD->setInvalidDecl();
15305   }
15306
15307   if (!InvalidDecl && getLangOpts().CPlusPlus) {
15308     if (Record->isUnion()) {
15309       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15310         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
15311         if (RDecl->getDefinition()) {
15312           // C++ [class.union]p1: An object of a class with a non-trivial
15313           // constructor, a non-trivial copy constructor, a non-trivial
15314           // destructor, or a non-trivial copy assignment operator
15315           // cannot be a member of a union, nor can an array of such
15316           // objects.
15317           if (CheckNontrivialField(NewFD))
15318             NewFD->setInvalidDecl();
15319         }
15320       }
15321
15322       // C++ [class.union]p1: If a union contains a member of reference type,
15323       // the program is ill-formed, except when compiling with MSVC extensions
15324       // enabled.
15325       if (EltTy->isReferenceType()) {
15326         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
15327                                     diag::ext_union_member_of_reference_type :
15328                                     diag::err_union_member_of_reference_type)
15329           << NewFD->getDeclName() << EltTy;
15330         if (!getLangOpts().MicrosoftExt)
15331           NewFD->setInvalidDecl();
15332       }
15333     }
15334   }
15335
15336   // FIXME: We need to pass in the attributes given an AST
15337   // representation, not a parser representation.
15338   if (D) {
15339     // FIXME: The current scope is almost... but not entirely... correct here.
15340     ProcessDeclAttributes(getCurScope(), NewFD, *D);
15341
15342     if (NewFD->hasAttrs())
15343       CheckAlignasUnderalignment(NewFD);
15344   }
15345
15346   // In auto-retain/release, infer strong retension for fields of
15347   // retainable type.
15348   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
15349     NewFD->setInvalidDecl();
15350
15351   if (T.isObjCGCWeak())
15352     Diag(Loc, diag::warn_attribute_weak_on_field);
15353
15354   NewFD->setAccess(AS);
15355   return NewFD;
15356 }
15357
15358 bool Sema::CheckNontrivialField(FieldDecl *FD) {
15359   assert(FD);
15360   assert(getLangOpts().CPlusPlus && "valid check only for C++");
15361
15362   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
15363     return false;
15364
15365   QualType EltTy = Context.getBaseElementType(FD->getType());
15366   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15367     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
15368     if (RDecl->getDefinition()) {
15369       // We check for copy constructors before constructors
15370       // because otherwise we'll never get complaints about
15371       // copy constructors.
15372
15373       CXXSpecialMember member = CXXInvalid;
15374       // We're required to check for any non-trivial constructors. Since the
15375       // implicit default constructor is suppressed if there are any
15376       // user-declared constructors, we just need to check that there is a
15377       // trivial default constructor and a trivial copy constructor. (We don't
15378       // worry about move constructors here, since this is a C++98 check.)
15379       if (RDecl->hasNonTrivialCopyConstructor())
15380         member = CXXCopyConstructor;
15381       else if (!RDecl->hasTrivialDefaultConstructor())
15382         member = CXXDefaultConstructor;
15383       else if (RDecl->hasNonTrivialCopyAssignment())
15384         member = CXXCopyAssignment;
15385       else if (RDecl->hasNonTrivialDestructor())
15386         member = CXXDestructor;
15387
15388       if (member != CXXInvalid) {
15389         if (!getLangOpts().CPlusPlus11 &&
15390             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
15391           // Objective-C++ ARC: it is an error to have a non-trivial field of
15392           // a union. However, system headers in Objective-C programs
15393           // occasionally have Objective-C lifetime objects within unions,
15394           // and rather than cause the program to fail, we make those
15395           // members unavailable.
15396           SourceLocation Loc = FD->getLocation();
15397           if (getSourceManager().isInSystemHeader(Loc)) {
15398             if (!FD->hasAttr<UnavailableAttr>())
15399               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15400                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
15401             return false;
15402           }
15403         }
15404
15405         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
15406                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
15407                diag::err_illegal_union_or_anon_struct_member)
15408           << FD->getParent()->isUnion() << FD->getDeclName() << member;
15409         DiagnoseNontrivial(RDecl, member);
15410         return !getLangOpts().CPlusPlus11;
15411       }
15412     }
15413   }
15414
15415   return false;
15416 }
15417
15418 /// TranslateIvarVisibility - Translate visibility from a token ID to an
15419 ///  AST enum value.
15420 static ObjCIvarDecl::AccessControl
15421 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
15422   switch (ivarVisibility) {
15423   default: llvm_unreachable("Unknown visitibility kind");
15424   case tok::objc_private: return ObjCIvarDecl::Private;
15425   case tok::objc_public: return ObjCIvarDecl::Public;
15426   case tok::objc_protected: return ObjCIvarDecl::Protected;
15427   case tok::objc_package: return ObjCIvarDecl::Package;
15428   }
15429 }
15430
15431 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
15432 /// in order to create an IvarDecl object for it.
15433 Decl *Sema::ActOnIvar(Scope *S,
15434                                 SourceLocation DeclStart,
15435                                 Declarator &D, Expr *BitfieldWidth,
15436                                 tok::ObjCKeywordKind Visibility) {
15437
15438   IdentifierInfo *II = D.getIdentifier();
15439   Expr *BitWidth = (Expr*)BitfieldWidth;
15440   SourceLocation Loc = DeclStart;
15441   if (II) Loc = D.getIdentifierLoc();
15442
15443   // FIXME: Unnamed fields can be handled in various different ways, for
15444   // example, unnamed unions inject all members into the struct namespace!
15445
15446   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15447   QualType T = TInfo->getType();
15448
15449   if (BitWidth) {
15450     // 6.7.2.1p3, 6.7.2.1p4
15451     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
15452     if (!BitWidth)
15453       D.setInvalidType();
15454   } else {
15455     // Not a bitfield.
15456
15457     // validate II.
15458
15459   }
15460   if (T->isReferenceType()) {
15461     Diag(Loc, diag::err_ivar_reference_type);
15462     D.setInvalidType();
15463   }
15464   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15465   // than a variably modified type.
15466   else if (T->isVariablyModifiedType()) {
15467     Diag(Loc, diag::err_typecheck_ivar_variable_size);
15468     D.setInvalidType();
15469   }
15470
15471   // Get the visibility (access control) for this ivar.
15472   ObjCIvarDecl::AccessControl ac =
15473     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
15474                                         : ObjCIvarDecl::None;
15475   // Must set ivar's DeclContext to its enclosing interface.
15476   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
15477   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
15478     return nullptr;
15479   ObjCContainerDecl *EnclosingContext;
15480   if (ObjCImplementationDecl *IMPDecl =
15481       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15482     if (LangOpts.ObjCRuntime.isFragile()) {
15483     // Case of ivar declared in an implementation. Context is that of its class.
15484       EnclosingContext = IMPDecl->getClassInterface();
15485       assert(EnclosingContext && "Implementation has no class interface!");
15486     }
15487     else
15488       EnclosingContext = EnclosingDecl;
15489   } else {
15490     if (ObjCCategoryDecl *CDecl =
15491         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15492       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
15493         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
15494         return nullptr;
15495       }
15496     }
15497     EnclosingContext = EnclosingDecl;
15498   }
15499
15500   // Construct the decl.
15501   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
15502                                              DeclStart, Loc, II, T,
15503                                              TInfo, ac, (Expr *)BitfieldWidth);
15504
15505   if (II) {
15506     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
15507                                            ForVisibleRedeclaration);
15508     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
15509         && !isa<TagDecl>(PrevDecl)) {
15510       Diag(Loc, diag::err_duplicate_member) << II;
15511       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15512       NewID->setInvalidDecl();
15513     }
15514   }
15515
15516   // Process attributes attached to the ivar.
15517   ProcessDeclAttributes(S, NewID, D);
15518
15519   if (D.isInvalidType())
15520     NewID->setInvalidDecl();
15521
15522   // In ARC, infer 'retaining' for ivars of retainable type.
15523   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
15524     NewID->setInvalidDecl();
15525
15526   if (D.getDeclSpec().isModulePrivateSpecified())
15527     NewID->setModulePrivate();
15528
15529   if (II) {
15530     // FIXME: When interfaces are DeclContexts, we'll need to add
15531     // these to the interface.
15532     S->AddDecl(NewID);
15533     IdResolver.AddDecl(NewID);
15534   }
15535
15536   if (LangOpts.ObjCRuntime.isNonFragile() &&
15537       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
15538     Diag(Loc, diag::warn_ivars_in_interface);
15539
15540   return NewID;
15541 }
15542
15543 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
15544 /// class and class extensions. For every class \@interface and class
15545 /// extension \@interface, if the last ivar is a bitfield of any type,
15546 /// then add an implicit `char :0` ivar to the end of that interface.
15547 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
15548                              SmallVectorImpl<Decl *> &AllIvarDecls) {
15549   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
15550     return;
15551
15552   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
15553   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
15554
15555   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
15556     return;
15557   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
15558   if (!ID) {
15559     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
15560       if (!CD->IsClassExtension())
15561         return;
15562     }
15563     // No need to add this to end of @implementation.
15564     else
15565       return;
15566   }
15567   // All conditions are met. Add a new bitfield to the tail end of ivars.
15568   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
15569   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
15570
15571   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
15572                               DeclLoc, DeclLoc, nullptr,
15573                               Context.CharTy,
15574                               Context.getTrivialTypeSourceInfo(Context.CharTy,
15575                                                                DeclLoc),
15576                               ObjCIvarDecl::Private, BW,
15577                               true);
15578   AllIvarDecls.push_back(Ivar);
15579 }
15580
15581 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
15582                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
15583                        SourceLocation RBrac,
15584                        const ParsedAttributesView &Attrs) {
15585   assert(EnclosingDecl && "missing record or interface decl");
15586
15587   // If this is an Objective-C @implementation or category and we have
15588   // new fields here we should reset the layout of the interface since
15589   // it will now change.
15590   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
15591     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
15592     switch (DC->getKind()) {
15593     default: break;
15594     case Decl::ObjCCategory:
15595       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
15596       break;
15597     case Decl::ObjCImplementation:
15598       Context.
15599         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
15600       break;
15601     }
15602   }
15603
15604   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
15605
15606   // Start counting up the number of named members; make sure to include
15607   // members of anonymous structs and unions in the total.
15608   unsigned NumNamedMembers = 0;
15609   if (Record) {
15610     for (const auto *I : Record->decls()) {
15611       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
15612         if (IFD->getDeclName())
15613           ++NumNamedMembers;
15614     }
15615   }
15616
15617   // Verify that all the fields are okay.
15618   SmallVector<FieldDecl*, 32> RecFields;
15619
15620   bool ObjCFieldLifetimeErrReported = false;
15621   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
15622        i != end; ++i) {
15623     FieldDecl *FD = cast<FieldDecl>(*i);
15624
15625     // Get the type for the field.
15626     const Type *FDTy = FD->getType().getTypePtr();
15627
15628     if (!FD->isAnonymousStructOrUnion()) {
15629       // Remember all fields written by the user.
15630       RecFields.push_back(FD);
15631     }
15632
15633     // If the field is already invalid for some reason, don't emit more
15634     // diagnostics about it.
15635     if (FD->isInvalidDecl()) {
15636       EnclosingDecl->setInvalidDecl();
15637       continue;
15638     }
15639
15640     // C99 6.7.2.1p2:
15641     //   A structure or union shall not contain a member with
15642     //   incomplete or function type (hence, a structure shall not
15643     //   contain an instance of itself, but may contain a pointer to
15644     //   an instance of itself), except that the last member of a
15645     //   structure with more than one named member may have incomplete
15646     //   array type; such a structure (and any union containing,
15647     //   possibly recursively, a member that is such a structure)
15648     //   shall not be a member of a structure or an element of an
15649     //   array.
15650     bool IsLastField = (i + 1 == Fields.end());
15651     if (FDTy->isFunctionType()) {
15652       // Field declared as a function.
15653       Diag(FD->getLocation(), diag::err_field_declared_as_function)
15654         << FD->getDeclName();
15655       FD->setInvalidDecl();
15656       EnclosingDecl->setInvalidDecl();
15657       continue;
15658     } else if (FDTy->isIncompleteArrayType() &&
15659                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
15660       if (Record) {
15661         // Flexible array member.
15662         // Microsoft and g++ is more permissive regarding flexible array.
15663         // It will accept flexible array in union and also
15664         // as the sole element of a struct/class.
15665         unsigned DiagID = 0;
15666         if (!Record->isUnion() && !IsLastField) {
15667           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
15668             << FD->getDeclName() << FD->getType() << Record->getTagKind();
15669           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
15670           FD->setInvalidDecl();
15671           EnclosingDecl->setInvalidDecl();
15672           continue;
15673         } else if (Record->isUnion())
15674           DiagID = getLangOpts().MicrosoftExt
15675                        ? diag::ext_flexible_array_union_ms
15676                        : getLangOpts().CPlusPlus
15677                              ? diag::ext_flexible_array_union_gnu
15678                              : diag::err_flexible_array_union;
15679         else if (NumNamedMembers < 1)
15680           DiagID = getLangOpts().MicrosoftExt
15681                        ? diag::ext_flexible_array_empty_aggregate_ms
15682                        : getLangOpts().CPlusPlus
15683                              ? diag::ext_flexible_array_empty_aggregate_gnu
15684                              : diag::err_flexible_array_empty_aggregate;
15685
15686         if (DiagID)
15687           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
15688                                           << Record->getTagKind();
15689         // While the layout of types that contain virtual bases is not specified
15690         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
15691         // virtual bases after the derived members.  This would make a flexible
15692         // array member declared at the end of an object not adjacent to the end
15693         // of the type.
15694         if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
15695           if (RD->getNumVBases() != 0)
15696             Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
15697               << FD->getDeclName() << Record->getTagKind();
15698         if (!getLangOpts().C99)
15699           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
15700             << FD->getDeclName() << Record->getTagKind();
15701
15702         // If the element type has a non-trivial destructor, we would not
15703         // implicitly destroy the elements, so disallow it for now.
15704         //
15705         // FIXME: GCC allows this. We should probably either implicitly delete
15706         // the destructor of the containing class, or just allow this.
15707         QualType BaseElem = Context.getBaseElementType(FD->getType());
15708         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
15709           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
15710             << FD->getDeclName() << FD->getType();
15711           FD->setInvalidDecl();
15712           EnclosingDecl->setInvalidDecl();
15713           continue;
15714         }
15715         // Okay, we have a legal flexible array member at the end of the struct.
15716         Record->setHasFlexibleArrayMember(true);
15717       } else {
15718         // In ObjCContainerDecl ivars with incomplete array type are accepted,
15719         // unless they are followed by another ivar. That check is done
15720         // elsewhere, after synthesized ivars are known.
15721       }
15722     } else if (!FDTy->isDependentType() &&
15723                RequireCompleteType(FD->getLocation(), FD->getType(),
15724                                    diag::err_field_incomplete)) {
15725       // Incomplete type
15726       FD->setInvalidDecl();
15727       EnclosingDecl->setInvalidDecl();
15728       continue;
15729     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
15730       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
15731         // A type which contains a flexible array member is considered to be a
15732         // flexible array member.
15733         Record->setHasFlexibleArrayMember(true);
15734         if (!Record->isUnion()) {
15735           // If this is a struct/class and this is not the last element, reject
15736           // it.  Note that GCC supports variable sized arrays in the middle of
15737           // structures.
15738           if (!IsLastField)
15739             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
15740               << FD->getDeclName() << FD->getType();
15741           else {
15742             // We support flexible arrays at the end of structs in
15743             // other structs as an extension.
15744             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
15745               << FD->getDeclName();
15746           }
15747         }
15748       }
15749       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
15750           RequireNonAbstractType(FD->getLocation(), FD->getType(),
15751                                  diag::err_abstract_type_in_decl,
15752                                  AbstractIvarType)) {
15753         // Ivars can not have abstract class types
15754         FD->setInvalidDecl();
15755       }
15756       if (Record && FDTTy->getDecl()->hasObjectMember())
15757         Record->setHasObjectMember(true);
15758       if (Record && FDTTy->getDecl()->hasVolatileMember())
15759         Record->setHasVolatileMember(true);
15760     } else if (FDTy->isObjCObjectType()) {
15761       /// A field cannot be an Objective-c object
15762       Diag(FD->getLocation(), diag::err_statically_allocated_object)
15763         << FixItHint::CreateInsertion(FD->getLocation(), "*");
15764       QualType T = Context.getObjCObjectPointerType(FD->getType());
15765       FD->setType(T);
15766     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
15767                Record && !ObjCFieldLifetimeErrReported && Record->isUnion()) {
15768       // It's an error in ARC or Weak if a field has lifetime.
15769       // We don't want to report this in a system header, though,
15770       // so we just make the field unavailable.
15771       // FIXME: that's really not sufficient; we need to make the type
15772       // itself invalid to, say, initialize or copy.
15773       QualType T = FD->getType();
15774       if (T.hasNonTrivialObjCLifetime()) {
15775         SourceLocation loc = FD->getLocation();
15776         if (getSourceManager().isInSystemHeader(loc)) {
15777           if (!FD->hasAttr<UnavailableAttr>()) {
15778             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15779                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
15780           }
15781         } else {
15782           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
15783             << T->isBlockPointerType() << Record->getTagKind();
15784         }
15785         ObjCFieldLifetimeErrReported = true;
15786       }
15787     } else if (getLangOpts().ObjC1 &&
15788                getLangOpts().getGC() != LangOptions::NonGC &&
15789                Record && !Record->hasObjectMember()) {
15790       if (FD->getType()->isObjCObjectPointerType() ||
15791           FD->getType().isObjCGCStrong())
15792         Record->setHasObjectMember(true);
15793       else if (Context.getAsArrayType(FD->getType())) {
15794         QualType BaseType = Context.getBaseElementType(FD->getType());
15795         if (BaseType->isRecordType() &&
15796             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
15797           Record->setHasObjectMember(true);
15798         else if (BaseType->isObjCObjectPointerType() ||
15799                  BaseType.isObjCGCStrong())
15800                Record->setHasObjectMember(true);
15801       }
15802     }
15803
15804     if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
15805       QualType FT = FD->getType();
15806       if (FT.isNonTrivialToPrimitiveDefaultInitialize())
15807         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
15808       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
15809       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial)
15810         Record->setNonTrivialToPrimitiveCopy(true);
15811       if (FT.isDestructedType()) {
15812         Record->setNonTrivialToPrimitiveDestroy(true);
15813         Record->setParamDestroyedInCallee(true);
15814       }
15815
15816       if (const auto *RT = FT->getAs<RecordType>()) {
15817         if (RT->getDecl()->getArgPassingRestrictions() ==
15818             RecordDecl::APK_CanNeverPassInRegs)
15819           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
15820       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
15821         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
15822     }
15823
15824     if (Record && FD->getType().isVolatileQualified())
15825       Record->setHasVolatileMember(true);
15826     // Keep track of the number of named members.
15827     if (FD->getIdentifier())
15828       ++NumNamedMembers;
15829   }
15830
15831   // Okay, we successfully defined 'Record'.
15832   if (Record) {
15833     bool Completed = false;
15834     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15835       if (!CXXRecord->isInvalidDecl()) {
15836         // Set access bits correctly on the directly-declared conversions.
15837         for (CXXRecordDecl::conversion_iterator
15838                I = CXXRecord->conversion_begin(),
15839                E = CXXRecord->conversion_end(); I != E; ++I)
15840           I.setAccess((*I)->getAccess());
15841       }
15842
15843       if (!CXXRecord->isDependentType()) {
15844         if (CXXRecord->hasUserDeclaredDestructor()) {
15845           // Adjust user-defined destructor exception spec.
15846           if (getLangOpts().CPlusPlus11)
15847             AdjustDestructorExceptionSpec(CXXRecord,
15848                                           CXXRecord->getDestructor());
15849         }
15850
15851         // Add any implicitly-declared members to this class.
15852         AddImplicitlyDeclaredMembersToClass(CXXRecord);
15853
15854         if (!CXXRecord->isInvalidDecl()) {
15855           // If we have virtual base classes, we may end up finding multiple
15856           // final overriders for a given virtual function. Check for this
15857           // problem now.
15858           if (CXXRecord->getNumVBases()) {
15859             CXXFinalOverriderMap FinalOverriders;
15860             CXXRecord->getFinalOverriders(FinalOverriders);
15861
15862             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
15863                                              MEnd = FinalOverriders.end();
15864                  M != MEnd; ++M) {
15865               for (OverridingMethods::iterator SO = M->second.begin(),
15866                                             SOEnd = M->second.end();
15867                    SO != SOEnd; ++SO) {
15868                 assert(SO->second.size() > 0 &&
15869                        "Virtual function without overriding functions?");
15870                 if (SO->second.size() == 1)
15871                   continue;
15872
15873                 // C++ [class.virtual]p2:
15874                 //   In a derived class, if a virtual member function of a base
15875                 //   class subobject has more than one final overrider the
15876                 //   program is ill-formed.
15877                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
15878                   << (const NamedDecl *)M->first << Record;
15879                 Diag(M->first->getLocation(),
15880                      diag::note_overridden_virtual_function);
15881                 for (OverridingMethods::overriding_iterator
15882                           OM = SO->second.begin(),
15883                        OMEnd = SO->second.end();
15884                      OM != OMEnd; ++OM)
15885                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
15886                     << (const NamedDecl *)M->first << OM->Method->getParent();
15887
15888                 Record->setInvalidDecl();
15889               }
15890             }
15891             CXXRecord->completeDefinition(&FinalOverriders);
15892             Completed = true;
15893           }
15894         }
15895       }
15896     }
15897
15898     if (!Completed)
15899       Record->completeDefinition();
15900
15901     // Handle attributes before checking the layout.
15902     ProcessDeclAttributeList(S, Record, Attrs);
15903
15904     // We may have deferred checking for a deleted destructor. Check now.
15905     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15906       auto *Dtor = CXXRecord->getDestructor();
15907       if (Dtor && Dtor->isImplicit() &&
15908           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
15909         CXXRecord->setImplicitDestructorIsDeleted();
15910         SetDeclDeleted(Dtor, CXXRecord->getLocation());
15911       }
15912     }
15913
15914     if (Record->hasAttrs()) {
15915       CheckAlignasUnderalignment(Record);
15916
15917       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
15918         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
15919                                            IA->getRange(), IA->getBestCase(),
15920                                            IA->getSemanticSpelling());
15921     }
15922
15923     // Check if the structure/union declaration is a type that can have zero
15924     // size in C. For C this is a language extension, for C++ it may cause
15925     // compatibility problems.
15926     bool CheckForZeroSize;
15927     if (!getLangOpts().CPlusPlus) {
15928       CheckForZeroSize = true;
15929     } else {
15930       // For C++ filter out types that cannot be referenced in C code.
15931       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
15932       CheckForZeroSize =
15933           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
15934           !CXXRecord->isDependentType() &&
15935           CXXRecord->isCLike();
15936     }
15937     if (CheckForZeroSize) {
15938       bool ZeroSize = true;
15939       bool IsEmpty = true;
15940       unsigned NonBitFields = 0;
15941       for (RecordDecl::field_iterator I = Record->field_begin(),
15942                                       E = Record->field_end();
15943            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
15944         IsEmpty = false;
15945         if (I->isUnnamedBitfield()) {
15946           if (!I->isZeroLengthBitField(Context))
15947             ZeroSize = false;
15948         } else {
15949           ++NonBitFields;
15950           QualType FieldType = I->getType();
15951           if (FieldType->isIncompleteType() ||
15952               !Context.getTypeSizeInChars(FieldType).isZero())
15953             ZeroSize = false;
15954         }
15955       }
15956
15957       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
15958       // allowed in C++, but warn if its declaration is inside
15959       // extern "C" block.
15960       if (ZeroSize) {
15961         Diag(RecLoc, getLangOpts().CPlusPlus ?
15962                          diag::warn_zero_size_struct_union_in_extern_c :
15963                          diag::warn_zero_size_struct_union_compat)
15964           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
15965       }
15966
15967       // Structs without named members are extension in C (C99 6.7.2.1p7),
15968       // but are accepted by GCC.
15969       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
15970         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
15971                                diag::ext_no_named_members_in_struct_union)
15972           << Record->isUnion();
15973       }
15974     }
15975   } else {
15976     ObjCIvarDecl **ClsFields =
15977       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
15978     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
15979       ID->setEndOfDefinitionLoc(RBrac);
15980       // Add ivar's to class's DeclContext.
15981       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15982         ClsFields[i]->setLexicalDeclContext(ID);
15983         ID->addDecl(ClsFields[i]);
15984       }
15985       // Must enforce the rule that ivars in the base classes may not be
15986       // duplicates.
15987       if (ID->getSuperClass())
15988         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
15989     } else if (ObjCImplementationDecl *IMPDecl =
15990                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15991       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
15992       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
15993         // Ivar declared in @implementation never belongs to the implementation.
15994         // Only it is in implementation's lexical context.
15995         ClsFields[I]->setLexicalDeclContext(IMPDecl);
15996       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
15997       IMPDecl->setIvarLBraceLoc(LBrac);
15998       IMPDecl->setIvarRBraceLoc(RBrac);
15999     } else if (ObjCCategoryDecl *CDecl =
16000                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16001       // case of ivars in class extension; all other cases have been
16002       // reported as errors elsewhere.
16003       // FIXME. Class extension does not have a LocEnd field.
16004       // CDecl->setLocEnd(RBrac);
16005       // Add ivar's to class extension's DeclContext.
16006       // Diagnose redeclaration of private ivars.
16007       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16008       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16009         if (IDecl) {
16010           if (const ObjCIvarDecl *ClsIvar =
16011               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16012             Diag(ClsFields[i]->getLocation(),
16013                  diag::err_duplicate_ivar_declaration);
16014             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16015             continue;
16016           }
16017           for (const auto *Ext : IDecl->known_extensions()) {
16018             if (const ObjCIvarDecl *ClsExtIvar
16019                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16020               Diag(ClsFields[i]->getLocation(),
16021                    diag::err_duplicate_ivar_declaration);
16022               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16023               continue;
16024             }
16025           }
16026         }
16027         ClsFields[i]->setLexicalDeclContext(CDecl);
16028         CDecl->addDecl(ClsFields[i]);
16029       }
16030       CDecl->setIvarLBraceLoc(LBrac);
16031       CDecl->setIvarRBraceLoc(RBrac);
16032     }
16033   }
16034 }
16035
16036 /// Determine whether the given integral value is representable within
16037 /// the given type T.
16038 static bool isRepresentableIntegerValue(ASTContext &Context,
16039                                         llvm::APSInt &Value,
16040                                         QualType T) {
16041   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
16042          "Integral type required!");
16043   unsigned BitWidth = Context.getIntWidth(T);
16044
16045   if (Value.isUnsigned() || Value.isNonNegative()) {
16046     if (T->isSignedIntegerOrEnumerationType())
16047       --BitWidth;
16048     return Value.getActiveBits() <= BitWidth;
16049   }
16050   return Value.getMinSignedBits() <= BitWidth;
16051 }
16052
16053 // Given an integral type, return the next larger integral type
16054 // (or a NULL type of no such type exists).
16055 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
16056   // FIXME: Int128/UInt128 support, which also needs to be introduced into
16057   // enum checking below.
16058   assert((T->isIntegralType(Context) ||
16059          T->isEnumeralType()) && "Integral type required!");
16060   const unsigned NumTypes = 4;
16061   QualType SignedIntegralTypes[NumTypes] = {
16062     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
16063   };
16064   QualType UnsignedIntegralTypes[NumTypes] = {
16065     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
16066     Context.UnsignedLongLongTy
16067   };
16068
16069   unsigned BitWidth = Context.getTypeSize(T);
16070   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
16071                                                         : UnsignedIntegralTypes;
16072   for (unsigned I = 0; I != NumTypes; ++I)
16073     if (Context.getTypeSize(Types[I]) > BitWidth)
16074       return Types[I];
16075
16076   return QualType();
16077 }
16078
16079 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
16080                                           EnumConstantDecl *LastEnumConst,
16081                                           SourceLocation IdLoc,
16082                                           IdentifierInfo *Id,
16083                                           Expr *Val) {
16084   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16085   llvm::APSInt EnumVal(IntWidth);
16086   QualType EltTy;
16087
16088   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
16089     Val = nullptr;
16090
16091   if (Val)
16092     Val = DefaultLvalueConversion(Val).get();
16093
16094   if (Val) {
16095     if (Enum->isDependentType() || Val->isTypeDependent())
16096       EltTy = Context.DependentTy;
16097     else {
16098       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
16099           !getLangOpts().MSVCCompat) {
16100         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
16101         // constant-expression in the enumerator-definition shall be a converted
16102         // constant expression of the underlying type.
16103         EltTy = Enum->getIntegerType();
16104         ExprResult Converted =
16105           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
16106                                            CCEK_Enumerator);
16107         if (Converted.isInvalid())
16108           Val = nullptr;
16109         else
16110           Val = Converted.get();
16111       } else if (!Val->isValueDependent() &&
16112                  !(Val = VerifyIntegerConstantExpression(Val,
16113                                                          &EnumVal).get())) {
16114         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
16115       } else {
16116         if (Enum->isComplete()) {
16117           EltTy = Enum->getIntegerType();
16118
16119           // In Obj-C and Microsoft mode, require the enumeration value to be
16120           // representable in the underlying type of the enumeration. In C++11,
16121           // we perform a non-narrowing conversion as part of converted constant
16122           // expression checking.
16123           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16124             if (getLangOpts().MSVCCompat) {
16125               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
16126               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
16127             } else
16128               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
16129           } else
16130             Val = ImpCastExprToType(Val, EltTy,
16131                                     EltTy->isBooleanType() ?
16132                                     CK_IntegralToBoolean : CK_IntegralCast)
16133                     .get();
16134         } else if (getLangOpts().CPlusPlus) {
16135           // C++11 [dcl.enum]p5:
16136           //   If the underlying type is not fixed, the type of each enumerator
16137           //   is the type of its initializing value:
16138           //     - If an initializer is specified for an enumerator, the
16139           //       initializing value has the same type as the expression.
16140           EltTy = Val->getType();
16141         } else {
16142           // C99 6.7.2.2p2:
16143           //   The expression that defines the value of an enumeration constant
16144           //   shall be an integer constant expression that has a value
16145           //   representable as an int.
16146
16147           // Complain if the value is not representable in an int.
16148           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
16149             Diag(IdLoc, diag::ext_enum_value_not_int)
16150               << EnumVal.toString(10) << Val->getSourceRange()
16151               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
16152           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
16153             // Force the type of the expression to 'int'.
16154             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
16155           }
16156           EltTy = Val->getType();
16157         }
16158       }
16159     }
16160   }
16161
16162   if (!Val) {
16163     if (Enum->isDependentType())
16164       EltTy = Context.DependentTy;
16165     else if (!LastEnumConst) {
16166       // C++0x [dcl.enum]p5:
16167       //   If the underlying type is not fixed, the type of each enumerator
16168       //   is the type of its initializing value:
16169       //     - If no initializer is specified for the first enumerator, the
16170       //       initializing value has an unspecified integral type.
16171       //
16172       // GCC uses 'int' for its unspecified integral type, as does
16173       // C99 6.7.2.2p3.
16174       if (Enum->isFixed()) {
16175         EltTy = Enum->getIntegerType();
16176       }
16177       else {
16178         EltTy = Context.IntTy;
16179       }
16180     } else {
16181       // Assign the last value + 1.
16182       EnumVal = LastEnumConst->getInitVal();
16183       ++EnumVal;
16184       EltTy = LastEnumConst->getType();
16185
16186       // Check for overflow on increment.
16187       if (EnumVal < LastEnumConst->getInitVal()) {
16188         // C++0x [dcl.enum]p5:
16189         //   If the underlying type is not fixed, the type of each enumerator
16190         //   is the type of its initializing value:
16191         //
16192         //     - Otherwise the type of the initializing value is the same as
16193         //       the type of the initializing value of the preceding enumerator
16194         //       unless the incremented value is not representable in that type,
16195         //       in which case the type is an unspecified integral type
16196         //       sufficient to contain the incremented value. If no such type
16197         //       exists, the program is ill-formed.
16198         QualType T = getNextLargerIntegralType(Context, EltTy);
16199         if (T.isNull() || Enum->isFixed()) {
16200           // There is no integral type larger enough to represent this
16201           // value. Complain, then allow the value to wrap around.
16202           EnumVal = LastEnumConst->getInitVal();
16203           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
16204           ++EnumVal;
16205           if (Enum->isFixed())
16206             // When the underlying type is fixed, this is ill-formed.
16207             Diag(IdLoc, diag::err_enumerator_wrapped)
16208               << EnumVal.toString(10)
16209               << EltTy;
16210           else
16211             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
16212               << EnumVal.toString(10);
16213         } else {
16214           EltTy = T;
16215         }
16216
16217         // Retrieve the last enumerator's value, extent that type to the
16218         // type that is supposed to be large enough to represent the incremented
16219         // value, then increment.
16220         EnumVal = LastEnumConst->getInitVal();
16221         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16222         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
16223         ++EnumVal;
16224
16225         // If we're not in C++, diagnose the overflow of enumerator values,
16226         // which in C99 means that the enumerator value is not representable in
16227         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
16228         // permits enumerator values that are representable in some larger
16229         // integral type.
16230         if (!getLangOpts().CPlusPlus && !T.isNull())
16231           Diag(IdLoc, diag::warn_enum_value_overflow);
16232       } else if (!getLangOpts().CPlusPlus &&
16233                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16234         // Enforce C99 6.7.2.2p2 even when we compute the next value.
16235         Diag(IdLoc, diag::ext_enum_value_not_int)
16236           << EnumVal.toString(10) << 1;
16237       }
16238     }
16239   }
16240
16241   if (!EltTy->isDependentType()) {
16242     // Make the enumerator value match the signedness and size of the
16243     // enumerator's type.
16244     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
16245     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16246   }
16247
16248   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
16249                                   Val, EnumVal);
16250 }
16251
16252 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
16253                                                 SourceLocation IILoc) {
16254   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
16255       !getLangOpts().CPlusPlus)
16256     return SkipBodyInfo();
16257
16258   // We have an anonymous enum definition. Look up the first enumerator to
16259   // determine if we should merge the definition with an existing one and
16260   // skip the body.
16261   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
16262                                          forRedeclarationInCurContext());
16263   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
16264   if (!PrevECD)
16265     return SkipBodyInfo();
16266
16267   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
16268   NamedDecl *Hidden;
16269   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
16270     SkipBodyInfo Skip;
16271     Skip.Previous = Hidden;
16272     return Skip;
16273   }
16274
16275   return SkipBodyInfo();
16276 }
16277
16278 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
16279                               SourceLocation IdLoc, IdentifierInfo *Id,
16280                               const ParsedAttributesView &Attrs,
16281                               SourceLocation EqualLoc, Expr *Val) {
16282   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
16283   EnumConstantDecl *LastEnumConst =
16284     cast_or_null<EnumConstantDecl>(lastEnumConst);
16285
16286   // The scope passed in may not be a decl scope.  Zip up the scope tree until
16287   // we find one that is.
16288   S = getNonFieldDeclScope(S);
16289
16290   // Verify that there isn't already something declared with this name in this
16291   // scope.
16292   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
16293                                          ForVisibleRedeclaration);
16294   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16295     // Maybe we will complain about the shadowed template parameter.
16296     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
16297     // Just pretend that we didn't see the previous declaration.
16298     PrevDecl = nullptr;
16299   }
16300
16301   // C++ [class.mem]p15:
16302   // If T is the name of a class, then each of the following shall have a name
16303   // different from T:
16304   // - every enumerator of every member of class T that is an unscoped
16305   // enumerated type
16306   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
16307     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
16308                             DeclarationNameInfo(Id, IdLoc));
16309
16310   EnumConstantDecl *New =
16311     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
16312   if (!New)
16313     return nullptr;
16314
16315   if (PrevDecl) {
16316     // When in C++, we may get a TagDecl with the same name; in this case the
16317     // enum constant will 'hide' the tag.
16318     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
16319            "Received TagDecl when not in C++!");
16320     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
16321       if (isa<EnumConstantDecl>(PrevDecl))
16322         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
16323       else
16324         Diag(IdLoc, diag::err_redefinition) << Id;
16325       notePreviousDefinition(PrevDecl, IdLoc);
16326       return nullptr;
16327     }
16328   }
16329
16330   // Process attributes.
16331   ProcessDeclAttributeList(S, New, Attrs);
16332   AddPragmaAttributes(S, New);
16333
16334   // Register this decl in the current scope stack.
16335   New->setAccess(TheEnumDecl->getAccess());
16336   PushOnScopeChains(New, S);
16337
16338   ActOnDocumentableDecl(New);
16339
16340   return New;
16341 }
16342
16343 // Returns true when the enum initial expression does not trigger the
16344 // duplicate enum warning.  A few common cases are exempted as follows:
16345 // Element2 = Element1
16346 // Element2 = Element1 + 1
16347 // Element2 = Element1 - 1
16348 // Where Element2 and Element1 are from the same enum.
16349 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
16350   Expr *InitExpr = ECD->getInitExpr();
16351   if (!InitExpr)
16352     return true;
16353   InitExpr = InitExpr->IgnoreImpCasts();
16354
16355   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
16356     if (!BO->isAdditiveOp())
16357       return true;
16358     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
16359     if (!IL)
16360       return true;
16361     if (IL->getValue() != 1)
16362       return true;
16363
16364     InitExpr = BO->getLHS();
16365   }
16366
16367   // This checks if the elements are from the same enum.
16368   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
16369   if (!DRE)
16370     return true;
16371
16372   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
16373   if (!EnumConstant)
16374     return true;
16375
16376   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
16377       Enum)
16378     return true;
16379
16380   return false;
16381 }
16382
16383 // Emits a warning when an element is implicitly set a value that
16384 // a previous element has already been set to.
16385 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
16386                                         EnumDecl *Enum, QualType EnumType) {
16387   // Avoid anonymous enums
16388   if (!Enum->getIdentifier())
16389     return;
16390
16391   // Only check for small enums.
16392   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
16393     return;
16394
16395   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
16396     return;
16397
16398   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
16399   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
16400
16401   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
16402   typedef llvm::DenseMap<int64_t, DeclOrVector> ValueToVectorMap;
16403
16404   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
16405   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
16406     llvm::APSInt Val = D->getInitVal();
16407     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
16408   };
16409
16410   DuplicatesVector DupVector;
16411   ValueToVectorMap EnumMap;
16412
16413   // Populate the EnumMap with all values represented by enum constants without
16414   // an initializer.
16415   for (auto *Element : Elements) {
16416     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
16417
16418     // Null EnumConstantDecl means a previous diagnostic has been emitted for
16419     // this constant.  Skip this enum since it may be ill-formed.
16420     if (!ECD) {
16421       return;
16422     }
16423
16424     // Constants with initalizers are handled in the next loop.
16425     if (ECD->getInitExpr())
16426       continue;
16427
16428     // Duplicate values are handled in the next loop.
16429     EnumMap.insert({EnumConstantToKey(ECD), ECD});
16430   }
16431
16432   if (EnumMap.size() == 0)
16433     return;
16434
16435   // Create vectors for any values that has duplicates.
16436   for (auto *Element : Elements) {
16437     // The last loop returned if any constant was null.
16438     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
16439     if (!ValidDuplicateEnum(ECD, Enum))
16440       continue;
16441
16442     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
16443     if (Iter == EnumMap.end())
16444       continue;
16445
16446     DeclOrVector& Entry = Iter->second;
16447     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
16448       // Ensure constants are different.
16449       if (D == ECD)
16450         continue;
16451
16452       // Create new vector and push values onto it.
16453       auto Vec = llvm::make_unique<ECDVector>();
16454       Vec->push_back(D);
16455       Vec->push_back(ECD);
16456
16457       // Update entry to point to the duplicates vector.
16458       Entry = Vec.get();
16459
16460       // Store the vector somewhere we can consult later for quick emission of
16461       // diagnostics.
16462       DupVector.emplace_back(std::move(Vec));
16463       continue;
16464     }
16465
16466     ECDVector *Vec = Entry.get<ECDVector*>();
16467     // Make sure constants are not added more than once.
16468     if (*Vec->begin() == ECD)
16469       continue;
16470
16471     Vec->push_back(ECD);
16472   }
16473
16474   // Emit diagnostics.
16475   for (const auto &Vec : DupVector) {
16476     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
16477
16478     // Emit warning for one enum constant.
16479     auto *FirstECD = Vec->front();
16480     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
16481       << FirstECD << FirstECD->getInitVal().toString(10)
16482       << FirstECD->getSourceRange();
16483
16484     // Emit one note for each of the remaining enum constants with
16485     // the same value.
16486     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
16487       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
16488         << ECD << ECD->getInitVal().toString(10)
16489         << ECD->getSourceRange();
16490   }
16491 }
16492
16493 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
16494                              bool AllowMask) const {
16495   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
16496   assert(ED->isCompleteDefinition() && "expected enum definition");
16497
16498   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
16499   llvm::APInt &FlagBits = R.first->second;
16500
16501   if (R.second) {
16502     for (auto *E : ED->enumerators()) {
16503       const auto &EVal = E->getInitVal();
16504       // Only single-bit enumerators introduce new flag values.
16505       if (EVal.isPowerOf2())
16506         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
16507     }
16508   }
16509
16510   // A value is in a flag enum if either its bits are a subset of the enum's
16511   // flag bits (the first condition) or we are allowing masks and the same is
16512   // true of its complement (the second condition). When masks are allowed, we
16513   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
16514   //
16515   // While it's true that any value could be used as a mask, the assumption is
16516   // that a mask will have all of the insignificant bits set. Anything else is
16517   // likely a logic error.
16518   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
16519   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
16520 }
16521
16522 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
16523                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
16524                          const ParsedAttributesView &Attrs) {
16525   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
16526   QualType EnumType = Context.getTypeDeclType(Enum);
16527
16528   ProcessDeclAttributeList(S, Enum, Attrs);
16529
16530   if (Enum->isDependentType()) {
16531     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16532       EnumConstantDecl *ECD =
16533         cast_or_null<EnumConstantDecl>(Elements[i]);
16534       if (!ECD) continue;
16535
16536       ECD->setType(EnumType);
16537     }
16538
16539     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
16540     return;
16541   }
16542
16543   // TODO: If the result value doesn't fit in an int, it must be a long or long
16544   // long value.  ISO C does not support this, but GCC does as an extension,
16545   // emit a warning.
16546   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16547   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
16548   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
16549
16550   // Verify that all the values are okay, compute the size of the values, and
16551   // reverse the list.
16552   unsigned NumNegativeBits = 0;
16553   unsigned NumPositiveBits = 0;
16554
16555   // Keep track of whether all elements have type int.
16556   bool AllElementsInt = true;
16557
16558   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16559     EnumConstantDecl *ECD =
16560       cast_or_null<EnumConstantDecl>(Elements[i]);
16561     if (!ECD) continue;  // Already issued a diagnostic.
16562
16563     const llvm::APSInt &InitVal = ECD->getInitVal();
16564
16565     // Keep track of the size of positive and negative values.
16566     if (InitVal.isUnsigned() || InitVal.isNonNegative())
16567       NumPositiveBits = std::max(NumPositiveBits,
16568                                  (unsigned)InitVal.getActiveBits());
16569     else
16570       NumNegativeBits = std::max(NumNegativeBits,
16571                                  (unsigned)InitVal.getMinSignedBits());
16572
16573     // Keep track of whether every enum element has type int (very commmon).
16574     if (AllElementsInt)
16575       AllElementsInt = ECD->getType() == Context.IntTy;
16576   }
16577
16578   // Figure out the type that should be used for this enum.
16579   QualType BestType;
16580   unsigned BestWidth;
16581
16582   // C++0x N3000 [conv.prom]p3:
16583   //   An rvalue of an unscoped enumeration type whose underlying
16584   //   type is not fixed can be converted to an rvalue of the first
16585   //   of the following types that can represent all the values of
16586   //   the enumeration: int, unsigned int, long int, unsigned long
16587   //   int, long long int, or unsigned long long int.
16588   // C99 6.4.4.3p2:
16589   //   An identifier declared as an enumeration constant has type int.
16590   // The C99 rule is modified by a gcc extension
16591   QualType BestPromotionType;
16592
16593   bool Packed = Enum->hasAttr<PackedAttr>();
16594   // -fshort-enums is the equivalent to specifying the packed attribute on all
16595   // enum definitions.
16596   if (LangOpts.ShortEnums)
16597     Packed = true;
16598
16599   // If the enum already has a type because it is fixed or dictated by the
16600   // target, promote that type instead of analyzing the enumerators.
16601   if (Enum->isComplete()) {
16602     BestType = Enum->getIntegerType();
16603     if (BestType->isPromotableIntegerType())
16604       BestPromotionType = Context.getPromotedIntegerType(BestType);
16605     else
16606       BestPromotionType = BestType;
16607
16608     BestWidth = Context.getIntWidth(BestType);
16609   }
16610   else if (NumNegativeBits) {
16611     // If there is a negative value, figure out the smallest integer type (of
16612     // int/long/longlong) that fits.
16613     // If it's packed, check also if it fits a char or a short.
16614     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
16615       BestType = Context.SignedCharTy;
16616       BestWidth = CharWidth;
16617     } else if (Packed && NumNegativeBits <= ShortWidth &&
16618                NumPositiveBits < ShortWidth) {
16619       BestType = Context.ShortTy;
16620       BestWidth = ShortWidth;
16621     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
16622       BestType = Context.IntTy;
16623       BestWidth = IntWidth;
16624     } else {
16625       BestWidth = Context.getTargetInfo().getLongWidth();
16626
16627       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
16628         BestType = Context.LongTy;
16629       } else {
16630         BestWidth = Context.getTargetInfo().getLongLongWidth();
16631
16632         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
16633           Diag(Enum->getLocation(), diag::ext_enum_too_large);
16634         BestType = Context.LongLongTy;
16635       }
16636     }
16637     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
16638   } else {
16639     // If there is no negative value, figure out the smallest type that fits
16640     // all of the enumerator values.
16641     // If it's packed, check also if it fits a char or a short.
16642     if (Packed && NumPositiveBits <= CharWidth) {
16643       BestType = Context.UnsignedCharTy;
16644       BestPromotionType = Context.IntTy;
16645       BestWidth = CharWidth;
16646     } else if (Packed && NumPositiveBits <= ShortWidth) {
16647       BestType = Context.UnsignedShortTy;
16648       BestPromotionType = Context.IntTy;
16649       BestWidth = ShortWidth;
16650     } else if (NumPositiveBits <= IntWidth) {
16651       BestType = Context.UnsignedIntTy;
16652       BestWidth = IntWidth;
16653       BestPromotionType
16654         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16655                            ? Context.UnsignedIntTy : Context.IntTy;
16656     } else if (NumPositiveBits <=
16657                (BestWidth = Context.getTargetInfo().getLongWidth())) {
16658       BestType = Context.UnsignedLongTy;
16659       BestPromotionType
16660         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16661                            ? Context.UnsignedLongTy : Context.LongTy;
16662     } else {
16663       BestWidth = Context.getTargetInfo().getLongLongWidth();
16664       assert(NumPositiveBits <= BestWidth &&
16665              "How could an initializer get larger than ULL?");
16666       BestType = Context.UnsignedLongLongTy;
16667       BestPromotionType
16668         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16669                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
16670     }
16671   }
16672
16673   // Loop over all of the enumerator constants, changing their types to match
16674   // the type of the enum if needed.
16675   for (auto *D : Elements) {
16676     auto *ECD = cast_or_null<EnumConstantDecl>(D);
16677     if (!ECD) continue;  // Already issued a diagnostic.
16678
16679     // Standard C says the enumerators have int type, but we allow, as an
16680     // extension, the enumerators to be larger than int size.  If each
16681     // enumerator value fits in an int, type it as an int, otherwise type it the
16682     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
16683     // that X has type 'int', not 'unsigned'.
16684
16685     // Determine whether the value fits into an int.
16686     llvm::APSInt InitVal = ECD->getInitVal();
16687
16688     // If it fits into an integer type, force it.  Otherwise force it to match
16689     // the enum decl type.
16690     QualType NewTy;
16691     unsigned NewWidth;
16692     bool NewSign;
16693     if (!getLangOpts().CPlusPlus &&
16694         !Enum->isFixed() &&
16695         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
16696       NewTy = Context.IntTy;
16697       NewWidth = IntWidth;
16698       NewSign = true;
16699     } else if (ECD->getType() == BestType) {
16700       // Already the right type!
16701       if (getLangOpts().CPlusPlus)
16702         // C++ [dcl.enum]p4: Following the closing brace of an
16703         // enum-specifier, each enumerator has the type of its
16704         // enumeration.
16705         ECD->setType(EnumType);
16706       continue;
16707     } else {
16708       NewTy = BestType;
16709       NewWidth = BestWidth;
16710       NewSign = BestType->isSignedIntegerOrEnumerationType();
16711     }
16712
16713     // Adjust the APSInt value.
16714     InitVal = InitVal.extOrTrunc(NewWidth);
16715     InitVal.setIsSigned(NewSign);
16716     ECD->setInitVal(InitVal);
16717
16718     // Adjust the Expr initializer and type.
16719     if (ECD->getInitExpr() &&
16720         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
16721       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
16722                                                 CK_IntegralCast,
16723                                                 ECD->getInitExpr(),
16724                                                 /*base paths*/ nullptr,
16725                                                 VK_RValue));
16726     if (getLangOpts().CPlusPlus)
16727       // C++ [dcl.enum]p4: Following the closing brace of an
16728       // enum-specifier, each enumerator has the type of its
16729       // enumeration.
16730       ECD->setType(EnumType);
16731     else
16732       ECD->setType(NewTy);
16733   }
16734
16735   Enum->completeDefinition(BestType, BestPromotionType,
16736                            NumPositiveBits, NumNegativeBits);
16737
16738   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
16739
16740   if (Enum->isClosedFlag()) {
16741     for (Decl *D : Elements) {
16742       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
16743       if (!ECD) continue;  // Already issued a diagnostic.
16744
16745       llvm::APSInt InitVal = ECD->getInitVal();
16746       if (InitVal != 0 && !InitVal.isPowerOf2() &&
16747           !IsValueInFlagEnum(Enum, InitVal, true))
16748         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
16749           << ECD << Enum;
16750     }
16751   }
16752
16753   // Now that the enum type is defined, ensure it's not been underaligned.
16754   if (Enum->hasAttrs())
16755     CheckAlignasUnderalignment(Enum);
16756 }
16757
16758 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
16759                                   SourceLocation StartLoc,
16760                                   SourceLocation EndLoc) {
16761   StringLiteral *AsmString = cast<StringLiteral>(expr);
16762
16763   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
16764                                                    AsmString, StartLoc,
16765                                                    EndLoc);
16766   CurContext->addDecl(New);
16767   return New;
16768 }
16769
16770 static void checkModuleImportContext(Sema &S, Module *M,
16771                                      SourceLocation ImportLoc, DeclContext *DC,
16772                                      bool FromInclude = false) {
16773   SourceLocation ExternCLoc;
16774
16775   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
16776     switch (LSD->getLanguage()) {
16777     case LinkageSpecDecl::lang_c:
16778       if (ExternCLoc.isInvalid())
16779         ExternCLoc = LSD->getLocStart();
16780       break;
16781     case LinkageSpecDecl::lang_cxx:
16782       break;
16783     }
16784     DC = LSD->getParent();
16785   }
16786
16787   while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
16788     DC = DC->getParent();
16789
16790   if (!isa<TranslationUnitDecl>(DC)) {
16791     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
16792                           ? diag::ext_module_import_not_at_top_level_noop
16793                           : diag::err_module_import_not_at_top_level_fatal)
16794         << M->getFullModuleName() << DC;
16795     S.Diag(cast<Decl>(DC)->getLocStart(),
16796            diag::note_module_import_not_at_top_level) << DC;
16797   } else if (!M->IsExternC && ExternCLoc.isValid()) {
16798     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
16799       << M->getFullModuleName();
16800     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
16801   }
16802 }
16803
16804 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
16805                                            SourceLocation ModuleLoc,
16806                                            ModuleDeclKind MDK,
16807                                            ModuleIdPath Path) {
16808   assert(getLangOpts().ModulesTS &&
16809          "should only have module decl in modules TS");
16810
16811   // A module implementation unit requires that we are not compiling a module
16812   // of any kind. A module interface unit requires that we are not compiling a
16813   // module map.
16814   switch (getLangOpts().getCompilingModule()) {
16815   case LangOptions::CMK_None:
16816     // It's OK to compile a module interface as a normal translation unit.
16817     break;
16818
16819   case LangOptions::CMK_ModuleInterface:
16820     if (MDK != ModuleDeclKind::Implementation)
16821       break;
16822
16823     // We were asked to compile a module interface unit but this is a module
16824     // implementation unit. That indicates the 'export' is missing.
16825     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
16826       << FixItHint::CreateInsertion(ModuleLoc, "export ");
16827     MDK = ModuleDeclKind::Interface;
16828     break;
16829
16830   case LangOptions::CMK_ModuleMap:
16831     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
16832     return nullptr;
16833   }
16834
16835   assert(ModuleScopes.size() == 1 && "expected to be at global module scope");
16836
16837   // FIXME: Most of this work should be done by the preprocessor rather than
16838   // here, in order to support macro import.
16839
16840   // Only one module-declaration is permitted per source file.
16841   if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) {
16842     Diag(ModuleLoc, diag::err_module_redeclaration);
16843     Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
16844          diag::note_prev_module_declaration);
16845     return nullptr;
16846   }
16847
16848   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
16849   // modules, the dots here are just another character that can appear in a
16850   // module name.
16851   std::string ModuleName;
16852   for (auto &Piece : Path) {
16853     if (!ModuleName.empty())
16854       ModuleName += ".";
16855     ModuleName += Piece.first->getName();
16856   }
16857
16858   // If a module name was explicitly specified on the command line, it must be
16859   // correct.
16860   if (!getLangOpts().CurrentModule.empty() &&
16861       getLangOpts().CurrentModule != ModuleName) {
16862     Diag(Path.front().second, diag::err_current_module_name_mismatch)
16863         << SourceRange(Path.front().second, Path.back().second)
16864         << getLangOpts().CurrentModule;
16865     return nullptr;
16866   }
16867   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
16868
16869   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
16870   Module *Mod;
16871
16872   switch (MDK) {
16873   case ModuleDeclKind::Interface: {
16874     // We can't have parsed or imported a definition of this module or parsed a
16875     // module map defining it already.
16876     if (auto *M = Map.findModule(ModuleName)) {
16877       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
16878       if (M->DefinitionLoc.isValid())
16879         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
16880       else if (const auto *FE = M->getASTFile())
16881         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
16882             << FE->getName();
16883       Mod = M;
16884       break;
16885     }
16886
16887     // Create a Module for the module that we're defining.
16888     Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16889                                            ModuleScopes.front().Module);
16890     assert(Mod && "module creation should not fail");
16891     break;
16892   }
16893
16894   case ModuleDeclKind::Partition:
16895     // FIXME: Check we are in a submodule of the named module.
16896     return nullptr;
16897
16898   case ModuleDeclKind::Implementation:
16899     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
16900         PP.getIdentifierInfo(ModuleName), Path[0].second);
16901     Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible,
16902                                        /*IsIncludeDirective=*/false);
16903     if (!Mod) {
16904       Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
16905       // Create an empty module interface unit for error recovery.
16906       Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16907                                              ModuleScopes.front().Module);
16908     }
16909     break;
16910   }
16911
16912   // Switch from the global module to the named module.
16913   ModuleScopes.back().Module = Mod;
16914   ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
16915   VisibleModules.setVisible(Mod, ModuleLoc);
16916
16917   // From now on, we have an owning module for all declarations we see.
16918   // However, those declarations are module-private unless explicitly
16919   // exported.
16920   auto *TU = Context.getTranslationUnitDecl();
16921   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
16922   TU->setLocalOwningModule(Mod);
16923
16924   // FIXME: Create a ModuleDecl.
16925   return nullptr;
16926 }
16927
16928 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
16929                                    SourceLocation ImportLoc,
16930                                    ModuleIdPath Path) {
16931   Module *Mod =
16932       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
16933                                    /*IsIncludeDirective=*/false);
16934   if (!Mod)
16935     return true;
16936
16937   VisibleModules.setVisible(Mod, ImportLoc);
16938
16939   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
16940
16941   // FIXME: we should support importing a submodule within a different submodule
16942   // of the same top-level module. Until we do, make it an error rather than
16943   // silently ignoring the import.
16944   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
16945   // warn on a redundant import of the current module?
16946   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
16947       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
16948     Diag(ImportLoc, getLangOpts().isCompilingModule()
16949                         ? diag::err_module_self_import
16950                         : diag::err_module_import_in_implementation)
16951         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
16952
16953   SmallVector<SourceLocation, 2> IdentifierLocs;
16954   Module *ModCheck = Mod;
16955   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
16956     // If we've run out of module parents, just drop the remaining identifiers.
16957     // We need the length to be consistent.
16958     if (!ModCheck)
16959       break;
16960     ModCheck = ModCheck->Parent;
16961
16962     IdentifierLocs.push_back(Path[I].second);
16963   }
16964
16965   ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
16966                                           Mod, IdentifierLocs);
16967   if (!ModuleScopes.empty())
16968     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
16969   CurContext->addDecl(Import);
16970
16971   // Re-export the module if needed.
16972   if (Import->isExported() &&
16973       !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface)
16974     getCurrentModule()->Exports.emplace_back(Mod, false);
16975
16976   return Import;
16977 }
16978
16979 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16980   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16981   BuildModuleInclude(DirectiveLoc, Mod);
16982 }
16983
16984 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16985   // Determine whether we're in the #include buffer for a module. The #includes
16986   // in that buffer do not qualify as module imports; they're just an
16987   // implementation detail of us building the module.
16988   //
16989   // FIXME: Should we even get ActOnModuleInclude calls for those?
16990   bool IsInModuleIncludes =
16991       TUKind == TU_Module &&
16992       getSourceManager().isWrittenInMainFile(DirectiveLoc);
16993
16994   bool ShouldAddImport = !IsInModuleIncludes;
16995
16996   // If this module import was due to an inclusion directive, create an
16997   // implicit import declaration to capture it in the AST.
16998   if (ShouldAddImport) {
16999     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
17000     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
17001                                                      DirectiveLoc, Mod,
17002                                                      DirectiveLoc);
17003     if (!ModuleScopes.empty())
17004       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
17005     TU->addDecl(ImportD);
17006     Consumer.HandleImplicitImportDecl(ImportD);
17007   }
17008
17009   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
17010   VisibleModules.setVisible(Mod, DirectiveLoc);
17011 }
17012
17013 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
17014   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
17015
17016   ModuleScopes.push_back({});
17017   ModuleScopes.back().Module = Mod;
17018   if (getLangOpts().ModulesLocalVisibility)
17019     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
17020
17021   VisibleModules.setVisible(Mod, DirectiveLoc);
17022
17023   // The enclosing context is now part of this module.
17024   // FIXME: Consider creating a child DeclContext to hold the entities
17025   // lexically within the module.
17026   if (getLangOpts().trackLocalOwningModule()) {
17027     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
17028       cast<Decl>(DC)->setModuleOwnershipKind(
17029           getLangOpts().ModulesLocalVisibility
17030               ? Decl::ModuleOwnershipKind::VisibleWhenImported
17031               : Decl::ModuleOwnershipKind::Visible);
17032       cast<Decl>(DC)->setLocalOwningModule(Mod);
17033     }
17034   }
17035 }
17036
17037 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
17038   if (getLangOpts().ModulesLocalVisibility) {
17039     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
17040     // Leaving a module hides namespace names, so our visible namespace cache
17041     // is now out of date.
17042     VisibleNamespaceCache.clear();
17043   }
17044
17045   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
17046          "left the wrong module scope");
17047   ModuleScopes.pop_back();
17048
17049   // We got to the end of processing a local module. Create an
17050   // ImportDecl as we would for an imported module.
17051   FileID File = getSourceManager().getFileID(EomLoc);
17052   SourceLocation DirectiveLoc;
17053   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
17054     // We reached the end of a #included module header. Use the #include loc.
17055     assert(File != getSourceManager().getMainFileID() &&
17056            "end of submodule in main source file");
17057     DirectiveLoc = getSourceManager().getIncludeLoc(File);
17058   } else {
17059     // We reached an EOM pragma. Use the pragma location.
17060     DirectiveLoc = EomLoc;
17061   }
17062   BuildModuleInclude(DirectiveLoc, Mod);
17063
17064   // Any further declarations are in whatever module we returned to.
17065   if (getLangOpts().trackLocalOwningModule()) {
17066     // The parser guarantees that this is the same context that we entered
17067     // the module within.
17068     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
17069       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
17070       if (!getCurrentModule())
17071         cast<Decl>(DC)->setModuleOwnershipKind(
17072             Decl::ModuleOwnershipKind::Unowned);
17073     }
17074   }
17075 }
17076
17077 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
17078                                                       Module *Mod) {
17079   // Bail if we're not allowed to implicitly import a module here.
17080   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
17081       VisibleModules.isVisible(Mod))
17082     return;
17083
17084   // Create the implicit import declaration.
17085   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
17086   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
17087                                                    Loc, Mod, Loc);
17088   TU->addDecl(ImportD);
17089   Consumer.HandleImplicitImportDecl(ImportD);
17090
17091   // Make the module visible.
17092   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
17093   VisibleModules.setVisible(Mod, Loc);
17094 }
17095
17096 /// We have parsed the start of an export declaration, including the '{'
17097 /// (if present).
17098 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
17099                                  SourceLocation LBraceLoc) {
17100   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
17101
17102   // C++ Modules TS draft:
17103   //   An export-declaration shall appear in the purview of a module other than
17104   //   the global module.
17105   if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface)
17106     Diag(ExportLoc, diag::err_export_not_in_module_interface);
17107
17108   //   An export-declaration [...] shall not contain more than one
17109   //   export keyword.
17110   //
17111   // The intent here is that an export-declaration cannot appear within another
17112   // export-declaration.
17113   if (D->isExported())
17114     Diag(ExportLoc, diag::err_export_within_export);
17115
17116   CurContext->addDecl(D);
17117   PushDeclContext(S, D);
17118   D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
17119   return D;
17120 }
17121
17122 /// Complete the definition of an export declaration.
17123 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
17124   auto *ED = cast<ExportDecl>(D);
17125   if (RBraceLoc.isValid())
17126     ED->setRBraceLoc(RBraceLoc);
17127
17128   // FIXME: Diagnose export of internal-linkage declaration (including
17129   // anonymous namespace).
17130
17131   PopDeclContext();
17132   return D;
17133 }
17134
17135 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17136                                       IdentifierInfo* AliasName,
17137                                       SourceLocation PragmaLoc,
17138                                       SourceLocation NameLoc,
17139                                       SourceLocation AliasNameLoc) {
17140   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17141                                          LookupOrdinaryName);
17142   AsmLabelAttr *Attr =
17143       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
17144
17145   // If a declaration that:
17146   // 1) declares a function or a variable
17147   // 2) has external linkage
17148   // already exists, add a label attribute to it.
17149   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17150     if (isDeclExternC(PrevDecl))
17151       PrevDecl->addAttr(Attr);
17152     else
17153       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17154           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17155   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17156   } else
17157     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17158 }
17159
17160 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17161                              SourceLocation PragmaLoc,
17162                              SourceLocation NameLoc) {
17163   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17164
17165   if (PrevDecl) {
17166     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
17167   } else {
17168     (void)WeakUndeclaredIdentifiers.insert(
17169       std::pair<IdentifierInfo*,WeakInfo>
17170         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17171   }
17172 }
17173
17174 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17175                                 IdentifierInfo* AliasName,
17176                                 SourceLocation PragmaLoc,
17177                                 SourceLocation NameLoc,
17178                                 SourceLocation AliasNameLoc) {
17179   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17180                                     LookupOrdinaryName);
17181   WeakInfo W = WeakInfo(Name, NameLoc);
17182
17183   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17184     if (!PrevDecl->hasAttr<AliasAttr>())
17185       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17186         DeclApplyPragmaWeak(TUScope, ND, W);
17187   } else {
17188     (void)WeakUndeclaredIdentifiers.insert(
17189       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17190   }
17191 }
17192
17193 Decl *Sema::getObjCDeclContext() const {
17194   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17195 }