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 "clang/Sema/SemaInternal.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/CommentDiagnostic.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50 
51 using namespace clang;
52 using namespace sema;
53 
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59 
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62 
63 namespace {
64 
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66  public:
67   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
68                        bool AllowTemplates=false)
69       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70         AllowClassTemplates(AllowTemplates) {
71     WantExpressionKeywords = false;
72     WantCXXNamedCasts = false;
73     WantRemainingKeywords = false;
74   }
75 
76   bool ValidateCandidate(const TypoCorrection &candidate) override {
77     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
78       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
79       bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
80       return (IsType || AllowedTemplate) &&
81              (AllowInvalidDecl || !ND->isInvalidDecl());
82     }
83     return !WantClassName && candidate.isKeyword();
84   }
85 
86  private:
87   bool AllowInvalidDecl;
88   bool WantClassName;
89   bool AllowClassTemplates;
90 };
91 
92 } // end anonymous namespace
93 
94 /// \brief Determine whether the token kind starts a simple-type-specifier.
95 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
96   switch (Kind) {
97   // FIXME: Take into account the current language when deciding whether a
98   // token kind is a valid type specifier
99   case tok::kw_short:
100   case tok::kw_long:
101   case tok::kw___int64:
102   case tok::kw___int128:
103   case tok::kw_signed:
104   case tok::kw_unsigned:
105   case tok::kw_void:
106   case tok::kw_char:
107   case tok::kw_int:
108   case tok::kw_half:
109   case tok::kw_float:
110   case tok::kw_double:
111   case tok::kw_wchar_t:
112   case tok::kw_bool:
113   case tok::kw___underlying_type:
114   case tok::kw___auto_type:
115     return true;
116 
117   case tok::annot_typename:
118   case tok::kw_char16_t:
119   case tok::kw_char32_t:
120   case tok::kw_typeof:
121   case tok::annot_decltype:
122   case tok::kw_decltype:
123     return getLangOpts().CPlusPlus;
124 
125   default:
126     break;
127   }
128 
129   return false;
130 }
131 
132 namespace {
133 enum class UnqualifiedTypeNameLookupResult {
134   NotFound,
135   FoundNonType,
136   FoundType
137 };
138 } // end anonymous namespace
139 
140 /// \brief Tries to perform unqualified lookup of the type decls in bases for
141 /// dependent class.
142 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
143 /// type decl, \a FoundType if only type decls are found.
144 static UnqualifiedTypeNameLookupResult
145 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
146                                 SourceLocation NameLoc,
147                                 const CXXRecordDecl *RD) {
148   if (!RD->hasDefinition())
149     return UnqualifiedTypeNameLookupResult::NotFound;
150   // Look for type decls in base classes.
151   UnqualifiedTypeNameLookupResult FoundTypeDecl =
152       UnqualifiedTypeNameLookupResult::NotFound;
153   for (const auto &Base : RD->bases()) {
154     const CXXRecordDecl *BaseRD = nullptr;
155     if (auto *BaseTT = Base.getType()->getAs<TagType>())
156       BaseRD = BaseTT->getAsCXXRecordDecl();
157     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
158       // Look for type decls in dependent base classes that have known primary
159       // templates.
160       if (!TST || !TST->isDependentType())
161         continue;
162       auto *TD = TST->getTemplateName().getAsTemplateDecl();
163       if (!TD)
164         continue;
165       auto *BasePrimaryTemplate =
166           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
167       if (!BasePrimaryTemplate)
168         continue;
169       BaseRD = BasePrimaryTemplate;
170     }
171     if (BaseRD) {
172       for (NamedDecl *ND : BaseRD->lookup(&II)) {
173         if (!isa<TypeDecl>(ND))
174           return UnqualifiedTypeNameLookupResult::FoundNonType;
175         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
176       }
177       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
178         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
179         case UnqualifiedTypeNameLookupResult::FoundNonType:
180           return UnqualifiedTypeNameLookupResult::FoundNonType;
181         case UnqualifiedTypeNameLookupResult::FoundType:
182           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
183           break;
184         case UnqualifiedTypeNameLookupResult::NotFound:
185           break;
186         }
187       }
188     }
189   }
190 
191   return FoundTypeDecl;
192 }
193 
194 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
195                                                       const IdentifierInfo &II,
196                                                       SourceLocation NameLoc) {
197   // Lookup in the parent class template context, if any.
198   const CXXRecordDecl *RD = nullptr;
199   UnqualifiedTypeNameLookupResult FoundTypeDecl =
200       UnqualifiedTypeNameLookupResult::NotFound;
201   for (DeclContext *DC = S.CurContext;
202        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
203        DC = DC->getParent()) {
204     // Look for type decls in dependent base classes that have known primary
205     // templates.
206     RD = dyn_cast<CXXRecordDecl>(DC);
207     if (RD && RD->getDescribedClassTemplate())
208       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
209   }
210   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
211     return nullptr;
212 
213   // We found some types in dependent base classes.  Recover as if the user
214   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
215   // lookup during template instantiation.
216   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
217 
218   ASTContext &Context = S.Context;
219   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
220                                           cast<Type>(Context.getRecordType(RD)));
221   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
222 
223   CXXScopeSpec SS;
224   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
225 
226   TypeLocBuilder Builder;
227   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
228   DepTL.setNameLoc(NameLoc);
229   DepTL.setElaboratedKeywordLoc(SourceLocation());
230   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
231   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
232 }
233 
234 /// \brief If the identifier refers to a type name within this scope,
235 /// return the declaration of that type.
236 ///
237 /// This routine performs ordinary name lookup of the identifier II
238 /// within the given scope, with optional C++ scope specifier SS, to
239 /// determine whether the name refers to a type. If so, returns an
240 /// opaque pointer (actually a QualType) corresponding to that
241 /// type. Otherwise, returns NULL.
242 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
243                              Scope *S, CXXScopeSpec *SS,
244                              bool isClassName, bool HasTrailingDot,
245                              ParsedType ObjectTypePtr,
246                              bool IsCtorOrDtorName,
247                              bool WantNontrivialTypeSourceInfo,
248                              IdentifierInfo **CorrectedII) {
249   // Determine where we will perform name lookup.
250   DeclContext *LookupCtx = nullptr;
251   if (ObjectTypePtr) {
252     QualType ObjectType = ObjectTypePtr.get();
253     if (ObjectType->isRecordType())
254       LookupCtx = computeDeclContext(ObjectType);
255   } else if (SS && SS->isNotEmpty()) {
256     LookupCtx = computeDeclContext(*SS, false);
257 
258     if (!LookupCtx) {
259       if (isDependentScopeSpecifier(*SS)) {
260         // C++ [temp.res]p3:
261         //   A qualified-id that refers to a type and in which the
262         //   nested-name-specifier depends on a template-parameter (14.6.2)
263         //   shall be prefixed by the keyword typename to indicate that the
264         //   qualified-id denotes a type, forming an
265         //   elaborated-type-specifier (7.1.5.3).
266         //
267         // We therefore do not perform any name lookup if the result would
268         // refer to a member of an unknown specialization.
269         if (!isClassName && !IsCtorOrDtorName)
270           return nullptr;
271 
272         // We know from the grammar that this name refers to a type,
273         // so build a dependent node to describe the type.
274         if (WantNontrivialTypeSourceInfo)
275           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
276 
277         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
278         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
279                                        II, NameLoc);
280         return ParsedType::make(T);
281       }
282 
283       return nullptr;
284     }
285 
286     if (!LookupCtx->isDependentContext() &&
287         RequireCompleteDeclContext(*SS, LookupCtx))
288       return nullptr;
289   }
290 
291   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
292   // lookup for class-names.
293   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
294                                       LookupOrdinaryName;
295   LookupResult Result(*this, &II, NameLoc, Kind);
296   if (LookupCtx) {
297     // Perform "qualified" name lookup into the declaration context we
298     // computed, which is either the type of the base of a member access
299     // expression or the declaration context associated with a prior
300     // nested-name-specifier.
301     LookupQualifiedName(Result, LookupCtx);
302 
303     if (ObjectTypePtr && Result.empty()) {
304       // C++ [basic.lookup.classref]p3:
305       //   If the unqualified-id is ~type-name, the type-name is looked up
306       //   in the context of the entire postfix-expression. If the type T of
307       //   the object expression is of a class type C, the type-name is also
308       //   looked up in the scope of class C. At least one of the lookups shall
309       //   find a name that refers to (possibly cv-qualified) T.
310       LookupName(Result, S);
311     }
312   } else {
313     // Perform unqualified name lookup.
314     LookupName(Result, S);
315 
316     // For unqualified lookup in a class template in MSVC mode, look into
317     // dependent base classes where the primary class template is known.
318     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
319       if (ParsedType TypeInBase =
320               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
321         return TypeInBase;
322     }
323   }
324 
325   NamedDecl *IIDecl = nullptr;
326   switch (Result.getResultKind()) {
327   case LookupResult::NotFound:
328   case LookupResult::NotFoundInCurrentInstantiation:
329     if (CorrectedII) {
330       TypoCorrection Correction = CorrectTypo(
331           Result.getLookupNameInfo(), Kind, S, SS,
332           llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
333           CTK_ErrorRecovery);
334       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
335       TemplateTy Template;
336       bool MemberOfUnknownSpecialization;
337       UnqualifiedId TemplateName;
338       TemplateName.setIdentifier(NewII, NameLoc);
339       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
340       CXXScopeSpec NewSS, *NewSSPtr = SS;
341       if (SS && NNS) {
342         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
343         NewSSPtr = &NewSS;
344       }
345       if (Correction && (NNS || NewII != &II) &&
346           // Ignore a correction to a template type as the to-be-corrected
347           // identifier is not a template (typo correction for template names
348           // is handled elsewhere).
349           !(getLangOpts().CPlusPlus && NewSSPtr &&
350             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
351                            Template, MemberOfUnknownSpecialization))) {
352         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
353                                     isClassName, HasTrailingDot, ObjectTypePtr,
354                                     IsCtorOrDtorName,
355                                     WantNontrivialTypeSourceInfo);
356         if (Ty) {
357           diagnoseTypo(Correction,
358                        PDiag(diag::err_unknown_type_or_class_name_suggest)
359                          << Result.getLookupName() << isClassName);
360           if (SS && NNS)
361             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
362           *CorrectedII = NewII;
363           return Ty;
364         }
365       }
366     }
367     // If typo correction failed or was not performed, fall through
368   case LookupResult::FoundOverloaded:
369   case LookupResult::FoundUnresolvedValue:
370     Result.suppressDiagnostics();
371     return nullptr;
372 
373   case LookupResult::Ambiguous:
374     // Recover from type-hiding ambiguities by hiding the type.  We'll
375     // do the lookup again when looking for an object, and we can
376     // diagnose the error then.  If we don't do this, then the error
377     // about hiding the type will be immediately followed by an error
378     // that only makes sense if the identifier was treated like a type.
379     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
380       Result.suppressDiagnostics();
381       return nullptr;
382     }
383 
384     // Look to see if we have a type anywhere in the list of results.
385     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
386          Res != ResEnd; ++Res) {
387       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
388         if (!IIDecl ||
389             (*Res)->getLocation().getRawEncoding() <
390               IIDecl->getLocation().getRawEncoding())
391           IIDecl = *Res;
392       }
393     }
394 
395     if (!IIDecl) {
396       // None of the entities we found is a type, so there is no way
397       // to even assume that the result is a type. In this case, don't
398       // complain about the ambiguity. The parser will either try to
399       // perform this lookup again (e.g., as an object name), which
400       // will produce the ambiguity, or will complain that it expected
401       // a type name.
402       Result.suppressDiagnostics();
403       return nullptr;
404     }
405 
406     // We found a type within the ambiguous lookup; diagnose the
407     // ambiguity and then return that type. This might be the right
408     // answer, or it might not be, but it suppresses any attempt to
409     // perform the name lookup again.
410     break;
411 
412   case LookupResult::Found:
413     IIDecl = Result.getFoundDecl();
414     break;
415   }
416 
417   assert(IIDecl && "Didn't find decl");
418 
419   QualType T;
420   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
421     DiagnoseUseOfDecl(IIDecl, NameLoc);
422 
423     T = Context.getTypeDeclType(TD);
424     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
425 
426     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
427     // constructor or destructor name (in such a case, the scope specifier
428     // will be attached to the enclosing Expr or Decl node).
429     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
430       if (WantNontrivialTypeSourceInfo) {
431         // Construct a type with type-source information.
432         TypeLocBuilder Builder;
433         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
434 
435         T = getElaboratedType(ETK_None, *SS, T);
436         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
437         ElabTL.setElaboratedKeywordLoc(SourceLocation());
438         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
439         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
440       } else {
441         T = getElaboratedType(ETK_None, *SS, T);
442       }
443     }
444   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
445     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
446     if (!HasTrailingDot)
447       T = Context.getObjCInterfaceType(IDecl);
448   }
449 
450   if (T.isNull()) {
451     // If it's not plausibly a type, suppress diagnostics.
452     Result.suppressDiagnostics();
453     return nullptr;
454   }
455   return ParsedType::make(T);
456 }
457 
458 // Builds a fake NNS for the given decl context.
459 static NestedNameSpecifier *
460 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
461   for (;; DC = DC->getLookupParent()) {
462     DC = DC->getPrimaryContext();
463     auto *ND = dyn_cast<NamespaceDecl>(DC);
464     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
465       return NestedNameSpecifier::Create(Context, nullptr, ND);
466     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
467       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
468                                          RD->getTypeForDecl());
469     else if (isa<TranslationUnitDecl>(DC))
470       return NestedNameSpecifier::GlobalSpecifier(Context);
471   }
472   llvm_unreachable("something isn't in TU scope?");
473 }
474 
475 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
476                                                 SourceLocation NameLoc) {
477   // Accepting an undeclared identifier as a default argument for a template
478   // type parameter is a Microsoft extension.
479   Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
480 
481   // Build a fake DependentNameType that will perform lookup into CurContext at
482   // instantiation time.  The name specifier isn't dependent, so template
483   // instantiation won't transform it.  It will retry the lookup, however.
484   NestedNameSpecifier *NNS =
485       synthesizeCurrentNestedNameSpecifier(Context, CurContext);
486   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
487 
488   // Build type location information.  We synthesized the qualifier, so we have
489   // to build a fake NestedNameSpecifierLoc.
490   NestedNameSpecifierLocBuilder NNSLocBuilder;
491   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
492   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
493 
494   TypeLocBuilder Builder;
495   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
496   DepTL.setNameLoc(NameLoc);
497   DepTL.setElaboratedKeywordLoc(SourceLocation());
498   DepTL.setQualifierLoc(QualifierLoc);
499   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
500 }
501 
502 /// isTagName() - This method is called *for error recovery purposes only*
503 /// to determine if the specified name is a valid tag name ("struct foo").  If
504 /// so, this returns the TST for the tag corresponding to it (TST_enum,
505 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
506 /// cases in C where the user forgot to specify the tag.
507 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
508   // Do a tag name lookup in this scope.
509   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
510   LookupName(R, S, false);
511   R.suppressDiagnostics();
512   if (R.getResultKind() == LookupResult::Found)
513     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
514       switch (TD->getTagKind()) {
515       case TTK_Struct: return DeclSpec::TST_struct;
516       case TTK_Interface: return DeclSpec::TST_interface;
517       case TTK_Union:  return DeclSpec::TST_union;
518       case TTK_Class:  return DeclSpec::TST_class;
519       case TTK_Enum:   return DeclSpec::TST_enum;
520       }
521     }
522 
523   return DeclSpec::TST_unspecified;
524 }
525 
526 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
527 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
528 /// then downgrade the missing typename error to a warning.
529 /// This is needed for MSVC compatibility; Example:
530 /// @code
531 /// template<class T> class A {
532 /// public:
533 ///   typedef int TYPE;
534 /// };
535 /// template<class T> class B : public A<T> {
536 /// public:
537 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
538 /// };
539 /// @endcode
540 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
541   if (CurContext->isRecord()) {
542     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
543       return true;
544 
545     const Type *Ty = SS->getScopeRep()->getAsType();
546 
547     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
548     for (const auto &Base : RD->bases())
549       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
550         return true;
551     return S->isFunctionPrototypeScope();
552   }
553   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
554 }
555 
556 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
557                                    SourceLocation IILoc,
558                                    Scope *S,
559                                    CXXScopeSpec *SS,
560                                    ParsedType &SuggestedType,
561                                    bool AllowClassTemplates) {
562   // We don't have anything to suggest (yet).
563   SuggestedType = nullptr;
564 
565   // There may have been a typo in the name of the type. Look up typo
566   // results, in case we have something that we can suggest.
567   if (TypoCorrection Corrected =
568           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
569                       llvm::make_unique<TypeNameValidatorCCC>(
570                           false, false, AllowClassTemplates),
571                       CTK_ErrorRecovery)) {
572     if (Corrected.isKeyword()) {
573       // We corrected to a keyword.
574       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
575       II = Corrected.getCorrectionAsIdentifierInfo();
576     } else {
577       // We found a similarly-named type or interface; suggest that.
578       if (!SS || !SS->isSet()) {
579         diagnoseTypo(Corrected,
580                      PDiag(diag::err_unknown_typename_suggest) << II);
581       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
582         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
583         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
584                                 II->getName().equals(CorrectedStr);
585         diagnoseTypo(Corrected,
586                      PDiag(diag::err_unknown_nested_typename_suggest)
587                        << II << DC << DroppedSpecifier << SS->getRange());
588       } else {
589         llvm_unreachable("could not have corrected a typo here");
590       }
591 
592       CXXScopeSpec tmpSS;
593       if (Corrected.getCorrectionSpecifier())
594         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
595                           SourceRange(IILoc));
596       SuggestedType =
597           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
598                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
599                       /*IsCtorOrDtorName=*/false,
600                       /*NonTrivialTypeSourceInfo=*/true);
601     }
602     return;
603   }
604 
605   if (getLangOpts().CPlusPlus) {
606     // See if II is a class template that the user forgot to pass arguments to.
607     UnqualifiedId Name;
608     Name.setIdentifier(II, IILoc);
609     CXXScopeSpec EmptySS;
610     TemplateTy TemplateResult;
611     bool MemberOfUnknownSpecialization;
612     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
613                        Name, nullptr, true, TemplateResult,
614                        MemberOfUnknownSpecialization) == TNK_Type_template) {
615       TemplateName TplName = TemplateResult.get();
616       Diag(IILoc, diag::err_template_missing_args) << TplName;
617       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
618         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
619           << TplDecl->getTemplateParameters()->getSourceRange();
620       }
621       return;
622     }
623   }
624 
625   // FIXME: Should we move the logic that tries to recover from a missing tag
626   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
627 
628   if (!SS || (!SS->isSet() && !SS->isInvalid()))
629     Diag(IILoc, diag::err_unknown_typename) << II;
630   else if (DeclContext *DC = computeDeclContext(*SS, false))
631     Diag(IILoc, diag::err_typename_nested_not_found)
632       << II << DC << SS->getRange();
633   else if (isDependentScopeSpecifier(*SS)) {
634     unsigned DiagID = diag::err_typename_missing;
635     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
636       DiagID = diag::ext_typename_missing;
637 
638     Diag(SS->getRange().getBegin(), DiagID)
639       << SS->getScopeRep() << II->getName()
640       << SourceRange(SS->getRange().getBegin(), IILoc)
641       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
642     SuggestedType = ActOnTypenameType(S, SourceLocation(),
643                                       *SS, *II, IILoc).get();
644   } else {
645     assert(SS && SS->isInvalid() &&
646            "Invalid scope specifier has already been diagnosed");
647   }
648 }
649 
650 /// \brief Determine whether the given result set contains either a type name
651 /// or
652 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
653   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
654                        NextToken.is(tok::less);
655 
656   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
657     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
658       return true;
659 
660     if (CheckTemplate && isa<TemplateDecl>(*I))
661       return true;
662   }
663 
664   return false;
665 }
666 
667 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
668                                     Scope *S, CXXScopeSpec &SS,
669                                     IdentifierInfo *&Name,
670                                     SourceLocation NameLoc) {
671   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
672   SemaRef.LookupParsedName(R, S, &SS);
673   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
674     StringRef FixItTagName;
675     switch (Tag->getTagKind()) {
676       case TTK_Class:
677         FixItTagName = "class ";
678         break;
679 
680       case TTK_Enum:
681         FixItTagName = "enum ";
682         break;
683 
684       case TTK_Struct:
685         FixItTagName = "struct ";
686         break;
687 
688       case TTK_Interface:
689         FixItTagName = "__interface ";
690         break;
691 
692       case TTK_Union:
693         FixItTagName = "union ";
694         break;
695     }
696 
697     StringRef TagName = FixItTagName.drop_back();
698     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
699       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
700       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
701 
702     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
703          I != IEnd; ++I)
704       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
705         << Name << TagName;
706 
707     // Replace lookup results with just the tag decl.
708     Result.clear(Sema::LookupTagName);
709     SemaRef.LookupParsedName(Result, S, &SS);
710     return true;
711   }
712 
713   return false;
714 }
715 
716 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
717 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
718                                   QualType T, SourceLocation NameLoc) {
719   ASTContext &Context = S.Context;
720 
721   TypeLocBuilder Builder;
722   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
723 
724   T = S.getElaboratedType(ETK_None, SS, T);
725   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
726   ElabTL.setElaboratedKeywordLoc(SourceLocation());
727   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
728   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
729 }
730 
731 Sema::NameClassification
732 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
733                    SourceLocation NameLoc, const Token &NextToken,
734                    bool IsAddressOfOperand,
735                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
736   DeclarationNameInfo NameInfo(Name, NameLoc);
737   ObjCMethodDecl *CurMethod = getCurMethodDecl();
738 
739   if (NextToken.is(tok::coloncolon)) {
740     BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
741                                 QualType(), false, SS, nullptr, false);
742   }
743 
744   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
745   LookupParsedName(Result, S, &SS, !CurMethod);
746 
747   // For unqualified lookup in a class template in MSVC mode, look into
748   // dependent base classes where the primary class template is known.
749   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
750     if (ParsedType TypeInBase =
751             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
752       return TypeInBase;
753   }
754 
755   // Perform lookup for Objective-C instance variables (including automatically
756   // synthesized instance variables), if we're in an Objective-C method.
757   // FIXME: This lookup really, really needs to be folded in to the normal
758   // unqualified lookup mechanism.
759   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
760     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
761     if (E.get() || E.isInvalid())
762       return E;
763   }
764 
765   bool SecondTry = false;
766   bool IsFilteredTemplateName = false;
767 
768 Corrected:
769   switch (Result.getResultKind()) {
770   case LookupResult::NotFound:
771     // If an unqualified-id is followed by a '(', then we have a function
772     // call.
773     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
774       // In C++, this is an ADL-only call.
775       // FIXME: Reference?
776       if (getLangOpts().CPlusPlus)
777         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
778 
779       // C90 6.3.2.2:
780       //   If the expression that precedes the parenthesized argument list in a
781       //   function call consists solely of an identifier, and if no
782       //   declaration is visible for this identifier, the identifier is
783       //   implicitly declared exactly as if, in the innermost block containing
784       //   the function call, the declaration
785       //
786       //     extern int identifier ();
787       //
788       //   appeared.
789       //
790       // We also allow this in C99 as an extension.
791       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
792         Result.addDecl(D);
793         Result.resolveKind();
794         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
795       }
796     }
797 
798     // In C, we first see whether there is a tag type by the same name, in
799     // which case it's likely that the user just forgot to write "enum",
800     // "struct", or "union".
801     if (!getLangOpts().CPlusPlus && !SecondTry &&
802         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
803       break;
804     }
805 
806     // Perform typo correction to determine if there is another name that is
807     // close to this name.
808     if (!SecondTry && CCC) {
809       SecondTry = true;
810       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
811                                                  Result.getLookupKind(), S,
812                                                  &SS, std::move(CCC),
813                                                  CTK_ErrorRecovery)) {
814         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
815         unsigned QualifiedDiag = diag::err_no_member_suggest;
816 
817         NamedDecl *FirstDecl = Corrected.getFoundDecl();
818         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
819         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
820             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
821           UnqualifiedDiag = diag::err_no_template_suggest;
822           QualifiedDiag = diag::err_no_member_template_suggest;
823         } else if (UnderlyingFirstDecl &&
824                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
825                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
826                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
827           UnqualifiedDiag = diag::err_unknown_typename_suggest;
828           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
829         }
830 
831         if (SS.isEmpty()) {
832           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
833         } else {// FIXME: is this even reachable? Test it.
834           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
835           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
836                                   Name->getName().equals(CorrectedStr);
837           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
838                                     << Name << computeDeclContext(SS, false)
839                                     << DroppedSpecifier << SS.getRange());
840         }
841 
842         // Update the name, so that the caller has the new name.
843         Name = Corrected.getCorrectionAsIdentifierInfo();
844 
845         // Typo correction corrected to a keyword.
846         if (Corrected.isKeyword())
847           return Name;
848 
849         // Also update the LookupResult...
850         // FIXME: This should probably go away at some point
851         Result.clear();
852         Result.setLookupName(Corrected.getCorrection());
853         if (FirstDecl)
854           Result.addDecl(FirstDecl);
855 
856         // If we found an Objective-C instance variable, let
857         // LookupInObjCMethod build the appropriate expression to
858         // reference the ivar.
859         // FIXME: This is a gross hack.
860         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
861           Result.clear();
862           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
863           return E;
864         }
865 
866         goto Corrected;
867       }
868     }
869 
870     // We failed to correct; just fall through and let the parser deal with it.
871     Result.suppressDiagnostics();
872     return NameClassification::Unknown();
873 
874   case LookupResult::NotFoundInCurrentInstantiation: {
875     // We performed name lookup into the current instantiation, and there were
876     // dependent bases, so we treat this result the same way as any other
877     // dependent nested-name-specifier.
878 
879     // C++ [temp.res]p2:
880     //   A name used in a template declaration or definition and that is
881     //   dependent on a template-parameter is assumed not to name a type
882     //   unless the applicable name lookup finds a type name or the name is
883     //   qualified by the keyword typename.
884     //
885     // FIXME: If the next token is '<', we might want to ask the parser to
886     // perform some heroics to see if we actually have a
887     // template-argument-list, which would indicate a missing 'template'
888     // keyword here.
889     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
890                                       NameInfo, IsAddressOfOperand,
891                                       /*TemplateArgs=*/nullptr);
892   }
893 
894   case LookupResult::Found:
895   case LookupResult::FoundOverloaded:
896   case LookupResult::FoundUnresolvedValue:
897     break;
898 
899   case LookupResult::Ambiguous:
900     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
901         hasAnyAcceptableTemplateNames(Result)) {
902       // C++ [temp.local]p3:
903       //   A lookup that finds an injected-class-name (10.2) can result in an
904       //   ambiguity in certain cases (for example, if it is found in more than
905       //   one base class). If all of the injected-class-names that are found
906       //   refer to specializations of the same class template, and if the name
907       //   is followed by a template-argument-list, the reference refers to the
908       //   class template itself and not a specialization thereof, and is not
909       //   ambiguous.
910       //
911       // This filtering can make an ambiguous result into an unambiguous one,
912       // so try again after filtering out template names.
913       FilterAcceptableTemplateNames(Result);
914       if (!Result.isAmbiguous()) {
915         IsFilteredTemplateName = true;
916         break;
917       }
918     }
919 
920     // Diagnose the ambiguity and return an error.
921     return NameClassification::Error();
922   }
923 
924   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
925       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
926     // C++ [temp.names]p3:
927     //   After name lookup (3.4) finds that a name is a template-name or that
928     //   an operator-function-id or a literal- operator-id refers to a set of
929     //   overloaded functions any member of which is a function template if
930     //   this is followed by a <, the < is always taken as the delimiter of a
931     //   template-argument-list and never as the less-than operator.
932     if (!IsFilteredTemplateName)
933       FilterAcceptableTemplateNames(Result);
934 
935     if (!Result.empty()) {
936       bool IsFunctionTemplate;
937       bool IsVarTemplate;
938       TemplateName Template;
939       if (Result.end() - Result.begin() > 1) {
940         IsFunctionTemplate = true;
941         Template = Context.getOverloadedTemplateName(Result.begin(),
942                                                      Result.end());
943       } else {
944         TemplateDecl *TD
945           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
946         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
947         IsVarTemplate = isa<VarTemplateDecl>(TD);
948 
949         if (SS.isSet() && !SS.isInvalid())
950           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
951                                                     /*TemplateKeyword=*/false,
952                                                       TD);
953         else
954           Template = TemplateName(TD);
955       }
956 
957       if (IsFunctionTemplate) {
958         // Function templates always go through overload resolution, at which
959         // point we'll perform the various checks (e.g., accessibility) we need
960         // to based on which function we selected.
961         Result.suppressDiagnostics();
962 
963         return NameClassification::FunctionTemplate(Template);
964       }
965 
966       return IsVarTemplate ? NameClassification::VarTemplate(Template)
967                            : NameClassification::TypeTemplate(Template);
968     }
969   }
970 
971   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
972   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
973     DiagnoseUseOfDecl(Type, NameLoc);
974     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
975     QualType T = Context.getTypeDeclType(Type);
976     if (SS.isNotEmpty())
977       return buildNestedType(*this, SS, T, NameLoc);
978     return ParsedType::make(T);
979   }
980 
981   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
982   if (!Class) {
983     // FIXME: It's unfortunate that we don't have a Type node for handling this.
984     if (ObjCCompatibleAliasDecl *Alias =
985             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
986       Class = Alias->getClassInterface();
987   }
988 
989   if (Class) {
990     DiagnoseUseOfDecl(Class, NameLoc);
991 
992     if (NextToken.is(tok::period)) {
993       // Interface. <something> is parsed as a property reference expression.
994       // Just return "unknown" as a fall-through for now.
995       Result.suppressDiagnostics();
996       return NameClassification::Unknown();
997     }
998 
999     QualType T = Context.getObjCInterfaceType(Class);
1000     return ParsedType::make(T);
1001   }
1002 
1003   // We can have a type template here if we're classifying a template argument.
1004   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
1005     return NameClassification::TypeTemplate(
1006         TemplateName(cast<TemplateDecl>(FirstDecl)));
1007 
1008   // Check for a tag type hidden by a non-type decl in a few cases where it
1009   // seems likely a type is wanted instead of the non-type that was found.
1010   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1011   if ((NextToken.is(tok::identifier) ||
1012        (NextIsOp &&
1013         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1014       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1015     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1016     DiagnoseUseOfDecl(Type, NameLoc);
1017     QualType T = Context.getTypeDeclType(Type);
1018     if (SS.isNotEmpty())
1019       return buildNestedType(*this, SS, T, NameLoc);
1020     return ParsedType::make(T);
1021   }
1022 
1023   if (FirstDecl->isCXXClassMember())
1024     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1025                                            nullptr, S);
1026 
1027   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1028   return BuildDeclarationNameExpr(SS, Result, ADL);
1029 }
1030 
1031 // Determines the context to return to after temporarily entering a
1032 // context.  This depends in an unnecessarily complicated way on the
1033 // exact ordering of callbacks from the parser.
1034 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1035 
1036   // Functions defined inline within classes aren't parsed until we've
1037   // finished parsing the top-level class, so the top-level class is
1038   // the context we'll need to return to.
1039   // A Lambda call operator whose parent is a class must not be treated
1040   // as an inline member function.  A Lambda can be used legally
1041   // either as an in-class member initializer or a default argument.  These
1042   // are parsed once the class has been marked complete and so the containing
1043   // context would be the nested class (when the lambda is defined in one);
1044   // If the class is not complete, then the lambda is being used in an
1045   // ill-formed fashion (such as to specify the width of a bit-field, or
1046   // in an array-bound) - in which case we still want to return the
1047   // lexically containing DC (which could be a nested class).
1048   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1049     DC = DC->getLexicalParent();
1050 
1051     // A function not defined within a class will always return to its
1052     // lexical context.
1053     if (!isa<CXXRecordDecl>(DC))
1054       return DC;
1055 
1056     // A C++ inline method/friend is parsed *after* the topmost class
1057     // it was declared in is fully parsed ("complete");  the topmost
1058     // class is the context we need to return to.
1059     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1060       DC = RD;
1061 
1062     // Return the declaration context of the topmost class the inline method is
1063     // declared in.
1064     return DC;
1065   }
1066 
1067   return DC->getLexicalParent();
1068 }
1069 
1070 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1071   assert(getContainingDC(DC) == CurContext &&
1072       "The next DeclContext should be lexically contained in the current one.");
1073   CurContext = DC;
1074   S->setEntity(DC);
1075 }
1076 
1077 void Sema::PopDeclContext() {
1078   assert(CurContext && "DeclContext imbalance!");
1079 
1080   CurContext = getContainingDC(CurContext);
1081   assert(CurContext && "Popped translation unit!");
1082 }
1083 
1084 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1085                                                                     Decl *D) {
1086   // Unlike PushDeclContext, the context to which we return is not necessarily
1087   // the containing DC of TD, because the new context will be some pre-existing
1088   // TagDecl definition instead of a fresh one.
1089   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1090   CurContext = cast<TagDecl>(D)->getDefinition();
1091   assert(CurContext && "skipping definition of undefined tag");
1092   // Start lookups from the parent of the current context; we don't want to look
1093   // into the pre-existing complete definition.
1094   S->setEntity(CurContext->getLookupParent());
1095   return Result;
1096 }
1097 
1098 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1099   CurContext = static_cast<decltype(CurContext)>(Context);
1100 }
1101 
1102 /// EnterDeclaratorContext - Used when we must lookup names in the context
1103 /// of a declarator's nested name specifier.
1104 ///
1105 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1106   // C++0x [basic.lookup.unqual]p13:
1107   //   A name used in the definition of a static data member of class
1108   //   X (after the qualified-id of the static member) is looked up as
1109   //   if the name was used in a member function of X.
1110   // C++0x [basic.lookup.unqual]p14:
1111   //   If a variable member of a namespace is defined outside of the
1112   //   scope of its namespace then any name used in the definition of
1113   //   the variable member (after the declarator-id) is looked up as
1114   //   if the definition of the variable member occurred in its
1115   //   namespace.
1116   // Both of these imply that we should push a scope whose context
1117   // is the semantic context of the declaration.  We can't use
1118   // PushDeclContext here because that context is not necessarily
1119   // lexically contained in the current context.  Fortunately,
1120   // the containing scope should have the appropriate information.
1121 
1122   assert(!S->getEntity() && "scope already has entity");
1123 
1124 #ifndef NDEBUG
1125   Scope *Ancestor = S->getParent();
1126   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1127   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1128 #endif
1129 
1130   CurContext = DC;
1131   S->setEntity(DC);
1132 }
1133 
1134 void Sema::ExitDeclaratorContext(Scope *S) {
1135   assert(S->getEntity() == CurContext && "Context imbalance!");
1136 
1137   // Switch back to the lexical context.  The safety of this is
1138   // enforced by an assert in EnterDeclaratorContext.
1139   Scope *Ancestor = S->getParent();
1140   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1141   CurContext = Ancestor->getEntity();
1142 
1143   // We don't need to do anything with the scope, which is going to
1144   // disappear.
1145 }
1146 
1147 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1148   // We assume that the caller has already called
1149   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1150   FunctionDecl *FD = D->getAsFunction();
1151   if (!FD)
1152     return;
1153 
1154   // Same implementation as PushDeclContext, but enters the context
1155   // from the lexical parent, rather than the top-level class.
1156   assert(CurContext == FD->getLexicalParent() &&
1157     "The next DeclContext should be lexically contained in the current one.");
1158   CurContext = FD;
1159   S->setEntity(CurContext);
1160 
1161   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1162     ParmVarDecl *Param = FD->getParamDecl(P);
1163     // If the parameter has an identifier, then add it to the scope
1164     if (Param->getIdentifier()) {
1165       S->AddDecl(Param);
1166       IdResolver.AddDecl(Param);
1167     }
1168   }
1169 }
1170 
1171 void Sema::ActOnExitFunctionContext() {
1172   // Same implementation as PopDeclContext, but returns to the lexical parent,
1173   // rather than the top-level class.
1174   assert(CurContext && "DeclContext imbalance!");
1175   CurContext = CurContext->getLexicalParent();
1176   assert(CurContext && "Popped translation unit!");
1177 }
1178 
1179 /// \brief Determine whether we allow overloading of the function
1180 /// PrevDecl with another declaration.
1181 ///
1182 /// This routine determines whether overloading is possible, not
1183 /// whether some new function is actually an overload. It will return
1184 /// true in C++ (where we can always provide overloads) or, as an
1185 /// extension, in C when the previous function is already an
1186 /// overloaded function declaration or has the "overloadable"
1187 /// attribute.
1188 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1189                                        ASTContext &Context) {
1190   if (Context.getLangOpts().CPlusPlus)
1191     return true;
1192 
1193   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1194     return true;
1195 
1196   return (Previous.getResultKind() == LookupResult::Found
1197           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1198 }
1199 
1200 /// Add this decl to the scope shadowed decl chains.
1201 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1202   // Move up the scope chain until we find the nearest enclosing
1203   // non-transparent context. The declaration will be introduced into this
1204   // scope.
1205   while (S->getEntity() && S->getEntity()->isTransparentContext())
1206     S = S->getParent();
1207 
1208   // Add scoped declarations into their context, so that they can be
1209   // found later. Declarations without a context won't be inserted
1210   // into any context.
1211   if (AddToContext)
1212     CurContext->addDecl(D);
1213 
1214   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1215   // are function-local declarations.
1216   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1217       !D->getDeclContext()->getRedeclContext()->Equals(
1218         D->getLexicalDeclContext()->getRedeclContext()) &&
1219       !D->getLexicalDeclContext()->isFunctionOrMethod())
1220     return;
1221 
1222   // Template instantiations should also not be pushed into scope.
1223   if (isa<FunctionDecl>(D) &&
1224       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1225     return;
1226 
1227   // If this replaces anything in the current scope,
1228   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1229                                IEnd = IdResolver.end();
1230   for (; I != IEnd; ++I) {
1231     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1232       S->RemoveDecl(*I);
1233       IdResolver.RemoveDecl(*I);
1234 
1235       // Should only need to replace one decl.
1236       break;
1237     }
1238   }
1239 
1240   S->AddDecl(D);
1241 
1242   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1243     // Implicitly-generated labels may end up getting generated in an order that
1244     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1245     // the label at the appropriate place in the identifier chain.
1246     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1247       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1248       if (IDC == CurContext) {
1249         if (!S->isDeclScope(*I))
1250           continue;
1251       } else if (IDC->Encloses(CurContext))
1252         break;
1253     }
1254 
1255     IdResolver.InsertDeclAfter(I, D);
1256   } else {
1257     IdResolver.AddDecl(D);
1258   }
1259 }
1260 
1261 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1262   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1263     TUScope->AddDecl(D);
1264 }
1265 
1266 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1267                          bool AllowInlineNamespace) {
1268   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1269 }
1270 
1271 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1272   DeclContext *TargetDC = DC->getPrimaryContext();
1273   do {
1274     if (DeclContext *ScopeDC = S->getEntity())
1275       if (ScopeDC->getPrimaryContext() == TargetDC)
1276         return S;
1277   } while ((S = S->getParent()));
1278 
1279   return nullptr;
1280 }
1281 
1282 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1283                                             DeclContext*,
1284                                             ASTContext&);
1285 
1286 /// Filters out lookup results that don't fall within the given scope
1287 /// as determined by isDeclInScope.
1288 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1289                                 bool ConsiderLinkage,
1290                                 bool AllowInlineNamespace) {
1291   LookupResult::Filter F = R.makeFilter();
1292   while (F.hasNext()) {
1293     NamedDecl *D = F.next();
1294 
1295     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1296       continue;
1297 
1298     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1299       continue;
1300 
1301     F.erase();
1302   }
1303 
1304   F.done();
1305 }
1306 
1307 static bool isUsingDecl(NamedDecl *D) {
1308   return isa<UsingShadowDecl>(D) ||
1309          isa<UnresolvedUsingTypenameDecl>(D) ||
1310          isa<UnresolvedUsingValueDecl>(D);
1311 }
1312 
1313 /// Removes using shadow declarations from the lookup results.
1314 static void RemoveUsingDecls(LookupResult &R) {
1315   LookupResult::Filter F = R.makeFilter();
1316   while (F.hasNext())
1317     if (isUsingDecl(F.next()))
1318       F.erase();
1319 
1320   F.done();
1321 }
1322 
1323 /// \brief Check for this common pattern:
1324 /// @code
1325 /// class S {
1326 ///   S(const S&); // DO NOT IMPLEMENT
1327 ///   void operator=(const S&); // DO NOT IMPLEMENT
1328 /// };
1329 /// @endcode
1330 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1331   // FIXME: Should check for private access too but access is set after we get
1332   // the decl here.
1333   if (D->doesThisDeclarationHaveABody())
1334     return false;
1335 
1336   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1337     return CD->isCopyConstructor();
1338   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1339     return Method->isCopyAssignmentOperator();
1340   return false;
1341 }
1342 
1343 // We need this to handle
1344 //
1345 // typedef struct {
1346 //   void *foo() { return 0; }
1347 // } A;
1348 //
1349 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1350 // for example. If 'A', foo will have external linkage. If we have '*A',
1351 // foo will have no linkage. Since we can't know until we get to the end
1352 // of the typedef, this function finds out if D might have non-external linkage.
1353 // Callers should verify at the end of the TU if it D has external linkage or
1354 // not.
1355 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1356   const DeclContext *DC = D->getDeclContext();
1357   while (!DC->isTranslationUnit()) {
1358     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1359       if (!RD->hasNameForLinkage())
1360         return true;
1361     }
1362     DC = DC->getParent();
1363   }
1364 
1365   return !D->isExternallyVisible();
1366 }
1367 
1368 // FIXME: This needs to be refactored; some other isInMainFile users want
1369 // these semantics.
1370 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1371   if (S.TUKind != TU_Complete)
1372     return false;
1373   return S.SourceMgr.isInMainFile(Loc);
1374 }
1375 
1376 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1377   assert(D);
1378 
1379   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1380     return false;
1381 
1382   // Ignore all entities declared within templates, and out-of-line definitions
1383   // of members of class templates.
1384   if (D->getDeclContext()->isDependentContext() ||
1385       D->getLexicalDeclContext()->isDependentContext())
1386     return false;
1387 
1388   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1389     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1390       return false;
1391 
1392     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1393       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1394         return false;
1395     } else {
1396       // 'static inline' functions are defined in headers; don't warn.
1397       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1398         return false;
1399     }
1400 
1401     if (FD->doesThisDeclarationHaveABody() &&
1402         Context.DeclMustBeEmitted(FD))
1403       return false;
1404   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1405     // Constants and utility variables are defined in headers with internal
1406     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1407     // like "inline".)
1408     if (!isMainFileLoc(*this, VD->getLocation()))
1409       return false;
1410 
1411     if (Context.DeclMustBeEmitted(VD))
1412       return false;
1413 
1414     if (VD->isStaticDataMember() &&
1415         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1416       return false;
1417   } else {
1418     return false;
1419   }
1420 
1421   // Only warn for unused decls internal to the translation unit.
1422   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1423   // for inline functions defined in the main source file, for instance.
1424   return mightHaveNonExternalLinkage(D);
1425 }
1426 
1427 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1428   if (!D)
1429     return;
1430 
1431   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1432     const FunctionDecl *First = FD->getFirstDecl();
1433     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1434       return; // First should already be in the vector.
1435   }
1436 
1437   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1438     const VarDecl *First = VD->getFirstDecl();
1439     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1440       return; // First should already be in the vector.
1441   }
1442 
1443   if (ShouldWarnIfUnusedFileScopedDecl(D))
1444     UnusedFileScopedDecls.push_back(D);
1445 }
1446 
1447 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1448   if (D->isInvalidDecl())
1449     return false;
1450 
1451   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1452       D->hasAttr<ObjCPreciseLifetimeAttr>())
1453     return false;
1454 
1455   if (isa<LabelDecl>(D))
1456     return true;
1457 
1458   // Except for labels, we only care about unused decls that are local to
1459   // functions.
1460   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1461   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1462     // For dependent types, the diagnostic is deferred.
1463     WithinFunction =
1464         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1465   if (!WithinFunction)
1466     return false;
1467 
1468   if (isa<TypedefNameDecl>(D))
1469     return true;
1470 
1471   // White-list anything that isn't a local variable.
1472   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1473     return false;
1474 
1475   // Types of valid local variables should be complete, so this should succeed.
1476   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1477 
1478     // White-list anything with an __attribute__((unused)) type.
1479     QualType Ty = VD->getType();
1480 
1481     // Only look at the outermost level of typedef.
1482     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1483       if (TT->getDecl()->hasAttr<UnusedAttr>())
1484         return false;
1485     }
1486 
1487     // If we failed to complete the type for some reason, or if the type is
1488     // dependent, don't diagnose the variable.
1489     if (Ty->isIncompleteType() || Ty->isDependentType())
1490       return false;
1491 
1492     if (const TagType *TT = Ty->getAs<TagType>()) {
1493       const TagDecl *Tag = TT->getDecl();
1494       if (Tag->hasAttr<UnusedAttr>())
1495         return false;
1496 
1497       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1498         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1499           return false;
1500 
1501         if (const Expr *Init = VD->getInit()) {
1502           if (const ExprWithCleanups *Cleanups =
1503                   dyn_cast<ExprWithCleanups>(Init))
1504             Init = Cleanups->getSubExpr();
1505           const CXXConstructExpr *Construct =
1506             dyn_cast<CXXConstructExpr>(Init);
1507           if (Construct && !Construct->isElidable()) {
1508             CXXConstructorDecl *CD = Construct->getConstructor();
1509             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1510               return false;
1511           }
1512         }
1513       }
1514     }
1515 
1516     // TODO: __attribute__((unused)) templates?
1517   }
1518 
1519   return true;
1520 }
1521 
1522 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1523                                      FixItHint &Hint) {
1524   if (isa<LabelDecl>(D)) {
1525     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1526                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1527     if (AfterColon.isInvalid())
1528       return;
1529     Hint = FixItHint::CreateRemoval(CharSourceRange::
1530                                     getCharRange(D->getLocStart(), AfterColon));
1531   }
1532 }
1533 
1534 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1535   if (D->getTypeForDecl()->isDependentType())
1536     return;
1537 
1538   for (auto *TmpD : D->decls()) {
1539     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1540       DiagnoseUnusedDecl(T);
1541     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1542       DiagnoseUnusedNestedTypedefs(R);
1543   }
1544 }
1545 
1546 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1547 /// unless they are marked attr(unused).
1548 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1549   if (!ShouldDiagnoseUnusedDecl(D))
1550     return;
1551 
1552   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1553     // typedefs can be referenced later on, so the diagnostics are emitted
1554     // at end-of-translation-unit.
1555     UnusedLocalTypedefNameCandidates.insert(TD);
1556     return;
1557   }
1558 
1559   FixItHint Hint;
1560   GenerateFixForUnusedDecl(D, Context, Hint);
1561 
1562   unsigned DiagID;
1563   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1564     DiagID = diag::warn_unused_exception_param;
1565   else if (isa<LabelDecl>(D))
1566     DiagID = diag::warn_unused_label;
1567   else
1568     DiagID = diag::warn_unused_variable;
1569 
1570   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1571 }
1572 
1573 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1574   // Verify that we have no forward references left.  If so, there was a goto
1575   // or address of a label taken, but no definition of it.  Label fwd
1576   // definitions are indicated with a null substmt which is also not a resolved
1577   // MS inline assembly label name.
1578   bool Diagnose = false;
1579   if (L->isMSAsmLabel())
1580     Diagnose = !L->isResolvedMSAsmLabel();
1581   else
1582     Diagnose = L->getStmt() == nullptr;
1583   if (Diagnose)
1584     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1585 }
1586 
1587 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1588   S->mergeNRVOIntoParent();
1589 
1590   if (S->decl_empty()) return;
1591   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1592          "Scope shouldn't contain decls!");
1593 
1594   for (auto *TmpD : S->decls()) {
1595     assert(TmpD && "This decl didn't get pushed??");
1596 
1597     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1598     NamedDecl *D = cast<NamedDecl>(TmpD);
1599 
1600     if (!D->getDeclName()) continue;
1601 
1602     // Diagnose unused variables in this scope.
1603     if (!S->hasUnrecoverableErrorOccurred()) {
1604       DiagnoseUnusedDecl(D);
1605       if (const auto *RD = dyn_cast<RecordDecl>(D))
1606         DiagnoseUnusedNestedTypedefs(RD);
1607     }
1608 
1609     // If this was a forward reference to a label, verify it was defined.
1610     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1611       CheckPoppedLabel(LD, *this);
1612 
1613     // Remove this name from our lexical scope.
1614     IdResolver.RemoveDecl(D);
1615   }
1616 }
1617 
1618 /// \brief Look for an Objective-C class in the translation unit.
1619 ///
1620 /// \param Id The name of the Objective-C class we're looking for. If
1621 /// typo-correction fixes this name, the Id will be updated
1622 /// to the fixed name.
1623 ///
1624 /// \param IdLoc The location of the name in the translation unit.
1625 ///
1626 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1627 /// if there is no class with the given name.
1628 ///
1629 /// \returns The declaration of the named Objective-C class, or NULL if the
1630 /// class could not be found.
1631 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1632                                               SourceLocation IdLoc,
1633                                               bool DoTypoCorrection) {
1634   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1635   // creation from this context.
1636   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1637 
1638   if (!IDecl && DoTypoCorrection) {
1639     // Perform typo correction at the given location, but only if we
1640     // find an Objective-C class name.
1641     if (TypoCorrection C = CorrectTypo(
1642             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1643             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1644             CTK_ErrorRecovery)) {
1645       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1646       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1647       Id = IDecl->getIdentifier();
1648     }
1649   }
1650   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1651   // This routine must always return a class definition, if any.
1652   if (Def && Def->getDefinition())
1653       Def = Def->getDefinition();
1654   return Def;
1655 }
1656 
1657 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1658 /// from S, where a non-field would be declared. This routine copes
1659 /// with the difference between C and C++ scoping rules in structs and
1660 /// unions. For example, the following code is well-formed in C but
1661 /// ill-formed in C++:
1662 /// @code
1663 /// struct S6 {
1664 ///   enum { BAR } e;
1665 /// };
1666 ///
1667 /// void test_S6() {
1668 ///   struct S6 a;
1669 ///   a.e = BAR;
1670 /// }
1671 /// @endcode
1672 /// For the declaration of BAR, this routine will return a different
1673 /// scope. The scope S will be the scope of the unnamed enumeration
1674 /// within S6. In C++, this routine will return the scope associated
1675 /// with S6, because the enumeration's scope is a transparent
1676 /// context but structures can contain non-field names. In C, this
1677 /// routine will return the translation unit scope, since the
1678 /// enumeration's scope is a transparent context and structures cannot
1679 /// contain non-field names.
1680 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1681   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1682          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1683          (S->isClassScope() && !getLangOpts().CPlusPlus))
1684     S = S->getParent();
1685   return S;
1686 }
1687 
1688 /// \brief Looks up the declaration of "struct objc_super" and
1689 /// saves it for later use in building builtin declaration of
1690 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1691 /// pre-existing declaration exists no action takes place.
1692 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1693                                         IdentifierInfo *II) {
1694   if (!II->isStr("objc_msgSendSuper"))
1695     return;
1696   ASTContext &Context = ThisSema.Context;
1697 
1698   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1699                       SourceLocation(), Sema::LookupTagName);
1700   ThisSema.LookupName(Result, S);
1701   if (Result.getResultKind() == LookupResult::Found)
1702     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1703       Context.setObjCSuperType(Context.getTagDeclType(TD));
1704 }
1705 
1706 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1707   switch (Error) {
1708   case ASTContext::GE_None:
1709     return "";
1710   case ASTContext::GE_Missing_stdio:
1711     return "stdio.h";
1712   case ASTContext::GE_Missing_setjmp:
1713     return "setjmp.h";
1714   case ASTContext::GE_Missing_ucontext:
1715     return "ucontext.h";
1716   }
1717   llvm_unreachable("unhandled error kind");
1718 }
1719 
1720 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1721 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1722 /// if we're creating this built-in in anticipation of redeclaring the
1723 /// built-in.
1724 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1725                                      Scope *S, bool ForRedeclaration,
1726                                      SourceLocation Loc) {
1727   LookupPredefedObjCSuperType(*this, S, II);
1728 
1729   ASTContext::GetBuiltinTypeError Error;
1730   QualType R = Context.GetBuiltinType(ID, Error);
1731   if (Error) {
1732     if (ForRedeclaration)
1733       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1734           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1735     return nullptr;
1736   }
1737 
1738   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
1739     Diag(Loc, diag::ext_implicit_lib_function_decl)
1740         << Context.BuiltinInfo.getName(ID) << R;
1741     if (Context.BuiltinInfo.getHeaderName(ID) &&
1742         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1743       Diag(Loc, diag::note_include_header_or_declare)
1744           << Context.BuiltinInfo.getHeaderName(ID)
1745           << Context.BuiltinInfo.getName(ID);
1746   }
1747 
1748   if (R.isNull())
1749     return nullptr;
1750 
1751   DeclContext *Parent = Context.getTranslationUnitDecl();
1752   if (getLangOpts().CPlusPlus) {
1753     LinkageSpecDecl *CLinkageDecl =
1754         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1755                                 LinkageSpecDecl::lang_c, false);
1756     CLinkageDecl->setImplicit();
1757     Parent->addDecl(CLinkageDecl);
1758     Parent = CLinkageDecl;
1759   }
1760 
1761   FunctionDecl *New = FunctionDecl::Create(Context,
1762                                            Parent,
1763                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1764                                            SC_Extern,
1765                                            false,
1766                                            R->isFunctionProtoType());
1767   New->setImplicit();
1768 
1769   // Create Decl objects for each parameter, adding them to the
1770   // FunctionDecl.
1771   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1772     SmallVector<ParmVarDecl*, 16> Params;
1773     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1774       ParmVarDecl *parm =
1775           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1776                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1777                               SC_None, nullptr);
1778       parm->setScopeInfo(0, i);
1779       Params.push_back(parm);
1780     }
1781     New->setParams(Params);
1782   }
1783 
1784   AddKnownFunctionAttributes(New);
1785   RegisterLocallyScopedExternCDecl(New, S);
1786 
1787   // TUScope is the translation-unit scope to insert this function into.
1788   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1789   // relate Scopes to DeclContexts, and probably eliminate CurContext
1790   // entirely, but we're not there yet.
1791   DeclContext *SavedContext = CurContext;
1792   CurContext = Parent;
1793   PushOnScopeChains(New, TUScope);
1794   CurContext = SavedContext;
1795   return New;
1796 }
1797 
1798 /// Typedef declarations don't have linkage, but they still denote the same
1799 /// entity if their types are the same.
1800 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1801 /// isSameEntity.
1802 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1803                                                      TypedefNameDecl *Decl,
1804                                                      LookupResult &Previous) {
1805   // This is only interesting when modules are enabled.
1806   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1807     return;
1808 
1809   // Empty sets are uninteresting.
1810   if (Previous.empty())
1811     return;
1812 
1813   LookupResult::Filter Filter = Previous.makeFilter();
1814   while (Filter.hasNext()) {
1815     NamedDecl *Old = Filter.next();
1816 
1817     // Non-hidden declarations are never ignored.
1818     if (S.isVisible(Old))
1819       continue;
1820 
1821     // Declarations of the same entity are not ignored, even if they have
1822     // different linkages.
1823     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1824       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1825                                 Decl->getUnderlyingType()))
1826         continue;
1827 
1828       // If both declarations give a tag declaration a typedef name for linkage
1829       // purposes, then they declare the same entity.
1830       if (S.getLangOpts().CPlusPlus &&
1831           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1832           Decl->getAnonDeclWithTypedefName())
1833         continue;
1834     }
1835 
1836     Filter.erase();
1837   }
1838 
1839   Filter.done();
1840 }
1841 
1842 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1843   QualType OldType;
1844   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1845     OldType = OldTypedef->getUnderlyingType();
1846   else
1847     OldType = Context.getTypeDeclType(Old);
1848   QualType NewType = New->getUnderlyingType();
1849 
1850   if (NewType->isVariablyModifiedType()) {
1851     // Must not redefine a typedef with a variably-modified type.
1852     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1853     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1854       << Kind << NewType;
1855     if (Old->getLocation().isValid())
1856       Diag(Old->getLocation(), diag::note_previous_definition);
1857     New->setInvalidDecl();
1858     return true;
1859   }
1860 
1861   if (OldType != NewType &&
1862       !OldType->isDependentType() &&
1863       !NewType->isDependentType() &&
1864       !Context.hasSameType(OldType, NewType)) {
1865     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1866     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1867       << Kind << NewType << OldType;
1868     if (Old->getLocation().isValid())
1869       Diag(Old->getLocation(), diag::note_previous_definition);
1870     New->setInvalidDecl();
1871     return true;
1872   }
1873   return false;
1874 }
1875 
1876 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1877 /// same name and scope as a previous declaration 'Old'.  Figure out
1878 /// how to resolve this situation, merging decls or emitting
1879 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1880 ///
1881 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
1882                                 LookupResult &OldDecls) {
1883   // If the new decl is known invalid already, don't bother doing any
1884   // merging checks.
1885   if (New->isInvalidDecl()) return;
1886 
1887   // Allow multiple definitions for ObjC built-in typedefs.
1888   // FIXME: Verify the underlying types are equivalent!
1889   if (getLangOpts().ObjC1) {
1890     const IdentifierInfo *TypeID = New->getIdentifier();
1891     switch (TypeID->getLength()) {
1892     default: break;
1893     case 2:
1894       {
1895         if (!TypeID->isStr("id"))
1896           break;
1897         QualType T = New->getUnderlyingType();
1898         if (!T->isPointerType())
1899           break;
1900         if (!T->isVoidPointerType()) {
1901           QualType PT = T->getAs<PointerType>()->getPointeeType();
1902           if (!PT->isStructureType())
1903             break;
1904         }
1905         Context.setObjCIdRedefinitionType(T);
1906         // Install the built-in type for 'id', ignoring the current definition.
1907         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1908         return;
1909       }
1910     case 5:
1911       if (!TypeID->isStr("Class"))
1912         break;
1913       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1914       // Install the built-in type for 'Class', ignoring the current definition.
1915       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1916       return;
1917     case 3:
1918       if (!TypeID->isStr("SEL"))
1919         break;
1920       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1921       // Install the built-in type for 'SEL', ignoring the current definition.
1922       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1923       return;
1924     }
1925     // Fall through - the typedef name was not a builtin type.
1926   }
1927 
1928   // Verify the old decl was also a type.
1929   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1930   if (!Old) {
1931     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1932       << New->getDeclName();
1933 
1934     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1935     if (OldD->getLocation().isValid())
1936       Diag(OldD->getLocation(), diag::note_previous_definition);
1937 
1938     return New->setInvalidDecl();
1939   }
1940 
1941   // If the old declaration is invalid, just give up here.
1942   if (Old->isInvalidDecl())
1943     return New->setInvalidDecl();
1944 
1945   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1946     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
1947     auto *NewTag = New->getAnonDeclWithTypedefName();
1948     NamedDecl *Hidden = nullptr;
1949     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
1950         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
1951         !hasVisibleDefinition(OldTag, &Hidden)) {
1952       // There is a definition of this tag, but it is not visible. Use it
1953       // instead of our tag.
1954       New->setTypeForDecl(OldTD->getTypeForDecl());
1955       if (OldTD->isModed())
1956         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
1957                                     OldTD->getUnderlyingType());
1958       else
1959         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
1960 
1961       // Make the old tag definition visible.
1962       makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
1963 
1964       // If this was an unscoped enumeration, yank all of its enumerators
1965       // out of the scope.
1966       if (isa<EnumDecl>(NewTag)) {
1967         Scope *EnumScope = getNonFieldDeclScope(S);
1968         for (auto *D : NewTag->decls()) {
1969           auto *ED = cast<EnumConstantDecl>(D);
1970           assert(EnumScope->isDeclScope(ED));
1971           EnumScope->RemoveDecl(ED);
1972           IdResolver.RemoveDecl(ED);
1973           ED->getLexicalDeclContext()->removeDecl(ED);
1974         }
1975       }
1976     }
1977   }
1978 
1979   // If the typedef types are not identical, reject them in all languages and
1980   // with any extensions enabled.
1981   if (isIncompatibleTypedef(Old, New))
1982     return;
1983 
1984   // The types match.  Link up the redeclaration chain and merge attributes if
1985   // the old declaration was a typedef.
1986   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
1987     New->setPreviousDecl(Typedef);
1988     mergeDeclAttributes(New, Old);
1989   }
1990 
1991   if (getLangOpts().MicrosoftExt)
1992     return;
1993 
1994   if (getLangOpts().CPlusPlus) {
1995     // C++ [dcl.typedef]p2:
1996     //   In a given non-class scope, a typedef specifier can be used to
1997     //   redefine the name of any type declared in that scope to refer
1998     //   to the type to which it already refers.
1999     if (!isa<CXXRecordDecl>(CurContext))
2000       return;
2001 
2002     // C++0x [dcl.typedef]p4:
2003     //   In a given class scope, a typedef specifier can be used to redefine
2004     //   any class-name declared in that scope that is not also a typedef-name
2005     //   to refer to the type to which it already refers.
2006     //
2007     // This wording came in via DR424, which was a correction to the
2008     // wording in DR56, which accidentally banned code like:
2009     //
2010     //   struct S {
2011     //     typedef struct A { } A;
2012     //   };
2013     //
2014     // in the C++03 standard. We implement the C++0x semantics, which
2015     // allow the above but disallow
2016     //
2017     //   struct S {
2018     //     typedef int I;
2019     //     typedef int I;
2020     //   };
2021     //
2022     // since that was the intent of DR56.
2023     if (!isa<TypedefNameDecl>(Old))
2024       return;
2025 
2026     Diag(New->getLocation(), diag::err_redefinition)
2027       << New->getDeclName();
2028     Diag(Old->getLocation(), diag::note_previous_definition);
2029     return New->setInvalidDecl();
2030   }
2031 
2032   // Modules always permit redefinition of typedefs, as does C11.
2033   if (getLangOpts().Modules || getLangOpts().C11)
2034     return;
2035 
2036   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2037   // is normally mapped to an error, but can be controlled with
2038   // -Wtypedef-redefinition.  If either the original or the redefinition is
2039   // in a system header, don't emit this for compatibility with GCC.
2040   if (getDiagnostics().getSuppressSystemWarnings() &&
2041       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2042        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2043     return;
2044 
2045   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2046     << New->getDeclName();
2047   Diag(Old->getLocation(), diag::note_previous_definition);
2048 }
2049 
2050 /// DeclhasAttr - returns true if decl Declaration already has the target
2051 /// attribute.
2052 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2053   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2054   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2055   for (const auto *i : D->attrs())
2056     if (i->getKind() == A->getKind()) {
2057       if (Ann) {
2058         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2059           return true;
2060         continue;
2061       }
2062       // FIXME: Don't hardcode this check
2063       if (OA && isa<OwnershipAttr>(i))
2064         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2065       return true;
2066     }
2067 
2068   return false;
2069 }
2070 
2071 static bool isAttributeTargetADefinition(Decl *D) {
2072   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2073     return VD->isThisDeclarationADefinition();
2074   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2075     return TD->isCompleteDefinition() || TD->isBeingDefined();
2076   return true;
2077 }
2078 
2079 /// Merge alignment attributes from \p Old to \p New, taking into account the
2080 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2081 ///
2082 /// \return \c true if any attributes were added to \p New.
2083 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2084   // Look for alignas attributes on Old, and pick out whichever attribute
2085   // specifies the strictest alignment requirement.
2086   AlignedAttr *OldAlignasAttr = nullptr;
2087   AlignedAttr *OldStrictestAlignAttr = nullptr;
2088   unsigned OldAlign = 0;
2089   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2090     // FIXME: We have no way of representing inherited dependent alignments
2091     // in a case like:
2092     //   template<int A, int B> struct alignas(A) X;
2093     //   template<int A, int B> struct alignas(B) X {};
2094     // For now, we just ignore any alignas attributes which are not on the
2095     // definition in such a case.
2096     if (I->isAlignmentDependent())
2097       return false;
2098 
2099     if (I->isAlignas())
2100       OldAlignasAttr = I;
2101 
2102     unsigned Align = I->getAlignment(S.Context);
2103     if (Align > OldAlign) {
2104       OldAlign = Align;
2105       OldStrictestAlignAttr = I;
2106     }
2107   }
2108 
2109   // Look for alignas attributes on New.
2110   AlignedAttr *NewAlignasAttr = nullptr;
2111   unsigned NewAlign = 0;
2112   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2113     if (I->isAlignmentDependent())
2114       return false;
2115 
2116     if (I->isAlignas())
2117       NewAlignasAttr = I;
2118 
2119     unsigned Align = I->getAlignment(S.Context);
2120     if (Align > NewAlign)
2121       NewAlign = Align;
2122   }
2123 
2124   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2125     // Both declarations have 'alignas' attributes. We require them to match.
2126     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2127     // fall short. (If two declarations both have alignas, they must both match
2128     // every definition, and so must match each other if there is a definition.)
2129 
2130     // If either declaration only contains 'alignas(0)' specifiers, then it
2131     // specifies the natural alignment for the type.
2132     if (OldAlign == 0 || NewAlign == 0) {
2133       QualType Ty;
2134       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2135         Ty = VD->getType();
2136       else
2137         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2138 
2139       if (OldAlign == 0)
2140         OldAlign = S.Context.getTypeAlign(Ty);
2141       if (NewAlign == 0)
2142         NewAlign = S.Context.getTypeAlign(Ty);
2143     }
2144 
2145     if (OldAlign != NewAlign) {
2146       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2147         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2148         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2149       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2150     }
2151   }
2152 
2153   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2154     // C++11 [dcl.align]p6:
2155     //   if any declaration of an entity has an alignment-specifier,
2156     //   every defining declaration of that entity shall specify an
2157     //   equivalent alignment.
2158     // C11 6.7.5/7:
2159     //   If the definition of an object does not have an alignment
2160     //   specifier, any other declaration of that object shall also
2161     //   have no alignment specifier.
2162     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2163       << OldAlignasAttr;
2164     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2165       << OldAlignasAttr;
2166   }
2167 
2168   bool AnyAdded = false;
2169 
2170   // Ensure we have an attribute representing the strictest alignment.
2171   if (OldAlign > NewAlign) {
2172     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2173     Clone->setInherited(true);
2174     New->addAttr(Clone);
2175     AnyAdded = true;
2176   }
2177 
2178   // Ensure we have an alignas attribute if the old declaration had one.
2179   if (OldAlignasAttr && !NewAlignasAttr &&
2180       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2181     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2182     Clone->setInherited(true);
2183     New->addAttr(Clone);
2184     AnyAdded = true;
2185   }
2186 
2187   return AnyAdded;
2188 }
2189 
2190 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2191                                const InheritableAttr *Attr,
2192                                Sema::AvailabilityMergeKind AMK) {
2193   InheritableAttr *NewAttr = nullptr;
2194   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2195   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2196     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2197                                       AA->getIntroduced(), AA->getDeprecated(),
2198                                       AA->getObsoleted(), AA->getUnavailable(),
2199                                       AA->getMessage(), AA->getStrict(),
2200                                       AA->getReplacement(), AMK,
2201                                       AttrSpellingListIndex);
2202   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2203     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2204                                     AttrSpellingListIndex);
2205   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2206     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2207                                         AttrSpellingListIndex);
2208   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2209     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2210                                    AttrSpellingListIndex);
2211   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2212     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2213                                    AttrSpellingListIndex);
2214   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2215     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2216                                 FA->getFormatIdx(), FA->getFirstArg(),
2217                                 AttrSpellingListIndex);
2218   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2219     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2220                                  AttrSpellingListIndex);
2221   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2222     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2223                                        AttrSpellingListIndex,
2224                                        IA->getSemanticSpelling());
2225   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2226     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2227                                       &S.Context.Idents.get(AA->getSpelling()),
2228                                       AttrSpellingListIndex);
2229   else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2230     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2231   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2232     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2233   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2234     NewAttr = S.mergeInternalLinkageAttr(
2235         D, InternalLinkageA->getRange(),
2236         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2237         AttrSpellingListIndex);
2238   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2239     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2240                                 &S.Context.Idents.get(CommonA->getSpelling()),
2241                                 AttrSpellingListIndex);
2242   else if (isa<AlignedAttr>(Attr))
2243     // AlignedAttrs are handled separately, because we need to handle all
2244     // such attributes on a declaration at the same time.
2245     NewAttr = nullptr;
2246   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2247            (AMK == Sema::AMK_Override ||
2248             AMK == Sema::AMK_ProtocolImplementation))
2249     NewAttr = nullptr;
2250   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2251     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2252 
2253   if (NewAttr) {
2254     NewAttr->setInherited(true);
2255     D->addAttr(NewAttr);
2256     if (isa<MSInheritanceAttr>(NewAttr))
2257       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2258     return true;
2259   }
2260 
2261   return false;
2262 }
2263 
2264 static const Decl *getDefinition(const Decl *D) {
2265   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2266     return TD->getDefinition();
2267   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2268     const VarDecl *Def = VD->getDefinition();
2269     if (Def)
2270       return Def;
2271     return VD->getActingDefinition();
2272   }
2273   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2274     const FunctionDecl* Def;
2275     if (FD->isDefined(Def))
2276       return Def;
2277   }
2278   return nullptr;
2279 }
2280 
2281 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2282   for (const auto *Attribute : D->attrs())
2283     if (Attribute->getKind() == Kind)
2284       return true;
2285   return false;
2286 }
2287 
2288 /// checkNewAttributesAfterDef - If we already have a definition, check that
2289 /// there are no new attributes in this declaration.
2290 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2291   if (!New->hasAttrs())
2292     return;
2293 
2294   const Decl *Def = getDefinition(Old);
2295   if (!Def || Def == New)
2296     return;
2297 
2298   AttrVec &NewAttributes = New->getAttrs();
2299   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2300     const Attr *NewAttribute = NewAttributes[I];
2301 
2302     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2303       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2304         Sema::SkipBodyInfo SkipBody;
2305         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2306 
2307         // If we're skipping this definition, drop the "alias" attribute.
2308         if (SkipBody.ShouldSkip) {
2309           NewAttributes.erase(NewAttributes.begin() + I);
2310           --E;
2311           continue;
2312         }
2313       } else {
2314         VarDecl *VD = cast<VarDecl>(New);
2315         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2316                                 VarDecl::TentativeDefinition
2317                             ? diag::err_alias_after_tentative
2318                             : diag::err_redefinition;
2319         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2320         S.Diag(Def->getLocation(), diag::note_previous_definition);
2321         VD->setInvalidDecl();
2322       }
2323       ++I;
2324       continue;
2325     }
2326 
2327     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2328       // Tentative definitions are only interesting for the alias check above.
2329       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2330         ++I;
2331         continue;
2332       }
2333     }
2334 
2335     if (hasAttribute(Def, NewAttribute->getKind())) {
2336       ++I;
2337       continue; // regular attr merging will take care of validating this.
2338     }
2339 
2340     if (isa<C11NoReturnAttr>(NewAttribute)) {
2341       // C's _Noreturn is allowed to be added to a function after it is defined.
2342       ++I;
2343       continue;
2344     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2345       if (AA->isAlignas()) {
2346         // C++11 [dcl.align]p6:
2347         //   if any declaration of an entity has an alignment-specifier,
2348         //   every defining declaration of that entity shall specify an
2349         //   equivalent alignment.
2350         // C11 6.7.5/7:
2351         //   If the definition of an object does not have an alignment
2352         //   specifier, any other declaration of that object shall also
2353         //   have no alignment specifier.
2354         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2355           << AA;
2356         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2357           << AA;
2358         NewAttributes.erase(NewAttributes.begin() + I);
2359         --E;
2360         continue;
2361       }
2362     }
2363 
2364     S.Diag(NewAttribute->getLocation(),
2365            diag::warn_attribute_precede_definition);
2366     S.Diag(Def->getLocation(), diag::note_previous_definition);
2367     NewAttributes.erase(NewAttributes.begin() + I);
2368     --E;
2369   }
2370 }
2371 
2372 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2373 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2374                                AvailabilityMergeKind AMK) {
2375   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2376     UsedAttr *NewAttr = OldAttr->clone(Context);
2377     NewAttr->setInherited(true);
2378     New->addAttr(NewAttr);
2379   }
2380 
2381   if (!Old->hasAttrs() && !New->hasAttrs())
2382     return;
2383 
2384   // Attributes declared post-definition are currently ignored.
2385   checkNewAttributesAfterDef(*this, New, Old);
2386 
2387   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2388     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2389       if (OldA->getLabel() != NewA->getLabel()) {
2390         // This redeclaration changes __asm__ label.
2391         Diag(New->getLocation(), diag::err_different_asm_label);
2392         Diag(OldA->getLocation(), diag::note_previous_declaration);
2393       }
2394     } else if (Old->isUsed()) {
2395       // This redeclaration adds an __asm__ label to a declaration that has
2396       // already been ODR-used.
2397       Diag(New->getLocation(), diag::err_late_asm_label_name)
2398         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2399     }
2400   }
2401 
2402   // Re-declaration cannot add abi_tag's.
2403   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2404     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2405       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2406         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2407                       NewTag) == OldAbiTagAttr->tags_end()) {
2408           Diag(NewAbiTagAttr->getLocation(),
2409                diag::err_new_abi_tag_on_redeclaration)
2410               << NewTag;
2411           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2412         }
2413       }
2414     } else {
2415       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2416       Diag(Old->getLocation(), diag::note_previous_declaration);
2417     }
2418   }
2419 
2420   if (!Old->hasAttrs())
2421     return;
2422 
2423   bool foundAny = New->hasAttrs();
2424 
2425   // Ensure that any moving of objects within the allocated map is done before
2426   // we process them.
2427   if (!foundAny) New->setAttrs(AttrVec());
2428 
2429   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2430     // Ignore deprecated/unavailable/availability attributes if requested.
2431     AvailabilityMergeKind LocalAMK = AMK_None;
2432     if (isa<DeprecatedAttr>(I) ||
2433         isa<UnavailableAttr>(I) ||
2434         isa<AvailabilityAttr>(I)) {
2435       switch (AMK) {
2436       case AMK_None:
2437         continue;
2438 
2439       case AMK_Redeclaration:
2440       case AMK_Override:
2441       case AMK_ProtocolImplementation:
2442         LocalAMK = AMK;
2443         break;
2444       }
2445     }
2446 
2447     // Already handled.
2448     if (isa<UsedAttr>(I))
2449       continue;
2450 
2451     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2452       foundAny = true;
2453   }
2454 
2455   if (mergeAlignedAttrs(*this, New, Old))
2456     foundAny = true;
2457 
2458   if (!foundAny) New->dropAttrs();
2459 }
2460 
2461 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2462 /// to the new one.
2463 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2464                                      const ParmVarDecl *oldDecl,
2465                                      Sema &S) {
2466   // C++11 [dcl.attr.depend]p2:
2467   //   The first declaration of a function shall specify the
2468   //   carries_dependency attribute for its declarator-id if any declaration
2469   //   of the function specifies the carries_dependency attribute.
2470   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2471   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2472     S.Diag(CDA->getLocation(),
2473            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2474     // Find the first declaration of the parameter.
2475     // FIXME: Should we build redeclaration chains for function parameters?
2476     const FunctionDecl *FirstFD =
2477       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2478     const ParmVarDecl *FirstVD =
2479       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2480     S.Diag(FirstVD->getLocation(),
2481            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2482   }
2483 
2484   if (!oldDecl->hasAttrs())
2485     return;
2486 
2487   bool foundAny = newDecl->hasAttrs();
2488 
2489   // Ensure that any moving of objects within the allocated map is
2490   // done before we process them.
2491   if (!foundAny) newDecl->setAttrs(AttrVec());
2492 
2493   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2494     if (!DeclHasAttr(newDecl, I)) {
2495       InheritableAttr *newAttr =
2496         cast<InheritableParamAttr>(I->clone(S.Context));
2497       newAttr->setInherited(true);
2498       newDecl->addAttr(newAttr);
2499       foundAny = true;
2500     }
2501   }
2502 
2503   if (!foundAny) newDecl->dropAttrs();
2504 }
2505 
2506 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2507                                 const ParmVarDecl *OldParam,
2508                                 Sema &S) {
2509   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2510     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2511       if (*Oldnullability != *Newnullability) {
2512         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2513           << DiagNullabilityKind(
2514                *Newnullability,
2515                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2516                 != 0))
2517           << DiagNullabilityKind(
2518                *Oldnullability,
2519                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2520                 != 0));
2521         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2522       }
2523     } else {
2524       QualType NewT = NewParam->getType();
2525       NewT = S.Context.getAttributedType(
2526                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2527                          NewT, NewT);
2528       NewParam->setType(NewT);
2529     }
2530   }
2531 }
2532 
2533 namespace {
2534 
2535 /// Used in MergeFunctionDecl to keep track of function parameters in
2536 /// C.
2537 struct GNUCompatibleParamWarning {
2538   ParmVarDecl *OldParm;
2539   ParmVarDecl *NewParm;
2540   QualType PromotedType;
2541 };
2542 
2543 } // end anonymous namespace
2544 
2545 /// getSpecialMember - get the special member enum for a method.
2546 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2547   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2548     if (Ctor->isDefaultConstructor())
2549       return Sema::CXXDefaultConstructor;
2550 
2551     if (Ctor->isCopyConstructor())
2552       return Sema::CXXCopyConstructor;
2553 
2554     if (Ctor->isMoveConstructor())
2555       return Sema::CXXMoveConstructor;
2556   } else if (isa<CXXDestructorDecl>(MD)) {
2557     return Sema::CXXDestructor;
2558   } else if (MD->isCopyAssignmentOperator()) {
2559     return Sema::CXXCopyAssignment;
2560   } else if (MD->isMoveAssignmentOperator()) {
2561     return Sema::CXXMoveAssignment;
2562   }
2563 
2564   return Sema::CXXInvalid;
2565 }
2566 
2567 // Determine whether the previous declaration was a definition, implicit
2568 // declaration, or a declaration.
2569 template <typename T>
2570 static std::pair<diag::kind, SourceLocation>
2571 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2572   diag::kind PrevDiag;
2573   SourceLocation OldLocation = Old->getLocation();
2574   if (Old->isThisDeclarationADefinition())
2575     PrevDiag = diag::note_previous_definition;
2576   else if (Old->isImplicit()) {
2577     PrevDiag = diag::note_previous_implicit_declaration;
2578     if (OldLocation.isInvalid())
2579       OldLocation = New->getLocation();
2580   } else
2581     PrevDiag = diag::note_previous_declaration;
2582   return std::make_pair(PrevDiag, OldLocation);
2583 }
2584 
2585 /// canRedefineFunction - checks if a function can be redefined. Currently,
2586 /// only extern inline functions can be redefined, and even then only in
2587 /// GNU89 mode.
2588 static bool canRedefineFunction(const FunctionDecl *FD,
2589                                 const LangOptions& LangOpts) {
2590   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2591           !LangOpts.CPlusPlus &&
2592           FD->isInlineSpecified() &&
2593           FD->getStorageClass() == SC_Extern);
2594 }
2595 
2596 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2597   const AttributedType *AT = T->getAs<AttributedType>();
2598   while (AT && !AT->isCallingConv())
2599     AT = AT->getModifiedType()->getAs<AttributedType>();
2600   return AT;
2601 }
2602 
2603 template <typename T>
2604 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2605   const DeclContext *DC = Old->getDeclContext();
2606   if (DC->isRecord())
2607     return false;
2608 
2609   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2610   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2611     return true;
2612   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2613     return true;
2614   return false;
2615 }
2616 
2617 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2618 static bool isExternC(VarTemplateDecl *) { return false; }
2619 
2620 /// \brief Check whether a redeclaration of an entity introduced by a
2621 /// using-declaration is valid, given that we know it's not an overload
2622 /// (nor a hidden tag declaration).
2623 template<typename ExpectedDecl>
2624 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2625                                    ExpectedDecl *New) {
2626   // C++11 [basic.scope.declarative]p4:
2627   //   Given a set of declarations in a single declarative region, each of
2628   //   which specifies the same unqualified name,
2629   //   -- they shall all refer to the same entity, or all refer to functions
2630   //      and function templates; or
2631   //   -- exactly one declaration shall declare a class name or enumeration
2632   //      name that is not a typedef name and the other declarations shall all
2633   //      refer to the same variable or enumerator, or all refer to functions
2634   //      and function templates; in this case the class name or enumeration
2635   //      name is hidden (3.3.10).
2636 
2637   // C++11 [namespace.udecl]p14:
2638   //   If a function declaration in namespace scope or block scope has the
2639   //   same name and the same parameter-type-list as a function introduced
2640   //   by a using-declaration, and the declarations do not declare the same
2641   //   function, the program is ill-formed.
2642 
2643   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2644   if (Old &&
2645       !Old->getDeclContext()->getRedeclContext()->Equals(
2646           New->getDeclContext()->getRedeclContext()) &&
2647       !(isExternC(Old) && isExternC(New)))
2648     Old = nullptr;
2649 
2650   if (!Old) {
2651     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2652     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2653     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2654     return true;
2655   }
2656   return false;
2657 }
2658 
2659 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2660                                             const FunctionDecl *B) {
2661   assert(A->getNumParams() == B->getNumParams());
2662 
2663   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2664     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2665     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2666     if (AttrA == AttrB)
2667       return true;
2668     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2669   };
2670 
2671   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2672 }
2673 
2674 /// MergeFunctionDecl - We just parsed a function 'New' from
2675 /// declarator D which has the same name and scope as a previous
2676 /// declaration 'Old'.  Figure out how to resolve this situation,
2677 /// merging decls or emitting diagnostics as appropriate.
2678 ///
2679 /// In C++, New and Old must be declarations that are not
2680 /// overloaded. Use IsOverload to determine whether New and Old are
2681 /// overloaded, and to select the Old declaration that New should be
2682 /// merged with.
2683 ///
2684 /// Returns true if there was an error, false otherwise.
2685 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2686                              Scope *S, bool MergeTypeWithOld) {
2687   // Verify the old decl was also a function.
2688   FunctionDecl *Old = OldD->getAsFunction();
2689   if (!Old) {
2690     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2691       if (New->getFriendObjectKind()) {
2692         Diag(New->getLocation(), diag::err_using_decl_friend);
2693         Diag(Shadow->getTargetDecl()->getLocation(),
2694              diag::note_using_decl_target);
2695         Diag(Shadow->getUsingDecl()->getLocation(),
2696              diag::note_using_decl) << 0;
2697         return true;
2698       }
2699 
2700       // Check whether the two declarations might declare the same function.
2701       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2702         return true;
2703       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2704     } else {
2705       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2706         << New->getDeclName();
2707       Diag(OldD->getLocation(), diag::note_previous_definition);
2708       return true;
2709     }
2710   }
2711 
2712   // If the old declaration is invalid, just give up here.
2713   if (Old->isInvalidDecl())
2714     return true;
2715 
2716   diag::kind PrevDiag;
2717   SourceLocation OldLocation;
2718   std::tie(PrevDiag, OldLocation) =
2719       getNoteDiagForInvalidRedeclaration(Old, New);
2720 
2721   // Don't complain about this if we're in GNU89 mode and the old function
2722   // is an extern inline function.
2723   // Don't complain about specializations. They are not supposed to have
2724   // storage classes.
2725   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2726       New->getStorageClass() == SC_Static &&
2727       Old->hasExternalFormalLinkage() &&
2728       !New->getTemplateSpecializationInfo() &&
2729       !canRedefineFunction(Old, getLangOpts())) {
2730     if (getLangOpts().MicrosoftExt) {
2731       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2732       Diag(OldLocation, PrevDiag);
2733     } else {
2734       Diag(New->getLocation(), diag::err_static_non_static) << New;
2735       Diag(OldLocation, PrevDiag);
2736       return true;
2737     }
2738   }
2739 
2740   if (New->hasAttr<InternalLinkageAttr>() &&
2741       !Old->hasAttr<InternalLinkageAttr>()) {
2742     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2743         << New->getDeclName();
2744     Diag(Old->getLocation(), diag::note_previous_definition);
2745     New->dropAttr<InternalLinkageAttr>();
2746   }
2747 
2748   // If a function is first declared with a calling convention, but is later
2749   // declared or defined without one, all following decls assume the calling
2750   // convention of the first.
2751   //
2752   // It's OK if a function is first declared without a calling convention,
2753   // but is later declared or defined with the default calling convention.
2754   //
2755   // To test if either decl has an explicit calling convention, we look for
2756   // AttributedType sugar nodes on the type as written.  If they are missing or
2757   // were canonicalized away, we assume the calling convention was implicit.
2758   //
2759   // Note also that we DO NOT return at this point, because we still have
2760   // other tests to run.
2761   QualType OldQType = Context.getCanonicalType(Old->getType());
2762   QualType NewQType = Context.getCanonicalType(New->getType());
2763   const FunctionType *OldType = cast<FunctionType>(OldQType);
2764   const FunctionType *NewType = cast<FunctionType>(NewQType);
2765   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2766   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2767   bool RequiresAdjustment = false;
2768 
2769   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2770     FunctionDecl *First = Old->getFirstDecl();
2771     const FunctionType *FT =
2772         First->getType().getCanonicalType()->castAs<FunctionType>();
2773     FunctionType::ExtInfo FI = FT->getExtInfo();
2774     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2775     if (!NewCCExplicit) {
2776       // Inherit the CC from the previous declaration if it was specified
2777       // there but not here.
2778       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2779       RequiresAdjustment = true;
2780     } else {
2781       // Calling conventions aren't compatible, so complain.
2782       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2783       Diag(New->getLocation(), diag::err_cconv_change)
2784         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2785         << !FirstCCExplicit
2786         << (!FirstCCExplicit ? "" :
2787             FunctionType::getNameForCallConv(FI.getCC()));
2788 
2789       // Put the note on the first decl, since it is the one that matters.
2790       Diag(First->getLocation(), diag::note_previous_declaration);
2791       return true;
2792     }
2793   }
2794 
2795   // FIXME: diagnose the other way around?
2796   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2797     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2798     RequiresAdjustment = true;
2799   }
2800 
2801   // Merge regparm attribute.
2802   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2803       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2804     if (NewTypeInfo.getHasRegParm()) {
2805       Diag(New->getLocation(), diag::err_regparm_mismatch)
2806         << NewType->getRegParmType()
2807         << OldType->getRegParmType();
2808       Diag(OldLocation, diag::note_previous_declaration);
2809       return true;
2810     }
2811 
2812     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2813     RequiresAdjustment = true;
2814   }
2815 
2816   // Merge ns_returns_retained attribute.
2817   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2818     if (NewTypeInfo.getProducesResult()) {
2819       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2820       Diag(OldLocation, diag::note_previous_declaration);
2821       return true;
2822     }
2823 
2824     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2825     RequiresAdjustment = true;
2826   }
2827 
2828   if (RequiresAdjustment) {
2829     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2830     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2831     New->setType(QualType(AdjustedType, 0));
2832     NewQType = Context.getCanonicalType(New->getType());
2833     NewType = cast<FunctionType>(NewQType);
2834   }
2835 
2836   // If this redeclaration makes the function inline, we may need to add it to
2837   // UndefinedButUsed.
2838   if (!Old->isInlined() && New->isInlined() &&
2839       !New->hasAttr<GNUInlineAttr>() &&
2840       !getLangOpts().GNUInline &&
2841       Old->isUsed(false) &&
2842       !Old->isDefined() && !New->isThisDeclarationADefinition())
2843     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2844                                            SourceLocation()));
2845 
2846   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2847   // about it.
2848   if (New->hasAttr<GNUInlineAttr>() &&
2849       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2850     UndefinedButUsed.erase(Old->getCanonicalDecl());
2851   }
2852 
2853   // If pass_object_size params don't match up perfectly, this isn't a valid
2854   // redeclaration.
2855   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
2856       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
2857     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
2858         << New->getDeclName();
2859     Diag(OldLocation, PrevDiag) << Old << Old->getType();
2860     return true;
2861   }
2862 
2863   if (getLangOpts().CPlusPlus) {
2864     // (C++98 13.1p2):
2865     //   Certain function declarations cannot be overloaded:
2866     //     -- Function declarations that differ only in the return type
2867     //        cannot be overloaded.
2868 
2869     // Go back to the type source info to compare the declared return types,
2870     // per C++1y [dcl.type.auto]p13:
2871     //   Redeclarations or specializations of a function or function template
2872     //   with a declared return type that uses a placeholder type shall also
2873     //   use that placeholder, not a deduced type.
2874     QualType OldDeclaredReturnType =
2875         (Old->getTypeSourceInfo()
2876              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2877              : OldType)->getReturnType();
2878     QualType NewDeclaredReturnType =
2879         (New->getTypeSourceInfo()
2880              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2881              : NewType)->getReturnType();
2882     QualType ResQT;
2883     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2884         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2885           New->isLocalExternDecl())) {
2886       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2887           OldDeclaredReturnType->isObjCObjectPointerType())
2888         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2889       if (ResQT.isNull()) {
2890         if (New->isCXXClassMember() && New->isOutOfLine())
2891           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2892               << New << New->getReturnTypeSourceRange();
2893         else
2894           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2895               << New->getReturnTypeSourceRange();
2896         Diag(OldLocation, PrevDiag) << Old << Old->getType()
2897                                     << Old->getReturnTypeSourceRange();
2898         return true;
2899       }
2900       else
2901         NewQType = ResQT;
2902     }
2903 
2904     QualType OldReturnType = OldType->getReturnType();
2905     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2906     if (OldReturnType != NewReturnType) {
2907       // If this function has a deduced return type and has already been
2908       // defined, copy the deduced value from the old declaration.
2909       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2910       if (OldAT && OldAT->isDeduced()) {
2911         New->setType(
2912             SubstAutoType(New->getType(),
2913                           OldAT->isDependentType() ? Context.DependentTy
2914                                                    : OldAT->getDeducedType()));
2915         NewQType = Context.getCanonicalType(
2916             SubstAutoType(NewQType,
2917                           OldAT->isDependentType() ? Context.DependentTy
2918                                                    : OldAT->getDeducedType()));
2919       }
2920     }
2921 
2922     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2923     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2924     if (OldMethod && NewMethod) {
2925       // Preserve triviality.
2926       NewMethod->setTrivial(OldMethod->isTrivial());
2927 
2928       // MSVC allows explicit template specialization at class scope:
2929       // 2 CXXMethodDecls referring to the same function will be injected.
2930       // We don't want a redeclaration error.
2931       bool IsClassScopeExplicitSpecialization =
2932                               OldMethod->isFunctionTemplateSpecialization() &&
2933                               NewMethod->isFunctionTemplateSpecialization();
2934       bool isFriend = NewMethod->getFriendObjectKind();
2935 
2936       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2937           !IsClassScopeExplicitSpecialization) {
2938         //    -- Member function declarations with the same name and the
2939         //       same parameter types cannot be overloaded if any of them
2940         //       is a static member function declaration.
2941         if (OldMethod->isStatic() != NewMethod->isStatic()) {
2942           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2943           Diag(OldLocation, PrevDiag) << Old << Old->getType();
2944           return true;
2945         }
2946 
2947         // C++ [class.mem]p1:
2948         //   [...] A member shall not be declared twice in the
2949         //   member-specification, except that a nested class or member
2950         //   class template can be declared and then later defined.
2951         if (ActiveTemplateInstantiations.empty()) {
2952           unsigned NewDiag;
2953           if (isa<CXXConstructorDecl>(OldMethod))
2954             NewDiag = diag::err_constructor_redeclared;
2955           else if (isa<CXXDestructorDecl>(NewMethod))
2956             NewDiag = diag::err_destructor_redeclared;
2957           else if (isa<CXXConversionDecl>(NewMethod))
2958             NewDiag = diag::err_conv_function_redeclared;
2959           else
2960             NewDiag = diag::err_member_redeclared;
2961 
2962           Diag(New->getLocation(), NewDiag);
2963         } else {
2964           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2965             << New << New->getType();
2966         }
2967         Diag(OldLocation, PrevDiag) << Old << Old->getType();
2968         return true;
2969 
2970       // Complain if this is an explicit declaration of a special
2971       // member that was initially declared implicitly.
2972       //
2973       // As an exception, it's okay to befriend such methods in order
2974       // to permit the implicit constructor/destructor/operator calls.
2975       } else if (OldMethod->isImplicit()) {
2976         if (isFriend) {
2977           NewMethod->setImplicit();
2978         } else {
2979           Diag(NewMethod->getLocation(),
2980                diag::err_definition_of_implicitly_declared_member)
2981             << New << getSpecialMember(OldMethod);
2982           return true;
2983         }
2984       } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2985         Diag(NewMethod->getLocation(),
2986              diag::err_definition_of_explicitly_defaulted_member)
2987           << getSpecialMember(OldMethod);
2988         return true;
2989       }
2990     }
2991 
2992     // C++11 [dcl.attr.noreturn]p1:
2993     //   The first declaration of a function shall specify the noreturn
2994     //   attribute if any declaration of that function specifies the noreturn
2995     //   attribute.
2996     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2997     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2998       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
2999       Diag(Old->getFirstDecl()->getLocation(),
3000            diag::note_noreturn_missing_first_decl);
3001     }
3002 
3003     // C++11 [dcl.attr.depend]p2:
3004     //   The first declaration of a function shall specify the
3005     //   carries_dependency attribute for its declarator-id if any declaration
3006     //   of the function specifies the carries_dependency attribute.
3007     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3008     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3009       Diag(CDA->getLocation(),
3010            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3011       Diag(Old->getFirstDecl()->getLocation(),
3012            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3013     }
3014 
3015     // (C++98 8.3.5p3):
3016     //   All declarations for a function shall agree exactly in both the
3017     //   return type and the parameter-type-list.
3018     // We also want to respect all the extended bits except noreturn.
3019 
3020     // noreturn should now match unless the old type info didn't have it.
3021     QualType OldQTypeForComparison = OldQType;
3022     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3023       assert(OldQType == QualType(OldType, 0));
3024       const FunctionType *OldTypeForComparison
3025         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3026       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3027       assert(OldQTypeForComparison.isCanonical());
3028     }
3029 
3030     if (haveIncompatibleLanguageLinkages(Old, New)) {
3031       // As a special case, retain the language linkage from previous
3032       // declarations of a friend function as an extension.
3033       //
3034       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3035       // and is useful because there's otherwise no way to specify language
3036       // linkage within class scope.
3037       //
3038       // Check cautiously as the friend object kind isn't yet complete.
3039       if (New->getFriendObjectKind() != Decl::FOK_None) {
3040         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3041         Diag(OldLocation, PrevDiag);
3042       } else {
3043         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3044         Diag(OldLocation, PrevDiag);
3045         return true;
3046       }
3047     }
3048 
3049     if (OldQTypeForComparison == NewQType)
3050       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3051 
3052     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3053         New->isLocalExternDecl()) {
3054       // It's OK if we couldn't merge types for a local function declaraton
3055       // if either the old or new type is dependent. We'll merge the types
3056       // when we instantiate the function.
3057       return false;
3058     }
3059 
3060     // Fall through for conflicting redeclarations and redefinitions.
3061   }
3062 
3063   // C: Function types need to be compatible, not identical. This handles
3064   // duplicate function decls like "void f(int); void f(enum X);" properly.
3065   if (!getLangOpts().CPlusPlus &&
3066       Context.typesAreCompatible(OldQType, NewQType)) {
3067     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3068     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3069     const FunctionProtoType *OldProto = nullptr;
3070     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3071         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3072       // The old declaration provided a function prototype, but the
3073       // new declaration does not. Merge in the prototype.
3074       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3075       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3076       NewQType =
3077           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3078                                   OldProto->getExtProtoInfo());
3079       New->setType(NewQType);
3080       New->setHasInheritedPrototype();
3081 
3082       // Synthesize parameters with the same types.
3083       SmallVector<ParmVarDecl*, 16> Params;
3084       for (const auto &ParamType : OldProto->param_types()) {
3085         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3086                                                  SourceLocation(), nullptr,
3087                                                  ParamType, /*TInfo=*/nullptr,
3088                                                  SC_None, nullptr);
3089         Param->setScopeInfo(0, Params.size());
3090         Param->setImplicit();
3091         Params.push_back(Param);
3092       }
3093 
3094       New->setParams(Params);
3095     }
3096 
3097     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3098   }
3099 
3100   // GNU C permits a K&R definition to follow a prototype declaration
3101   // if the declared types of the parameters in the K&R definition
3102   // match the types in the prototype declaration, even when the
3103   // promoted types of the parameters from the K&R definition differ
3104   // from the types in the prototype. GCC then keeps the types from
3105   // the prototype.
3106   //
3107   // If a variadic prototype is followed by a non-variadic K&R definition,
3108   // the K&R definition becomes variadic.  This is sort of an edge case, but
3109   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3110   // C99 6.9.1p8.
3111   if (!getLangOpts().CPlusPlus &&
3112       Old->hasPrototype() && !New->hasPrototype() &&
3113       New->getType()->getAs<FunctionProtoType>() &&
3114       Old->getNumParams() == New->getNumParams()) {
3115     SmallVector<QualType, 16> ArgTypes;
3116     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3117     const FunctionProtoType *OldProto
3118       = Old->getType()->getAs<FunctionProtoType>();
3119     const FunctionProtoType *NewProto
3120       = New->getType()->getAs<FunctionProtoType>();
3121 
3122     // Determine whether this is the GNU C extension.
3123     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3124                                                NewProto->getReturnType());
3125     bool LooseCompatible = !MergedReturn.isNull();
3126     for (unsigned Idx = 0, End = Old->getNumParams();
3127          LooseCompatible && Idx != End; ++Idx) {
3128       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3129       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3130       if (Context.typesAreCompatible(OldParm->getType(),
3131                                      NewProto->getParamType(Idx))) {
3132         ArgTypes.push_back(NewParm->getType());
3133       } else if (Context.typesAreCompatible(OldParm->getType(),
3134                                             NewParm->getType(),
3135                                             /*CompareUnqualified=*/true)) {
3136         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3137                                            NewProto->getParamType(Idx) };
3138         Warnings.push_back(Warn);
3139         ArgTypes.push_back(NewParm->getType());
3140       } else
3141         LooseCompatible = false;
3142     }
3143 
3144     if (LooseCompatible) {
3145       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3146         Diag(Warnings[Warn].NewParm->getLocation(),
3147              diag::ext_param_promoted_not_compatible_with_prototype)
3148           << Warnings[Warn].PromotedType
3149           << Warnings[Warn].OldParm->getType();
3150         if (Warnings[Warn].OldParm->getLocation().isValid())
3151           Diag(Warnings[Warn].OldParm->getLocation(),
3152                diag::note_previous_declaration);
3153       }
3154 
3155       if (MergeTypeWithOld)
3156         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3157                                              OldProto->getExtProtoInfo()));
3158       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3159     }
3160 
3161     // Fall through to diagnose conflicting types.
3162   }
3163 
3164   // A function that has already been declared has been redeclared or
3165   // defined with a different type; show an appropriate diagnostic.
3166 
3167   // If the previous declaration was an implicitly-generated builtin
3168   // declaration, then at the very least we should use a specialized note.
3169   unsigned BuiltinID;
3170   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3171     // If it's actually a library-defined builtin function like 'malloc'
3172     // or 'printf', just warn about the incompatible redeclaration.
3173     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3174       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3175       Diag(OldLocation, diag::note_previous_builtin_declaration)
3176         << Old << Old->getType();
3177 
3178       // If this is a global redeclaration, just forget hereafter
3179       // about the "builtin-ness" of the function.
3180       //
3181       // Doing this for local extern declarations is problematic.  If
3182       // the builtin declaration remains visible, a second invalid
3183       // local declaration will produce a hard error; if it doesn't
3184       // remain visible, a single bogus local redeclaration (which is
3185       // actually only a warning) could break all the downstream code.
3186       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3187         New->getIdentifier()->revertBuiltin();
3188 
3189       return false;
3190     }
3191 
3192     PrevDiag = diag::note_previous_builtin_declaration;
3193   }
3194 
3195   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3196   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3197   return true;
3198 }
3199 
3200 /// \brief Completes the merge of two function declarations that are
3201 /// known to be compatible.
3202 ///
3203 /// This routine handles the merging of attributes and other
3204 /// properties of function declarations from the old declaration to
3205 /// the new declaration, once we know that New is in fact a
3206 /// redeclaration of Old.
3207 ///
3208 /// \returns false
3209 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3210                                         Scope *S, bool MergeTypeWithOld) {
3211   // Merge the attributes
3212   mergeDeclAttributes(New, Old);
3213 
3214   // Merge "pure" flag.
3215   if (Old->isPure())
3216     New->setPure();
3217 
3218   // Merge "used" flag.
3219   if (Old->getMostRecentDecl()->isUsed(false))
3220     New->setIsUsed();
3221 
3222   // Merge attributes from the parameters.  These can mismatch with K&R
3223   // declarations.
3224   if (New->getNumParams() == Old->getNumParams())
3225       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3226         ParmVarDecl *NewParam = New->getParamDecl(i);
3227         ParmVarDecl *OldParam = Old->getParamDecl(i);
3228         mergeParamDeclAttributes(NewParam, OldParam, *this);
3229         mergeParamDeclTypes(NewParam, OldParam, *this);
3230       }
3231 
3232   if (getLangOpts().CPlusPlus)
3233     return MergeCXXFunctionDecl(New, Old, S);
3234 
3235   // Merge the function types so the we get the composite types for the return
3236   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3237   // was visible.
3238   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3239   if (!Merged.isNull() && MergeTypeWithOld)
3240     New->setType(Merged);
3241 
3242   return false;
3243 }
3244 
3245 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3246                                 ObjCMethodDecl *oldMethod) {
3247   // Merge the attributes, including deprecated/unavailable
3248   AvailabilityMergeKind MergeKind =
3249     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3250       ? AMK_ProtocolImplementation
3251       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3252                                                        : AMK_Override;
3253 
3254   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3255 
3256   // Merge attributes from the parameters.
3257   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3258                                        oe = oldMethod->param_end();
3259   for (ObjCMethodDecl::param_iterator
3260          ni = newMethod->param_begin(), ne = newMethod->param_end();
3261        ni != ne && oi != oe; ++ni, ++oi)
3262     mergeParamDeclAttributes(*ni, *oi, *this);
3263 
3264   CheckObjCMethodOverride(newMethod, oldMethod);
3265 }
3266 
3267 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3268   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3269 
3270   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3271          ? diag::err_redefinition_different_type
3272          : diag::err_redeclaration_different_type)
3273     << New->getDeclName() << New->getType() << Old->getType();
3274 
3275   diag::kind PrevDiag;
3276   SourceLocation OldLocation;
3277   std::tie(PrevDiag, OldLocation)
3278     = getNoteDiagForInvalidRedeclaration(Old, New);
3279   S.Diag(OldLocation, PrevDiag);
3280   New->setInvalidDecl();
3281 }
3282 
3283 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3284 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3285 /// emitting diagnostics as appropriate.
3286 ///
3287 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3288 /// to here in AddInitializerToDecl. We can't check them before the initializer
3289 /// is attached.
3290 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3291                              bool MergeTypeWithOld) {
3292   if (New->isInvalidDecl() || Old->isInvalidDecl())
3293     return;
3294 
3295   QualType MergedT;
3296   if (getLangOpts().CPlusPlus) {
3297     if (New->getType()->isUndeducedType()) {
3298       // We don't know what the new type is until the initializer is attached.
3299       return;
3300     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3301       // These could still be something that needs exception specs checked.
3302       return MergeVarDeclExceptionSpecs(New, Old);
3303     }
3304     // C++ [basic.link]p10:
3305     //   [...] the types specified by all declarations referring to a given
3306     //   object or function shall be identical, except that declarations for an
3307     //   array object can specify array types that differ by the presence or
3308     //   absence of a major array bound (8.3.4).
3309     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3310       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3311       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3312 
3313       // We are merging a variable declaration New into Old. If it has an array
3314       // bound, and that bound differs from Old's bound, we should diagnose the
3315       // mismatch.
3316       if (!NewArray->isIncompleteArrayType()) {
3317         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3318              PrevVD = PrevVD->getPreviousDecl()) {
3319           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3320           if (PrevVDTy->isIncompleteArrayType())
3321             continue;
3322 
3323           if (!Context.hasSameType(NewArray, PrevVDTy))
3324             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3325         }
3326       }
3327 
3328       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3329         if (Context.hasSameType(OldArray->getElementType(),
3330                                 NewArray->getElementType()))
3331           MergedT = New->getType();
3332       }
3333       // FIXME: Check visibility. New is hidden but has a complete type. If New
3334       // has no array bound, it should not inherit one from Old, if Old is not
3335       // visible.
3336       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3337         if (Context.hasSameType(OldArray->getElementType(),
3338                                 NewArray->getElementType()))
3339           MergedT = Old->getType();
3340       }
3341     }
3342     else if (New->getType()->isObjCObjectPointerType() &&
3343                Old->getType()->isObjCObjectPointerType()) {
3344       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3345                                               Old->getType());
3346     }
3347   } else {
3348     // C 6.2.7p2:
3349     //   All declarations that refer to the same object or function shall have
3350     //   compatible type.
3351     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3352   }
3353   if (MergedT.isNull()) {
3354     // It's OK if we couldn't merge types if either type is dependent, for a
3355     // block-scope variable. In other cases (static data members of class
3356     // templates, variable templates, ...), we require the types to be
3357     // equivalent.
3358     // FIXME: The C++ standard doesn't say anything about this.
3359     if ((New->getType()->isDependentType() ||
3360          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3361       // If the old type was dependent, we can't merge with it, so the new type
3362       // becomes dependent for now. We'll reproduce the original type when we
3363       // instantiate the TypeSourceInfo for the variable.
3364       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3365         New->setType(Context.DependentTy);
3366       return;
3367     }
3368     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3369   }
3370 
3371   // Don't actually update the type on the new declaration if the old
3372   // declaration was an extern declaration in a different scope.
3373   if (MergeTypeWithOld)
3374     New->setType(MergedT);
3375 }
3376 
3377 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3378                                   LookupResult &Previous) {
3379   // C11 6.2.7p4:
3380   //   For an identifier with internal or external linkage declared
3381   //   in a scope in which a prior declaration of that identifier is
3382   //   visible, if the prior declaration specifies internal or
3383   //   external linkage, the type of the identifier at the later
3384   //   declaration becomes the composite type.
3385   //
3386   // If the variable isn't visible, we do not merge with its type.
3387   if (Previous.isShadowed())
3388     return false;
3389 
3390   if (S.getLangOpts().CPlusPlus) {
3391     // C++11 [dcl.array]p3:
3392     //   If there is a preceding declaration of the entity in the same
3393     //   scope in which the bound was specified, an omitted array bound
3394     //   is taken to be the same as in that earlier declaration.
3395     return NewVD->isPreviousDeclInSameBlockScope() ||
3396            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3397             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3398   } else {
3399     // If the old declaration was function-local, don't merge with its
3400     // type unless we're in the same function.
3401     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3402            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3403   }
3404 }
3405 
3406 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3407 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3408 /// situation, merging decls or emitting diagnostics as appropriate.
3409 ///
3410 /// Tentative definition rules (C99 6.9.2p2) are checked by
3411 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3412 /// definitions here, since the initializer hasn't been attached.
3413 ///
3414 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3415   // If the new decl is already invalid, don't do any other checking.
3416   if (New->isInvalidDecl())
3417     return;
3418 
3419   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3420     return;
3421 
3422   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3423 
3424   // Verify the old decl was also a variable or variable template.
3425   VarDecl *Old = nullptr;
3426   VarTemplateDecl *OldTemplate = nullptr;
3427   if (Previous.isSingleResult()) {
3428     if (NewTemplate) {
3429       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3430       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3431 
3432       if (auto *Shadow =
3433               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3434         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3435           return New->setInvalidDecl();
3436     } else {
3437       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3438 
3439       if (auto *Shadow =
3440               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3441         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3442           return New->setInvalidDecl();
3443     }
3444   }
3445   if (!Old) {
3446     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3447       << New->getDeclName();
3448     Diag(Previous.getRepresentativeDecl()->getLocation(),
3449          diag::note_previous_definition);
3450     return New->setInvalidDecl();
3451   }
3452 
3453   // Ensure the template parameters are compatible.
3454   if (NewTemplate &&
3455       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3456                                       OldTemplate->getTemplateParameters(),
3457                                       /*Complain=*/true, TPL_TemplateMatch))
3458     return New->setInvalidDecl();
3459 
3460   // C++ [class.mem]p1:
3461   //   A member shall not be declared twice in the member-specification [...]
3462   //
3463   // Here, we need only consider static data members.
3464   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3465     Diag(New->getLocation(), diag::err_duplicate_member)
3466       << New->getIdentifier();
3467     Diag(Old->getLocation(), diag::note_previous_declaration);
3468     New->setInvalidDecl();
3469   }
3470 
3471   mergeDeclAttributes(New, Old);
3472   // Warn if an already-declared variable is made a weak_import in a subsequent
3473   // declaration
3474   if (New->hasAttr<WeakImportAttr>() &&
3475       Old->getStorageClass() == SC_None &&
3476       !Old->hasAttr<WeakImportAttr>()) {
3477     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3478     Diag(Old->getLocation(), diag::note_previous_definition);
3479     // Remove weak_import attribute on new declaration.
3480     New->dropAttr<WeakImportAttr>();
3481   }
3482 
3483   if (New->hasAttr<InternalLinkageAttr>() &&
3484       !Old->hasAttr<InternalLinkageAttr>()) {
3485     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3486         << New->getDeclName();
3487     Diag(Old->getLocation(), diag::note_previous_definition);
3488     New->dropAttr<InternalLinkageAttr>();
3489   }
3490 
3491   // Merge the types.
3492   VarDecl *MostRecent = Old->getMostRecentDecl();
3493   if (MostRecent != Old) {
3494     MergeVarDeclTypes(New, MostRecent,
3495                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3496     if (New->isInvalidDecl())
3497       return;
3498   }
3499 
3500   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3501   if (New->isInvalidDecl())
3502     return;
3503 
3504   diag::kind PrevDiag;
3505   SourceLocation OldLocation;
3506   std::tie(PrevDiag, OldLocation) =
3507       getNoteDiagForInvalidRedeclaration(Old, New);
3508 
3509   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3510   if (New->getStorageClass() == SC_Static &&
3511       !New->isStaticDataMember() &&
3512       Old->hasExternalFormalLinkage()) {
3513     if (getLangOpts().MicrosoftExt) {
3514       Diag(New->getLocation(), diag::ext_static_non_static)
3515           << New->getDeclName();
3516       Diag(OldLocation, PrevDiag);
3517     } else {
3518       Diag(New->getLocation(), diag::err_static_non_static)
3519           << New->getDeclName();
3520       Diag(OldLocation, PrevDiag);
3521       return New->setInvalidDecl();
3522     }
3523   }
3524   // C99 6.2.2p4:
3525   //   For an identifier declared with the storage-class specifier
3526   //   extern in a scope in which a prior declaration of that
3527   //   identifier is visible,23) if the prior declaration specifies
3528   //   internal or external linkage, the linkage of the identifier at
3529   //   the later declaration is the same as the linkage specified at
3530   //   the prior declaration. If no prior declaration is visible, or
3531   //   if the prior declaration specifies no linkage, then the
3532   //   identifier has external linkage.
3533   if (New->hasExternalStorage() && Old->hasLinkage())
3534     /* Okay */;
3535   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3536            !New->isStaticDataMember() &&
3537            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3538     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3539     Diag(OldLocation, PrevDiag);
3540     return New->setInvalidDecl();
3541   }
3542 
3543   // Check if extern is followed by non-extern and vice-versa.
3544   if (New->hasExternalStorage() &&
3545       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3546     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3547     Diag(OldLocation, PrevDiag);
3548     return New->setInvalidDecl();
3549   }
3550   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3551       !New->hasExternalStorage()) {
3552     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3553     Diag(OldLocation, PrevDiag);
3554     return New->setInvalidDecl();
3555   }
3556 
3557   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3558 
3559   // FIXME: The test for external storage here seems wrong? We still
3560   // need to check for mismatches.
3561   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3562       // Don't complain about out-of-line definitions of static members.
3563       !(Old->getLexicalDeclContext()->isRecord() &&
3564         !New->getLexicalDeclContext()->isRecord())) {
3565     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3566     Diag(OldLocation, PrevDiag);
3567     return New->setInvalidDecl();
3568   }
3569 
3570   if (New->getTLSKind() != Old->getTLSKind()) {
3571     if (!Old->getTLSKind()) {
3572       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3573       Diag(OldLocation, PrevDiag);
3574     } else if (!New->getTLSKind()) {
3575       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3576       Diag(OldLocation, PrevDiag);
3577     } else {
3578       // Do not allow redeclaration to change the variable between requiring
3579       // static and dynamic initialization.
3580       // FIXME: GCC allows this, but uses the TLS keyword on the first
3581       // declaration to determine the kind. Do we need to be compatible here?
3582       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3583         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3584       Diag(OldLocation, PrevDiag);
3585     }
3586   }
3587 
3588   // C++ doesn't have tentative definitions, so go right ahead and check here.
3589   VarDecl *Def;
3590   if (getLangOpts().CPlusPlus &&
3591       New->isThisDeclarationADefinition() == VarDecl::Definition &&
3592       (Def = Old->getDefinition())) {
3593     NamedDecl *Hidden = nullptr;
3594     if (!hasVisibleDefinition(Def, &Hidden) &&
3595         (New->getFormalLinkage() == InternalLinkage ||
3596          New->getDescribedVarTemplate() ||
3597          New->getNumTemplateParameterLists() ||
3598          New->getDeclContext()->isDependentContext())) {
3599       // The previous definition is hidden, and multiple definitions are
3600       // permitted (in separate TUs). Form another definition of it.
3601     } else {
3602       Diag(New->getLocation(), diag::err_redefinition) << New;
3603       Diag(Def->getLocation(), diag::note_previous_definition);
3604       New->setInvalidDecl();
3605       return;
3606     }
3607   }
3608 
3609   if (haveIncompatibleLanguageLinkages(Old, New)) {
3610     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3611     Diag(OldLocation, PrevDiag);
3612     New->setInvalidDecl();
3613     return;
3614   }
3615 
3616   // Merge "used" flag.
3617   if (Old->getMostRecentDecl()->isUsed(false))
3618     New->setIsUsed();
3619 
3620   // Keep a chain of previous declarations.
3621   New->setPreviousDecl(Old);
3622   if (NewTemplate)
3623     NewTemplate->setPreviousDecl(OldTemplate);
3624 
3625   // Inherit access appropriately.
3626   New->setAccess(Old->getAccess());
3627   if (NewTemplate)
3628     NewTemplate->setAccess(New->getAccess());
3629 }
3630 
3631 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3632 /// no declarator (e.g. "struct foo;") is parsed.
3633 Decl *
3634 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3635                                  RecordDecl *&AnonRecord) {
3636   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3637                                     AnonRecord);
3638 }
3639 
3640 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3641 // disambiguate entities defined in different scopes.
3642 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3643 // compatibility.
3644 // We will pick our mangling number depending on which version of MSVC is being
3645 // targeted.
3646 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3647   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3648              ? S->getMSCurManglingNumber()
3649              : S->getMSLastManglingNumber();
3650 }
3651 
3652 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3653   if (!Context.getLangOpts().CPlusPlus)
3654     return;
3655 
3656   if (isa<CXXRecordDecl>(Tag->getParent())) {
3657     // If this tag is the direct child of a class, number it if
3658     // it is anonymous.
3659     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3660       return;
3661     MangleNumberingContext &MCtx =
3662         Context.getManglingNumberContext(Tag->getParent());
3663     Context.setManglingNumber(
3664         Tag, MCtx.getManglingNumber(
3665                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3666     return;
3667   }
3668 
3669   // If this tag isn't a direct child of a class, number it if it is local.
3670   Decl *ManglingContextDecl;
3671   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3672           Tag->getDeclContext(), ManglingContextDecl)) {
3673     Context.setManglingNumber(
3674         Tag, MCtx->getManglingNumber(
3675                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3676   }
3677 }
3678 
3679 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3680                                         TypedefNameDecl *NewTD) {
3681   if (TagFromDeclSpec->isInvalidDecl())
3682     return;
3683 
3684   // Do nothing if the tag already has a name for linkage purposes.
3685   if (TagFromDeclSpec->hasNameForLinkage())
3686     return;
3687 
3688   // A well-formed anonymous tag must always be a TUK_Definition.
3689   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3690 
3691   // The type must match the tag exactly;  no qualifiers allowed.
3692   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3693                            Context.getTagDeclType(TagFromDeclSpec))) {
3694     if (getLangOpts().CPlusPlus)
3695       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3696     return;
3697   }
3698 
3699   // If we've already computed linkage for the anonymous tag, then
3700   // adding a typedef name for the anonymous decl can change that
3701   // linkage, which might be a serious problem.  Diagnose this as
3702   // unsupported and ignore the typedef name.  TODO: we should
3703   // pursue this as a language defect and establish a formal rule
3704   // for how to handle it.
3705   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3706     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3707 
3708     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3709     tagLoc = getLocForEndOfToken(tagLoc);
3710 
3711     llvm::SmallString<40> textToInsert;
3712     textToInsert += ' ';
3713     textToInsert += NewTD->getIdentifier()->getName();
3714     Diag(tagLoc, diag::note_typedef_changes_linkage)
3715         << FixItHint::CreateInsertion(tagLoc, textToInsert);
3716     return;
3717   }
3718 
3719   // Otherwise, set this is the anon-decl typedef for the tag.
3720   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3721 }
3722 
3723 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3724   switch (T) {
3725   case DeclSpec::TST_class:
3726     return 0;
3727   case DeclSpec::TST_struct:
3728     return 1;
3729   case DeclSpec::TST_interface:
3730     return 2;
3731   case DeclSpec::TST_union:
3732     return 3;
3733   case DeclSpec::TST_enum:
3734     return 4;
3735   default:
3736     llvm_unreachable("unexpected type specifier");
3737   }
3738 }
3739 
3740 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3741 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3742 /// parameters to cope with template friend declarations.
3743 Decl *
3744 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3745                                  MultiTemplateParamsArg TemplateParams,
3746                                  bool IsExplicitInstantiation,
3747                                  RecordDecl *&AnonRecord) {
3748   Decl *TagD = nullptr;
3749   TagDecl *Tag = nullptr;
3750   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3751       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3752       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3753       DS.getTypeSpecType() == DeclSpec::TST_union ||
3754       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3755     TagD = DS.getRepAsDecl();
3756 
3757     if (!TagD) // We probably had an error
3758       return nullptr;
3759 
3760     // Note that the above type specs guarantee that the
3761     // type rep is a Decl, whereas in many of the others
3762     // it's a Type.
3763     if (isa<TagDecl>(TagD))
3764       Tag = cast<TagDecl>(TagD);
3765     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3766       Tag = CTD->getTemplatedDecl();
3767   }
3768 
3769   if (Tag) {
3770     handleTagNumbering(Tag, S);
3771     Tag->setFreeStanding();
3772     if (Tag->isInvalidDecl())
3773       return Tag;
3774   }
3775 
3776   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3777     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3778     // or incomplete types shall not be restrict-qualified."
3779     if (TypeQuals & DeclSpec::TQ_restrict)
3780       Diag(DS.getRestrictSpecLoc(),
3781            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3782            << DS.getSourceRange();
3783   }
3784 
3785   if (DS.isConstexprSpecified()) {
3786     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3787     // and definitions of functions and variables.
3788     if (Tag)
3789       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3790           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3791     else
3792       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3793     // Don't emit warnings after this error.
3794     return TagD;
3795   }
3796 
3797   if (DS.isConceptSpecified()) {
3798     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3799     // either a function concept and its definition or a variable concept and
3800     // its initializer.
3801     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3802     return TagD;
3803   }
3804 
3805   DiagnoseFunctionSpecifiers(DS);
3806 
3807   if (DS.isFriendSpecified()) {
3808     // If we're dealing with a decl but not a TagDecl, assume that
3809     // whatever routines created it handled the friendship aspect.
3810     if (TagD && !Tag)
3811       return nullptr;
3812     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3813   }
3814 
3815   const CXXScopeSpec &SS = DS.getTypeSpecScope();
3816   bool IsExplicitSpecialization =
3817     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3818   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3819       !IsExplicitInstantiation && !IsExplicitSpecialization &&
3820       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
3821     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3822     // nested-name-specifier unless it is an explicit instantiation
3823     // or an explicit specialization.
3824     //
3825     // FIXME: We allow class template partial specializations here too, per the
3826     // obvious intent of DR1819.
3827     //
3828     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3829     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3830         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
3831     return nullptr;
3832   }
3833 
3834   // Track whether this decl-specifier declares anything.
3835   bool DeclaresAnything = true;
3836 
3837   // Handle anonymous struct definitions.
3838   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3839     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3840         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3841       if (getLangOpts().CPlusPlus ||
3842           Record->getDeclContext()->isRecord()) {
3843         // If CurContext is a DeclContext that can contain statements,
3844         // RecursiveASTVisitor won't visit the decls that
3845         // BuildAnonymousStructOrUnion() will put into CurContext.
3846         // Also store them here so that they can be part of the
3847         // DeclStmt that gets created in this case.
3848         // FIXME: Also return the IndirectFieldDecls created by
3849         // BuildAnonymousStructOr union, for the same reason?
3850         if (CurContext->isFunctionOrMethod())
3851           AnonRecord = Record;
3852         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3853                                            Context.getPrintingPolicy());
3854       }
3855 
3856       DeclaresAnything = false;
3857     }
3858   }
3859 
3860   // C11 6.7.2.1p2:
3861   //   A struct-declaration that does not declare an anonymous structure or
3862   //   anonymous union shall contain a struct-declarator-list.
3863   //
3864   // This rule also existed in C89 and C99; the grammar for struct-declaration
3865   // did not permit a struct-declaration without a struct-declarator-list.
3866   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3867       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3868     // Check for Microsoft C extension: anonymous struct/union member.
3869     // Handle 2 kinds of anonymous struct/union:
3870     //   struct STRUCT;
3871     //   union UNION;
3872     // and
3873     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3874     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
3875     if ((Tag && Tag->getDeclName()) ||
3876         DS.getTypeSpecType() == DeclSpec::TST_typename) {
3877       RecordDecl *Record = nullptr;
3878       if (Tag)
3879         Record = dyn_cast<RecordDecl>(Tag);
3880       else if (const RecordType *RT =
3881                    DS.getRepAsType().get()->getAsStructureType())
3882         Record = RT->getDecl();
3883       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3884         Record = UT->getDecl();
3885 
3886       if (Record && getLangOpts().MicrosoftExt) {
3887         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3888           << Record->isUnion() << DS.getSourceRange();
3889         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3890       }
3891 
3892       DeclaresAnything = false;
3893     }
3894   }
3895 
3896   // Skip all the checks below if we have a type error.
3897   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3898       (TagD && TagD->isInvalidDecl()))
3899     return TagD;
3900 
3901   if (getLangOpts().CPlusPlus &&
3902       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3903     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3904       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3905           !Enum->getIdentifier() && !Enum->isInvalidDecl())
3906         DeclaresAnything = false;
3907 
3908   if (!DS.isMissingDeclaratorOk()) {
3909     // Customize diagnostic for a typedef missing a name.
3910     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3911       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3912         << DS.getSourceRange();
3913     else
3914       DeclaresAnything = false;
3915   }
3916 
3917   if (DS.isModulePrivateSpecified() &&
3918       Tag && Tag->getDeclContext()->isFunctionOrMethod())
3919     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3920       << Tag->getTagKind()
3921       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3922 
3923   ActOnDocumentableDecl(TagD);
3924 
3925   // C 6.7/2:
3926   //   A declaration [...] shall declare at least a declarator [...], a tag,
3927   //   or the members of an enumeration.
3928   // C++ [dcl.dcl]p3:
3929   //   [If there are no declarators], and except for the declaration of an
3930   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
3931   //   names into the program, or shall redeclare a name introduced by a
3932   //   previous declaration.
3933   if (!DeclaresAnything) {
3934     // In C, we allow this as a (popular) extension / bug. Don't bother
3935     // producing further diagnostics for redundant qualifiers after this.
3936     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3937     return TagD;
3938   }
3939 
3940   // C++ [dcl.stc]p1:
3941   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3942   //   init-declarator-list of the declaration shall not be empty.
3943   // C++ [dcl.fct.spec]p1:
3944   //   If a cv-qualifier appears in a decl-specifier-seq, the
3945   //   init-declarator-list of the declaration shall not be empty.
3946   //
3947   // Spurious qualifiers here appear to be valid in C.
3948   unsigned DiagID = diag::warn_standalone_specifier;
3949   if (getLangOpts().CPlusPlus)
3950     DiagID = diag::ext_standalone_specifier;
3951 
3952   // Note that a linkage-specification sets a storage class, but
3953   // 'extern "C" struct foo;' is actually valid and not theoretically
3954   // useless.
3955   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3956     if (SCS == DeclSpec::SCS_mutable)
3957       // Since mutable is not a viable storage class specifier in C, there is
3958       // no reason to treat it as an extension. Instead, diagnose as an error.
3959       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
3960     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3961       Diag(DS.getStorageClassSpecLoc(), DiagID)
3962         << DeclSpec::getSpecifierName(SCS);
3963   }
3964 
3965   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3966     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3967       << DeclSpec::getSpecifierName(TSCS);
3968   if (DS.getTypeQualifiers()) {
3969     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3970       Diag(DS.getConstSpecLoc(), DiagID) << "const";
3971     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3972       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3973     // Restrict is covered above.
3974     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3975       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3976   }
3977 
3978   // Warn about ignored type attributes, for example:
3979   // __attribute__((aligned)) struct A;
3980   // Attributes should be placed after tag to apply to type declaration.
3981   if (!DS.getAttributes().empty()) {
3982     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3983     if (TypeSpecType == DeclSpec::TST_class ||
3984         TypeSpecType == DeclSpec::TST_struct ||
3985         TypeSpecType == DeclSpec::TST_interface ||
3986         TypeSpecType == DeclSpec::TST_union ||
3987         TypeSpecType == DeclSpec::TST_enum) {
3988       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
3989            attrs = attrs->getNext())
3990         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
3991             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
3992     }
3993   }
3994 
3995   return TagD;
3996 }
3997 
3998 /// We are trying to inject an anonymous member into the given scope;
3999 /// check if there's an existing declaration that can't be overloaded.
4000 ///
4001 /// \return true if this is a forbidden redeclaration
4002 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4003                                          Scope *S,
4004                                          DeclContext *Owner,
4005                                          DeclarationName Name,
4006                                          SourceLocation NameLoc,
4007                                          bool IsUnion) {
4008   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4009                  Sema::ForRedeclaration);
4010   if (!SemaRef.LookupName(R, S)) return false;
4011 
4012   // Pick a representative declaration.
4013   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4014   assert(PrevDecl && "Expected a non-null Decl");
4015 
4016   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4017     return false;
4018 
4019   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4020     << IsUnion << Name;
4021   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4022 
4023   return true;
4024 }
4025 
4026 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4027 /// anonymous struct or union AnonRecord into the owning context Owner
4028 /// and scope S. This routine will be invoked just after we realize
4029 /// that an unnamed union or struct is actually an anonymous union or
4030 /// struct, e.g.,
4031 ///
4032 /// @code
4033 /// union {
4034 ///   int i;
4035 ///   float f;
4036 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4037 ///    // f into the surrounding scope.x
4038 /// @endcode
4039 ///
4040 /// This routine is recursive, injecting the names of nested anonymous
4041 /// structs/unions into the owning context and scope as well.
4042 static bool
4043 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4044                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4045                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4046   bool Invalid = false;
4047 
4048   // Look every FieldDecl and IndirectFieldDecl with a name.
4049   for (auto *D : AnonRecord->decls()) {
4050     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4051         cast<NamedDecl>(D)->getDeclName()) {
4052       ValueDecl *VD = cast<ValueDecl>(D);
4053       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4054                                        VD->getLocation(),
4055                                        AnonRecord->isUnion())) {
4056         // C++ [class.union]p2:
4057         //   The names of the members of an anonymous union shall be
4058         //   distinct from the names of any other entity in the
4059         //   scope in which the anonymous union is declared.
4060         Invalid = true;
4061       } else {
4062         // C++ [class.union]p2:
4063         //   For the purpose of name lookup, after the anonymous union
4064         //   definition, the members of the anonymous union are
4065         //   considered to have been defined in the scope in which the
4066         //   anonymous union is declared.
4067         unsigned OldChainingSize = Chaining.size();
4068         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4069           Chaining.append(IF->chain_begin(), IF->chain_end());
4070         else
4071           Chaining.push_back(VD);
4072 
4073         assert(Chaining.size() >= 2);
4074         NamedDecl **NamedChain =
4075           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4076         for (unsigned i = 0; i < Chaining.size(); i++)
4077           NamedChain[i] = Chaining[i];
4078 
4079         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4080             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4081             VD->getType(), NamedChain, Chaining.size());
4082 
4083         for (const auto *Attr : VD->attrs())
4084           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4085 
4086         IndirectField->setAccess(AS);
4087         IndirectField->setImplicit();
4088         SemaRef.PushOnScopeChains(IndirectField, S);
4089 
4090         // That includes picking up the appropriate access specifier.
4091         if (AS != AS_none) IndirectField->setAccess(AS);
4092 
4093         Chaining.resize(OldChainingSize);
4094       }
4095     }
4096   }
4097 
4098   return Invalid;
4099 }
4100 
4101 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4102 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4103 /// illegal input values are mapped to SC_None.
4104 static StorageClass
4105 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4106   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4107   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4108          "Parser allowed 'typedef' as storage class VarDecl.");
4109   switch (StorageClassSpec) {
4110   case DeclSpec::SCS_unspecified:    return SC_None;
4111   case DeclSpec::SCS_extern:
4112     if (DS.isExternInLinkageSpec())
4113       return SC_None;
4114     return SC_Extern;
4115   case DeclSpec::SCS_static:         return SC_Static;
4116   case DeclSpec::SCS_auto:           return SC_Auto;
4117   case DeclSpec::SCS_register:       return SC_Register;
4118   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4119     // Illegal SCSs map to None: error reporting is up to the caller.
4120   case DeclSpec::SCS_mutable:        // Fall through.
4121   case DeclSpec::SCS_typedef:        return SC_None;
4122   }
4123   llvm_unreachable("unknown storage class specifier");
4124 }
4125 
4126 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4127   assert(Record->hasInClassInitializer());
4128 
4129   for (const auto *I : Record->decls()) {
4130     const auto *FD = dyn_cast<FieldDecl>(I);
4131     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4132       FD = IFD->getAnonField();
4133     if (FD && FD->hasInClassInitializer())
4134       return FD->getLocation();
4135   }
4136 
4137   llvm_unreachable("couldn't find in-class initializer");
4138 }
4139 
4140 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4141                                       SourceLocation DefaultInitLoc) {
4142   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4143     return;
4144 
4145   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4146   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4147 }
4148 
4149 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4150                                       CXXRecordDecl *AnonUnion) {
4151   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4152     return;
4153 
4154   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4155 }
4156 
4157 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4158 /// anonymous structure or union. Anonymous unions are a C++ feature
4159 /// (C++ [class.union]) and a C11 feature; anonymous structures
4160 /// are a C11 feature and GNU C++ extension.
4161 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4162                                         AccessSpecifier AS,
4163                                         RecordDecl *Record,
4164                                         const PrintingPolicy &Policy) {
4165   DeclContext *Owner = Record->getDeclContext();
4166 
4167   // Diagnose whether this anonymous struct/union is an extension.
4168   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4169     Diag(Record->getLocation(), diag::ext_anonymous_union);
4170   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4171     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4172   else if (!Record->isUnion() && !getLangOpts().C11)
4173     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4174 
4175   // C and C++ require different kinds of checks for anonymous
4176   // structs/unions.
4177   bool Invalid = false;
4178   if (getLangOpts().CPlusPlus) {
4179     const char *PrevSpec = nullptr;
4180     unsigned DiagID;
4181     if (Record->isUnion()) {
4182       // C++ [class.union]p6:
4183       //   Anonymous unions declared in a named namespace or in the
4184       //   global namespace shall be declared static.
4185       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4186           (isa<TranslationUnitDecl>(Owner) ||
4187            (isa<NamespaceDecl>(Owner) &&
4188             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4189         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4190           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4191 
4192         // Recover by adding 'static'.
4193         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4194                                PrevSpec, DiagID, Policy);
4195       }
4196       // C++ [class.union]p6:
4197       //   A storage class is not allowed in a declaration of an
4198       //   anonymous union in a class scope.
4199       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4200                isa<RecordDecl>(Owner)) {
4201         Diag(DS.getStorageClassSpecLoc(),
4202              diag::err_anonymous_union_with_storage_spec)
4203           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4204 
4205         // Recover by removing the storage specifier.
4206         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4207                                SourceLocation(),
4208                                PrevSpec, DiagID, Context.getPrintingPolicy());
4209       }
4210     }
4211 
4212     // Ignore const/volatile/restrict qualifiers.
4213     if (DS.getTypeQualifiers()) {
4214       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4215         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4216           << Record->isUnion() << "const"
4217           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4218       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4219         Diag(DS.getVolatileSpecLoc(),
4220              diag::ext_anonymous_struct_union_qualified)
4221           << Record->isUnion() << "volatile"
4222           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4223       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4224         Diag(DS.getRestrictSpecLoc(),
4225              diag::ext_anonymous_struct_union_qualified)
4226           << Record->isUnion() << "restrict"
4227           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4228       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4229         Diag(DS.getAtomicSpecLoc(),
4230              diag::ext_anonymous_struct_union_qualified)
4231           << Record->isUnion() << "_Atomic"
4232           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4233 
4234       DS.ClearTypeQualifiers();
4235     }
4236 
4237     // C++ [class.union]p2:
4238     //   The member-specification of an anonymous union shall only
4239     //   define non-static data members. [Note: nested types and
4240     //   functions cannot be declared within an anonymous union. ]
4241     for (auto *Mem : Record->decls()) {
4242       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4243         // C++ [class.union]p3:
4244         //   An anonymous union shall not have private or protected
4245         //   members (clause 11).
4246         assert(FD->getAccess() != AS_none);
4247         if (FD->getAccess() != AS_public) {
4248           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4249             << Record->isUnion() << (FD->getAccess() == AS_protected);
4250           Invalid = true;
4251         }
4252 
4253         // C++ [class.union]p1
4254         //   An object of a class with a non-trivial constructor, a non-trivial
4255         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4256         //   assignment operator cannot be a member of a union, nor can an
4257         //   array of such objects.
4258         if (CheckNontrivialField(FD))
4259           Invalid = true;
4260       } else if (Mem->isImplicit()) {
4261         // Any implicit members are fine.
4262       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4263         // This is a type that showed up in an
4264         // elaborated-type-specifier inside the anonymous struct or
4265         // union, but which actually declares a type outside of the
4266         // anonymous struct or union. It's okay.
4267       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4268         if (!MemRecord->isAnonymousStructOrUnion() &&
4269             MemRecord->getDeclName()) {
4270           // Visual C++ allows type definition in anonymous struct or union.
4271           if (getLangOpts().MicrosoftExt)
4272             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4273               << Record->isUnion();
4274           else {
4275             // This is a nested type declaration.
4276             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4277               << Record->isUnion();
4278             Invalid = true;
4279           }
4280         } else {
4281           // This is an anonymous type definition within another anonymous type.
4282           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4283           // not part of standard C++.
4284           Diag(MemRecord->getLocation(),
4285                diag::ext_anonymous_record_with_anonymous_type)
4286             << Record->isUnion();
4287         }
4288       } else if (isa<AccessSpecDecl>(Mem)) {
4289         // Any access specifier is fine.
4290       } else if (isa<StaticAssertDecl>(Mem)) {
4291         // In C++1z, static_assert declarations are also fine.
4292       } else {
4293         // We have something that isn't a non-static data
4294         // member. Complain about it.
4295         unsigned DK = diag::err_anonymous_record_bad_member;
4296         if (isa<TypeDecl>(Mem))
4297           DK = diag::err_anonymous_record_with_type;
4298         else if (isa<FunctionDecl>(Mem))
4299           DK = diag::err_anonymous_record_with_function;
4300         else if (isa<VarDecl>(Mem))
4301           DK = diag::err_anonymous_record_with_static;
4302 
4303         // Visual C++ allows type definition in anonymous struct or union.
4304         if (getLangOpts().MicrosoftExt &&
4305             DK == diag::err_anonymous_record_with_type)
4306           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4307             << Record->isUnion();
4308         else {
4309           Diag(Mem->getLocation(), DK) << Record->isUnion();
4310           Invalid = true;
4311         }
4312       }
4313     }
4314 
4315     // C++11 [class.union]p8 (DR1460):
4316     //   At most one variant member of a union may have a
4317     //   brace-or-equal-initializer.
4318     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4319         Owner->isRecord())
4320       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4321                                 cast<CXXRecordDecl>(Record));
4322   }
4323 
4324   if (!Record->isUnion() && !Owner->isRecord()) {
4325     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4326       << getLangOpts().CPlusPlus;
4327     Invalid = true;
4328   }
4329 
4330   // Mock up a declarator.
4331   Declarator Dc(DS, Declarator::MemberContext);
4332   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4333   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4334 
4335   // Create a declaration for this anonymous struct/union.
4336   NamedDecl *Anon = nullptr;
4337   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4338     Anon = FieldDecl::Create(Context, OwningClass,
4339                              DS.getLocStart(),
4340                              Record->getLocation(),
4341                              /*IdentifierInfo=*/nullptr,
4342                              Context.getTypeDeclType(Record),
4343                              TInfo,
4344                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4345                              /*InitStyle=*/ICIS_NoInit);
4346     Anon->setAccess(AS);
4347     if (getLangOpts().CPlusPlus)
4348       FieldCollector->Add(cast<FieldDecl>(Anon));
4349   } else {
4350     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4351     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4352     if (SCSpec == DeclSpec::SCS_mutable) {
4353       // mutable can only appear on non-static class members, so it's always
4354       // an error here
4355       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4356       Invalid = true;
4357       SC = SC_None;
4358     }
4359 
4360     Anon = VarDecl::Create(Context, Owner,
4361                            DS.getLocStart(),
4362                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4363                            Context.getTypeDeclType(Record),
4364                            TInfo, SC);
4365 
4366     // Default-initialize the implicit variable. This initialization will be
4367     // trivial in almost all cases, except if a union member has an in-class
4368     // initializer:
4369     //   union { int n = 0; };
4370     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4371   }
4372   Anon->setImplicit();
4373 
4374   // Mark this as an anonymous struct/union type.
4375   Record->setAnonymousStructOrUnion(true);
4376 
4377   // Add the anonymous struct/union object to the current
4378   // context. We'll be referencing this object when we refer to one of
4379   // its members.
4380   Owner->addDecl(Anon);
4381 
4382   // Inject the members of the anonymous struct/union into the owning
4383   // context and into the identifier resolver chain for name lookup
4384   // purposes.
4385   SmallVector<NamedDecl*, 2> Chain;
4386   Chain.push_back(Anon);
4387 
4388   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4389     Invalid = true;
4390 
4391   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4392     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4393       Decl *ManglingContextDecl;
4394       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4395               NewVD->getDeclContext(), ManglingContextDecl)) {
4396         Context.setManglingNumber(
4397             NewVD, MCtx->getManglingNumber(
4398                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4399         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4400       }
4401     }
4402   }
4403 
4404   if (Invalid)
4405     Anon->setInvalidDecl();
4406 
4407   return Anon;
4408 }
4409 
4410 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4411 /// Microsoft C anonymous structure.
4412 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4413 /// Example:
4414 ///
4415 /// struct A { int a; };
4416 /// struct B { struct A; int b; };
4417 ///
4418 /// void foo() {
4419 ///   B var;
4420 ///   var.a = 3;
4421 /// }
4422 ///
4423 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4424                                            RecordDecl *Record) {
4425   assert(Record && "expected a record!");
4426 
4427   // Mock up a declarator.
4428   Declarator Dc(DS, Declarator::TypeNameContext);
4429   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4430   assert(TInfo && "couldn't build declarator info for anonymous struct");
4431 
4432   auto *ParentDecl = cast<RecordDecl>(CurContext);
4433   QualType RecTy = Context.getTypeDeclType(Record);
4434 
4435   // Create a declaration for this anonymous struct.
4436   NamedDecl *Anon = FieldDecl::Create(Context,
4437                              ParentDecl,
4438                              DS.getLocStart(),
4439                              DS.getLocStart(),
4440                              /*IdentifierInfo=*/nullptr,
4441                              RecTy,
4442                              TInfo,
4443                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4444                              /*InitStyle=*/ICIS_NoInit);
4445   Anon->setImplicit();
4446 
4447   // Add the anonymous struct object to the current context.
4448   CurContext->addDecl(Anon);
4449 
4450   // Inject the members of the anonymous struct into the current
4451   // context and into the identifier resolver chain for name lookup
4452   // purposes.
4453   SmallVector<NamedDecl*, 2> Chain;
4454   Chain.push_back(Anon);
4455 
4456   RecordDecl *RecordDef = Record->getDefinition();
4457   if (RequireCompleteType(Anon->getLocation(), RecTy,
4458                           diag::err_field_incomplete) ||
4459       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4460                                           AS_none, Chain)) {
4461     Anon->setInvalidDecl();
4462     ParentDecl->setInvalidDecl();
4463   }
4464 
4465   return Anon;
4466 }
4467 
4468 /// GetNameForDeclarator - Determine the full declaration name for the
4469 /// given Declarator.
4470 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4471   return GetNameFromUnqualifiedId(D.getName());
4472 }
4473 
4474 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4475 DeclarationNameInfo
4476 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4477   DeclarationNameInfo NameInfo;
4478   NameInfo.setLoc(Name.StartLocation);
4479 
4480   switch (Name.getKind()) {
4481 
4482   case UnqualifiedId::IK_ImplicitSelfParam:
4483   case UnqualifiedId::IK_Identifier:
4484     NameInfo.setName(Name.Identifier);
4485     NameInfo.setLoc(Name.StartLocation);
4486     return NameInfo;
4487 
4488   case UnqualifiedId::IK_OperatorFunctionId:
4489     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4490                                            Name.OperatorFunctionId.Operator));
4491     NameInfo.setLoc(Name.StartLocation);
4492     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4493       = Name.OperatorFunctionId.SymbolLocations[0];
4494     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4495       = Name.EndLocation.getRawEncoding();
4496     return NameInfo;
4497 
4498   case UnqualifiedId::IK_LiteralOperatorId:
4499     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4500                                                            Name.Identifier));
4501     NameInfo.setLoc(Name.StartLocation);
4502     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4503     return NameInfo;
4504 
4505   case UnqualifiedId::IK_ConversionFunctionId: {
4506     TypeSourceInfo *TInfo;
4507     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4508     if (Ty.isNull())
4509       return DeclarationNameInfo();
4510     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4511                                                Context.getCanonicalType(Ty)));
4512     NameInfo.setLoc(Name.StartLocation);
4513     NameInfo.setNamedTypeInfo(TInfo);
4514     return NameInfo;
4515   }
4516 
4517   case UnqualifiedId::IK_ConstructorName: {
4518     TypeSourceInfo *TInfo;
4519     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4520     if (Ty.isNull())
4521       return DeclarationNameInfo();
4522     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4523                                               Context.getCanonicalType(Ty)));
4524     NameInfo.setLoc(Name.StartLocation);
4525     NameInfo.setNamedTypeInfo(TInfo);
4526     return NameInfo;
4527   }
4528 
4529   case UnqualifiedId::IK_ConstructorTemplateId: {
4530     // In well-formed code, we can only have a constructor
4531     // template-id that refers to the current context, so go there
4532     // to find the actual type being constructed.
4533     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4534     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4535       return DeclarationNameInfo();
4536 
4537     // Determine the type of the class being constructed.
4538     QualType CurClassType = Context.getTypeDeclType(CurClass);
4539 
4540     // FIXME: Check two things: that the template-id names the same type as
4541     // CurClassType, and that the template-id does not occur when the name
4542     // was qualified.
4543 
4544     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4545                                     Context.getCanonicalType(CurClassType)));
4546     NameInfo.setLoc(Name.StartLocation);
4547     // FIXME: should we retrieve TypeSourceInfo?
4548     NameInfo.setNamedTypeInfo(nullptr);
4549     return NameInfo;
4550   }
4551 
4552   case UnqualifiedId::IK_DestructorName: {
4553     TypeSourceInfo *TInfo;
4554     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4555     if (Ty.isNull())
4556       return DeclarationNameInfo();
4557     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4558                                               Context.getCanonicalType(Ty)));
4559     NameInfo.setLoc(Name.StartLocation);
4560     NameInfo.setNamedTypeInfo(TInfo);
4561     return NameInfo;
4562   }
4563 
4564   case UnqualifiedId::IK_TemplateId: {
4565     TemplateName TName = Name.TemplateId->Template.get();
4566     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4567     return Context.getNameForTemplate(TName, TNameLoc);
4568   }
4569 
4570   } // switch (Name.getKind())
4571 
4572   llvm_unreachable("Unknown name kind");
4573 }
4574 
4575 static QualType getCoreType(QualType Ty) {
4576   do {
4577     if (Ty->isPointerType() || Ty->isReferenceType())
4578       Ty = Ty->getPointeeType();
4579     else if (Ty->isArrayType())
4580       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4581     else
4582       return Ty.withoutLocalFastQualifiers();
4583   } while (true);
4584 }
4585 
4586 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4587 /// and Definition have "nearly" matching parameters. This heuristic is
4588 /// used to improve diagnostics in the case where an out-of-line function
4589 /// definition doesn't match any declaration within the class or namespace.
4590 /// Also sets Params to the list of indices to the parameters that differ
4591 /// between the declaration and the definition. If hasSimilarParameters
4592 /// returns true and Params is empty, then all of the parameters match.
4593 static bool hasSimilarParameters(ASTContext &Context,
4594                                      FunctionDecl *Declaration,
4595                                      FunctionDecl *Definition,
4596                                      SmallVectorImpl<unsigned> &Params) {
4597   Params.clear();
4598   if (Declaration->param_size() != Definition->param_size())
4599     return false;
4600   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4601     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4602     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4603 
4604     // The parameter types are identical
4605     if (Context.hasSameType(DefParamTy, DeclParamTy))
4606       continue;
4607 
4608     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4609     QualType DefParamBaseTy = getCoreType(DefParamTy);
4610     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4611     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4612 
4613     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4614         (DeclTyName && DeclTyName == DefTyName))
4615       Params.push_back(Idx);
4616     else  // The two parameters aren't even close
4617       return false;
4618   }
4619 
4620   return true;
4621 }
4622 
4623 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4624 /// declarator needs to be rebuilt in the current instantiation.
4625 /// Any bits of declarator which appear before the name are valid for
4626 /// consideration here.  That's specifically the type in the decl spec
4627 /// and the base type in any member-pointer chunks.
4628 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4629                                                     DeclarationName Name) {
4630   // The types we specifically need to rebuild are:
4631   //   - typenames, typeofs, and decltypes
4632   //   - types which will become injected class names
4633   // Of course, we also need to rebuild any type referencing such a
4634   // type.  It's safest to just say "dependent", but we call out a
4635   // few cases here.
4636 
4637   DeclSpec &DS = D.getMutableDeclSpec();
4638   switch (DS.getTypeSpecType()) {
4639   case DeclSpec::TST_typename:
4640   case DeclSpec::TST_typeofType:
4641   case DeclSpec::TST_underlyingType:
4642   case DeclSpec::TST_atomic: {
4643     // Grab the type from the parser.
4644     TypeSourceInfo *TSI = nullptr;
4645     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4646     if (T.isNull() || !T->isDependentType()) break;
4647 
4648     // Make sure there's a type source info.  This isn't really much
4649     // of a waste; most dependent types should have type source info
4650     // attached already.
4651     if (!TSI)
4652       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4653 
4654     // Rebuild the type in the current instantiation.
4655     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4656     if (!TSI) return true;
4657 
4658     // Store the new type back in the decl spec.
4659     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4660     DS.UpdateTypeRep(LocType);
4661     break;
4662   }
4663 
4664   case DeclSpec::TST_decltype:
4665   case DeclSpec::TST_typeofExpr: {
4666     Expr *E = DS.getRepAsExpr();
4667     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4668     if (Result.isInvalid()) return true;
4669     DS.UpdateExprRep(Result.get());
4670     break;
4671   }
4672 
4673   default:
4674     // Nothing to do for these decl specs.
4675     break;
4676   }
4677 
4678   // It doesn't matter what order we do this in.
4679   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4680     DeclaratorChunk &Chunk = D.getTypeObject(I);
4681 
4682     // The only type information in the declarator which can come
4683     // before the declaration name is the base type of a member
4684     // pointer.
4685     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4686       continue;
4687 
4688     // Rebuild the scope specifier in-place.
4689     CXXScopeSpec &SS = Chunk.Mem.Scope();
4690     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4691       return true;
4692   }
4693 
4694   return false;
4695 }
4696 
4697 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4698   D.setFunctionDefinitionKind(FDK_Declaration);
4699   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4700 
4701   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4702       Dcl && Dcl->getDeclContext()->isFileContext())
4703     Dcl->setTopLevelDeclInObjCContainer();
4704 
4705   return Dcl;
4706 }
4707 
4708 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4709 ///   If T is the name of a class, then each of the following shall have a
4710 ///   name different from T:
4711 ///     - every static data member of class T;
4712 ///     - every member function of class T
4713 ///     - every member of class T that is itself a type;
4714 /// \returns true if the declaration name violates these rules.
4715 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4716                                    DeclarationNameInfo NameInfo) {
4717   DeclarationName Name = NameInfo.getName();
4718 
4719   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
4720   while (Record && Record->isAnonymousStructOrUnion())
4721     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
4722   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
4723     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4724     return true;
4725   }
4726 
4727   return false;
4728 }
4729 
4730 /// \brief Diagnose a declaration whose declarator-id has the given
4731 /// nested-name-specifier.
4732 ///
4733 /// \param SS The nested-name-specifier of the declarator-id.
4734 ///
4735 /// \param DC The declaration context to which the nested-name-specifier
4736 /// resolves.
4737 ///
4738 /// \param Name The name of the entity being declared.
4739 ///
4740 /// \param Loc The location of the name of the entity being declared.
4741 ///
4742 /// \returns true if we cannot safely recover from this error, false otherwise.
4743 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4744                                         DeclarationName Name,
4745                                         SourceLocation Loc) {
4746   DeclContext *Cur = CurContext;
4747   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4748     Cur = Cur->getParent();
4749 
4750   // If the user provided a superfluous scope specifier that refers back to the
4751   // class in which the entity is already declared, diagnose and ignore it.
4752   //
4753   // class X {
4754   //   void X::f();
4755   // };
4756   //
4757   // Note, it was once ill-formed to give redundant qualification in all
4758   // contexts, but that rule was removed by DR482.
4759   if (Cur->Equals(DC)) {
4760     if (Cur->isRecord()) {
4761       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4762                                       : diag::err_member_extra_qualification)
4763         << Name << FixItHint::CreateRemoval(SS.getRange());
4764       SS.clear();
4765     } else {
4766       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4767     }
4768     return false;
4769   }
4770 
4771   // Check whether the qualifying scope encloses the scope of the original
4772   // declaration.
4773   if (!Cur->Encloses(DC)) {
4774     if (Cur->isRecord())
4775       Diag(Loc, diag::err_member_qualification)
4776         << Name << SS.getRange();
4777     else if (isa<TranslationUnitDecl>(DC))
4778       Diag(Loc, diag::err_invalid_declarator_global_scope)
4779         << Name << SS.getRange();
4780     else if (isa<FunctionDecl>(Cur))
4781       Diag(Loc, diag::err_invalid_declarator_in_function)
4782         << Name << SS.getRange();
4783     else if (isa<BlockDecl>(Cur))
4784       Diag(Loc, diag::err_invalid_declarator_in_block)
4785         << Name << SS.getRange();
4786     else
4787       Diag(Loc, diag::err_invalid_declarator_scope)
4788       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4789 
4790     return true;
4791   }
4792 
4793   if (Cur->isRecord()) {
4794     // Cannot qualify members within a class.
4795     Diag(Loc, diag::err_member_qualification)
4796       << Name << SS.getRange();
4797     SS.clear();
4798 
4799     // C++ constructors and destructors with incorrect scopes can break
4800     // our AST invariants by having the wrong underlying types. If
4801     // that's the case, then drop this declaration entirely.
4802     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4803          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4804         !Context.hasSameType(Name.getCXXNameType(),
4805                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4806       return true;
4807 
4808     return false;
4809   }
4810 
4811   // C++11 [dcl.meaning]p1:
4812   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4813   //   not begin with a decltype-specifer"
4814   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4815   while (SpecLoc.getPrefix())
4816     SpecLoc = SpecLoc.getPrefix();
4817   if (dyn_cast_or_null<DecltypeType>(
4818         SpecLoc.getNestedNameSpecifier()->getAsType()))
4819     Diag(Loc, diag::err_decltype_in_declarator)
4820       << SpecLoc.getTypeLoc().getSourceRange();
4821 
4822   return false;
4823 }
4824 
4825 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4826                                   MultiTemplateParamsArg TemplateParamLists) {
4827   // TODO: consider using NameInfo for diagnostic.
4828   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4829   DeclarationName Name = NameInfo.getName();
4830 
4831   // All of these full declarators require an identifier.  If it doesn't have
4832   // one, the ParsedFreeStandingDeclSpec action should be used.
4833   if (!Name) {
4834     if (!D.isInvalidType())  // Reject this if we think it is valid.
4835       Diag(D.getDeclSpec().getLocStart(),
4836            diag::err_declarator_need_ident)
4837         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4838     return nullptr;
4839   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4840     return nullptr;
4841 
4842   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4843   // we find one that is.
4844   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4845          (S->getFlags() & Scope::TemplateParamScope) != 0)
4846     S = S->getParent();
4847 
4848   DeclContext *DC = CurContext;
4849   if (D.getCXXScopeSpec().isInvalid())
4850     D.setInvalidType();
4851   else if (D.getCXXScopeSpec().isSet()) {
4852     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4853                                         UPPC_DeclarationQualifier))
4854       return nullptr;
4855 
4856     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4857     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4858     if (!DC || isa<EnumDecl>(DC)) {
4859       // If we could not compute the declaration context, it's because the
4860       // declaration context is dependent but does not refer to a class,
4861       // class template, or class template partial specialization. Complain
4862       // and return early, to avoid the coming semantic disaster.
4863       Diag(D.getIdentifierLoc(),
4864            diag::err_template_qualified_declarator_no_match)
4865         << D.getCXXScopeSpec().getScopeRep()
4866         << D.getCXXScopeSpec().getRange();
4867       return nullptr;
4868     }
4869     bool IsDependentContext = DC->isDependentContext();
4870 
4871     if (!IsDependentContext &&
4872         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4873       return nullptr;
4874 
4875     // If a class is incomplete, do not parse entities inside it.
4876     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4877       Diag(D.getIdentifierLoc(),
4878            diag::err_member_def_undefined_record)
4879         << Name << DC << D.getCXXScopeSpec().getRange();
4880       return nullptr;
4881     }
4882     if (!D.getDeclSpec().isFriendSpecified()) {
4883       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4884                                       Name, D.getIdentifierLoc())) {
4885         if (DC->isRecord())
4886           return nullptr;
4887 
4888         D.setInvalidType();
4889       }
4890     }
4891 
4892     // Check whether we need to rebuild the type of the given
4893     // declaration in the current instantiation.
4894     if (EnteringContext && IsDependentContext &&
4895         TemplateParamLists.size() != 0) {
4896       ContextRAII SavedContext(*this, DC);
4897       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4898         D.setInvalidType();
4899     }
4900   }
4901 
4902   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4903   QualType R = TInfo->getType();
4904 
4905   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
4906     // If this is a typedef, we'll end up spewing multiple diagnostics.
4907     // Just return early; it's safer. If this is a function, let the
4908     // "constructor cannot have a return type" diagnostic handle it.
4909     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4910       return nullptr;
4911 
4912   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4913                                       UPPC_DeclarationType))
4914     D.setInvalidType();
4915 
4916   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4917                         ForRedeclaration);
4918 
4919   // See if this is a redefinition of a variable in the same scope.
4920   if (!D.getCXXScopeSpec().isSet()) {
4921     bool IsLinkageLookup = false;
4922     bool CreateBuiltins = false;
4923 
4924     // If the declaration we're planning to build will be a function
4925     // or object with linkage, then look for another declaration with
4926     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4927     //
4928     // If the declaration we're planning to build will be declared with
4929     // external linkage in the translation unit, create any builtin with
4930     // the same name.
4931     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4932       /* Do nothing*/;
4933     else if (CurContext->isFunctionOrMethod() &&
4934              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4935               R->isFunctionType())) {
4936       IsLinkageLookup = true;
4937       CreateBuiltins =
4938           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4939     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4940                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4941       CreateBuiltins = true;
4942 
4943     if (IsLinkageLookup)
4944       Previous.clear(LookupRedeclarationWithLinkage);
4945 
4946     LookupName(Previous, S, CreateBuiltins);
4947   } else { // Something like "int foo::x;"
4948     LookupQualifiedName(Previous, DC);
4949 
4950     // C++ [dcl.meaning]p1:
4951     //   When the declarator-id is qualified, the declaration shall refer to a
4952     //  previously declared member of the class or namespace to which the
4953     //  qualifier refers (or, in the case of a namespace, of an element of the
4954     //  inline namespace set of that namespace (7.3.1)) or to a specialization
4955     //  thereof; [...]
4956     //
4957     // Note that we already checked the context above, and that we do not have
4958     // enough information to make sure that Previous contains the declaration
4959     // we want to match. For example, given:
4960     //
4961     //   class X {
4962     //     void f();
4963     //     void f(float);
4964     //   };
4965     //
4966     //   void X::f(int) { } // ill-formed
4967     //
4968     // In this case, Previous will point to the overload set
4969     // containing the two f's declared in X, but neither of them
4970     // matches.
4971 
4972     // C++ [dcl.meaning]p1:
4973     //   [...] the member shall not merely have been introduced by a
4974     //   using-declaration in the scope of the class or namespace nominated by
4975     //   the nested-name-specifier of the declarator-id.
4976     RemoveUsingDecls(Previous);
4977   }
4978 
4979   if (Previous.isSingleResult() &&
4980       Previous.getFoundDecl()->isTemplateParameter()) {
4981     // Maybe we will complain about the shadowed template parameter.
4982     if (!D.isInvalidType())
4983       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4984                                       Previous.getFoundDecl());
4985 
4986     // Just pretend that we didn't see the previous declaration.
4987     Previous.clear();
4988   }
4989 
4990   // In C++, the previous declaration we find might be a tag type
4991   // (class or enum). In this case, the new declaration will hide the
4992   // tag type. Note that this does does not apply if we're declaring a
4993   // typedef (C++ [dcl.typedef]p4).
4994   if (Previous.isSingleTagDecl() &&
4995       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
4996     Previous.clear();
4997 
4998   // Check that there are no default arguments other than in the parameters
4999   // of a function declaration (C++ only).
5000   if (getLangOpts().CPlusPlus)
5001     CheckExtraCXXDefaultArguments(D);
5002 
5003   if (D.getDeclSpec().isConceptSpecified()) {
5004     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5005     // applied only to the definition of a function template or variable
5006     // template, declared in namespace scope
5007     if (!TemplateParamLists.size()) {
5008       Diag(D.getDeclSpec().getConceptSpecLoc(),
5009            diag:: err_concept_wrong_decl_kind);
5010       return nullptr;
5011     }
5012 
5013     if (!DC->getRedeclContext()->isFileContext()) {
5014       Diag(D.getIdentifierLoc(),
5015            diag::err_concept_decls_may_only_appear_in_namespace_scope);
5016       return nullptr;
5017     }
5018   }
5019 
5020   NamedDecl *New;
5021 
5022   bool AddToScope = true;
5023   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5024     if (TemplateParamLists.size()) {
5025       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5026       return nullptr;
5027     }
5028 
5029     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5030   } else if (R->isFunctionType()) {
5031     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5032                                   TemplateParamLists,
5033                                   AddToScope);
5034   } else {
5035     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5036                                   AddToScope);
5037   }
5038 
5039   if (!New)
5040     return nullptr;
5041 
5042   // If this has an identifier and is not an invalid redeclaration or
5043   // function template specialization, add it to the scope stack.
5044   if (New->getDeclName() && AddToScope &&
5045        !(D.isRedeclaration() && New->isInvalidDecl())) {
5046     // Only make a locally-scoped extern declaration visible if it is the first
5047     // declaration of this entity. Qualified lookup for such an entity should
5048     // only find this declaration if there is no visible declaration of it.
5049     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5050     PushOnScopeChains(New, S, AddToContext);
5051     if (!AddToContext)
5052       CurContext->addHiddenDecl(New);
5053   }
5054 
5055   if (isInOpenMPDeclareTargetContext())
5056     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5057 
5058   return New;
5059 }
5060 
5061 /// Helper method to turn variable array types into constant array
5062 /// types in certain situations which would otherwise be errors (for
5063 /// GCC compatibility).
5064 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5065                                                     ASTContext &Context,
5066                                                     bool &SizeIsNegative,
5067                                                     llvm::APSInt &Oversized) {
5068   // This method tries to turn a variable array into a constant
5069   // array even when the size isn't an ICE.  This is necessary
5070   // for compatibility with code that depends on gcc's buggy
5071   // constant expression folding, like struct {char x[(int)(char*)2];}
5072   SizeIsNegative = false;
5073   Oversized = 0;
5074 
5075   if (T->isDependentType())
5076     return QualType();
5077 
5078   QualifierCollector Qs;
5079   const Type *Ty = Qs.strip(T);
5080 
5081   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5082     QualType Pointee = PTy->getPointeeType();
5083     QualType FixedType =
5084         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5085                                             Oversized);
5086     if (FixedType.isNull()) return FixedType;
5087     FixedType = Context.getPointerType(FixedType);
5088     return Qs.apply(Context, FixedType);
5089   }
5090   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5091     QualType Inner = PTy->getInnerType();
5092     QualType FixedType =
5093         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5094                                             Oversized);
5095     if (FixedType.isNull()) return FixedType;
5096     FixedType = Context.getParenType(FixedType);
5097     return Qs.apply(Context, FixedType);
5098   }
5099 
5100   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5101   if (!VLATy)
5102     return QualType();
5103   // FIXME: We should probably handle this case
5104   if (VLATy->getElementType()->isVariablyModifiedType())
5105     return QualType();
5106 
5107   llvm::APSInt Res;
5108   if (!VLATy->getSizeExpr() ||
5109       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5110     return QualType();
5111 
5112   // Check whether the array size is negative.
5113   if (Res.isSigned() && Res.isNegative()) {
5114     SizeIsNegative = true;
5115     return QualType();
5116   }
5117 
5118   // Check whether the array is too large to be addressed.
5119   unsigned ActiveSizeBits
5120     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5121                                               Res);
5122   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5123     Oversized = Res;
5124     return QualType();
5125   }
5126 
5127   return Context.getConstantArrayType(VLATy->getElementType(),
5128                                       Res, ArrayType::Normal, 0);
5129 }
5130 
5131 static void
5132 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5133   SrcTL = SrcTL.getUnqualifiedLoc();
5134   DstTL = DstTL.getUnqualifiedLoc();
5135   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5136     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5137     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5138                                       DstPTL.getPointeeLoc());
5139     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5140     return;
5141   }
5142   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5143     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5144     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5145                                       DstPTL.getInnerLoc());
5146     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5147     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5148     return;
5149   }
5150   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5151   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5152   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5153   TypeLoc DstElemTL = DstATL.getElementLoc();
5154   DstElemTL.initializeFullCopy(SrcElemTL);
5155   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5156   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5157   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5158 }
5159 
5160 /// Helper method to turn variable array types into constant array
5161 /// types in certain situations which would otherwise be errors (for
5162 /// GCC compatibility).
5163 static TypeSourceInfo*
5164 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5165                                               ASTContext &Context,
5166                                               bool &SizeIsNegative,
5167                                               llvm::APSInt &Oversized) {
5168   QualType FixedTy
5169     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5170                                           SizeIsNegative, Oversized);
5171   if (FixedTy.isNull())
5172     return nullptr;
5173   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5174   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5175                                     FixedTInfo->getTypeLoc());
5176   return FixedTInfo;
5177 }
5178 
5179 /// \brief Register the given locally-scoped extern "C" declaration so
5180 /// that it can be found later for redeclarations. We include any extern "C"
5181 /// declaration that is not visible in the translation unit here, not just
5182 /// function-scope declarations.
5183 void
5184 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5185   if (!getLangOpts().CPlusPlus &&
5186       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5187     // Don't need to track declarations in the TU in C.
5188     return;
5189 
5190   // Note that we have a locally-scoped external with this name.
5191   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5192 }
5193 
5194 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5195   // FIXME: We can have multiple results via __attribute__((overloadable)).
5196   auto Result = Context.getExternCContextDecl()->lookup(Name);
5197   return Result.empty() ? nullptr : *Result.begin();
5198 }
5199 
5200 /// \brief Diagnose function specifiers on a declaration of an identifier that
5201 /// does not identify a function.
5202 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5203   // FIXME: We should probably indicate the identifier in question to avoid
5204   // confusion for constructs like "inline int a(), b;"
5205   if (DS.isInlineSpecified())
5206     Diag(DS.getInlineSpecLoc(),
5207          diag::err_inline_non_function);
5208 
5209   if (DS.isVirtualSpecified())
5210     Diag(DS.getVirtualSpecLoc(),
5211          diag::err_virtual_non_function);
5212 
5213   if (DS.isExplicitSpecified())
5214     Diag(DS.getExplicitSpecLoc(),
5215          diag::err_explicit_non_function);
5216 
5217   if (DS.isNoreturnSpecified())
5218     Diag(DS.getNoreturnSpecLoc(),
5219          diag::err_noreturn_non_function);
5220 }
5221 
5222 NamedDecl*
5223 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5224                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5225   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5226   if (D.getCXXScopeSpec().isSet()) {
5227     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5228       << D.getCXXScopeSpec().getRange();
5229     D.setInvalidType();
5230     // Pretend we didn't see the scope specifier.
5231     DC = CurContext;
5232     Previous.clear();
5233   }
5234 
5235   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5236 
5237   if (D.getDeclSpec().isConstexprSpecified())
5238     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5239       << 1;
5240   if (D.getDeclSpec().isConceptSpecified())
5241     Diag(D.getDeclSpec().getConceptSpecLoc(),
5242          diag::err_concept_wrong_decl_kind);
5243 
5244   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5245     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5246       << D.getName().getSourceRange();
5247     return nullptr;
5248   }
5249 
5250   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5251   if (!NewTD) return nullptr;
5252 
5253   // Handle attributes prior to checking for duplicates in MergeVarDecl
5254   ProcessDeclAttributes(S, NewTD, D);
5255 
5256   CheckTypedefForVariablyModifiedType(S, NewTD);
5257 
5258   bool Redeclaration = D.isRedeclaration();
5259   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5260   D.setRedeclaration(Redeclaration);
5261   return ND;
5262 }
5263 
5264 void
5265 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5266   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5267   // then it shall have block scope.
5268   // Note that variably modified types must be fixed before merging the decl so
5269   // that redeclarations will match.
5270   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5271   QualType T = TInfo->getType();
5272   if (T->isVariablyModifiedType()) {
5273     getCurFunction()->setHasBranchProtectedScope();
5274 
5275     if (S->getFnParent() == nullptr) {
5276       bool SizeIsNegative;
5277       llvm::APSInt Oversized;
5278       TypeSourceInfo *FixedTInfo =
5279         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5280                                                       SizeIsNegative,
5281                                                       Oversized);
5282       if (FixedTInfo) {
5283         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5284         NewTD->setTypeSourceInfo(FixedTInfo);
5285       } else {
5286         if (SizeIsNegative)
5287           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5288         else if (T->isVariableArrayType())
5289           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5290         else if (Oversized.getBoolValue())
5291           Diag(NewTD->getLocation(), diag::err_array_too_large)
5292             << Oversized.toString(10);
5293         else
5294           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5295         NewTD->setInvalidDecl();
5296       }
5297     }
5298   }
5299 }
5300 
5301 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5302 /// declares a typedef-name, either using the 'typedef' type specifier or via
5303 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5304 NamedDecl*
5305 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5306                            LookupResult &Previous, bool &Redeclaration) {
5307   // Merge the decl with the existing one if appropriate. If the decl is
5308   // in an outer scope, it isn't the same thing.
5309   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5310                        /*AllowInlineNamespace*/false);
5311   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5312   if (!Previous.empty()) {
5313     Redeclaration = true;
5314     MergeTypedefNameDecl(S, NewTD, Previous);
5315   }
5316 
5317   // If this is the C FILE type, notify the AST context.
5318   if (IdentifierInfo *II = NewTD->getIdentifier())
5319     if (!NewTD->isInvalidDecl() &&
5320         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5321       if (II->isStr("FILE"))
5322         Context.setFILEDecl(NewTD);
5323       else if (II->isStr("jmp_buf"))
5324         Context.setjmp_bufDecl(NewTD);
5325       else if (II->isStr("sigjmp_buf"))
5326         Context.setsigjmp_bufDecl(NewTD);
5327       else if (II->isStr("ucontext_t"))
5328         Context.setucontext_tDecl(NewTD);
5329     }
5330 
5331   return NewTD;
5332 }
5333 
5334 /// \brief Determines whether the given declaration is an out-of-scope
5335 /// previous declaration.
5336 ///
5337 /// This routine should be invoked when name lookup has found a
5338 /// previous declaration (PrevDecl) that is not in the scope where a
5339 /// new declaration by the same name is being introduced. If the new
5340 /// declaration occurs in a local scope, previous declarations with
5341 /// linkage may still be considered previous declarations (C99
5342 /// 6.2.2p4-5, C++ [basic.link]p6).
5343 ///
5344 /// \param PrevDecl the previous declaration found by name
5345 /// lookup
5346 ///
5347 /// \param DC the context in which the new declaration is being
5348 /// declared.
5349 ///
5350 /// \returns true if PrevDecl is an out-of-scope previous declaration
5351 /// for a new delcaration with the same name.
5352 static bool
5353 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5354                                 ASTContext &Context) {
5355   if (!PrevDecl)
5356     return false;
5357 
5358   if (!PrevDecl->hasLinkage())
5359     return false;
5360 
5361   if (Context.getLangOpts().CPlusPlus) {
5362     // C++ [basic.link]p6:
5363     //   If there is a visible declaration of an entity with linkage
5364     //   having the same name and type, ignoring entities declared
5365     //   outside the innermost enclosing namespace scope, the block
5366     //   scope declaration declares that same entity and receives the
5367     //   linkage of the previous declaration.
5368     DeclContext *OuterContext = DC->getRedeclContext();
5369     if (!OuterContext->isFunctionOrMethod())
5370       // This rule only applies to block-scope declarations.
5371       return false;
5372 
5373     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5374     if (PrevOuterContext->isRecord())
5375       // We found a member function: ignore it.
5376       return false;
5377 
5378     // Find the innermost enclosing namespace for the new and
5379     // previous declarations.
5380     OuterContext = OuterContext->getEnclosingNamespaceContext();
5381     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5382 
5383     // The previous declaration is in a different namespace, so it
5384     // isn't the same function.
5385     if (!OuterContext->Equals(PrevOuterContext))
5386       return false;
5387   }
5388 
5389   return true;
5390 }
5391 
5392 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5393   CXXScopeSpec &SS = D.getCXXScopeSpec();
5394   if (!SS.isSet()) return;
5395   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5396 }
5397 
5398 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5399   QualType type = decl->getType();
5400   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5401   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5402     // Various kinds of declaration aren't allowed to be __autoreleasing.
5403     unsigned kind = -1U;
5404     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5405       if (var->hasAttr<BlocksAttr>())
5406         kind = 0; // __block
5407       else if (!var->hasLocalStorage())
5408         kind = 1; // global
5409     } else if (isa<ObjCIvarDecl>(decl)) {
5410       kind = 3; // ivar
5411     } else if (isa<FieldDecl>(decl)) {
5412       kind = 2; // field
5413     }
5414 
5415     if (kind != -1U) {
5416       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5417         << kind;
5418     }
5419   } else if (lifetime == Qualifiers::OCL_None) {
5420     // Try to infer lifetime.
5421     if (!type->isObjCLifetimeType())
5422       return false;
5423 
5424     lifetime = type->getObjCARCImplicitLifetime();
5425     type = Context.getLifetimeQualifiedType(type, lifetime);
5426     decl->setType(type);
5427   }
5428 
5429   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5430     // Thread-local variables cannot have lifetime.
5431     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5432         var->getTLSKind()) {
5433       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5434         << var->getType();
5435       return true;
5436     }
5437   }
5438 
5439   return false;
5440 }
5441 
5442 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5443   // Ensure that an auto decl is deduced otherwise the checks below might cache
5444   // the wrong linkage.
5445   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5446 
5447   // 'weak' only applies to declarations with external linkage.
5448   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5449     if (!ND.isExternallyVisible()) {
5450       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5451       ND.dropAttr<WeakAttr>();
5452     }
5453   }
5454   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5455     if (ND.isExternallyVisible()) {
5456       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5457       ND.dropAttr<WeakRefAttr>();
5458       ND.dropAttr<AliasAttr>();
5459     }
5460   }
5461 
5462   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5463     if (VD->hasInit()) {
5464       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5465         assert(VD->isThisDeclarationADefinition() &&
5466                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5467         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5468         VD->dropAttr<AliasAttr>();
5469       }
5470     }
5471   }
5472 
5473   // 'selectany' only applies to externally visible variable declarations.
5474   // It does not apply to functions.
5475   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5476     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5477       S.Diag(Attr->getLocation(),
5478              diag::err_attribute_selectany_non_extern_data);
5479       ND.dropAttr<SelectAnyAttr>();
5480     }
5481   }
5482 
5483   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5484     // dll attributes require external linkage. Static locals may have external
5485     // linkage but still cannot be explicitly imported or exported.
5486     auto *VD = dyn_cast<VarDecl>(&ND);
5487     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5488       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5489         << &ND << Attr;
5490       ND.setInvalidDecl();
5491     }
5492   }
5493 
5494   // Virtual functions cannot be marked as 'notail'.
5495   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5496     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5497       if (MD->isVirtual()) {
5498         S.Diag(ND.getLocation(),
5499                diag::err_invalid_attribute_on_virtual_function)
5500             << Attr;
5501         ND.dropAttr<NotTailCalledAttr>();
5502       }
5503 }
5504 
5505 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5506                                            NamedDecl *NewDecl,
5507                                            bool IsSpecialization) {
5508   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
5509     OldDecl = OldTD->getTemplatedDecl();
5510   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5511     NewDecl = NewTD->getTemplatedDecl();
5512 
5513   if (!OldDecl || !NewDecl)
5514     return;
5515 
5516   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5517   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5518   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5519   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5520 
5521   // dllimport and dllexport are inheritable attributes so we have to exclude
5522   // inherited attribute instances.
5523   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5524                     (NewExportAttr && !NewExportAttr->isInherited());
5525 
5526   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5527   // the only exception being explicit specializations.
5528   // Implicitly generated declarations are also excluded for now because there
5529   // is no other way to switch these to use dllimport or dllexport.
5530   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5531 
5532   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5533     // Allow with a warning for free functions and global variables.
5534     bool JustWarn = false;
5535     if (!OldDecl->isCXXClassMember()) {
5536       auto *VD = dyn_cast<VarDecl>(OldDecl);
5537       if (VD && !VD->getDescribedVarTemplate())
5538         JustWarn = true;
5539       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5540       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5541         JustWarn = true;
5542     }
5543 
5544     // We cannot change a declaration that's been used because IR has already
5545     // been emitted. Dllimported functions will still work though (modulo
5546     // address equality) as they can use the thunk.
5547     if (OldDecl->isUsed())
5548       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5549         JustWarn = false;
5550 
5551     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5552                                : diag::err_attribute_dll_redeclaration;
5553     S.Diag(NewDecl->getLocation(), DiagID)
5554         << NewDecl
5555         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5556     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5557     if (!JustWarn) {
5558       NewDecl->setInvalidDecl();
5559       return;
5560     }
5561   }
5562 
5563   // A redeclaration is not allowed to drop a dllimport attribute, the only
5564   // exceptions being inline function definitions, local extern declarations,
5565   // and qualified friend declarations.
5566   // NB: MSVC converts such a declaration to dllexport.
5567   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5568   if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
5569     // Ignore static data because out-of-line definitions are diagnosed
5570     // separately.
5571     IsStaticDataMember = VD->isStaticDataMember();
5572   else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5573     IsInline = FD->isInlined();
5574     IsQualifiedFriend = FD->getQualifier() &&
5575                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5576   }
5577 
5578   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5579       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5580     S.Diag(NewDecl->getLocation(),
5581            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5582       << NewDecl << OldImportAttr;
5583     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5584     S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5585     OldDecl->dropAttr<DLLImportAttr>();
5586     NewDecl->dropAttr<DLLImportAttr>();
5587   } else if (IsInline && OldImportAttr &&
5588              !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5589     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5590     OldDecl->dropAttr<DLLImportAttr>();
5591     NewDecl->dropAttr<DLLImportAttr>();
5592     S.Diag(NewDecl->getLocation(),
5593            diag::warn_dllimport_dropped_from_inline_function)
5594         << NewDecl << OldImportAttr;
5595   }
5596 }
5597 
5598 /// Given that we are within the definition of the given function,
5599 /// will that definition behave like C99's 'inline', where the
5600 /// definition is discarded except for optimization purposes?
5601 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5602   // Try to avoid calling GetGVALinkageForFunction.
5603 
5604   // All cases of this require the 'inline' keyword.
5605   if (!FD->isInlined()) return false;
5606 
5607   // This is only possible in C++ with the gnu_inline attribute.
5608   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5609     return false;
5610 
5611   // Okay, go ahead and call the relatively-more-expensive function.
5612 
5613 #ifndef NDEBUG
5614   // AST quite reasonably asserts that it's working on a function
5615   // definition.  We don't really have a way to tell it that we're
5616   // currently defining the function, so just lie to it in +Asserts
5617   // builds.  This is an awful hack.
5618   FD->setLazyBody(1);
5619 #endif
5620 
5621   bool isC99Inline =
5622       S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5623 
5624 #ifndef NDEBUG
5625   FD->setLazyBody(0);
5626 #endif
5627 
5628   return isC99Inline;
5629 }
5630 
5631 /// Determine whether a variable is extern "C" prior to attaching
5632 /// an initializer. We can't just call isExternC() here, because that
5633 /// will also compute and cache whether the declaration is externally
5634 /// visible, which might change when we attach the initializer.
5635 ///
5636 /// This can only be used if the declaration is known to not be a
5637 /// redeclaration of an internal linkage declaration.
5638 ///
5639 /// For instance:
5640 ///
5641 ///   auto x = []{};
5642 ///
5643 /// Attaching the initializer here makes this declaration not externally
5644 /// visible, because its type has internal linkage.
5645 ///
5646 /// FIXME: This is a hack.
5647 template<typename T>
5648 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5649   if (S.getLangOpts().CPlusPlus) {
5650     // In C++, the overloadable attribute negates the effects of extern "C".
5651     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5652       return false;
5653 
5654     // So do CUDA's host/device attributes.
5655     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
5656                                  D->template hasAttr<CUDAHostAttr>()))
5657       return false;
5658   }
5659   return D->isExternC();
5660 }
5661 
5662 static bool shouldConsiderLinkage(const VarDecl *VD) {
5663   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5664   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
5665     return VD->hasExternalStorage();
5666   if (DC->isFileContext())
5667     return true;
5668   if (DC->isRecord())
5669     return false;
5670   llvm_unreachable("Unexpected context");
5671 }
5672 
5673 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5674   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5675   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
5676       isa<OMPDeclareReductionDecl>(DC))
5677     return true;
5678   if (DC->isRecord())
5679     return false;
5680   llvm_unreachable("Unexpected context");
5681 }
5682 
5683 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5684                           AttributeList::Kind Kind) {
5685   for (const AttributeList *L = AttrList; L; L = L->getNext())
5686     if (L->getKind() == Kind)
5687       return true;
5688   return false;
5689 }
5690 
5691 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5692                           AttributeList::Kind Kind) {
5693   // Check decl attributes on the DeclSpec.
5694   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5695     return true;
5696 
5697   // Walk the declarator structure, checking decl attributes that were in a type
5698   // position to the decl itself.
5699   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5700     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5701       return true;
5702   }
5703 
5704   // Finally, check attributes on the decl itself.
5705   return hasParsedAttr(S, PD.getAttributes(), Kind);
5706 }
5707 
5708 /// Adjust the \c DeclContext for a function or variable that might be a
5709 /// function-local external declaration.
5710 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5711   if (!DC->isFunctionOrMethod())
5712     return false;
5713 
5714   // If this is a local extern function or variable declared within a function
5715   // template, don't add it into the enclosing namespace scope until it is
5716   // instantiated; it might have a dependent type right now.
5717   if (DC->isDependentContext())
5718     return true;
5719 
5720   // C++11 [basic.link]p7:
5721   //   When a block scope declaration of an entity with linkage is not found to
5722   //   refer to some other declaration, then that entity is a member of the
5723   //   innermost enclosing namespace.
5724   //
5725   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5726   // semantically-enclosing namespace, not a lexically-enclosing one.
5727   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5728     DC = DC->getParent();
5729   return true;
5730 }
5731 
5732 /// \brief Returns true if given declaration has external C language linkage.
5733 static bool isDeclExternC(const Decl *D) {
5734   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5735     return FD->isExternC();
5736   if (const auto *VD = dyn_cast<VarDecl>(D))
5737     return VD->isExternC();
5738 
5739   llvm_unreachable("Unknown type of decl!");
5740 }
5741 
5742 NamedDecl *
5743 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5744                               TypeSourceInfo *TInfo, LookupResult &Previous,
5745                               MultiTemplateParamsArg TemplateParamLists,
5746                               bool &AddToScope) {
5747   QualType R = TInfo->getType();
5748   DeclarationName Name = GetNameForDeclarator(D).getName();
5749 
5750   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
5751   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
5752   // argument.
5753   if (getLangOpts().OpenCL && (R->isImageType() || R->isPipeType())) {
5754     Diag(D.getIdentifierLoc(),
5755          diag::err_opencl_type_can_only_be_used_as_function_parameter)
5756         << R;
5757     D.setInvalidType();
5758     return nullptr;
5759   }
5760 
5761   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5762   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5763 
5764   // dllimport globals without explicit storage class are treated as extern. We
5765   // have to change the storage class this early to get the right DeclContext.
5766   if (SC == SC_None && !DC->isRecord() &&
5767       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5768       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5769     SC = SC_Extern;
5770 
5771   DeclContext *OriginalDC = DC;
5772   bool IsLocalExternDecl = SC == SC_Extern &&
5773                            adjustContextForLocalExternDecl(DC);
5774 
5775   if (getLangOpts().OpenCL) {
5776     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5777     QualType NR = R;
5778     while (NR->isPointerType()) {
5779       if (NR->isFunctionPointerType()) {
5780         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5781         D.setInvalidType();
5782         break;
5783       }
5784       NR = NR->getPointeeType();
5785     }
5786 
5787     if (!getOpenCLOptions().cl_khr_fp16) {
5788       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5789       // half array type (unless the cl_khr_fp16 extension is enabled).
5790       if (Context.getBaseElementType(R)->isHalfType()) {
5791         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5792         D.setInvalidType();
5793       }
5794     }
5795   }
5796 
5797   if (SCSpec == DeclSpec::SCS_mutable) {
5798     // mutable can only appear on non-static class members, so it's always
5799     // an error here
5800     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5801     D.setInvalidType();
5802     SC = SC_None;
5803   }
5804 
5805   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5806       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5807                               D.getDeclSpec().getStorageClassSpecLoc())) {
5808     // In C++11, the 'register' storage class specifier is deprecated.
5809     // Suppress the warning in system macros, it's used in macros in some
5810     // popular C system headers, such as in glibc's htonl() macro.
5811     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5812          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
5813                                    : diag::warn_deprecated_register)
5814       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5815   }
5816 
5817   IdentifierInfo *II = Name.getAsIdentifierInfo();
5818   if (!II) {
5819     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5820       << Name;
5821     return nullptr;
5822   }
5823 
5824   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5825 
5826   if (!DC->isRecord() && S->getFnParent() == nullptr) {
5827     // C99 6.9p2: The storage-class specifiers auto and register shall not
5828     // appear in the declaration specifiers in an external declaration.
5829     // Global Register+Asm is a GNU extension we support.
5830     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5831       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5832       D.setInvalidType();
5833     }
5834   }
5835 
5836   if (getLangOpts().OpenCL) {
5837     // OpenCL v1.2 s6.9.b p4:
5838     // The sampler type cannot be used with the __local and __global address
5839     // space qualifiers.
5840     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5841       R.getAddressSpace() == LangAS::opencl_global)) {
5842       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5843     }
5844 
5845     // OpenCL 1.2 spec, p6.9 r:
5846     // The event type cannot be used to declare a program scope variable.
5847     // The event type cannot be used with the __local, __constant and __global
5848     // address space qualifiers.
5849     if (R->isEventT()) {
5850       if (S->getParent() == nullptr) {
5851         Diag(D.getLocStart(), diag::err_event_t_global_var);
5852         D.setInvalidType();
5853       }
5854 
5855       if (R.getAddressSpace()) {
5856         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5857         D.setInvalidType();
5858       }
5859     }
5860   }
5861 
5862   bool IsExplicitSpecialization = false;
5863   bool IsVariableTemplateSpecialization = false;
5864   bool IsPartialSpecialization = false;
5865   bool IsVariableTemplate = false;
5866   VarDecl *NewVD = nullptr;
5867   VarTemplateDecl *NewTemplate = nullptr;
5868   TemplateParameterList *TemplateParams = nullptr;
5869   if (!getLangOpts().CPlusPlus) {
5870     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5871                             D.getIdentifierLoc(), II,
5872                             R, TInfo, SC);
5873 
5874     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5875       ParsingInitForAutoVars.insert(NewVD);
5876 
5877     if (D.isInvalidType())
5878       NewVD->setInvalidDecl();
5879   } else {
5880     bool Invalid = false;
5881 
5882     if (DC->isRecord() && !CurContext->isRecord()) {
5883       // This is an out-of-line definition of a static data member.
5884       switch (SC) {
5885       case SC_None:
5886         break;
5887       case SC_Static:
5888         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5889              diag::err_static_out_of_line)
5890           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5891         break;
5892       case SC_Auto:
5893       case SC_Register:
5894       case SC_Extern:
5895         // [dcl.stc] p2: The auto or register specifiers shall be applied only
5896         // to names of variables declared in a block or to function parameters.
5897         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5898         // of class members
5899 
5900         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5901              diag::err_storage_class_for_static_member)
5902           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5903         break;
5904       case SC_PrivateExtern:
5905         llvm_unreachable("C storage class in c++!");
5906       }
5907     }
5908 
5909     if (SC == SC_Static && CurContext->isRecord()) {
5910       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5911         if (RD->isLocalClass())
5912           Diag(D.getIdentifierLoc(),
5913                diag::err_static_data_member_not_allowed_in_local_class)
5914             << Name << RD->getDeclName();
5915 
5916         // C++98 [class.union]p1: If a union contains a static data member,
5917         // the program is ill-formed. C++11 drops this restriction.
5918         if (RD->isUnion())
5919           Diag(D.getIdentifierLoc(),
5920                getLangOpts().CPlusPlus11
5921                  ? diag::warn_cxx98_compat_static_data_member_in_union
5922                  : diag::ext_static_data_member_in_union) << Name;
5923         // We conservatively disallow static data members in anonymous structs.
5924         else if (!RD->getDeclName())
5925           Diag(D.getIdentifierLoc(),
5926                diag::err_static_data_member_not_allowed_in_anon_struct)
5927             << Name << RD->isUnion();
5928       }
5929     }
5930 
5931     // Match up the template parameter lists with the scope specifier, then
5932     // determine whether we have a template or a template specialization.
5933     TemplateParams = MatchTemplateParametersToScopeSpecifier(
5934         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5935         D.getCXXScopeSpec(),
5936         D.getName().getKind() == UnqualifiedId::IK_TemplateId
5937             ? D.getName().TemplateId
5938             : nullptr,
5939         TemplateParamLists,
5940         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5941 
5942     if (TemplateParams) {
5943       if (!TemplateParams->size() &&
5944           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5945         // There is an extraneous 'template<>' for this variable. Complain
5946         // about it, but allow the declaration of the variable.
5947         Diag(TemplateParams->getTemplateLoc(),
5948              diag::err_template_variable_noparams)
5949           << II
5950           << SourceRange(TemplateParams->getTemplateLoc(),
5951                          TemplateParams->getRAngleLoc());
5952         TemplateParams = nullptr;
5953       } else {
5954         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5955           // This is an explicit specialization or a partial specialization.
5956           // FIXME: Check that we can declare a specialization here.
5957           IsVariableTemplateSpecialization = true;
5958           IsPartialSpecialization = TemplateParams->size() > 0;
5959         } else { // if (TemplateParams->size() > 0)
5960           // This is a template declaration.
5961           IsVariableTemplate = true;
5962 
5963           // Check that we can declare a template here.
5964           if (CheckTemplateDeclScope(S, TemplateParams))
5965             return nullptr;
5966 
5967           // Only C++1y supports variable templates (N3651).
5968           Diag(D.getIdentifierLoc(),
5969                getLangOpts().CPlusPlus14
5970                    ? diag::warn_cxx11_compat_variable_template
5971                    : diag::ext_variable_template);
5972         }
5973       }
5974     } else {
5975       assert(
5976           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
5977           "should have a 'template<>' for this decl");
5978     }
5979 
5980     if (IsVariableTemplateSpecialization) {
5981       SourceLocation TemplateKWLoc =
5982           TemplateParamLists.size() > 0
5983               ? TemplateParamLists[0]->getTemplateLoc()
5984               : SourceLocation();
5985       DeclResult Res = ActOnVarTemplateSpecialization(
5986           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5987           IsPartialSpecialization);
5988       if (Res.isInvalid())
5989         return nullptr;
5990       NewVD = cast<VarDecl>(Res.get());
5991       AddToScope = false;
5992     } else
5993       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5994                               D.getIdentifierLoc(), II, R, TInfo, SC);
5995 
5996     // If this is supposed to be a variable template, create it as such.
5997     if (IsVariableTemplate) {
5998       NewTemplate =
5999           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6000                                   TemplateParams, NewVD);
6001       NewVD->setDescribedVarTemplate(NewTemplate);
6002     }
6003 
6004     // If this decl has an auto type in need of deduction, make a note of the
6005     // Decl so we can diagnose uses of it in its own initializer.
6006     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
6007       ParsingInitForAutoVars.insert(NewVD);
6008 
6009     if (D.isInvalidType() || Invalid) {
6010       NewVD->setInvalidDecl();
6011       if (NewTemplate)
6012         NewTemplate->setInvalidDecl();
6013     }
6014 
6015     SetNestedNameSpecifier(NewVD, D);
6016 
6017     // If we have any template parameter lists that don't directly belong to
6018     // the variable (matching the scope specifier), store them.
6019     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6020     if (TemplateParamLists.size() > VDTemplateParamLists)
6021       NewVD->setTemplateParameterListsInfo(
6022           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6023 
6024     if (D.getDeclSpec().isConstexprSpecified())
6025       NewVD->setConstexpr(true);
6026 
6027     if (D.getDeclSpec().isConceptSpecified()) {
6028       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6029         VTD->setConcept();
6030 
6031       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6032       // be declared with the thread_local, inline, friend, or constexpr
6033       // specifiers, [...]
6034       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6035         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6036              diag::err_concept_decl_invalid_specifiers)
6037             << 0 << 0;
6038         NewVD->setInvalidDecl(true);
6039       }
6040 
6041       if (D.getDeclSpec().isConstexprSpecified()) {
6042         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6043              diag::err_concept_decl_invalid_specifiers)
6044             << 0 << 3;
6045         NewVD->setInvalidDecl(true);
6046       }
6047 
6048       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6049       // applied only to the definition of a function template or variable
6050       // template, declared in namespace scope.
6051       if (IsVariableTemplateSpecialization) {
6052         Diag(D.getDeclSpec().getConceptSpecLoc(),
6053              diag::err_concept_specified_specialization)
6054             << (IsPartialSpecialization ? 2 : 1);
6055       }
6056 
6057       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6058       // following restrictions:
6059       // - The declared type shall have the type bool.
6060       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6061           !NewVD->isInvalidDecl()) {
6062         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6063         NewVD->setInvalidDecl(true);
6064       }
6065     }
6066   }
6067 
6068   // Set the lexical context. If the declarator has a C++ scope specifier, the
6069   // lexical context will be different from the semantic context.
6070   NewVD->setLexicalDeclContext(CurContext);
6071   if (NewTemplate)
6072     NewTemplate->setLexicalDeclContext(CurContext);
6073 
6074   if (IsLocalExternDecl)
6075     NewVD->setLocalExternDecl();
6076 
6077   bool EmitTLSUnsupportedError = false;
6078   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6079     // C++11 [dcl.stc]p4:
6080     //   When thread_local is applied to a variable of block scope the
6081     //   storage-class-specifier static is implied if it does not appear
6082     //   explicitly.
6083     // Core issue: 'static' is not implied if the variable is declared
6084     //   'extern'.
6085     if (NewVD->hasLocalStorage() &&
6086         (SCSpec != DeclSpec::SCS_unspecified ||
6087          TSCS != DeclSpec::TSCS_thread_local ||
6088          !DC->isFunctionOrMethod()))
6089       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6090            diag::err_thread_non_global)
6091         << DeclSpec::getSpecifierName(TSCS);
6092     else if (!Context.getTargetInfo().isTLSSupported()) {
6093       if (getLangOpts().CUDA) {
6094         // Postpone error emission until we've collected attributes required to
6095         // figure out whether it's a host or device variable and whether the
6096         // error should be ignored.
6097         EmitTLSUnsupportedError = true;
6098         // We still need to mark the variable as TLS so it shows up in AST with
6099         // proper storage class for other tools to use even if we're not going
6100         // to emit any code for it.
6101         NewVD->setTSCSpec(TSCS);
6102       } else
6103         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6104              diag::err_thread_unsupported);
6105     } else
6106       NewVD->setTSCSpec(TSCS);
6107   }
6108 
6109   // C99 6.7.4p3
6110   //   An inline definition of a function with external linkage shall
6111   //   not contain a definition of a modifiable object with static or
6112   //   thread storage duration...
6113   // We only apply this when the function is required to be defined
6114   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6115   // that a local variable with thread storage duration still has to
6116   // be marked 'static'.  Also note that it's possible to get these
6117   // semantics in C++ using __attribute__((gnu_inline)).
6118   if (SC == SC_Static && S->getFnParent() != nullptr &&
6119       !NewVD->getType().isConstQualified()) {
6120     FunctionDecl *CurFD = getCurFunctionDecl();
6121     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6122       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6123            diag::warn_static_local_in_extern_inline);
6124       MaybeSuggestAddingStaticToDecl(CurFD);
6125     }
6126   }
6127 
6128   if (D.getDeclSpec().isModulePrivateSpecified()) {
6129     if (IsVariableTemplateSpecialization)
6130       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6131           << (IsPartialSpecialization ? 1 : 0)
6132           << FixItHint::CreateRemoval(
6133                  D.getDeclSpec().getModulePrivateSpecLoc());
6134     else if (IsExplicitSpecialization)
6135       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6136         << 2
6137         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6138     else if (NewVD->hasLocalStorage())
6139       Diag(NewVD->getLocation(), diag::err_module_private_local)
6140         << 0 << NewVD->getDeclName()
6141         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6142         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6143     else {
6144       NewVD->setModulePrivate();
6145       if (NewTemplate)
6146         NewTemplate->setModulePrivate();
6147     }
6148   }
6149 
6150   // Handle attributes prior to checking for duplicates in MergeVarDecl
6151   ProcessDeclAttributes(S, NewVD, D);
6152 
6153   if (getLangOpts().CUDA) {
6154     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6155       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6156            diag::err_thread_unsupported);
6157     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6158     // storage [duration]."
6159     if (SC == SC_None && S->getFnParent() != nullptr &&
6160         (NewVD->hasAttr<CUDASharedAttr>() ||
6161          NewVD->hasAttr<CUDAConstantAttr>())) {
6162       NewVD->setStorageClass(SC_Static);
6163     }
6164   }
6165 
6166   // Ensure that dllimport globals without explicit storage class are treated as
6167   // extern. The storage class is set above using parsed attributes. Now we can
6168   // check the VarDecl itself.
6169   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6170          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6171          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6172 
6173   // In auto-retain/release, infer strong retension for variables of
6174   // retainable type.
6175   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6176     NewVD->setInvalidDecl();
6177 
6178   // Handle GNU asm-label extension (encoded as an attribute).
6179   if (Expr *E = (Expr*)D.getAsmLabel()) {
6180     // The parser guarantees this is a string.
6181     StringLiteral *SE = cast<StringLiteral>(E);
6182     StringRef Label = SE->getString();
6183     if (S->getFnParent() != nullptr) {
6184       switch (SC) {
6185       case SC_None:
6186       case SC_Auto:
6187         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6188         break;
6189       case SC_Register:
6190         // Local Named register
6191         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6192             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6193           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6194         break;
6195       case SC_Static:
6196       case SC_Extern:
6197       case SC_PrivateExtern:
6198         break;
6199       }
6200     } else if (SC == SC_Register) {
6201       // Global Named register
6202       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6203         const auto &TI = Context.getTargetInfo();
6204         bool HasSizeMismatch;
6205 
6206         if (!TI.isValidGCCRegisterName(Label))
6207           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6208         else if (!TI.validateGlobalRegisterVariable(Label,
6209                                                     Context.getTypeSize(R),
6210                                                     HasSizeMismatch))
6211           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6212         else if (HasSizeMismatch)
6213           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6214       }
6215 
6216       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6217         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6218         NewVD->setInvalidDecl(true);
6219       }
6220     }
6221 
6222     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6223                                                 Context, Label, 0));
6224   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6225     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6226       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6227     if (I != ExtnameUndeclaredIdentifiers.end()) {
6228       if (isDeclExternC(NewVD)) {
6229         NewVD->addAttr(I->second);
6230         ExtnameUndeclaredIdentifiers.erase(I);
6231       } else
6232         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6233             << /*Variable*/1 << NewVD;
6234     }
6235   }
6236 
6237   // Diagnose shadowed variables before filtering for scope.
6238   if (D.getCXXScopeSpec().isEmpty())
6239     CheckShadow(S, NewVD, Previous);
6240 
6241   // Don't consider existing declarations that are in a different
6242   // scope and are out-of-semantic-context declarations (if the new
6243   // declaration has linkage).
6244   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6245                        D.getCXXScopeSpec().isNotEmpty() ||
6246                        IsExplicitSpecialization ||
6247                        IsVariableTemplateSpecialization);
6248 
6249   // Check whether the previous declaration is in the same block scope. This
6250   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6251   if (getLangOpts().CPlusPlus &&
6252       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6253     NewVD->setPreviousDeclInSameBlockScope(
6254         Previous.isSingleResult() && !Previous.isShadowed() &&
6255         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6256 
6257   if (!getLangOpts().CPlusPlus) {
6258     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6259   } else {
6260     // If this is an explicit specialization of a static data member, check it.
6261     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6262         CheckMemberSpecialization(NewVD, Previous))
6263       NewVD->setInvalidDecl();
6264 
6265     // Merge the decl with the existing one if appropriate.
6266     if (!Previous.empty()) {
6267       if (Previous.isSingleResult() &&
6268           isa<FieldDecl>(Previous.getFoundDecl()) &&
6269           D.getCXXScopeSpec().isSet()) {
6270         // The user tried to define a non-static data member
6271         // out-of-line (C++ [dcl.meaning]p1).
6272         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6273           << D.getCXXScopeSpec().getRange();
6274         Previous.clear();
6275         NewVD->setInvalidDecl();
6276       }
6277     } else if (D.getCXXScopeSpec().isSet()) {
6278       // No previous declaration in the qualifying scope.
6279       Diag(D.getIdentifierLoc(), diag::err_no_member)
6280         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6281         << D.getCXXScopeSpec().getRange();
6282       NewVD->setInvalidDecl();
6283     }
6284 
6285     if (!IsVariableTemplateSpecialization)
6286       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6287 
6288     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6289     // an explicit specialization (14.8.3) or a partial specialization of a
6290     // concept definition.
6291     if (IsVariableTemplateSpecialization &&
6292         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6293         Previous.isSingleResult()) {
6294       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6295       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6296         if (VarTmpl->isConcept()) {
6297           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6298               << 1                            /*variable*/
6299               << (IsPartialSpecialization ? 2 /*partially specialized*/
6300                                           : 1 /*explicitly specialized*/);
6301           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6302           NewVD->setInvalidDecl();
6303         }
6304       }
6305     }
6306 
6307     if (NewTemplate) {
6308       VarTemplateDecl *PrevVarTemplate =
6309           NewVD->getPreviousDecl()
6310               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6311               : nullptr;
6312 
6313       // Check the template parameter list of this declaration, possibly
6314       // merging in the template parameter list from the previous variable
6315       // template declaration.
6316       if (CheckTemplateParameterList(
6317               TemplateParams,
6318               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6319                               : nullptr,
6320               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6321                DC->isDependentContext())
6322                   ? TPC_ClassTemplateMember
6323                   : TPC_VarTemplate))
6324         NewVD->setInvalidDecl();
6325 
6326       // If we are providing an explicit specialization of a static variable
6327       // template, make a note of that.
6328       if (PrevVarTemplate &&
6329           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6330         PrevVarTemplate->setMemberSpecialization();
6331     }
6332   }
6333 
6334   ProcessPragmaWeak(S, NewVD);
6335 
6336   // If this is the first declaration of an extern C variable, update
6337   // the map of such variables.
6338   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6339       isIncompleteDeclExternC(*this, NewVD))
6340     RegisterLocallyScopedExternCDecl(NewVD, S);
6341 
6342   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6343     Decl *ManglingContextDecl;
6344     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6345             NewVD->getDeclContext(), ManglingContextDecl)) {
6346       Context.setManglingNumber(
6347           NewVD, MCtx->getManglingNumber(
6348                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6349       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6350     }
6351   }
6352 
6353   // Special handling of variable named 'main'.
6354   if (Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main") &&
6355       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6356       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6357 
6358     // C++ [basic.start.main]p3
6359     // A program that declares a variable main at global scope is ill-formed.
6360     if (getLangOpts().CPlusPlus)
6361       Diag(D.getLocStart(), diag::err_main_global_variable);
6362 
6363     // In C, and external-linkage variable named main results in undefined
6364     // behavior.
6365     else if (NewVD->hasExternalFormalLinkage())
6366       Diag(D.getLocStart(), diag::warn_main_redefined);
6367   }
6368 
6369   if (D.isRedeclaration() && !Previous.empty()) {
6370     checkDLLAttributeRedeclaration(
6371         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6372         IsExplicitSpecialization);
6373   }
6374 
6375   if (NewTemplate) {
6376     if (NewVD->isInvalidDecl())
6377       NewTemplate->setInvalidDecl();
6378     ActOnDocumentableDecl(NewTemplate);
6379     return NewTemplate;
6380   }
6381 
6382   return NewVD;
6383 }
6384 
6385 /// \brief Diagnose variable or built-in function shadowing.  Implements
6386 /// -Wshadow.
6387 ///
6388 /// This method is called whenever a VarDecl is added to a "useful"
6389 /// scope.
6390 ///
6391 /// \param S the scope in which the shadowing name is being declared
6392 /// \param R the lookup of the name
6393 ///
6394 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
6395   // Return if warning is ignored.
6396   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6397     return;
6398 
6399   // Don't diagnose declarations at file scope.
6400   if (D->hasGlobalStorage())
6401     return;
6402 
6403   DeclContext *NewDC = D->getDeclContext();
6404 
6405   // Only diagnose if we're shadowing an unambiguous field or variable.
6406   if (R.getResultKind() != LookupResult::Found)
6407     return;
6408 
6409   NamedDecl* ShadowedDecl = R.getFoundDecl();
6410   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
6411     return;
6412 
6413   // Fields are not shadowed by variables in C++ static methods.
6414   if (isa<FieldDecl>(ShadowedDecl))
6415     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6416       if (MD->isStatic())
6417         return;
6418 
6419   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6420     if (shadowedVar->isExternC()) {
6421       // For shadowing external vars, make sure that we point to the global
6422       // declaration, not a locally scoped extern declaration.
6423       for (auto I : shadowedVar->redecls())
6424         if (I->isFileVarDecl()) {
6425           ShadowedDecl = I;
6426           break;
6427         }
6428     }
6429 
6430   DeclContext *OldDC = ShadowedDecl->getDeclContext();
6431 
6432   // Only warn about certain kinds of shadowing for class members.
6433   if (NewDC && NewDC->isRecord()) {
6434     // In particular, don't warn about shadowing non-class members.
6435     if (!OldDC->isRecord())
6436       return;
6437 
6438     // TODO: should we warn about static data members shadowing
6439     // static data members from base classes?
6440 
6441     // TODO: don't diagnose for inaccessible shadowed members.
6442     // This is hard to do perfectly because we might friend the
6443     // shadowing context, but that's just a false negative.
6444   }
6445 
6446   // Determine what kind of declaration we're shadowing.
6447 
6448   // The order must be consistent with the %select in the warning message.
6449   enum ShadowedDeclKind { Local, Global, StaticMember, Field };
6450   ShadowedDeclKind Kind;
6451   if (isa<RecordDecl>(OldDC)) {
6452     if (isa<FieldDecl>(ShadowedDecl))
6453       Kind = Field;
6454     else
6455       Kind = StaticMember;
6456   } else if (OldDC->isFileContext()) {
6457     Kind = Global;
6458   } else {
6459     Kind = Local;
6460   }
6461 
6462   DeclarationName Name = R.getLookupName();
6463 
6464   // Emit warning and note.
6465   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6466     return;
6467   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
6468   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6469 }
6470 
6471 /// \brief Check -Wshadow without the advantage of a previous lookup.
6472 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6473   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6474     return;
6475 
6476   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6477                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6478   LookupName(R, S);
6479   CheckShadow(S, D, R);
6480 }
6481 
6482 /// Check for conflict between this global or extern "C" declaration and
6483 /// previous global or extern "C" declarations. This is only used in C++.
6484 template<typename T>
6485 static bool checkGlobalOrExternCConflict(
6486     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6487   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6488   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6489 
6490   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6491     // The common case: this global doesn't conflict with any extern "C"
6492     // declaration.
6493     return false;
6494   }
6495 
6496   if (Prev) {
6497     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6498       // Both the old and new declarations have C language linkage. This is a
6499       // redeclaration.
6500       Previous.clear();
6501       Previous.addDecl(Prev);
6502       return true;
6503     }
6504 
6505     // This is a global, non-extern "C" declaration, and there is a previous
6506     // non-global extern "C" declaration. Diagnose if this is a variable
6507     // declaration.
6508     if (!isa<VarDecl>(ND))
6509       return false;
6510   } else {
6511     // The declaration is extern "C". Check for any declaration in the
6512     // translation unit which might conflict.
6513     if (IsGlobal) {
6514       // We have already performed the lookup into the translation unit.
6515       IsGlobal = false;
6516       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6517            I != E; ++I) {
6518         if (isa<VarDecl>(*I)) {
6519           Prev = *I;
6520           break;
6521         }
6522       }
6523     } else {
6524       DeclContext::lookup_result R =
6525           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6526       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6527            I != E; ++I) {
6528         if (isa<VarDecl>(*I)) {
6529           Prev = *I;
6530           break;
6531         }
6532         // FIXME: If we have any other entity with this name in global scope,
6533         // the declaration is ill-formed, but that is a defect: it breaks the
6534         // 'stat' hack, for instance. Only variables can have mangled name
6535         // clashes with extern "C" declarations, so only they deserve a
6536         // diagnostic.
6537       }
6538     }
6539 
6540     if (!Prev)
6541       return false;
6542   }
6543 
6544   // Use the first declaration's location to ensure we point at something which
6545   // is lexically inside an extern "C" linkage-spec.
6546   assert(Prev && "should have found a previous declaration to diagnose");
6547   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6548     Prev = FD->getFirstDecl();
6549   else
6550     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6551 
6552   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6553     << IsGlobal << ND;
6554   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6555     << IsGlobal;
6556   return false;
6557 }
6558 
6559 /// Apply special rules for handling extern "C" declarations. Returns \c true
6560 /// if we have found that this is a redeclaration of some prior entity.
6561 ///
6562 /// Per C++ [dcl.link]p6:
6563 ///   Two declarations [for a function or variable] with C language linkage
6564 ///   with the same name that appear in different scopes refer to the same
6565 ///   [entity]. An entity with C language linkage shall not be declared with
6566 ///   the same name as an entity in global scope.
6567 template<typename T>
6568 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6569                                                   LookupResult &Previous) {
6570   if (!S.getLangOpts().CPlusPlus) {
6571     // In C, when declaring a global variable, look for a corresponding 'extern'
6572     // variable declared in function scope. We don't need this in C++, because
6573     // we find local extern decls in the surrounding file-scope DeclContext.
6574     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6575       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6576         Previous.clear();
6577         Previous.addDecl(Prev);
6578         return true;
6579       }
6580     }
6581     return false;
6582   }
6583 
6584   // A declaration in the translation unit can conflict with an extern "C"
6585   // declaration.
6586   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6587     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6588 
6589   // An extern "C" declaration can conflict with a declaration in the
6590   // translation unit or can be a redeclaration of an extern "C" declaration
6591   // in another scope.
6592   if (isIncompleteDeclExternC(S,ND))
6593     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6594 
6595   // Neither global nor extern "C": nothing to do.
6596   return false;
6597 }
6598 
6599 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6600   // If the decl is already known invalid, don't check it.
6601   if (NewVD->isInvalidDecl())
6602     return;
6603 
6604   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6605   QualType T = TInfo->getType();
6606 
6607   // Defer checking an 'auto' type until its initializer is attached.
6608   if (T->isUndeducedType())
6609     return;
6610 
6611   if (NewVD->hasAttrs())
6612     CheckAlignasUnderalignment(NewVD);
6613 
6614   if (T->isObjCObjectType()) {
6615     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6616       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6617     T = Context.getObjCObjectPointerType(T);
6618     NewVD->setType(T);
6619   }
6620 
6621   // Emit an error if an address space was applied to decl with local storage.
6622   // This includes arrays of objects with address space qualifiers, but not
6623   // automatic variables that point to other address spaces.
6624   // ISO/IEC TR 18037 S5.1.2
6625   if (!getLangOpts().OpenCL
6626       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6627     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6628     NewVD->setInvalidDecl();
6629     return;
6630   }
6631 
6632   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
6633   // scope.
6634   if (getLangOpts().OpenCLVersion == 120 &&
6635       !getOpenCLOptions().cl_clang_storage_class_specifiers &&
6636       NewVD->isStaticLocal()) {
6637     Diag(NewVD->getLocation(), diag::err_static_function_scope);
6638     NewVD->setInvalidDecl();
6639     return;
6640   }
6641 
6642   if (getLangOpts().OpenCL) {
6643     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
6644     if (NewVD->hasAttr<BlocksAttr>()) {
6645       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
6646       return;
6647     }
6648 
6649     if (T->isBlockPointerType()) {
6650       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
6651       // can't use 'extern' storage class.
6652       if (!T.isConstQualified()) {
6653         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
6654             << 0 /*const*/;
6655         NewVD->setInvalidDecl();
6656         return;
6657       }
6658       if (NewVD->hasExternalStorage()) {
6659         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
6660         NewVD->setInvalidDecl();
6661         return;
6662       }
6663       // OpenCL v2.0 s6.12.5 - Blocks with variadic arguments are not supported.
6664       // TODO: this check is not enough as it doesn't diagnose the typedef
6665       const BlockPointerType *BlkTy = T->getAs<BlockPointerType>();
6666       const FunctionProtoType *FTy =
6667           BlkTy->getPointeeType()->getAs<FunctionProtoType>();
6668       if (FTy && FTy->isVariadic()) {
6669         Diag(NewVD->getLocation(), diag::err_opencl_block_proto_variadic)
6670             << T << NewVD->getSourceRange();
6671         NewVD->setInvalidDecl();
6672         return;
6673       }
6674     }
6675     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6676     // __constant address space.
6677     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6678     // variables inside a function can also be declared in the global
6679     // address space.
6680     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
6681         NewVD->hasExternalStorage()) {
6682       if (!T->isSamplerT() &&
6683           !(T.getAddressSpace() == LangAS::opencl_constant ||
6684             (T.getAddressSpace() == LangAS::opencl_global &&
6685              getLangOpts().OpenCLVersion == 200))) {
6686         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
6687         if (getLangOpts().OpenCLVersion == 200)
6688           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6689               << Scope << "global or constant";
6690         else
6691           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6692               << Scope << "constant";
6693         NewVD->setInvalidDecl();
6694         return;
6695       }
6696     } else {
6697       if (T.getAddressSpace() == LangAS::opencl_global) {
6698         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6699             << 1 /*is any function*/ << "global";
6700         NewVD->setInvalidDecl();
6701         return;
6702       }
6703       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
6704       // in functions.
6705       if (T.getAddressSpace() == LangAS::opencl_constant ||
6706           T.getAddressSpace() == LangAS::opencl_local) {
6707         FunctionDecl *FD = getCurFunctionDecl();
6708         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
6709           if (T.getAddressSpace() == LangAS::opencl_constant)
6710             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6711                 << 0 /*non-kernel only*/ << "constant";
6712           else
6713             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6714                 << 0 /*non-kernel only*/ << "local";
6715           NewVD->setInvalidDecl();
6716           return;
6717         }
6718       }
6719     }
6720   }
6721 
6722   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6723       && !NewVD->hasAttr<BlocksAttr>()) {
6724     if (getLangOpts().getGC() != LangOptions::NonGC)
6725       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6726     else {
6727       assert(!getLangOpts().ObjCAutoRefCount);
6728       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6729     }
6730   }
6731 
6732   bool isVM = T->isVariablyModifiedType();
6733   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6734       NewVD->hasAttr<BlocksAttr>())
6735     getCurFunction()->setHasBranchProtectedScope();
6736 
6737   if ((isVM && NewVD->hasLinkage()) ||
6738       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6739     bool SizeIsNegative;
6740     llvm::APSInt Oversized;
6741     TypeSourceInfo *FixedTInfo =
6742       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6743                                                     SizeIsNegative, Oversized);
6744     if (!FixedTInfo && T->isVariableArrayType()) {
6745       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6746       // FIXME: This won't give the correct result for
6747       // int a[10][n];
6748       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6749 
6750       if (NewVD->isFileVarDecl())
6751         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6752         << SizeRange;
6753       else if (NewVD->isStaticLocal())
6754         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6755         << SizeRange;
6756       else
6757         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6758         << SizeRange;
6759       NewVD->setInvalidDecl();
6760       return;
6761     }
6762 
6763     if (!FixedTInfo) {
6764       if (NewVD->isFileVarDecl())
6765         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6766       else
6767         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6768       NewVD->setInvalidDecl();
6769       return;
6770     }
6771 
6772     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6773     NewVD->setType(FixedTInfo->getType());
6774     NewVD->setTypeSourceInfo(FixedTInfo);
6775   }
6776 
6777   if (T->isVoidType()) {
6778     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6779     //                    of objects and functions.
6780     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6781       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6782         << T;
6783       NewVD->setInvalidDecl();
6784       return;
6785     }
6786   }
6787 
6788   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6789     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6790     NewVD->setInvalidDecl();
6791     return;
6792   }
6793 
6794   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6795     Diag(NewVD->getLocation(), diag::err_block_on_vm);
6796     NewVD->setInvalidDecl();
6797     return;
6798   }
6799 
6800   if (NewVD->isConstexpr() && !T->isDependentType() &&
6801       RequireLiteralType(NewVD->getLocation(), T,
6802                          diag::err_constexpr_var_non_literal)) {
6803     NewVD->setInvalidDecl();
6804     return;
6805   }
6806 }
6807 
6808 /// \brief Perform semantic checking on a newly-created variable
6809 /// declaration.
6810 ///
6811 /// This routine performs all of the type-checking required for a
6812 /// variable declaration once it has been built. It is used both to
6813 /// check variables after they have been parsed and their declarators
6814 /// have been translated into a declaration, and to check variables
6815 /// that have been instantiated from a template.
6816 ///
6817 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6818 ///
6819 /// Returns true if the variable declaration is a redeclaration.
6820 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6821   CheckVariableDeclarationType(NewVD);
6822 
6823   // If the decl is already known invalid, don't check it.
6824   if (NewVD->isInvalidDecl())
6825     return false;
6826 
6827   // If we did not find anything by this name, look for a non-visible
6828   // extern "C" declaration with the same name.
6829   if (Previous.empty() &&
6830       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6831     Previous.setShadowed();
6832 
6833   if (!Previous.empty()) {
6834     MergeVarDecl(NewVD, Previous);
6835     return true;
6836   }
6837   return false;
6838 }
6839 
6840 namespace {
6841 struct FindOverriddenMethod {
6842   Sema *S;
6843   CXXMethodDecl *Method;
6844 
6845   /// Member lookup function that determines whether a given C++
6846   /// method overrides a method in a base class, to be used with
6847   /// CXXRecordDecl::lookupInBases().
6848   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
6849     RecordDecl *BaseRecord =
6850         Specifier->getType()->getAs<RecordType>()->getDecl();
6851 
6852     DeclarationName Name = Method->getDeclName();
6853 
6854     // FIXME: Do we care about other names here too?
6855     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6856       // We really want to find the base class destructor here.
6857       QualType T = S->Context.getTypeDeclType(BaseRecord);
6858       CanQualType CT = S->Context.getCanonicalType(T);
6859 
6860       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
6861     }
6862 
6863     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
6864          Path.Decls = Path.Decls.slice(1)) {
6865       NamedDecl *D = Path.Decls.front();
6866       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6867         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
6868           return true;
6869       }
6870     }
6871 
6872     return false;
6873   }
6874 };
6875 
6876 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6877 } // end anonymous namespace
6878 
6879 /// \brief Report an error regarding overriding, along with any relevant
6880 /// overriden methods.
6881 ///
6882 /// \param DiagID the primary error to report.
6883 /// \param MD the overriding method.
6884 /// \param OEK which overrides to include as notes.
6885 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6886                             OverrideErrorKind OEK = OEK_All) {
6887   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6888   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6889                                       E = MD->end_overridden_methods();
6890        I != E; ++I) {
6891     // This check (& the OEK parameter) could be replaced by a predicate, but
6892     // without lambdas that would be overkill. This is still nicer than writing
6893     // out the diag loop 3 times.
6894     if ((OEK == OEK_All) ||
6895         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6896         (OEK == OEK_Deleted && (*I)->isDeleted()))
6897       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6898   }
6899 }
6900 
6901 /// AddOverriddenMethods - See if a method overrides any in the base classes,
6902 /// and if so, check that it's a valid override and remember it.
6903 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
6904   // Look for methods in base classes that this method might override.
6905   CXXBasePaths Paths;
6906   FindOverriddenMethod FOM;
6907   FOM.Method = MD;
6908   FOM.S = this;
6909   bool hasDeletedOverridenMethods = false;
6910   bool hasNonDeletedOverridenMethods = false;
6911   bool AddedAny = false;
6912   if (DC->lookupInBases(FOM, Paths)) {
6913     for (auto *I : Paths.found_decls()) {
6914       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
6915         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
6916         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
6917             !CheckOverridingFunctionAttributes(MD, OldMD) &&
6918             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
6919             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
6920           hasDeletedOverridenMethods |= OldMD->isDeleted();
6921           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
6922           AddedAny = true;
6923         }
6924       }
6925     }
6926   }
6927 
6928   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6929     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6930   }
6931   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6932     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6933   }
6934 
6935   return AddedAny;
6936 }
6937 
6938 namespace {
6939   // Struct for holding all of the extra arguments needed by
6940   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6941   struct ActOnFDArgs {
6942     Scope *S;
6943     Declarator &D;
6944     MultiTemplateParamsArg TemplateParamLists;
6945     bool AddToScope;
6946   };
6947 } // end anonymous namespace
6948 
6949 namespace {
6950 
6951 // Callback to only accept typo corrections that have a non-zero edit distance.
6952 // Also only accept corrections that have the same parent decl.
6953 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6954  public:
6955   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6956                             CXXRecordDecl *Parent)
6957       : Context(Context), OriginalFD(TypoFD),
6958         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
6959 
6960   bool ValidateCandidate(const TypoCorrection &candidate) override {
6961     if (candidate.getEditDistance() == 0)
6962       return false;
6963 
6964     SmallVector<unsigned, 1> MismatchedParams;
6965     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6966                                           CDeclEnd = candidate.end();
6967          CDecl != CDeclEnd; ++CDecl) {
6968       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6969 
6970       if (FD && !FD->hasBody() &&
6971           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6972         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6973           CXXRecordDecl *Parent = MD->getParent();
6974           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6975             return true;
6976         } else if (!ExpectedParent) {
6977           return true;
6978         }
6979       }
6980     }
6981 
6982     return false;
6983   }
6984 
6985  private:
6986   ASTContext &Context;
6987   FunctionDecl *OriginalFD;
6988   CXXRecordDecl *ExpectedParent;
6989 };
6990 
6991 } // end anonymous namespace
6992 
6993 /// \brief Generate diagnostics for an invalid function redeclaration.
6994 ///
6995 /// This routine handles generating the diagnostic messages for an invalid
6996 /// function redeclaration, including finding possible similar declarations
6997 /// or performing typo correction if there are no previous declarations with
6998 /// the same name.
6999 ///
7000 /// Returns a NamedDecl iff typo correction was performed and substituting in
7001 /// the new declaration name does not cause new errors.
7002 static NamedDecl *DiagnoseInvalidRedeclaration(
7003     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7004     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7005   DeclarationName Name = NewFD->getDeclName();
7006   DeclContext *NewDC = NewFD->getDeclContext();
7007   SmallVector<unsigned, 1> MismatchedParams;
7008   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7009   TypoCorrection Correction;
7010   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7011   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7012                                    : diag::err_member_decl_does_not_match;
7013   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7014                     IsLocalFriend ? Sema::LookupLocalFriendName
7015                                   : Sema::LookupOrdinaryName,
7016                     Sema::ForRedeclaration);
7017 
7018   NewFD->setInvalidDecl();
7019   if (IsLocalFriend)
7020     SemaRef.LookupName(Prev, S);
7021   else
7022     SemaRef.LookupQualifiedName(Prev, NewDC);
7023   assert(!Prev.isAmbiguous() &&
7024          "Cannot have an ambiguity in previous-declaration lookup");
7025   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7026   if (!Prev.empty()) {
7027     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7028          Func != FuncEnd; ++Func) {
7029       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7030       if (FD &&
7031           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7032         // Add 1 to the index so that 0 can mean the mismatch didn't
7033         // involve a parameter
7034         unsigned ParamNum =
7035             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7036         NearMatches.push_back(std::make_pair(FD, ParamNum));
7037       }
7038     }
7039   // If the qualified name lookup yielded nothing, try typo correction
7040   } else if ((Correction = SemaRef.CorrectTypo(
7041                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7042                   &ExtraArgs.D.getCXXScopeSpec(),
7043                   llvm::make_unique<DifferentNameValidatorCCC>(
7044                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7045                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7046     // Set up everything for the call to ActOnFunctionDeclarator
7047     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7048                               ExtraArgs.D.getIdentifierLoc());
7049     Previous.clear();
7050     Previous.setLookupName(Correction.getCorrection());
7051     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7052                                     CDeclEnd = Correction.end();
7053          CDecl != CDeclEnd; ++CDecl) {
7054       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7055       if (FD && !FD->hasBody() &&
7056           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7057         Previous.addDecl(FD);
7058       }
7059     }
7060     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7061 
7062     NamedDecl *Result;
7063     // Retry building the function declaration with the new previous
7064     // declarations, and with errors suppressed.
7065     {
7066       // Trap errors.
7067       Sema::SFINAETrap Trap(SemaRef);
7068 
7069       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7070       // pieces need to verify the typo-corrected C++ declaration and hopefully
7071       // eliminate the need for the parameter pack ExtraArgs.
7072       Result = SemaRef.ActOnFunctionDeclarator(
7073           ExtraArgs.S, ExtraArgs.D,
7074           Correction.getCorrectionDecl()->getDeclContext(),
7075           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7076           ExtraArgs.AddToScope);
7077 
7078       if (Trap.hasErrorOccurred())
7079         Result = nullptr;
7080     }
7081 
7082     if (Result) {
7083       // Determine which correction we picked.
7084       Decl *Canonical = Result->getCanonicalDecl();
7085       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7086            I != E; ++I)
7087         if ((*I)->getCanonicalDecl() == Canonical)
7088           Correction.setCorrectionDecl(*I);
7089 
7090       SemaRef.diagnoseTypo(
7091           Correction,
7092           SemaRef.PDiag(IsLocalFriend
7093                           ? diag::err_no_matching_local_friend_suggest
7094                           : diag::err_member_decl_does_not_match_suggest)
7095             << Name << NewDC << IsDefinition);
7096       return Result;
7097     }
7098 
7099     // Pretend the typo correction never occurred
7100     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7101                               ExtraArgs.D.getIdentifierLoc());
7102     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7103     Previous.clear();
7104     Previous.setLookupName(Name);
7105   }
7106 
7107   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7108       << Name << NewDC << IsDefinition << NewFD->getLocation();
7109 
7110   bool NewFDisConst = false;
7111   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7112     NewFDisConst = NewMD->isConst();
7113 
7114   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7115        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7116        NearMatch != NearMatchEnd; ++NearMatch) {
7117     FunctionDecl *FD = NearMatch->first;
7118     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7119     bool FDisConst = MD && MD->isConst();
7120     bool IsMember = MD || !IsLocalFriend;
7121 
7122     // FIXME: These notes are poorly worded for the local friend case.
7123     if (unsigned Idx = NearMatch->second) {
7124       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7125       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7126       if (Loc.isInvalid()) Loc = FD->getLocation();
7127       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7128                                  : diag::note_local_decl_close_param_match)
7129         << Idx << FDParam->getType()
7130         << NewFD->getParamDecl(Idx - 1)->getType();
7131     } else if (FDisConst != NewFDisConst) {
7132       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7133           << NewFDisConst << FD->getSourceRange().getEnd();
7134     } else
7135       SemaRef.Diag(FD->getLocation(),
7136                    IsMember ? diag::note_member_def_close_match
7137                             : diag::note_local_decl_close_match);
7138   }
7139   return nullptr;
7140 }
7141 
7142 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7143   switch (D.getDeclSpec().getStorageClassSpec()) {
7144   default: llvm_unreachable("Unknown storage class!");
7145   case DeclSpec::SCS_auto:
7146   case DeclSpec::SCS_register:
7147   case DeclSpec::SCS_mutable:
7148     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7149                  diag::err_typecheck_sclass_func);
7150     D.setInvalidType();
7151     break;
7152   case DeclSpec::SCS_unspecified: break;
7153   case DeclSpec::SCS_extern:
7154     if (D.getDeclSpec().isExternInLinkageSpec())
7155       return SC_None;
7156     return SC_Extern;
7157   case DeclSpec::SCS_static: {
7158     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7159       // C99 6.7.1p5:
7160       //   The declaration of an identifier for a function that has
7161       //   block scope shall have no explicit storage-class specifier
7162       //   other than extern
7163       // See also (C++ [dcl.stc]p4).
7164       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7165                    diag::err_static_block_func);
7166       break;
7167     } else
7168       return SC_Static;
7169   }
7170   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7171   }
7172 
7173   // No explicit storage class has already been returned
7174   return SC_None;
7175 }
7176 
7177 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7178                                            DeclContext *DC, QualType &R,
7179                                            TypeSourceInfo *TInfo,
7180                                            StorageClass SC,
7181                                            bool &IsVirtualOkay) {
7182   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7183   DeclarationName Name = NameInfo.getName();
7184 
7185   FunctionDecl *NewFD = nullptr;
7186   bool isInline = D.getDeclSpec().isInlineSpecified();
7187 
7188   if (!SemaRef.getLangOpts().CPlusPlus) {
7189     // Determine whether the function was written with a
7190     // prototype. This true when:
7191     //   - there is a prototype in the declarator, or
7192     //   - the type R of the function is some kind of typedef or other reference
7193     //     to a type name (which eventually refers to a function type).
7194     bool HasPrototype =
7195       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7196       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
7197 
7198     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7199                                  D.getLocStart(), NameInfo, R,
7200                                  TInfo, SC, isInline,
7201                                  HasPrototype, false);
7202     if (D.isInvalidType())
7203       NewFD->setInvalidDecl();
7204 
7205     return NewFD;
7206   }
7207 
7208   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7209   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7210 
7211   // Check that the return type is not an abstract class type.
7212   // For record types, this is done by the AbstractClassUsageDiagnoser once
7213   // the class has been completely parsed.
7214   if (!DC->isRecord() &&
7215       SemaRef.RequireNonAbstractType(
7216           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7217           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7218     D.setInvalidType();
7219 
7220   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7221     // This is a C++ constructor declaration.
7222     assert(DC->isRecord() &&
7223            "Constructors can only be declared in a member context");
7224 
7225     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7226     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7227                                       D.getLocStart(), NameInfo,
7228                                       R, TInfo, isExplicit, isInline,
7229                                       /*isImplicitlyDeclared=*/false,
7230                                       isConstexpr);
7231 
7232   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7233     // This is a C++ destructor declaration.
7234     if (DC->isRecord()) {
7235       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7236       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7237       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7238                                         SemaRef.Context, Record,
7239                                         D.getLocStart(),
7240                                         NameInfo, R, TInfo, isInline,
7241                                         /*isImplicitlyDeclared=*/false);
7242 
7243       // If the class is complete, then we now create the implicit exception
7244       // specification. If the class is incomplete or dependent, we can't do
7245       // it yet.
7246       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7247           Record->getDefinition() && !Record->isBeingDefined() &&
7248           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7249         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7250       }
7251 
7252       IsVirtualOkay = true;
7253       return NewDD;
7254 
7255     } else {
7256       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7257       D.setInvalidType();
7258 
7259       // Create a FunctionDecl to satisfy the function definition parsing
7260       // code path.
7261       return FunctionDecl::Create(SemaRef.Context, DC,
7262                                   D.getLocStart(),
7263                                   D.getIdentifierLoc(), Name, R, TInfo,
7264                                   SC, isInline,
7265                                   /*hasPrototype=*/true, isConstexpr);
7266     }
7267 
7268   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7269     if (!DC->isRecord()) {
7270       SemaRef.Diag(D.getIdentifierLoc(),
7271            diag::err_conv_function_not_member);
7272       return nullptr;
7273     }
7274 
7275     SemaRef.CheckConversionDeclarator(D, R, SC);
7276     IsVirtualOkay = true;
7277     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7278                                      D.getLocStart(), NameInfo,
7279                                      R, TInfo, isInline, isExplicit,
7280                                      isConstexpr, SourceLocation());
7281 
7282   } else if (DC->isRecord()) {
7283     // If the name of the function is the same as the name of the record,
7284     // then this must be an invalid constructor that has a return type.
7285     // (The parser checks for a return type and makes the declarator a
7286     // constructor if it has no return type).
7287     if (Name.getAsIdentifierInfo() &&
7288         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7289       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7290         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7291         << SourceRange(D.getIdentifierLoc());
7292       return nullptr;
7293     }
7294 
7295     // This is a C++ method declaration.
7296     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7297                                                cast<CXXRecordDecl>(DC),
7298                                                D.getLocStart(), NameInfo, R,
7299                                                TInfo, SC, isInline,
7300                                                isConstexpr, SourceLocation());
7301     IsVirtualOkay = !Ret->isStatic();
7302     return Ret;
7303   } else {
7304     bool isFriend =
7305         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7306     if (!isFriend && SemaRef.CurContext->isRecord())
7307       return nullptr;
7308 
7309     // Determine whether the function was written with a
7310     // prototype. This true when:
7311     //   - we're in C++ (where every function has a prototype),
7312     return FunctionDecl::Create(SemaRef.Context, DC,
7313                                 D.getLocStart(),
7314                                 NameInfo, R, TInfo, SC, isInline,
7315                                 true/*HasPrototype*/, isConstexpr);
7316   }
7317 }
7318 
7319 enum OpenCLParamType {
7320   ValidKernelParam,
7321   PtrPtrKernelParam,
7322   PtrKernelParam,
7323   PrivatePtrKernelParam,
7324   InvalidKernelParam,
7325   RecordKernelParam
7326 };
7327 
7328 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
7329   if (PT->isPointerType()) {
7330     QualType PointeeType = PT->getPointeeType();
7331     if (PointeeType->isPointerType())
7332       return PtrPtrKernelParam;
7333     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
7334                                               : PtrKernelParam;
7335   }
7336 
7337   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7338   // be used as builtin types.
7339 
7340   if (PT->isImageType())
7341     return PtrKernelParam;
7342 
7343   if (PT->isBooleanType())
7344     return InvalidKernelParam;
7345 
7346   if (PT->isEventT())
7347     return InvalidKernelParam;
7348 
7349   if (PT->isHalfType())
7350     return InvalidKernelParam;
7351 
7352   if (PT->isRecordType())
7353     return RecordKernelParam;
7354 
7355   return ValidKernelParam;
7356 }
7357 
7358 static void checkIsValidOpenCLKernelParameter(
7359   Sema &S,
7360   Declarator &D,
7361   ParmVarDecl *Param,
7362   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7363   QualType PT = Param->getType();
7364 
7365   // Cache the valid types we encounter to avoid rechecking structs that are
7366   // used again
7367   if (ValidTypes.count(PT.getTypePtr()))
7368     return;
7369 
7370   switch (getOpenCLKernelParameterType(PT)) {
7371   case PtrPtrKernelParam:
7372     // OpenCL v1.2 s6.9.a:
7373     // A kernel function argument cannot be declared as a
7374     // pointer to a pointer type.
7375     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7376     D.setInvalidType();
7377     return;
7378 
7379   case PrivatePtrKernelParam:
7380     // OpenCL v1.2 s6.9.a:
7381     // A kernel function argument cannot be declared as a
7382     // pointer to the private address space.
7383     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
7384     D.setInvalidType();
7385     return;
7386 
7387     // OpenCL v1.2 s6.9.k:
7388     // Arguments to kernel functions in a program cannot be declared with the
7389     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7390     // uintptr_t or a struct and/or union that contain fields declared to be
7391     // one of these built-in scalar types.
7392 
7393   case InvalidKernelParam:
7394     // OpenCL v1.2 s6.8 n:
7395     // A kernel function argument cannot be declared
7396     // of event_t type.
7397     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7398     D.setInvalidType();
7399     return;
7400 
7401   case PtrKernelParam:
7402   case ValidKernelParam:
7403     ValidTypes.insert(PT.getTypePtr());
7404     return;
7405 
7406   case RecordKernelParam:
7407     break;
7408   }
7409 
7410   // Track nested structs we will inspect
7411   SmallVector<const Decl *, 4> VisitStack;
7412 
7413   // Track where we are in the nested structs. Items will migrate from
7414   // VisitStack to HistoryStack as we do the DFS for bad field.
7415   SmallVector<const FieldDecl *, 4> HistoryStack;
7416   HistoryStack.push_back(nullptr);
7417 
7418   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7419   VisitStack.push_back(PD);
7420 
7421   assert(VisitStack.back() && "First decl null?");
7422 
7423   do {
7424     const Decl *Next = VisitStack.pop_back_val();
7425     if (!Next) {
7426       assert(!HistoryStack.empty());
7427       // Found a marker, we have gone up a level
7428       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7429         ValidTypes.insert(Hist->getType().getTypePtr());
7430 
7431       continue;
7432     }
7433 
7434     // Adds everything except the original parameter declaration (which is not a
7435     // field itself) to the history stack.
7436     const RecordDecl *RD;
7437     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7438       HistoryStack.push_back(Field);
7439       RD = Field->getType()->castAs<RecordType>()->getDecl();
7440     } else {
7441       RD = cast<RecordDecl>(Next);
7442     }
7443 
7444     // Add a null marker so we know when we've gone back up a level
7445     VisitStack.push_back(nullptr);
7446 
7447     for (const auto *FD : RD->fields()) {
7448       QualType QT = FD->getType();
7449 
7450       if (ValidTypes.count(QT.getTypePtr()))
7451         continue;
7452 
7453       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
7454       if (ParamType == ValidKernelParam)
7455         continue;
7456 
7457       if (ParamType == RecordKernelParam) {
7458         VisitStack.push_back(FD);
7459         continue;
7460       }
7461 
7462       // OpenCL v1.2 s6.9.p:
7463       // Arguments to kernel functions that are declared to be a struct or union
7464       // do not allow OpenCL objects to be passed as elements of the struct or
7465       // union.
7466       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7467           ParamType == PrivatePtrKernelParam) {
7468         S.Diag(Param->getLocation(),
7469                diag::err_record_with_pointers_kernel_param)
7470           << PT->isUnionType()
7471           << PT;
7472       } else {
7473         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7474       }
7475 
7476       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7477         << PD->getDeclName();
7478 
7479       // We have an error, now let's go back up through history and show where
7480       // the offending field came from
7481       for (ArrayRef<const FieldDecl *>::const_iterator
7482                I = HistoryStack.begin() + 1,
7483                E = HistoryStack.end();
7484            I != E; ++I) {
7485         const FieldDecl *OuterField = *I;
7486         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7487           << OuterField->getType();
7488       }
7489 
7490       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7491         << QT->isPointerType()
7492         << QT;
7493       D.setInvalidType();
7494       return;
7495     }
7496   } while (!VisitStack.empty());
7497 }
7498 
7499 NamedDecl*
7500 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7501                               TypeSourceInfo *TInfo, LookupResult &Previous,
7502                               MultiTemplateParamsArg TemplateParamLists,
7503                               bool &AddToScope) {
7504   QualType R = TInfo->getType();
7505 
7506   assert(R.getTypePtr()->isFunctionType());
7507 
7508   // TODO: consider using NameInfo for diagnostic.
7509   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7510   DeclarationName Name = NameInfo.getName();
7511   StorageClass SC = getFunctionStorageClass(*this, D);
7512 
7513   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7514     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7515          diag::err_invalid_thread)
7516       << DeclSpec::getSpecifierName(TSCS);
7517 
7518   if (D.isFirstDeclarationOfMember())
7519     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7520                            D.getIdentifierLoc());
7521 
7522   bool isFriend = false;
7523   FunctionTemplateDecl *FunctionTemplate = nullptr;
7524   bool isExplicitSpecialization = false;
7525   bool isFunctionTemplateSpecialization = false;
7526 
7527   bool isDependentClassScopeExplicitSpecialization = false;
7528   bool HasExplicitTemplateArgs = false;
7529   TemplateArgumentListInfo TemplateArgs;
7530 
7531   bool isVirtualOkay = false;
7532 
7533   DeclContext *OriginalDC = DC;
7534   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7535 
7536   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7537                                               isVirtualOkay);
7538   if (!NewFD) return nullptr;
7539 
7540   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7541     NewFD->setTopLevelDeclInObjCContainer();
7542 
7543   // Set the lexical context. If this is a function-scope declaration, or has a
7544   // C++ scope specifier, or is the object of a friend declaration, the lexical
7545   // context will be different from the semantic context.
7546   NewFD->setLexicalDeclContext(CurContext);
7547 
7548   if (IsLocalExternDecl)
7549     NewFD->setLocalExternDecl();
7550 
7551   if (getLangOpts().CPlusPlus) {
7552     bool isInline = D.getDeclSpec().isInlineSpecified();
7553     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7554     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7555     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7556     bool isConcept = D.getDeclSpec().isConceptSpecified();
7557     isFriend = D.getDeclSpec().isFriendSpecified();
7558     if (isFriend && !isInline && D.isFunctionDefinition()) {
7559       // C++ [class.friend]p5
7560       //   A function can be defined in a friend declaration of a
7561       //   class . . . . Such a function is implicitly inline.
7562       NewFD->setImplicitlyInline();
7563     }
7564 
7565     // If this is a method defined in an __interface, and is not a constructor
7566     // or an overloaded operator, then set the pure flag (isVirtual will already
7567     // return true).
7568     if (const CXXRecordDecl *Parent =
7569           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7570       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7571         NewFD->setPure(true);
7572 
7573       // C++ [class.union]p2
7574       //   A union can have member functions, but not virtual functions.
7575       if (isVirtual && Parent->isUnion())
7576         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7577     }
7578 
7579     SetNestedNameSpecifier(NewFD, D);
7580     isExplicitSpecialization = false;
7581     isFunctionTemplateSpecialization = false;
7582     if (D.isInvalidType())
7583       NewFD->setInvalidDecl();
7584 
7585     // Match up the template parameter lists with the scope specifier, then
7586     // determine whether we have a template or a template specialization.
7587     bool Invalid = false;
7588     if (TemplateParameterList *TemplateParams =
7589             MatchTemplateParametersToScopeSpecifier(
7590                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7591                 D.getCXXScopeSpec(),
7592                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7593                     ? D.getName().TemplateId
7594                     : nullptr,
7595                 TemplateParamLists, isFriend, isExplicitSpecialization,
7596                 Invalid)) {
7597       if (TemplateParams->size() > 0) {
7598         // This is a function template
7599 
7600         // Check that we can declare a template here.
7601         if (CheckTemplateDeclScope(S, TemplateParams))
7602           NewFD->setInvalidDecl();
7603 
7604         // A destructor cannot be a template.
7605         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7606           Diag(NewFD->getLocation(), diag::err_destructor_template);
7607           NewFD->setInvalidDecl();
7608         }
7609 
7610         // If we're adding a template to a dependent context, we may need to
7611         // rebuilding some of the types used within the template parameter list,
7612         // now that we know what the current instantiation is.
7613         if (DC->isDependentContext()) {
7614           ContextRAII SavedContext(*this, DC);
7615           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7616             Invalid = true;
7617         }
7618 
7619         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7620                                                         NewFD->getLocation(),
7621                                                         Name, TemplateParams,
7622                                                         NewFD);
7623         FunctionTemplate->setLexicalDeclContext(CurContext);
7624         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7625 
7626         // For source fidelity, store the other template param lists.
7627         if (TemplateParamLists.size() > 1) {
7628           NewFD->setTemplateParameterListsInfo(Context,
7629                                                TemplateParamLists.drop_back(1));
7630         }
7631       } else {
7632         // This is a function template specialization.
7633         isFunctionTemplateSpecialization = true;
7634         // For source fidelity, store all the template param lists.
7635         if (TemplateParamLists.size() > 0)
7636           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7637 
7638         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7639         if (isFriend) {
7640           // We want to remove the "template<>", found here.
7641           SourceRange RemoveRange = TemplateParams->getSourceRange();
7642 
7643           // If we remove the template<> and the name is not a
7644           // template-id, we're actually silently creating a problem:
7645           // the friend declaration will refer to an untemplated decl,
7646           // and clearly the user wants a template specialization.  So
7647           // we need to insert '<>' after the name.
7648           SourceLocation InsertLoc;
7649           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7650             InsertLoc = D.getName().getSourceRange().getEnd();
7651             InsertLoc = getLocForEndOfToken(InsertLoc);
7652           }
7653 
7654           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7655             << Name << RemoveRange
7656             << FixItHint::CreateRemoval(RemoveRange)
7657             << FixItHint::CreateInsertion(InsertLoc, "<>");
7658         }
7659       }
7660     }
7661     else {
7662       // All template param lists were matched against the scope specifier:
7663       // this is NOT (an explicit specialization of) a template.
7664       if (TemplateParamLists.size() > 0)
7665         // For source fidelity, store all the template param lists.
7666         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7667     }
7668 
7669     if (Invalid) {
7670       NewFD->setInvalidDecl();
7671       if (FunctionTemplate)
7672         FunctionTemplate->setInvalidDecl();
7673     }
7674 
7675     // C++ [dcl.fct.spec]p5:
7676     //   The virtual specifier shall only be used in declarations of
7677     //   nonstatic class member functions that appear within a
7678     //   member-specification of a class declaration; see 10.3.
7679     //
7680     if (isVirtual && !NewFD->isInvalidDecl()) {
7681       if (!isVirtualOkay) {
7682         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7683              diag::err_virtual_non_function);
7684       } else if (!CurContext->isRecord()) {
7685         // 'virtual' was specified outside of the class.
7686         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7687              diag::err_virtual_out_of_class)
7688           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7689       } else if (NewFD->getDescribedFunctionTemplate()) {
7690         // C++ [temp.mem]p3:
7691         //  A member function template shall not be virtual.
7692         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7693              diag::err_virtual_member_function_template)
7694           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7695       } else {
7696         // Okay: Add virtual to the method.
7697         NewFD->setVirtualAsWritten(true);
7698       }
7699 
7700       if (getLangOpts().CPlusPlus14 &&
7701           NewFD->getReturnType()->isUndeducedType())
7702         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7703     }
7704 
7705     if (getLangOpts().CPlusPlus14 &&
7706         (NewFD->isDependentContext() ||
7707          (isFriend && CurContext->isDependentContext())) &&
7708         NewFD->getReturnType()->isUndeducedType()) {
7709       // If the function template is referenced directly (for instance, as a
7710       // member of the current instantiation), pretend it has a dependent type.
7711       // This is not really justified by the standard, but is the only sane
7712       // thing to do.
7713       // FIXME: For a friend function, we have not marked the function as being
7714       // a friend yet, so 'isDependentContext' on the FD doesn't work.
7715       const FunctionProtoType *FPT =
7716           NewFD->getType()->castAs<FunctionProtoType>();
7717       QualType Result =
7718           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7719       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7720                                              FPT->getExtProtoInfo()));
7721     }
7722 
7723     // C++ [dcl.fct.spec]p3:
7724     //  The inline specifier shall not appear on a block scope function
7725     //  declaration.
7726     if (isInline && !NewFD->isInvalidDecl()) {
7727       if (CurContext->isFunctionOrMethod()) {
7728         // 'inline' is not allowed on block scope function declaration.
7729         Diag(D.getDeclSpec().getInlineSpecLoc(),
7730              diag::err_inline_declaration_block_scope) << Name
7731           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7732       }
7733     }
7734 
7735     // C++ [dcl.fct.spec]p6:
7736     //  The explicit specifier shall be used only in the declaration of a
7737     //  constructor or conversion function within its class definition;
7738     //  see 12.3.1 and 12.3.2.
7739     if (isExplicit && !NewFD->isInvalidDecl()) {
7740       if (!CurContext->isRecord()) {
7741         // 'explicit' was specified outside of the class.
7742         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7743              diag::err_explicit_out_of_class)
7744           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7745       } else if (!isa<CXXConstructorDecl>(NewFD) &&
7746                  !isa<CXXConversionDecl>(NewFD)) {
7747         // 'explicit' was specified on a function that wasn't a constructor
7748         // or conversion function.
7749         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7750              diag::err_explicit_non_ctor_or_conv_function)
7751           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7752       }
7753     }
7754 
7755     if (isConstexpr) {
7756       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7757       // are implicitly inline.
7758       NewFD->setImplicitlyInline();
7759 
7760       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7761       // be either constructors or to return a literal type. Therefore,
7762       // destructors cannot be declared constexpr.
7763       if (isa<CXXDestructorDecl>(NewFD))
7764         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7765     }
7766 
7767     if (isConcept) {
7768       // This is a function concept.
7769       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
7770         FTD->setConcept();
7771 
7772       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7773       // applied only to the definition of a function template [...]
7774       if (!D.isFunctionDefinition()) {
7775         Diag(D.getDeclSpec().getConceptSpecLoc(),
7776              diag::err_function_concept_not_defined);
7777         NewFD->setInvalidDecl();
7778       }
7779 
7780       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
7781       // have no exception-specification and is treated as if it were specified
7782       // with noexcept(true) (15.4). [...]
7783       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
7784         if (FPT->hasExceptionSpec()) {
7785           SourceRange Range;
7786           if (D.isFunctionDeclarator())
7787             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
7788           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
7789               << FixItHint::CreateRemoval(Range);
7790           NewFD->setInvalidDecl();
7791         } else {
7792           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
7793         }
7794 
7795         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7796         // following restrictions:
7797         // - The declared return type shall have the type bool.
7798         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
7799           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
7800           NewFD->setInvalidDecl();
7801         }
7802 
7803         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7804         // following restrictions:
7805         // - The declaration's parameter list shall be equivalent to an empty
7806         //   parameter list.
7807         if (FPT->getNumParams() > 0 || FPT->isVariadic())
7808           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
7809       }
7810 
7811       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
7812       // implicity defined to be a constexpr declaration (implicitly inline)
7813       NewFD->setImplicitlyInline();
7814 
7815       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
7816       // be declared with the thread_local, inline, friend, or constexpr
7817       // specifiers, [...]
7818       if (isInline) {
7819         Diag(D.getDeclSpec().getInlineSpecLoc(),
7820              diag::err_concept_decl_invalid_specifiers)
7821             << 1 << 1;
7822         NewFD->setInvalidDecl(true);
7823       }
7824 
7825       if (isFriend) {
7826         Diag(D.getDeclSpec().getFriendSpecLoc(),
7827              diag::err_concept_decl_invalid_specifiers)
7828             << 1 << 2;
7829         NewFD->setInvalidDecl(true);
7830       }
7831 
7832       if (isConstexpr) {
7833         Diag(D.getDeclSpec().getConstexprSpecLoc(),
7834              diag::err_concept_decl_invalid_specifiers)
7835             << 1 << 3;
7836         NewFD->setInvalidDecl(true);
7837       }
7838 
7839       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7840       // applied only to the definition of a function template or variable
7841       // template, declared in namespace scope.
7842       if (isFunctionTemplateSpecialization) {
7843         Diag(D.getDeclSpec().getConceptSpecLoc(),
7844              diag::err_concept_specified_specialization) << 1;
7845         NewFD->setInvalidDecl(true);
7846         return NewFD;
7847       }
7848     }
7849 
7850     // If __module_private__ was specified, mark the function accordingly.
7851     if (D.getDeclSpec().isModulePrivateSpecified()) {
7852       if (isFunctionTemplateSpecialization) {
7853         SourceLocation ModulePrivateLoc
7854           = D.getDeclSpec().getModulePrivateSpecLoc();
7855         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
7856           << 0
7857           << FixItHint::CreateRemoval(ModulePrivateLoc);
7858       } else {
7859         NewFD->setModulePrivate();
7860         if (FunctionTemplate)
7861           FunctionTemplate->setModulePrivate();
7862       }
7863     }
7864 
7865     if (isFriend) {
7866       if (FunctionTemplate) {
7867         FunctionTemplate->setObjectOfFriendDecl();
7868         FunctionTemplate->setAccess(AS_public);
7869       }
7870       NewFD->setObjectOfFriendDecl();
7871       NewFD->setAccess(AS_public);
7872     }
7873 
7874     // If a function is defined as defaulted or deleted, mark it as such now.
7875     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
7876     // definition kind to FDK_Definition.
7877     switch (D.getFunctionDefinitionKind()) {
7878       case FDK_Declaration:
7879       case FDK_Definition:
7880         break;
7881 
7882       case FDK_Defaulted:
7883         NewFD->setDefaulted();
7884         break;
7885 
7886       case FDK_Deleted:
7887         NewFD->setDeletedAsWritten();
7888         break;
7889     }
7890 
7891     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
7892         D.isFunctionDefinition()) {
7893       // C++ [class.mfct]p2:
7894       //   A member function may be defined (8.4) in its class definition, in
7895       //   which case it is an inline member function (7.1.2)
7896       NewFD->setImplicitlyInline();
7897     }
7898 
7899     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
7900         !CurContext->isRecord()) {
7901       // C++ [class.static]p1:
7902       //   A data or function member of a class may be declared static
7903       //   in a class definition, in which case it is a static member of
7904       //   the class.
7905 
7906       // Complain about the 'static' specifier if it's on an out-of-line
7907       // member function definition.
7908       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7909            diag::err_static_out_of_line)
7910         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7911     }
7912 
7913     // C++11 [except.spec]p15:
7914     //   A deallocation function with no exception-specification is treated
7915     //   as if it were specified with noexcept(true).
7916     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
7917     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
7918          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
7919         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
7920       NewFD->setType(Context.getFunctionType(
7921           FPT->getReturnType(), FPT->getParamTypes(),
7922           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
7923   }
7924 
7925   // Filter out previous declarations that don't match the scope.
7926   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
7927                        D.getCXXScopeSpec().isNotEmpty() ||
7928                        isExplicitSpecialization ||
7929                        isFunctionTemplateSpecialization);
7930 
7931   // Handle GNU asm-label extension (encoded as an attribute).
7932   if (Expr *E = (Expr*) D.getAsmLabel()) {
7933     // The parser guarantees this is a string.
7934     StringLiteral *SE = cast<StringLiteral>(E);
7935     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
7936                                                 SE->getString(), 0));
7937   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7938     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7939       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
7940     if (I != ExtnameUndeclaredIdentifiers.end()) {
7941       if (isDeclExternC(NewFD)) {
7942         NewFD->addAttr(I->second);
7943         ExtnameUndeclaredIdentifiers.erase(I);
7944       } else
7945         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
7946             << /*Variable*/0 << NewFD;
7947     }
7948   }
7949 
7950   // Copy the parameter declarations from the declarator D to the function
7951   // declaration NewFD, if they are available.  First scavenge them into Params.
7952   SmallVector<ParmVarDecl*, 16> Params;
7953   if (D.isFunctionDeclarator()) {
7954     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7955 
7956     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
7957     // function that takes no arguments, not a function that takes a
7958     // single void argument.
7959     // We let through "const void" here because Sema::GetTypeForDeclarator
7960     // already checks for that case.
7961     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
7962       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
7963         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
7964         assert(Param->getDeclContext() != NewFD && "Was set before ?");
7965         Param->setDeclContext(NewFD);
7966         Params.push_back(Param);
7967 
7968         if (Param->isInvalidDecl())
7969           NewFD->setInvalidDecl();
7970       }
7971     }
7972   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
7973     // When we're declaring a function with a typedef, typeof, etc as in the
7974     // following example, we'll need to synthesize (unnamed)
7975     // parameters for use in the declaration.
7976     //
7977     // @code
7978     // typedef void fn(int);
7979     // fn f;
7980     // @endcode
7981 
7982     // Synthesize a parameter for each argument type.
7983     for (const auto &AI : FT->param_types()) {
7984       ParmVarDecl *Param =
7985           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
7986       Param->setScopeInfo(0, Params.size());
7987       Params.push_back(Param);
7988     }
7989   } else {
7990     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
7991            "Should not need args for typedef of non-prototype fn");
7992   }
7993 
7994   // Finally, we know we have the right number of parameters, install them.
7995   NewFD->setParams(Params);
7996 
7997   // Find all anonymous symbols defined during the declaration of this function
7998   // and add to NewFD. This lets us track decls such 'enum Y' in:
7999   //
8000   //   void f(enum Y {AA} x) {}
8001   //
8002   // which would otherwise incorrectly end up in the translation unit scope.
8003   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
8004   DeclsInPrototypeScope.clear();
8005 
8006   if (D.getDeclSpec().isNoreturnSpecified())
8007     NewFD->addAttr(
8008         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8009                                        Context, 0));
8010 
8011   // Functions returning a variably modified type violate C99 6.7.5.2p2
8012   // because all functions have linkage.
8013   if (!NewFD->isInvalidDecl() &&
8014       NewFD->getReturnType()->isVariablyModifiedType()) {
8015     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8016     NewFD->setInvalidDecl();
8017   }
8018 
8019   // Apply an implicit SectionAttr if #pragma code_seg is active.
8020   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8021       !NewFD->hasAttr<SectionAttr>()) {
8022     NewFD->addAttr(
8023         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8024                                     CodeSegStack.CurrentValue->getString(),
8025                                     CodeSegStack.CurrentPragmaLocation));
8026     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8027                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8028                          ASTContext::PSF_Read,
8029                      NewFD))
8030       NewFD->dropAttr<SectionAttr>();
8031   }
8032 
8033   // Handle attributes.
8034   ProcessDeclAttributes(S, NewFD, D);
8035 
8036   if (getLangOpts().CUDA)
8037     maybeAddCUDAHostDeviceAttrs(S, NewFD, Previous);
8038 
8039   if (getLangOpts().OpenCL) {
8040     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8041     // type declaration will generate a compilation error.
8042     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8043     if (AddressSpace == LangAS::opencl_local ||
8044         AddressSpace == LangAS::opencl_global ||
8045         AddressSpace == LangAS::opencl_constant) {
8046       Diag(NewFD->getLocation(),
8047            diag::err_opencl_return_value_with_address_space);
8048       NewFD->setInvalidDecl();
8049     }
8050   }
8051 
8052   if (!getLangOpts().CPlusPlus) {
8053     // Perform semantic checking on the function declaration.
8054     bool isExplicitSpecialization=false;
8055     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8056       CheckMain(NewFD, D.getDeclSpec());
8057 
8058     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8059       CheckMSVCRTEntryPoint(NewFD);
8060 
8061     if (!NewFD->isInvalidDecl())
8062       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8063                                                   isExplicitSpecialization));
8064     else if (!Previous.empty())
8065       // Recover gracefully from an invalid redeclaration.
8066       D.setRedeclaration(true);
8067     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8068             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8069            "previous declaration set still overloaded");
8070 
8071     // Diagnose no-prototype function declarations with calling conventions that
8072     // don't support variadic calls. Only do this in C and do it after merging
8073     // possibly prototyped redeclarations.
8074     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8075     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8076       CallingConv CC = FT->getExtInfo().getCC();
8077       if (!supportsVariadicCall(CC)) {
8078         // Windows system headers sometimes accidentally use stdcall without
8079         // (void) parameters, so we relax this to a warning.
8080         int DiagID =
8081             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8082         Diag(NewFD->getLocation(), DiagID)
8083             << FunctionType::getNameForCallConv(CC);
8084       }
8085     }
8086   } else {
8087     // C++11 [replacement.functions]p3:
8088     //  The program's definitions shall not be specified as inline.
8089     //
8090     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8091     //
8092     // Suppress the diagnostic if the function is __attribute__((used)), since
8093     // that forces an external definition to be emitted.
8094     if (D.getDeclSpec().isInlineSpecified() &&
8095         NewFD->isReplaceableGlobalAllocationFunction() &&
8096         !NewFD->hasAttr<UsedAttr>())
8097       Diag(D.getDeclSpec().getInlineSpecLoc(),
8098            diag::ext_operator_new_delete_declared_inline)
8099         << NewFD->getDeclName();
8100 
8101     // If the declarator is a template-id, translate the parser's template
8102     // argument list into our AST format.
8103     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8104       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8105       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8106       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8107       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8108                                          TemplateId->NumArgs);
8109       translateTemplateArguments(TemplateArgsPtr,
8110                                  TemplateArgs);
8111 
8112       HasExplicitTemplateArgs = true;
8113 
8114       if (NewFD->isInvalidDecl()) {
8115         HasExplicitTemplateArgs = false;
8116       } else if (FunctionTemplate) {
8117         // Function template with explicit template arguments.
8118         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8119           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8120 
8121         HasExplicitTemplateArgs = false;
8122       } else {
8123         assert((isFunctionTemplateSpecialization ||
8124                 D.getDeclSpec().isFriendSpecified()) &&
8125                "should have a 'template<>' for this decl");
8126         // "friend void foo<>(int);" is an implicit specialization decl.
8127         isFunctionTemplateSpecialization = true;
8128       }
8129     } else if (isFriend && isFunctionTemplateSpecialization) {
8130       // This combination is only possible in a recovery case;  the user
8131       // wrote something like:
8132       //   template <> friend void foo(int);
8133       // which we're recovering from as if the user had written:
8134       //   friend void foo<>(int);
8135       // Go ahead and fake up a template id.
8136       HasExplicitTemplateArgs = true;
8137       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8138       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8139     }
8140 
8141     // If it's a friend (and only if it's a friend), it's possible
8142     // that either the specialized function type or the specialized
8143     // template is dependent, and therefore matching will fail.  In
8144     // this case, don't check the specialization yet.
8145     bool InstantiationDependent = false;
8146     if (isFunctionTemplateSpecialization && isFriend &&
8147         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8148          TemplateSpecializationType::anyDependentTemplateArguments(
8149             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
8150             InstantiationDependent))) {
8151       assert(HasExplicitTemplateArgs &&
8152              "friend function specialization without template args");
8153       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8154                                                        Previous))
8155         NewFD->setInvalidDecl();
8156     } else if (isFunctionTemplateSpecialization) {
8157       if (CurContext->isDependentContext() && CurContext->isRecord()
8158           && !isFriend) {
8159         isDependentClassScopeExplicitSpecialization = true;
8160         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8161           diag::ext_function_specialization_in_class :
8162           diag::err_function_specialization_in_class)
8163           << NewFD->getDeclName();
8164       } else if (CheckFunctionTemplateSpecialization(NewFD,
8165                                   (HasExplicitTemplateArgs ? &TemplateArgs
8166                                                            : nullptr),
8167                                                      Previous))
8168         NewFD->setInvalidDecl();
8169 
8170       // C++ [dcl.stc]p1:
8171       //   A storage-class-specifier shall not be specified in an explicit
8172       //   specialization (14.7.3)
8173       FunctionTemplateSpecializationInfo *Info =
8174           NewFD->getTemplateSpecializationInfo();
8175       if (Info && SC != SC_None) {
8176         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8177           Diag(NewFD->getLocation(),
8178                diag::err_explicit_specialization_inconsistent_storage_class)
8179             << SC
8180             << FixItHint::CreateRemoval(
8181                                       D.getDeclSpec().getStorageClassSpecLoc());
8182 
8183         else
8184           Diag(NewFD->getLocation(),
8185                diag::ext_explicit_specialization_storage_class)
8186             << FixItHint::CreateRemoval(
8187                                       D.getDeclSpec().getStorageClassSpecLoc());
8188       }
8189     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
8190       if (CheckMemberSpecialization(NewFD, Previous))
8191           NewFD->setInvalidDecl();
8192     }
8193 
8194     // Perform semantic checking on the function declaration.
8195     if (!isDependentClassScopeExplicitSpecialization) {
8196       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8197         CheckMain(NewFD, D.getDeclSpec());
8198 
8199       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8200         CheckMSVCRTEntryPoint(NewFD);
8201 
8202       if (!NewFD->isInvalidDecl())
8203         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8204                                                     isExplicitSpecialization));
8205       else if (!Previous.empty())
8206         // Recover gracefully from an invalid redeclaration.
8207         D.setRedeclaration(true);
8208     }
8209 
8210     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8211             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8212            "previous declaration set still overloaded");
8213 
8214     NamedDecl *PrincipalDecl = (FunctionTemplate
8215                                 ? cast<NamedDecl>(FunctionTemplate)
8216                                 : NewFD);
8217 
8218     if (isFriend && D.isRedeclaration()) {
8219       AccessSpecifier Access = AS_public;
8220       if (!NewFD->isInvalidDecl())
8221         Access = NewFD->getPreviousDecl()->getAccess();
8222 
8223       NewFD->setAccess(Access);
8224       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8225     }
8226 
8227     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8228         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8229       PrincipalDecl->setNonMemberOperator();
8230 
8231     // If we have a function template, check the template parameter
8232     // list. This will check and merge default template arguments.
8233     if (FunctionTemplate) {
8234       FunctionTemplateDecl *PrevTemplate =
8235                                      FunctionTemplate->getPreviousDecl();
8236       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8237                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8238                                     : nullptr,
8239                             D.getDeclSpec().isFriendSpecified()
8240                               ? (D.isFunctionDefinition()
8241                                    ? TPC_FriendFunctionTemplateDefinition
8242                                    : TPC_FriendFunctionTemplate)
8243                               : (D.getCXXScopeSpec().isSet() &&
8244                                  DC && DC->isRecord() &&
8245                                  DC->isDependentContext())
8246                                   ? TPC_ClassTemplateMember
8247                                   : TPC_FunctionTemplate);
8248     }
8249 
8250     if (NewFD->isInvalidDecl()) {
8251       // Ignore all the rest of this.
8252     } else if (!D.isRedeclaration()) {
8253       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8254                                        AddToScope };
8255       // Fake up an access specifier if it's supposed to be a class member.
8256       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8257         NewFD->setAccess(AS_public);
8258 
8259       // Qualified decls generally require a previous declaration.
8260       if (D.getCXXScopeSpec().isSet()) {
8261         // ...with the major exception of templated-scope or
8262         // dependent-scope friend declarations.
8263 
8264         // TODO: we currently also suppress this check in dependent
8265         // contexts because (1) the parameter depth will be off when
8266         // matching friend templates and (2) we might actually be
8267         // selecting a friend based on a dependent factor.  But there
8268         // are situations where these conditions don't apply and we
8269         // can actually do this check immediately.
8270         if (isFriend &&
8271             (TemplateParamLists.size() ||
8272              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8273              CurContext->isDependentContext())) {
8274           // ignore these
8275         } else {
8276           // The user tried to provide an out-of-line definition for a
8277           // function that is a member of a class or namespace, but there
8278           // was no such member function declared (C++ [class.mfct]p2,
8279           // C++ [namespace.memdef]p2). For example:
8280           //
8281           // class X {
8282           //   void f() const;
8283           // };
8284           //
8285           // void X::f() { } // ill-formed
8286           //
8287           // Complain about this problem, and attempt to suggest close
8288           // matches (e.g., those that differ only in cv-qualifiers and
8289           // whether the parameter types are references).
8290 
8291           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8292                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8293             AddToScope = ExtraArgs.AddToScope;
8294             return Result;
8295           }
8296         }
8297 
8298         // Unqualified local friend declarations are required to resolve
8299         // to something.
8300       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8301         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8302                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8303           AddToScope = ExtraArgs.AddToScope;
8304           return Result;
8305         }
8306       }
8307     } else if (!D.isFunctionDefinition() &&
8308                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8309                !isFriend && !isFunctionTemplateSpecialization &&
8310                !isExplicitSpecialization) {
8311       // An out-of-line member function declaration must also be a
8312       // definition (C++ [class.mfct]p2).
8313       // Note that this is not the case for explicit specializations of
8314       // function templates or member functions of class templates, per
8315       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8316       // extension for compatibility with old SWIG code which likes to
8317       // generate them.
8318       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8319         << D.getCXXScopeSpec().getRange();
8320     }
8321   }
8322 
8323   ProcessPragmaWeak(S, NewFD);
8324   checkAttributesAfterMerging(*this, *NewFD);
8325 
8326   AddKnownFunctionAttributes(NewFD);
8327 
8328   if (NewFD->hasAttr<OverloadableAttr>() &&
8329       !NewFD->getType()->getAs<FunctionProtoType>()) {
8330     Diag(NewFD->getLocation(),
8331          diag::err_attribute_overloadable_no_prototype)
8332       << NewFD;
8333 
8334     // Turn this into a variadic function with no parameters.
8335     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8336     FunctionProtoType::ExtProtoInfo EPI(
8337         Context.getDefaultCallingConvention(true, false));
8338     EPI.Variadic = true;
8339     EPI.ExtInfo = FT->getExtInfo();
8340 
8341     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8342     NewFD->setType(R);
8343   }
8344 
8345   // If there's a #pragma GCC visibility in scope, and this isn't a class
8346   // member, set the visibility of this function.
8347   if (!DC->isRecord() && NewFD->isExternallyVisible())
8348     AddPushedVisibilityAttribute(NewFD);
8349 
8350   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8351   // marking the function.
8352   AddCFAuditedAttribute(NewFD);
8353 
8354   // If this is a function definition, check if we have to apply optnone due to
8355   // a pragma.
8356   if(D.isFunctionDefinition())
8357     AddRangeBasedOptnone(NewFD);
8358 
8359   // If this is the first declaration of an extern C variable, update
8360   // the map of such variables.
8361   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8362       isIncompleteDeclExternC(*this, NewFD))
8363     RegisterLocallyScopedExternCDecl(NewFD, S);
8364 
8365   // Set this FunctionDecl's range up to the right paren.
8366   NewFD->setRangeEnd(D.getSourceRange().getEnd());
8367 
8368   if (D.isRedeclaration() && !Previous.empty()) {
8369     checkDLLAttributeRedeclaration(
8370         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8371         isExplicitSpecialization || isFunctionTemplateSpecialization);
8372   }
8373 
8374   if (getLangOpts().CUDA) {
8375     IdentifierInfo *II = NewFD->getIdentifier();
8376     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
8377         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8378       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8379         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8380 
8381       Context.setcudaConfigureCallDecl(NewFD);
8382     }
8383 
8384     // Variadic functions, other than a *declaration* of printf, are not allowed
8385     // in device-side CUDA code, unless someone passed
8386     // -fcuda-allow-variadic-functions.
8387     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
8388         (NewFD->hasAttr<CUDADeviceAttr>() ||
8389          NewFD->hasAttr<CUDAGlobalAttr>()) &&
8390         !(II && II->isStr("printf") && NewFD->isExternC() &&
8391           !D.isFunctionDefinition())) {
8392       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
8393     }
8394   }
8395 
8396   if (getLangOpts().CPlusPlus) {
8397     if (FunctionTemplate) {
8398       if (NewFD->isInvalidDecl())
8399         FunctionTemplate->setInvalidDecl();
8400       return FunctionTemplate;
8401     }
8402   }
8403 
8404   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8405     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8406     if ((getLangOpts().OpenCLVersion >= 120)
8407         && (SC == SC_Static)) {
8408       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8409       D.setInvalidType();
8410     }
8411 
8412     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8413     if (!NewFD->getReturnType()->isVoidType()) {
8414       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8415       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8416           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8417                                 : FixItHint());
8418       D.setInvalidType();
8419     }
8420 
8421     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8422     for (auto Param : NewFD->params())
8423       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8424   }
8425   for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
8426        PE = NewFD->param_end(); PI != PE; ++PI) {
8427     ParmVarDecl *Param = *PI;
8428     QualType PT = Param->getType();
8429 
8430     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8431     // types.
8432     if (getLangOpts().OpenCLVersion >= 200) {
8433       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8434         QualType ElemTy = PipeTy->getElementType();
8435           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8436             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8437             D.setInvalidType();
8438           }
8439       }
8440     }
8441   }
8442 
8443   MarkUnusedFileScopedDecl(NewFD);
8444 
8445   // Here we have an function template explicit specialization at class scope.
8446   // The actually specialization will be postponed to template instatiation
8447   // time via the ClassScopeFunctionSpecializationDecl node.
8448   if (isDependentClassScopeExplicitSpecialization) {
8449     ClassScopeFunctionSpecializationDecl *NewSpec =
8450                          ClassScopeFunctionSpecializationDecl::Create(
8451                                 Context, CurContext, SourceLocation(),
8452                                 cast<CXXMethodDecl>(NewFD),
8453                                 HasExplicitTemplateArgs, TemplateArgs);
8454     CurContext->addDecl(NewSpec);
8455     AddToScope = false;
8456   }
8457 
8458   return NewFD;
8459 }
8460 
8461 /// \brief Perform semantic checking of a new function declaration.
8462 ///
8463 /// Performs semantic analysis of the new function declaration
8464 /// NewFD. This routine performs all semantic checking that does not
8465 /// require the actual declarator involved in the declaration, and is
8466 /// used both for the declaration of functions as they are parsed
8467 /// (called via ActOnDeclarator) and for the declaration of functions
8468 /// that have been instantiated via C++ template instantiation (called
8469 /// via InstantiateDecl).
8470 ///
8471 /// \param IsExplicitSpecialization whether this new function declaration is
8472 /// an explicit specialization of the previous declaration.
8473 ///
8474 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8475 ///
8476 /// \returns true if the function declaration is a redeclaration.
8477 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8478                                     LookupResult &Previous,
8479                                     bool IsExplicitSpecialization) {
8480   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8481          "Variably modified return types are not handled here");
8482 
8483   // Determine whether the type of this function should be merged with
8484   // a previous visible declaration. This never happens for functions in C++,
8485   // and always happens in C if the previous declaration was visible.
8486   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8487                                !Previous.isShadowed();
8488 
8489   bool Redeclaration = false;
8490   NamedDecl *OldDecl = nullptr;
8491 
8492   // Merge or overload the declaration with an existing declaration of
8493   // the same name, if appropriate.
8494   if (!Previous.empty()) {
8495     // Determine whether NewFD is an overload of PrevDecl or
8496     // a declaration that requires merging. If it's an overload,
8497     // there's no more work to do here; we'll just add the new
8498     // function to the scope.
8499     if (!AllowOverloadingOfFunction(Previous, Context)) {
8500       NamedDecl *Candidate = Previous.getRepresentativeDecl();
8501       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8502         Redeclaration = true;
8503         OldDecl = Candidate;
8504       }
8505     } else {
8506       switch (CheckOverload(S, NewFD, Previous, OldDecl,
8507                             /*NewIsUsingDecl*/ false)) {
8508       case Ovl_Match:
8509         Redeclaration = true;
8510         break;
8511 
8512       case Ovl_NonFunction:
8513         Redeclaration = true;
8514         break;
8515 
8516       case Ovl_Overload:
8517         Redeclaration = false;
8518         break;
8519       }
8520 
8521       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8522         // If a function name is overloadable in C, then every function
8523         // with that name must be marked "overloadable".
8524         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8525           << Redeclaration << NewFD;
8526         NamedDecl *OverloadedDecl = nullptr;
8527         if (Redeclaration)
8528           OverloadedDecl = OldDecl;
8529         else if (!Previous.empty())
8530           OverloadedDecl = Previous.getRepresentativeDecl();
8531         if (OverloadedDecl)
8532           Diag(OverloadedDecl->getLocation(),
8533                diag::note_attribute_overloadable_prev_overload);
8534         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8535       }
8536     }
8537   }
8538 
8539   // Check for a previous extern "C" declaration with this name.
8540   if (!Redeclaration &&
8541       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8542     if (!Previous.empty()) {
8543       // This is an extern "C" declaration with the same name as a previous
8544       // declaration, and thus redeclares that entity...
8545       Redeclaration = true;
8546       OldDecl = Previous.getFoundDecl();
8547       MergeTypeWithPrevious = false;
8548 
8549       // ... except in the presence of __attribute__((overloadable)).
8550       if (OldDecl->hasAttr<OverloadableAttr>()) {
8551         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8552           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8553             << Redeclaration << NewFD;
8554           Diag(Previous.getFoundDecl()->getLocation(),
8555                diag::note_attribute_overloadable_prev_overload);
8556           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8557         }
8558         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8559           Redeclaration = false;
8560           OldDecl = nullptr;
8561         }
8562       }
8563     }
8564   }
8565 
8566   // C++11 [dcl.constexpr]p8:
8567   //   A constexpr specifier for a non-static member function that is not
8568   //   a constructor declares that member function to be const.
8569   //
8570   // This needs to be delayed until we know whether this is an out-of-line
8571   // definition of a static member function.
8572   //
8573   // This rule is not present in C++1y, so we produce a backwards
8574   // compatibility warning whenever it happens in C++11.
8575   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8576   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8577       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8578       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8579     CXXMethodDecl *OldMD = nullptr;
8580     if (OldDecl)
8581       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8582     if (!OldMD || !OldMD->isStatic()) {
8583       const FunctionProtoType *FPT =
8584         MD->getType()->castAs<FunctionProtoType>();
8585       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8586       EPI.TypeQuals |= Qualifiers::Const;
8587       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8588                                           FPT->getParamTypes(), EPI));
8589 
8590       // Warn that we did this, if we're not performing template instantiation.
8591       // In that case, we'll have warned already when the template was defined.
8592       if (ActiveTemplateInstantiations.empty()) {
8593         SourceLocation AddConstLoc;
8594         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
8595                 .IgnoreParens().getAs<FunctionTypeLoc>())
8596           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
8597 
8598         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
8599           << FixItHint::CreateInsertion(AddConstLoc, " const");
8600       }
8601     }
8602   }
8603 
8604   if (Redeclaration) {
8605     // NewFD and OldDecl represent declarations that need to be
8606     // merged.
8607     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
8608       NewFD->setInvalidDecl();
8609       return Redeclaration;
8610     }
8611 
8612     Previous.clear();
8613     Previous.addDecl(OldDecl);
8614 
8615     if (FunctionTemplateDecl *OldTemplateDecl
8616                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
8617       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
8618       FunctionTemplateDecl *NewTemplateDecl
8619         = NewFD->getDescribedFunctionTemplate();
8620       assert(NewTemplateDecl && "Template/non-template mismatch");
8621       if (CXXMethodDecl *Method
8622             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
8623         Method->setAccess(OldTemplateDecl->getAccess());
8624         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8625       }
8626 
8627       // If this is an explicit specialization of a member that is a function
8628       // template, mark it as a member specialization.
8629       if (IsExplicitSpecialization &&
8630           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
8631         NewTemplateDecl->setMemberSpecialization();
8632         assert(OldTemplateDecl->isMemberSpecialization());
8633         // Explicit specializations of a member template do not inherit deleted
8634         // status from the parent member template that they are specializing.
8635         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
8636           FunctionDecl *const OldTemplatedDecl =
8637               OldTemplateDecl->getTemplatedDecl();
8638           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
8639           OldTemplatedDecl->setDeletedAsWritten(false);
8640         }
8641       }
8642 
8643     } else {
8644       // This needs to happen first so that 'inline' propagates.
8645       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
8646 
8647       if (isa<CXXMethodDecl>(NewFD))
8648         NewFD->setAccess(OldDecl->getAccess());
8649     }
8650   }
8651 
8652   // Semantic checking for this function declaration (in isolation).
8653 
8654   if (getLangOpts().CPlusPlus) {
8655     // C++-specific checks.
8656     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
8657       CheckConstructor(Constructor);
8658     } else if (CXXDestructorDecl *Destructor =
8659                 dyn_cast<CXXDestructorDecl>(NewFD)) {
8660       CXXRecordDecl *Record = Destructor->getParent();
8661       QualType ClassType = Context.getTypeDeclType(Record);
8662 
8663       // FIXME: Shouldn't we be able to perform this check even when the class
8664       // type is dependent? Both gcc and edg can handle that.
8665       if (!ClassType->isDependentType()) {
8666         DeclarationName Name
8667           = Context.DeclarationNames.getCXXDestructorName(
8668                                         Context.getCanonicalType(ClassType));
8669         if (NewFD->getDeclName() != Name) {
8670           Diag(NewFD->getLocation(), diag::err_destructor_name);
8671           NewFD->setInvalidDecl();
8672           return Redeclaration;
8673         }
8674       }
8675     } else if (CXXConversionDecl *Conversion
8676                = dyn_cast<CXXConversionDecl>(NewFD)) {
8677       ActOnConversionDeclarator(Conversion);
8678     }
8679 
8680     // Find any virtual functions that this function overrides.
8681     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8682       if (!Method->isFunctionTemplateSpecialization() &&
8683           !Method->getDescribedFunctionTemplate() &&
8684           Method->isCanonicalDecl()) {
8685         if (AddOverriddenMethods(Method->getParent(), Method)) {
8686           // If the function was marked as "static", we have a problem.
8687           if (NewFD->getStorageClass() == SC_Static) {
8688             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8689           }
8690         }
8691       }
8692 
8693       if (Method->isStatic())
8694         checkThisInStaticMemberFunctionType(Method);
8695     }
8696 
8697     // Extra checking for C++ overloaded operators (C++ [over.oper]).
8698     if (NewFD->isOverloadedOperator() &&
8699         CheckOverloadedOperatorDeclaration(NewFD)) {
8700       NewFD->setInvalidDecl();
8701       return Redeclaration;
8702     }
8703 
8704     // Extra checking for C++0x literal operators (C++0x [over.literal]).
8705     if (NewFD->getLiteralIdentifier() &&
8706         CheckLiteralOperatorDeclaration(NewFD)) {
8707       NewFD->setInvalidDecl();
8708       return Redeclaration;
8709     }
8710 
8711     // In C++, check default arguments now that we have merged decls. Unless
8712     // the lexical context is the class, because in this case this is done
8713     // during delayed parsing anyway.
8714     if (!CurContext->isRecord())
8715       CheckCXXDefaultArguments(NewFD);
8716 
8717     // If this function declares a builtin function, check the type of this
8718     // declaration against the expected type for the builtin.
8719     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8720       ASTContext::GetBuiltinTypeError Error;
8721       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8722       QualType T = Context.GetBuiltinType(BuiltinID, Error);
8723       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8724         // The type of this function differs from the type of the builtin,
8725         // so forget about the builtin entirely.
8726         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
8727       }
8728     }
8729 
8730     // If this function is declared as being extern "C", then check to see if
8731     // the function returns a UDT (class, struct, or union type) that is not C
8732     // compatible, and if it does, warn the user.
8733     // But, issue any diagnostic on the first declaration only.
8734     if (Previous.empty() && NewFD->isExternC()) {
8735       QualType R = NewFD->getReturnType();
8736       if (R->isIncompleteType() && !R->isVoidType())
8737         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8738             << NewFD << R;
8739       else if (!R.isPODType(Context) && !R->isVoidType() &&
8740                !R->isObjCObjectPointerType())
8741         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8742     }
8743   }
8744   return Redeclaration;
8745 }
8746 
8747 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8748   // C++11 [basic.start.main]p3:
8749   //   A program that [...] declares main to be inline, static or
8750   //   constexpr is ill-formed.
8751   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
8752   //   appear in a declaration of main.
8753   // static main is not an error under C99, but we should warn about it.
8754   // We accept _Noreturn main as an extension.
8755   if (FD->getStorageClass() == SC_Static)
8756     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8757          ? diag::err_static_main : diag::warn_static_main)
8758       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8759   if (FD->isInlineSpecified())
8760     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8761       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8762   if (DS.isNoreturnSpecified()) {
8763     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8764     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8765     Diag(NoreturnLoc, diag::ext_noreturn_main);
8766     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8767       << FixItHint::CreateRemoval(NoreturnRange);
8768   }
8769   if (FD->isConstexpr()) {
8770     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8771       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8772     FD->setConstexpr(false);
8773   }
8774 
8775   if (getLangOpts().OpenCL) {
8776     Diag(FD->getLocation(), diag::err_opencl_no_main)
8777         << FD->hasAttr<OpenCLKernelAttr>();
8778     FD->setInvalidDecl();
8779     return;
8780   }
8781 
8782   QualType T = FD->getType();
8783   assert(T->isFunctionType() && "function decl is not of function type");
8784   const FunctionType* FT = T->castAs<FunctionType>();
8785 
8786   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8787     // In C with GNU extensions we allow main() to have non-integer return
8788     // type, but we should warn about the extension, and we disable the
8789     // implicit-return-zero rule.
8790 
8791     // GCC in C mode accepts qualified 'int'.
8792     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8793       FD->setHasImplicitReturnZero(true);
8794     else {
8795       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8796       SourceRange RTRange = FD->getReturnTypeSourceRange();
8797       if (RTRange.isValid())
8798         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8799             << FixItHint::CreateReplacement(RTRange, "int");
8800     }
8801   } else {
8802     // In C and C++, main magically returns 0 if you fall off the end;
8803     // set the flag which tells us that.
8804     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8805 
8806     // All the standards say that main() should return 'int'.
8807     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8808       FD->setHasImplicitReturnZero(true);
8809     else {
8810       // Otherwise, this is just a flat-out error.
8811       SourceRange RTRange = FD->getReturnTypeSourceRange();
8812       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8813           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8814                                 : FixItHint());
8815       FD->setInvalidDecl(true);
8816     }
8817   }
8818 
8819   // Treat protoless main() as nullary.
8820   if (isa<FunctionNoProtoType>(FT)) return;
8821 
8822   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8823   unsigned nparams = FTP->getNumParams();
8824   assert(FD->getNumParams() == nparams);
8825 
8826   bool HasExtraParameters = (nparams > 3);
8827 
8828   if (FTP->isVariadic()) {
8829     Diag(FD->getLocation(), diag::ext_variadic_main);
8830     // FIXME: if we had information about the location of the ellipsis, we
8831     // could add a FixIt hint to remove it as a parameter.
8832   }
8833 
8834   // Darwin passes an undocumented fourth argument of type char**.  If
8835   // other platforms start sprouting these, the logic below will start
8836   // getting shifty.
8837   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8838     HasExtraParameters = false;
8839 
8840   if (HasExtraParameters) {
8841     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8842     FD->setInvalidDecl(true);
8843     nparams = 3;
8844   }
8845 
8846   // FIXME: a lot of the following diagnostics would be improved
8847   // if we had some location information about types.
8848 
8849   QualType CharPP =
8850     Context.getPointerType(Context.getPointerType(Context.CharTy));
8851   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
8852 
8853   for (unsigned i = 0; i < nparams; ++i) {
8854     QualType AT = FTP->getParamType(i);
8855 
8856     bool mismatch = true;
8857 
8858     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
8859       mismatch = false;
8860     else if (Expected[i] == CharPP) {
8861       // As an extension, the following forms are okay:
8862       //   char const **
8863       //   char const * const *
8864       //   char * const *
8865 
8866       QualifierCollector qs;
8867       const PointerType* PT;
8868       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
8869           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
8870           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
8871                               Context.CharTy)) {
8872         qs.removeConst();
8873         mismatch = !qs.empty();
8874       }
8875     }
8876 
8877     if (mismatch) {
8878       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
8879       // TODO: suggest replacing given type with expected type
8880       FD->setInvalidDecl(true);
8881     }
8882   }
8883 
8884   if (nparams == 1 && !FD->isInvalidDecl()) {
8885     Diag(FD->getLocation(), diag::warn_main_one_arg);
8886   }
8887 
8888   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8889     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8890     FD->setInvalidDecl();
8891   }
8892 }
8893 
8894 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
8895   QualType T = FD->getType();
8896   assert(T->isFunctionType() && "function decl is not of function type");
8897   const FunctionType *FT = T->castAs<FunctionType>();
8898 
8899   // Set an implicit return of 'zero' if the function can return some integral,
8900   // enumeration, pointer or nullptr type.
8901   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
8902       FT->getReturnType()->isAnyPointerType() ||
8903       FT->getReturnType()->isNullPtrType())
8904     // DllMain is exempt because a return value of zero means it failed.
8905     if (FD->getName() != "DllMain")
8906       FD->setHasImplicitReturnZero(true);
8907 
8908   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8909     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8910     FD->setInvalidDecl();
8911   }
8912 }
8913 
8914 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
8915   // FIXME: Need strict checking.  In C89, we need to check for
8916   // any assignment, increment, decrement, function-calls, or
8917   // commas outside of a sizeof.  In C99, it's the same list,
8918   // except that the aforementioned are allowed in unevaluated
8919   // expressions.  Everything else falls under the
8920   // "may accept other forms of constant expressions" exception.
8921   // (We never end up here for C++, so the constant expression
8922   // rules there don't matter.)
8923   const Expr *Culprit;
8924   if (Init->isConstantInitializer(Context, false, &Culprit))
8925     return false;
8926   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
8927     << Culprit->getSourceRange();
8928   return true;
8929 }
8930 
8931 namespace {
8932   // Visits an initialization expression to see if OrigDecl is evaluated in
8933   // its own initialization and throws a warning if it does.
8934   class SelfReferenceChecker
8935       : public EvaluatedExprVisitor<SelfReferenceChecker> {
8936     Sema &S;
8937     Decl *OrigDecl;
8938     bool isRecordType;
8939     bool isPODType;
8940     bool isReferenceType;
8941 
8942     bool isInitList;
8943     llvm::SmallVector<unsigned, 4> InitFieldIndex;
8944 
8945   public:
8946     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
8947 
8948     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
8949                                                     S(S), OrigDecl(OrigDecl) {
8950       isPODType = false;
8951       isRecordType = false;
8952       isReferenceType = false;
8953       isInitList = false;
8954       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
8955         isPODType = VD->getType().isPODType(S.Context);
8956         isRecordType = VD->getType()->isRecordType();
8957         isReferenceType = VD->getType()->isReferenceType();
8958       }
8959     }
8960 
8961     // For most expressions, just call the visitor.  For initializer lists,
8962     // track the index of the field being initialized since fields are
8963     // initialized in order allowing use of previously initialized fields.
8964     void CheckExpr(Expr *E) {
8965       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
8966       if (!InitList) {
8967         Visit(E);
8968         return;
8969       }
8970 
8971       // Track and increment the index here.
8972       isInitList = true;
8973       InitFieldIndex.push_back(0);
8974       for (auto Child : InitList->children()) {
8975         CheckExpr(cast<Expr>(Child));
8976         ++InitFieldIndex.back();
8977       }
8978       InitFieldIndex.pop_back();
8979     }
8980 
8981     // Returns true if MemberExpr is checked and no futher checking is needed.
8982     // Returns false if additional checking is required.
8983     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
8984       llvm::SmallVector<FieldDecl*, 4> Fields;
8985       Expr *Base = E;
8986       bool ReferenceField = false;
8987 
8988       // Get the field memebers used.
8989       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8990         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
8991         if (!FD)
8992           return false;
8993         Fields.push_back(FD);
8994         if (FD->getType()->isReferenceType())
8995           ReferenceField = true;
8996         Base = ME->getBase()->IgnoreParenImpCasts();
8997       }
8998 
8999       // Keep checking only if the base Decl is the same.
9000       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9001       if (!DRE || DRE->getDecl() != OrigDecl)
9002         return false;
9003 
9004       // A reference field can be bound to an unininitialized field.
9005       if (CheckReference && !ReferenceField)
9006         return true;
9007 
9008       // Convert FieldDecls to their index number.
9009       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9010       for (const FieldDecl *I : llvm::reverse(Fields))
9011         UsedFieldIndex.push_back(I->getFieldIndex());
9012 
9013       // See if a warning is needed by checking the first difference in index
9014       // numbers.  If field being used has index less than the field being
9015       // initialized, then the use is safe.
9016       for (auto UsedIter = UsedFieldIndex.begin(),
9017                 UsedEnd = UsedFieldIndex.end(),
9018                 OrigIter = InitFieldIndex.begin(),
9019                 OrigEnd = InitFieldIndex.end();
9020            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9021         if (*UsedIter < *OrigIter)
9022           return true;
9023         if (*UsedIter > *OrigIter)
9024           break;
9025       }
9026 
9027       // TODO: Add a different warning which will print the field names.
9028       HandleDeclRefExpr(DRE);
9029       return true;
9030     }
9031 
9032     // For most expressions, the cast is directly above the DeclRefExpr.
9033     // For conditional operators, the cast can be outside the conditional
9034     // operator if both expressions are DeclRefExpr's.
9035     void HandleValue(Expr *E) {
9036       E = E->IgnoreParens();
9037       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9038         HandleDeclRefExpr(DRE);
9039         return;
9040       }
9041 
9042       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9043         Visit(CO->getCond());
9044         HandleValue(CO->getTrueExpr());
9045         HandleValue(CO->getFalseExpr());
9046         return;
9047       }
9048 
9049       if (BinaryConditionalOperator *BCO =
9050               dyn_cast<BinaryConditionalOperator>(E)) {
9051         Visit(BCO->getCond());
9052         HandleValue(BCO->getFalseExpr());
9053         return;
9054       }
9055 
9056       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9057         HandleValue(OVE->getSourceExpr());
9058         return;
9059       }
9060 
9061       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9062         if (BO->getOpcode() == BO_Comma) {
9063           Visit(BO->getLHS());
9064           HandleValue(BO->getRHS());
9065           return;
9066         }
9067       }
9068 
9069       if (isa<MemberExpr>(E)) {
9070         if (isInitList) {
9071           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9072                                       false /*CheckReference*/))
9073             return;
9074         }
9075 
9076         Expr *Base = E->IgnoreParenImpCasts();
9077         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9078           // Check for static member variables and don't warn on them.
9079           if (!isa<FieldDecl>(ME->getMemberDecl()))
9080             return;
9081           Base = ME->getBase()->IgnoreParenImpCasts();
9082         }
9083         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9084           HandleDeclRefExpr(DRE);
9085         return;
9086       }
9087 
9088       Visit(E);
9089     }
9090 
9091     // Reference types not handled in HandleValue are handled here since all
9092     // uses of references are bad, not just r-value uses.
9093     void VisitDeclRefExpr(DeclRefExpr *E) {
9094       if (isReferenceType)
9095         HandleDeclRefExpr(E);
9096     }
9097 
9098     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9099       if (E->getCastKind() == CK_LValueToRValue) {
9100         HandleValue(E->getSubExpr());
9101         return;
9102       }
9103 
9104       Inherited::VisitImplicitCastExpr(E);
9105     }
9106 
9107     void VisitMemberExpr(MemberExpr *E) {
9108       if (isInitList) {
9109         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9110           return;
9111       }
9112 
9113       // Don't warn on arrays since they can be treated as pointers.
9114       if (E->getType()->canDecayToPointerType()) return;
9115 
9116       // Warn when a non-static method call is followed by non-static member
9117       // field accesses, which is followed by a DeclRefExpr.
9118       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9119       bool Warn = (MD && !MD->isStatic());
9120       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9121       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9122         if (!isa<FieldDecl>(ME->getMemberDecl()))
9123           Warn = false;
9124         Base = ME->getBase()->IgnoreParenImpCasts();
9125       }
9126 
9127       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9128         if (Warn)
9129           HandleDeclRefExpr(DRE);
9130         return;
9131       }
9132 
9133       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9134       // Visit that expression.
9135       Visit(Base);
9136     }
9137 
9138     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9139       Expr *Callee = E->getCallee();
9140 
9141       if (isa<UnresolvedLookupExpr>(Callee))
9142         return Inherited::VisitCXXOperatorCallExpr(E);
9143 
9144       Visit(Callee);
9145       for (auto Arg: E->arguments())
9146         HandleValue(Arg->IgnoreParenImpCasts());
9147     }
9148 
9149     void VisitUnaryOperator(UnaryOperator *E) {
9150       // For POD record types, addresses of its own members are well-defined.
9151       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9152           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9153         if (!isPODType)
9154           HandleValue(E->getSubExpr());
9155         return;
9156       }
9157 
9158       if (E->isIncrementDecrementOp()) {
9159         HandleValue(E->getSubExpr());
9160         return;
9161       }
9162 
9163       Inherited::VisitUnaryOperator(E);
9164     }
9165 
9166     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9167 
9168     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9169       if (E->getConstructor()->isCopyConstructor()) {
9170         Expr *ArgExpr = E->getArg(0);
9171         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9172           if (ILE->getNumInits() == 1)
9173             ArgExpr = ILE->getInit(0);
9174         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9175           if (ICE->getCastKind() == CK_NoOp)
9176             ArgExpr = ICE->getSubExpr();
9177         HandleValue(ArgExpr);
9178         return;
9179       }
9180       Inherited::VisitCXXConstructExpr(E);
9181     }
9182 
9183     void VisitCallExpr(CallExpr *E) {
9184       // Treat std::move as a use.
9185       if (E->getNumArgs() == 1) {
9186         if (FunctionDecl *FD = E->getDirectCallee()) {
9187           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9188               FD->getIdentifier()->isStr("move")) {
9189             HandleValue(E->getArg(0));
9190             return;
9191           }
9192         }
9193       }
9194 
9195       Inherited::VisitCallExpr(E);
9196     }
9197 
9198     void VisitBinaryOperator(BinaryOperator *E) {
9199       if (E->isCompoundAssignmentOp()) {
9200         HandleValue(E->getLHS());
9201         Visit(E->getRHS());
9202         return;
9203       }
9204 
9205       Inherited::VisitBinaryOperator(E);
9206     }
9207 
9208     // A custom visitor for BinaryConditionalOperator is needed because the
9209     // regular visitor would check the condition and true expression separately
9210     // but both point to the same place giving duplicate diagnostics.
9211     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9212       Visit(E->getCond());
9213       Visit(E->getFalseExpr());
9214     }
9215 
9216     void HandleDeclRefExpr(DeclRefExpr *DRE) {
9217       Decl* ReferenceDecl = DRE->getDecl();
9218       if (OrigDecl != ReferenceDecl) return;
9219       unsigned diag;
9220       if (isReferenceType) {
9221         diag = diag::warn_uninit_self_reference_in_reference_init;
9222       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9223         diag = diag::warn_static_self_reference_in_init;
9224       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9225                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9226                  DRE->getDecl()->getType()->isRecordType()) {
9227         diag = diag::warn_uninit_self_reference_in_init;
9228       } else {
9229         // Local variables will be handled by the CFG analysis.
9230         return;
9231       }
9232 
9233       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9234                             S.PDiag(diag)
9235                               << DRE->getNameInfo().getName()
9236                               << OrigDecl->getLocation()
9237                               << DRE->getSourceRange());
9238     }
9239   };
9240 
9241   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9242   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9243                                  bool DirectInit) {
9244     // Parameters arguments are occassionially constructed with itself,
9245     // for instance, in recursive functions.  Skip them.
9246     if (isa<ParmVarDecl>(OrigDecl))
9247       return;
9248 
9249     E = E->IgnoreParens();
9250 
9251     // Skip checking T a = a where T is not a record or reference type.
9252     // Doing so is a way to silence uninitialized warnings.
9253     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9254       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9255         if (ICE->getCastKind() == CK_LValueToRValue)
9256           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9257             if (DRE->getDecl() == OrigDecl)
9258               return;
9259 
9260     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9261   }
9262 } // end anonymous namespace
9263 
9264 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9265                                             DeclarationName Name, QualType Type,
9266                                             TypeSourceInfo *TSI,
9267                                             SourceRange Range, bool DirectInit,
9268                                             Expr *Init) {
9269   bool IsInitCapture = !VDecl;
9270   assert((!VDecl || !VDecl->isInitCapture()) &&
9271          "init captures are expected to be deduced prior to initialization");
9272 
9273   ArrayRef<Expr *> DeduceInits = Init;
9274   if (DirectInit) {
9275     if (auto *PL = dyn_cast<ParenListExpr>(Init))
9276       DeduceInits = PL->exprs();
9277     else if (auto *IL = dyn_cast<InitListExpr>(Init))
9278       DeduceInits = IL->inits();
9279   }
9280 
9281   // Deduction only works if we have exactly one source expression.
9282   if (DeduceInits.empty()) {
9283     // It isn't possible to write this directly, but it is possible to
9284     // end up in this situation with "auto x(some_pack...);"
9285     Diag(Init->getLocStart(), IsInitCapture
9286                                   ? diag::err_init_capture_no_expression
9287                                   : diag::err_auto_var_init_no_expression)
9288         << Name << Type << Range;
9289     return QualType();
9290   }
9291 
9292   if (DeduceInits.size() > 1) {
9293     Diag(DeduceInits[1]->getLocStart(),
9294          IsInitCapture ? diag::err_init_capture_multiple_expressions
9295                        : diag::err_auto_var_init_multiple_expressions)
9296         << Name << Type << Range;
9297     return QualType();
9298   }
9299 
9300   Expr *DeduceInit = DeduceInits[0];
9301   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9302     Diag(Init->getLocStart(), IsInitCapture
9303                                   ? diag::err_init_capture_paren_braces
9304                                   : diag::err_auto_var_init_paren_braces)
9305         << isa<InitListExpr>(Init) << Name << Type << Range;
9306     return QualType();
9307   }
9308 
9309   // Expressions default to 'id' when we're in a debugger.
9310   bool DefaultedAnyToId = false;
9311   if (getLangOpts().DebuggerCastResultToId &&
9312       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9313     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9314     if (Result.isInvalid()) {
9315       return QualType();
9316     }
9317     Init = Result.get();
9318     DefaultedAnyToId = true;
9319   }
9320 
9321   QualType DeducedType;
9322   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9323     if (!IsInitCapture)
9324       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9325     else if (isa<InitListExpr>(Init))
9326       Diag(Range.getBegin(),
9327            diag::err_init_capture_deduction_failure_from_init_list)
9328           << Name
9329           << (DeduceInit->getType().isNull() ? TSI->getType()
9330                                              : DeduceInit->getType())
9331           << DeduceInit->getSourceRange();
9332     else
9333       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9334           << Name << TSI->getType()
9335           << (DeduceInit->getType().isNull() ? TSI->getType()
9336                                              : DeduceInit->getType())
9337           << DeduceInit->getSourceRange();
9338   }
9339 
9340   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9341   // 'id' instead of a specific object type prevents most of our usual
9342   // checks.
9343   // We only want to warn outside of template instantiations, though:
9344   // inside a template, the 'id' could have come from a parameter.
9345   if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
9346       !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9347     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9348     Diag(Loc, diag::warn_auto_var_is_id) << Name << Range;
9349   }
9350 
9351   return DeducedType;
9352 }
9353 
9354 /// AddInitializerToDecl - Adds the initializer Init to the
9355 /// declaration dcl. If DirectInit is true, this is C++ direct
9356 /// initialization rather than copy initialization.
9357 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
9358                                 bool DirectInit, bool TypeMayContainAuto) {
9359   // If there is no declaration, there was an error parsing it.  Just ignore
9360   // the initializer.
9361   if (!RealDecl || RealDecl->isInvalidDecl()) {
9362     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
9363     return;
9364   }
9365 
9366   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
9367     // Pure-specifiers are handled in ActOnPureSpecifier.
9368     Diag(Method->getLocation(), diag::err_member_function_initialization)
9369       << Method->getDeclName() << Init->getSourceRange();
9370     Method->setInvalidDecl();
9371     return;
9372   }
9373 
9374   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9375   if (!VDecl) {
9376     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
9377     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9378     RealDecl->setInvalidDecl();
9379     return;
9380   }
9381 
9382   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9383   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
9384     // Attempt typo correction early so that the type of the init expression can
9385     // be deduced based on the chosen correction if the original init contains a
9386     // TypoExpr.
9387     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
9388     if (!Res.isUsable()) {
9389       RealDecl->setInvalidDecl();
9390       return;
9391     }
9392     Init = Res.get();
9393 
9394     QualType DeducedType = deduceVarTypeFromInitializer(
9395         VDecl, VDecl->getDeclName(), VDecl->getType(),
9396         VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
9397     if (DeducedType.isNull()) {
9398       RealDecl->setInvalidDecl();
9399       return;
9400     }
9401 
9402     VDecl->setType(DeducedType);
9403     assert(VDecl->isLinkageValid());
9404 
9405     // In ARC, infer lifetime.
9406     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9407       VDecl->setInvalidDecl();
9408 
9409     // If this is a redeclaration, check that the type we just deduced matches
9410     // the previously declared type.
9411     if (VarDecl *Old = VDecl->getPreviousDecl()) {
9412       // We never need to merge the type, because we cannot form an incomplete
9413       // array of auto, nor deduce such a type.
9414       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9415     }
9416 
9417     // Check the deduced type is valid for a variable declaration.
9418     CheckVariableDeclarationType(VDecl);
9419     if (VDecl->isInvalidDecl())
9420       return;
9421   }
9422 
9423   // dllimport cannot be used on variable definitions.
9424   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
9425     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
9426     VDecl->setInvalidDecl();
9427     return;
9428   }
9429 
9430   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
9431     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
9432     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
9433     VDecl->setInvalidDecl();
9434     return;
9435   }
9436 
9437   if (!VDecl->getType()->isDependentType()) {
9438     // A definition must end up with a complete type, which means it must be
9439     // complete with the restriction that an array type might be completed by
9440     // the initializer; note that later code assumes this restriction.
9441     QualType BaseDeclType = VDecl->getType();
9442     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
9443       BaseDeclType = Array->getElementType();
9444     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
9445                             diag::err_typecheck_decl_incomplete_type)) {
9446       RealDecl->setInvalidDecl();
9447       return;
9448     }
9449 
9450     // The variable can not have an abstract class type.
9451     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9452                                diag::err_abstract_type_in_decl,
9453                                AbstractVariableType))
9454       VDecl->setInvalidDecl();
9455   }
9456 
9457   VarDecl *Def;
9458   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
9459     NamedDecl *Hidden = nullptr;
9460     if (!hasVisibleDefinition(Def, &Hidden) &&
9461         (VDecl->getFormalLinkage() == InternalLinkage ||
9462          VDecl->getDescribedVarTemplate() ||
9463          VDecl->getNumTemplateParameterLists() ||
9464          VDecl->getDeclContext()->isDependentContext())) {
9465       // The previous definition is hidden, and multiple definitions are
9466       // permitted (in separate TUs). Form another definition of it.
9467     } else {
9468       Diag(VDecl->getLocation(), diag::err_redefinition)
9469         << VDecl->getDeclName();
9470       Diag(Def->getLocation(), diag::note_previous_definition);
9471       VDecl->setInvalidDecl();
9472       return;
9473     }
9474   }
9475 
9476   if (getLangOpts().CPlusPlus) {
9477     // C++ [class.static.data]p4
9478     //   If a static data member is of const integral or const
9479     //   enumeration type, its declaration in the class definition can
9480     //   specify a constant-initializer which shall be an integral
9481     //   constant expression (5.19). In that case, the member can appear
9482     //   in integral constant expressions. The member shall still be
9483     //   defined in a namespace scope if it is used in the program and the
9484     //   namespace scope definition shall not contain an initializer.
9485     //
9486     // We already performed a redefinition check above, but for static
9487     // data members we also need to check whether there was an in-class
9488     // declaration with an initializer.
9489     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9490       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9491           << VDecl->getDeclName();
9492       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9493            diag::note_previous_initializer)
9494           << 0;
9495       return;
9496     }
9497 
9498     if (VDecl->hasLocalStorage())
9499       getCurFunction()->setHasBranchProtectedScope();
9500 
9501     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9502       VDecl->setInvalidDecl();
9503       return;
9504     }
9505   }
9506 
9507   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9508   // a kernel function cannot be initialized."
9509   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
9510     Diag(VDecl->getLocation(), diag::err_local_cant_init);
9511     VDecl->setInvalidDecl();
9512     return;
9513   }
9514 
9515   // Get the decls type and save a reference for later, since
9516   // CheckInitializerTypes may change it.
9517   QualType DclT = VDecl->getType(), SavT = DclT;
9518 
9519   // Expressions default to 'id' when we're in a debugger
9520   // and we are assigning it to a variable of Objective-C pointer type.
9521   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9522       Init->getType() == Context.UnknownAnyTy) {
9523     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9524     if (Result.isInvalid()) {
9525       VDecl->setInvalidDecl();
9526       return;
9527     }
9528     Init = Result.get();
9529   }
9530 
9531   // Perform the initialization.
9532   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
9533   if (!VDecl->isInvalidDecl()) {
9534     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9535     InitializationKind Kind =
9536         DirectInit
9537             ? CXXDirectInit
9538                   ? InitializationKind::CreateDirect(VDecl->getLocation(),
9539                                                      Init->getLocStart(),
9540                                                      Init->getLocEnd())
9541                   : InitializationKind::CreateDirectList(VDecl->getLocation())
9542             : InitializationKind::CreateCopy(VDecl->getLocation(),
9543                                              Init->getLocStart());
9544 
9545     MultiExprArg Args = Init;
9546     if (CXXDirectInit)
9547       Args = MultiExprArg(CXXDirectInit->getExprs(),
9548                           CXXDirectInit->getNumExprs());
9549 
9550     // Try to correct any TypoExprs in the initialization arguments.
9551     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
9552       ExprResult Res = CorrectDelayedTyposInExpr(
9553           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
9554             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
9555             return Init.Failed() ? ExprError() : E;
9556           });
9557       if (Res.isInvalid()) {
9558         VDecl->setInvalidDecl();
9559       } else if (Res.get() != Args[Idx]) {
9560         Args[Idx] = Res.get();
9561       }
9562     }
9563     if (VDecl->isInvalidDecl())
9564       return;
9565 
9566     InitializationSequence InitSeq(*this, Entity, Kind, Args,
9567                                    /*TopLevelOfInitList=*/false,
9568                                    /*TreatUnavailableAsInvalid=*/false);
9569     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
9570     if (Result.isInvalid()) {
9571       VDecl->setInvalidDecl();
9572       return;
9573     }
9574 
9575     Init = Result.getAs<Expr>();
9576   }
9577 
9578   // Check for self-references within variable initializers.
9579   // Variables declared within a function/method body (except for references)
9580   // are handled by a dataflow analysis.
9581   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
9582       VDecl->getType()->isReferenceType()) {
9583     CheckSelfReference(*this, RealDecl, Init, DirectInit);
9584   }
9585 
9586   // If the type changed, it means we had an incomplete type that was
9587   // completed by the initializer. For example:
9588   //   int ary[] = { 1, 3, 5 };
9589   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
9590   if (!VDecl->isInvalidDecl() && (DclT != SavT))
9591     VDecl->setType(DclT);
9592 
9593   if (!VDecl->isInvalidDecl()) {
9594     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
9595 
9596     if (VDecl->hasAttr<BlocksAttr>())
9597       checkRetainCycles(VDecl, Init);
9598 
9599     // It is safe to assign a weak reference into a strong variable.
9600     // Although this code can still have problems:
9601     //   id x = self.weakProp;
9602     //   id y = self.weakProp;
9603     // we do not warn to warn spuriously when 'x' and 'y' are on separate
9604     // paths through the function. This should be revisited if
9605     // -Wrepeated-use-of-weak is made flow-sensitive.
9606     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
9607         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9608                          Init->getLocStart()))
9609       getCurFunction()->markSafeWeakUse(Init);
9610   }
9611 
9612   // The initialization is usually a full-expression.
9613   //
9614   // FIXME: If this is a braced initialization of an aggregate, it is not
9615   // an expression, and each individual field initializer is a separate
9616   // full-expression. For instance, in:
9617   //
9618   //   struct Temp { ~Temp(); };
9619   //   struct S { S(Temp); };
9620   //   struct T { S a, b; } t = { Temp(), Temp() }
9621   //
9622   // we should destroy the first Temp before constructing the second.
9623   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
9624                                           false,
9625                                           VDecl->isConstexpr());
9626   if (Result.isInvalid()) {
9627     VDecl->setInvalidDecl();
9628     return;
9629   }
9630   Init = Result.get();
9631 
9632   // Attach the initializer to the decl.
9633   VDecl->setInit(Init);
9634 
9635   if (VDecl->isLocalVarDecl()) {
9636     // C99 6.7.8p4: All the expressions in an initializer for an object that has
9637     // static storage duration shall be constant expressions or string literals.
9638     // C++ does not have this restriction.
9639     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
9640       const Expr *Culprit;
9641       if (VDecl->getStorageClass() == SC_Static)
9642         CheckForConstantInitializer(Init, DclT);
9643       // C89 is stricter than C99 for non-static aggregate types.
9644       // C89 6.5.7p3: All the expressions [...] in an initializer list
9645       // for an object that has aggregate or union type shall be
9646       // constant expressions.
9647       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
9648                isa<InitListExpr>(Init) &&
9649                !Init->isConstantInitializer(Context, false, &Culprit))
9650         Diag(Culprit->getExprLoc(),
9651              diag::ext_aggregate_init_not_constant)
9652           << Culprit->getSourceRange();
9653     }
9654   } else if (VDecl->isStaticDataMember() &&
9655              VDecl->getLexicalDeclContext()->isRecord()) {
9656     // This is an in-class initialization for a static data member, e.g.,
9657     //
9658     // struct S {
9659     //   static const int value = 17;
9660     // };
9661 
9662     // C++ [class.mem]p4:
9663     //   A member-declarator can contain a constant-initializer only
9664     //   if it declares a static member (9.4) of const integral or
9665     //   const enumeration type, see 9.4.2.
9666     //
9667     // C++11 [class.static.data]p3:
9668     //   If a non-volatile const static data member is of integral or
9669     //   enumeration type, its declaration in the class definition can
9670     //   specify a brace-or-equal-initializer in which every initalizer-clause
9671     //   that is an assignment-expression is a constant expression. A static
9672     //   data member of literal type can be declared in the class definition
9673     //   with the constexpr specifier; if so, its declaration shall specify a
9674     //   brace-or-equal-initializer in which every initializer-clause that is
9675     //   an assignment-expression is a constant expression.
9676 
9677     // Do nothing on dependent types.
9678     if (DclT->isDependentType()) {
9679 
9680     // Allow any 'static constexpr' members, whether or not they are of literal
9681     // type. We separately check that every constexpr variable is of literal
9682     // type.
9683     } else if (VDecl->isConstexpr()) {
9684 
9685     // Require constness.
9686     } else if (!DclT.isConstQualified()) {
9687       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
9688         << Init->getSourceRange();
9689       VDecl->setInvalidDecl();
9690 
9691     // We allow integer constant expressions in all cases.
9692     } else if (DclT->isIntegralOrEnumerationType()) {
9693       // Check whether the expression is a constant expression.
9694       SourceLocation Loc;
9695       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
9696         // In C++11, a non-constexpr const static data member with an
9697         // in-class initializer cannot be volatile.
9698         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
9699       else if (Init->isValueDependent())
9700         ; // Nothing to check.
9701       else if (Init->isIntegerConstantExpr(Context, &Loc))
9702         ; // Ok, it's an ICE!
9703       else if (Init->isEvaluatable(Context)) {
9704         // If we can constant fold the initializer through heroics, accept it,
9705         // but report this as a use of an extension for -pedantic.
9706         Diag(Loc, diag::ext_in_class_initializer_non_constant)
9707           << Init->getSourceRange();
9708       } else {
9709         // Otherwise, this is some crazy unknown case.  Report the issue at the
9710         // location provided by the isIntegerConstantExpr failed check.
9711         Diag(Loc, diag::err_in_class_initializer_non_constant)
9712           << Init->getSourceRange();
9713         VDecl->setInvalidDecl();
9714       }
9715 
9716     // We allow foldable floating-point constants as an extension.
9717     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
9718       // In C++98, this is a GNU extension. In C++11, it is not, but we support
9719       // it anyway and provide a fixit to add the 'constexpr'.
9720       if (getLangOpts().CPlusPlus11) {
9721         Diag(VDecl->getLocation(),
9722              diag::ext_in_class_initializer_float_type_cxx11)
9723             << DclT << Init->getSourceRange();
9724         Diag(VDecl->getLocStart(),
9725              diag::note_in_class_initializer_float_type_cxx11)
9726             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9727       } else {
9728         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
9729           << DclT << Init->getSourceRange();
9730 
9731         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
9732           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
9733             << Init->getSourceRange();
9734           VDecl->setInvalidDecl();
9735         }
9736       }
9737 
9738     // Suggest adding 'constexpr' in C++11 for literal types.
9739     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9740       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9741         << DclT << Init->getSourceRange()
9742         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9743       VDecl->setConstexpr(true);
9744 
9745     } else {
9746       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9747         << DclT << Init->getSourceRange();
9748       VDecl->setInvalidDecl();
9749     }
9750   } else if (VDecl->isFileVarDecl()) {
9751     if (VDecl->getStorageClass() == SC_Extern &&
9752         (!getLangOpts().CPlusPlus ||
9753          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
9754            VDecl->isExternC())) &&
9755         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
9756       Diag(VDecl->getLocation(), diag::warn_extern_init);
9757 
9758     // C99 6.7.8p4. All file scoped initializers need to be constant.
9759     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9760       CheckForConstantInitializer(Init, DclT);
9761   }
9762 
9763   // We will represent direct-initialization similarly to copy-initialization:
9764   //    int x(1);  -as-> int x = 1;
9765   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9766   //
9767   // Clients that want to distinguish between the two forms, can check for
9768   // direct initializer using VarDecl::getInitStyle().
9769   // A major benefit is that clients that don't particularly care about which
9770   // exactly form was it (like the CodeGen) can handle both cases without
9771   // special case code.
9772 
9773   // C++ 8.5p11:
9774   // The form of initialization (using parentheses or '=') is generally
9775   // insignificant, but does matter when the entity being initialized has a
9776   // class type.
9777   if (CXXDirectInit) {
9778     assert(DirectInit && "Call-style initializer must be direct init.");
9779     VDecl->setInitStyle(VarDecl::CallInit);
9780   } else if (DirectInit) {
9781     // This must be list-initialization. No other way is direct-initialization.
9782     VDecl->setInitStyle(VarDecl::ListInit);
9783   }
9784 
9785   CheckCompleteVariableDeclaration(VDecl);
9786 }
9787 
9788 /// ActOnInitializerError - Given that there was an error parsing an
9789 /// initializer for the given declaration, try to return to some form
9790 /// of sanity.
9791 void Sema::ActOnInitializerError(Decl *D) {
9792   // Our main concern here is re-establishing invariants like "a
9793   // variable's type is either dependent or complete".
9794   if (!D || D->isInvalidDecl()) return;
9795 
9796   VarDecl *VD = dyn_cast<VarDecl>(D);
9797   if (!VD) return;
9798 
9799   // Auto types are meaningless if we can't make sense of the initializer.
9800   if (ParsingInitForAutoVars.count(D)) {
9801     D->setInvalidDecl();
9802     return;
9803   }
9804 
9805   QualType Ty = VD->getType();
9806   if (Ty->isDependentType()) return;
9807 
9808   // Require a complete type.
9809   if (RequireCompleteType(VD->getLocation(),
9810                           Context.getBaseElementType(Ty),
9811                           diag::err_typecheck_decl_incomplete_type)) {
9812     VD->setInvalidDecl();
9813     return;
9814   }
9815 
9816   // Require a non-abstract type.
9817   if (RequireNonAbstractType(VD->getLocation(), Ty,
9818                              diag::err_abstract_type_in_decl,
9819                              AbstractVariableType)) {
9820     VD->setInvalidDecl();
9821     return;
9822   }
9823 
9824   // Don't bother complaining about constructors or destructors,
9825   // though.
9826 }
9827 
9828 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
9829                                   bool TypeMayContainAuto) {
9830   // If there is no declaration, there was an error parsing it. Just ignore it.
9831   if (!RealDecl)
9832     return;
9833 
9834   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9835     QualType Type = Var->getType();
9836 
9837     // C++11 [dcl.spec.auto]p3
9838     if (TypeMayContainAuto && Type->getContainedAutoType()) {
9839       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
9840         << Var->getDeclName() << Type;
9841       Var->setInvalidDecl();
9842       return;
9843     }
9844 
9845     // C++11 [class.static.data]p3: A static data member can be declared with
9846     // the constexpr specifier; if so, its declaration shall specify
9847     // a brace-or-equal-initializer.
9848     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
9849     // the definition of a variable [...] or the declaration of a static data
9850     // member.
9851     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
9852       if (Var->isStaticDataMember())
9853         Diag(Var->getLocation(),
9854              diag::err_constexpr_static_mem_var_requires_init)
9855           << Var->getDeclName();
9856       else
9857         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
9858       Var->setInvalidDecl();
9859       return;
9860     }
9861 
9862     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
9863     // definition having the concept specifier is called a variable concept. A
9864     // concept definition refers to [...] a variable concept and its initializer.
9865     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
9866       if (VTD->isConcept()) {
9867         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
9868         Var->setInvalidDecl();
9869         return;
9870       }
9871     }
9872 
9873     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
9874     // be initialized.
9875     if (!Var->isInvalidDecl() &&
9876         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
9877         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
9878       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
9879       Var->setInvalidDecl();
9880       return;
9881     }
9882 
9883     switch (Var->isThisDeclarationADefinition()) {
9884     case VarDecl::Definition:
9885       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
9886         break;
9887 
9888       // We have an out-of-line definition of a static data member
9889       // that has an in-class initializer, so we type-check this like
9890       // a declaration.
9891       //
9892       // Fall through
9893 
9894     case VarDecl::DeclarationOnly:
9895       // It's only a declaration.
9896 
9897       // Block scope. C99 6.7p7: If an identifier for an object is
9898       // declared with no linkage (C99 6.2.2p6), the type for the
9899       // object shall be complete.
9900       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
9901           !Var->hasLinkage() && !Var->isInvalidDecl() &&
9902           RequireCompleteType(Var->getLocation(), Type,
9903                               diag::err_typecheck_decl_incomplete_type))
9904         Var->setInvalidDecl();
9905 
9906       // Make sure that the type is not abstract.
9907       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9908           RequireNonAbstractType(Var->getLocation(), Type,
9909                                  diag::err_abstract_type_in_decl,
9910                                  AbstractVariableType))
9911         Var->setInvalidDecl();
9912       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9913           Var->getStorageClass() == SC_PrivateExtern) {
9914         Diag(Var->getLocation(), diag::warn_private_extern);
9915         Diag(Var->getLocation(), diag::note_private_extern);
9916       }
9917 
9918       return;
9919 
9920     case VarDecl::TentativeDefinition:
9921       // File scope. C99 6.9.2p2: A declaration of an identifier for an
9922       // object that has file scope without an initializer, and without a
9923       // storage-class specifier or with the storage-class specifier "static",
9924       // constitutes a tentative definition. Note: A tentative definition with
9925       // external linkage is valid (C99 6.2.2p5).
9926       if (!Var->isInvalidDecl()) {
9927         if (const IncompleteArrayType *ArrayT
9928                                     = Context.getAsIncompleteArrayType(Type)) {
9929           if (RequireCompleteType(Var->getLocation(),
9930                                   ArrayT->getElementType(),
9931                                   diag::err_illegal_decl_array_incomplete_type))
9932             Var->setInvalidDecl();
9933         } else if (Var->getStorageClass() == SC_Static) {
9934           // C99 6.9.2p3: If the declaration of an identifier for an object is
9935           // a tentative definition and has internal linkage (C99 6.2.2p3), the
9936           // declared type shall not be an incomplete type.
9937           // NOTE: code such as the following
9938           //     static struct s;
9939           //     struct s { int a; };
9940           // is accepted by gcc. Hence here we issue a warning instead of
9941           // an error and we do not invalidate the static declaration.
9942           // NOTE: to avoid multiple warnings, only check the first declaration.
9943           if (Var->isFirstDecl())
9944             RequireCompleteType(Var->getLocation(), Type,
9945                                 diag::ext_typecheck_decl_incomplete_type);
9946         }
9947       }
9948 
9949       // Record the tentative definition; we're done.
9950       if (!Var->isInvalidDecl())
9951         TentativeDefinitions.push_back(Var);
9952       return;
9953     }
9954 
9955     // Provide a specific diagnostic for uninitialized variable
9956     // definitions with incomplete array type.
9957     if (Type->isIncompleteArrayType()) {
9958       Diag(Var->getLocation(),
9959            diag::err_typecheck_incomplete_array_needs_initializer);
9960       Var->setInvalidDecl();
9961       return;
9962     }
9963 
9964     // Provide a specific diagnostic for uninitialized variable
9965     // definitions with reference type.
9966     if (Type->isReferenceType()) {
9967       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
9968         << Var->getDeclName()
9969         << SourceRange(Var->getLocation(), Var->getLocation());
9970       Var->setInvalidDecl();
9971       return;
9972     }
9973 
9974     // Do not attempt to type-check the default initializer for a
9975     // variable with dependent type.
9976     if (Type->isDependentType())
9977       return;
9978 
9979     if (Var->isInvalidDecl())
9980       return;
9981 
9982     if (!Var->hasAttr<AliasAttr>()) {
9983       if (RequireCompleteType(Var->getLocation(),
9984                               Context.getBaseElementType(Type),
9985                               diag::err_typecheck_decl_incomplete_type)) {
9986         Var->setInvalidDecl();
9987         return;
9988       }
9989     } else {
9990       return;
9991     }
9992 
9993     // The variable can not have an abstract class type.
9994     if (RequireNonAbstractType(Var->getLocation(), Type,
9995                                diag::err_abstract_type_in_decl,
9996                                AbstractVariableType)) {
9997       Var->setInvalidDecl();
9998       return;
9999     }
10000 
10001     // Check for jumps past the implicit initializer.  C++0x
10002     // clarifies that this applies to a "variable with automatic
10003     // storage duration", not a "local variable".
10004     // C++11 [stmt.dcl]p3
10005     //   A program that jumps from a point where a variable with automatic
10006     //   storage duration is not in scope to a point where it is in scope is
10007     //   ill-formed unless the variable has scalar type, class type with a
10008     //   trivial default constructor and a trivial destructor, a cv-qualified
10009     //   version of one of these types, or an array of one of the preceding
10010     //   types and is declared without an initializer.
10011     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10012       if (const RecordType *Record
10013             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10014         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10015         // Mark the function for further checking even if the looser rules of
10016         // C++11 do not require such checks, so that we can diagnose
10017         // incompatibilities with C++98.
10018         if (!CXXRecord->isPOD())
10019           getCurFunction()->setHasBranchProtectedScope();
10020       }
10021     }
10022 
10023     // C++03 [dcl.init]p9:
10024     //   If no initializer is specified for an object, and the
10025     //   object is of (possibly cv-qualified) non-POD class type (or
10026     //   array thereof), the object shall be default-initialized; if
10027     //   the object is of const-qualified type, the underlying class
10028     //   type shall have a user-declared default
10029     //   constructor. Otherwise, if no initializer is specified for
10030     //   a non- static object, the object and its subobjects, if
10031     //   any, have an indeterminate initial value); if the object
10032     //   or any of its subobjects are of const-qualified type, the
10033     //   program is ill-formed.
10034     // C++0x [dcl.init]p11:
10035     //   If no initializer is specified for an object, the object is
10036     //   default-initialized; [...].
10037     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10038     InitializationKind Kind
10039       = InitializationKind::CreateDefault(Var->getLocation());
10040 
10041     InitializationSequence InitSeq(*this, Entity, Kind, None);
10042     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10043     if (Init.isInvalid())
10044       Var->setInvalidDecl();
10045     else if (Init.get()) {
10046       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10047       // This is important for template substitution.
10048       Var->setInitStyle(VarDecl::CallInit);
10049     }
10050 
10051     CheckCompleteVariableDeclaration(Var);
10052   }
10053 }
10054 
10055 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10056   // If there is no declaration, there was an error parsing it. Ignore it.
10057   if (!D)
10058     return;
10059 
10060   VarDecl *VD = dyn_cast<VarDecl>(D);
10061   if (!VD) {
10062     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10063     D->setInvalidDecl();
10064     return;
10065   }
10066 
10067   VD->setCXXForRangeDecl(true);
10068 
10069   // for-range-declaration cannot be given a storage class specifier.
10070   int Error = -1;
10071   switch (VD->getStorageClass()) {
10072   case SC_None:
10073     break;
10074   case SC_Extern:
10075     Error = 0;
10076     break;
10077   case SC_Static:
10078     Error = 1;
10079     break;
10080   case SC_PrivateExtern:
10081     Error = 2;
10082     break;
10083   case SC_Auto:
10084     Error = 3;
10085     break;
10086   case SC_Register:
10087     Error = 4;
10088     break;
10089   }
10090   if (Error != -1) {
10091     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10092       << VD->getDeclName() << Error;
10093     D->setInvalidDecl();
10094   }
10095 }
10096 
10097 StmtResult
10098 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10099                                  IdentifierInfo *Ident,
10100                                  ParsedAttributes &Attrs,
10101                                  SourceLocation AttrEnd) {
10102   // C++1y [stmt.iter]p1:
10103   //   A range-based for statement of the form
10104   //      for ( for-range-identifier : for-range-initializer ) statement
10105   //   is equivalent to
10106   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
10107   DeclSpec DS(Attrs.getPool().getFactory());
10108 
10109   const char *PrevSpec;
10110   unsigned DiagID;
10111   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10112                      getPrintingPolicy());
10113 
10114   Declarator D(DS, Declarator::ForContext);
10115   D.SetIdentifier(Ident, IdentLoc);
10116   D.takeAttributes(Attrs, AttrEnd);
10117 
10118   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10119   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10120                 EmptyAttrs, IdentLoc);
10121   Decl *Var = ActOnDeclarator(S, D);
10122   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10123   FinalizeDeclaration(Var);
10124   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10125                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
10126 }
10127 
10128 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10129   if (var->isInvalidDecl()) return;
10130 
10131   if (getLangOpts().OpenCL) {
10132     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10133     // initialiser
10134     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10135         !var->hasInit()) {
10136       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10137           << 1 /*Init*/;
10138       var->setInvalidDecl();
10139       return;
10140     }
10141   }
10142 
10143   // In Objective-C, don't allow jumps past the implicit initialization of a
10144   // local retaining variable.
10145   if (getLangOpts().ObjC1 &&
10146       var->hasLocalStorage()) {
10147     switch (var->getType().getObjCLifetime()) {
10148     case Qualifiers::OCL_None:
10149     case Qualifiers::OCL_ExplicitNone:
10150     case Qualifiers::OCL_Autoreleasing:
10151       break;
10152 
10153     case Qualifiers::OCL_Weak:
10154     case Qualifiers::OCL_Strong:
10155       getCurFunction()->setHasBranchProtectedScope();
10156       break;
10157     }
10158   }
10159 
10160   // Warn about externally-visible variables being defined without a
10161   // prior declaration.  We only want to do this for global
10162   // declarations, but we also specifically need to avoid doing it for
10163   // class members because the linkage of an anonymous class can
10164   // change if it's later given a typedef name.
10165   if (var->isThisDeclarationADefinition() &&
10166       var->getDeclContext()->getRedeclContext()->isFileContext() &&
10167       var->isExternallyVisible() && var->hasLinkage() &&
10168       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10169                                   var->getLocation())) {
10170     // Find a previous declaration that's not a definition.
10171     VarDecl *prev = var->getPreviousDecl();
10172     while (prev && prev->isThisDeclarationADefinition())
10173       prev = prev->getPreviousDecl();
10174 
10175     if (!prev)
10176       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10177   }
10178 
10179   if (var->getTLSKind() == VarDecl::TLS_Static) {
10180     const Expr *Culprit;
10181     if (var->getType().isDestructedType()) {
10182       // GNU C++98 edits for __thread, [basic.start.term]p3:
10183       //   The type of an object with thread storage duration shall not
10184       //   have a non-trivial destructor.
10185       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10186       if (getLangOpts().CPlusPlus11)
10187         Diag(var->getLocation(), diag::note_use_thread_local);
10188     } else if (getLangOpts().CPlusPlus && var->hasInit() &&
10189                !var->getInit()->isConstantInitializer(
10190                    Context, var->getType()->isReferenceType(), &Culprit)) {
10191       // GNU C++98 edits for __thread, [basic.start.init]p4:
10192       //   An object of thread storage duration shall not require dynamic
10193       //   initialization.
10194       // FIXME: Need strict checking here.
10195       Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
10196         << Culprit->getSourceRange();
10197       if (getLangOpts().CPlusPlus11)
10198         Diag(var->getLocation(), diag::note_use_thread_local);
10199     }
10200   }
10201 
10202   // Apply section attributes and pragmas to global variables.
10203   bool GlobalStorage = var->hasGlobalStorage();
10204   if (GlobalStorage && var->isThisDeclarationADefinition() &&
10205       ActiveTemplateInstantiations.empty()) {
10206     PragmaStack<StringLiteral *> *Stack = nullptr;
10207     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10208     if (var->getType().isConstQualified())
10209       Stack = &ConstSegStack;
10210     else if (!var->getInit()) {
10211       Stack = &BSSSegStack;
10212       SectionFlags |= ASTContext::PSF_Write;
10213     } else {
10214       Stack = &DataSegStack;
10215       SectionFlags |= ASTContext::PSF_Write;
10216     }
10217     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10218       var->addAttr(SectionAttr::CreateImplicit(
10219           Context, SectionAttr::Declspec_allocate,
10220           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10221     }
10222     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10223       if (UnifySection(SA->getName(), SectionFlags, var))
10224         var->dropAttr<SectionAttr>();
10225 
10226     // Apply the init_seg attribute if this has an initializer.  If the
10227     // initializer turns out to not be dynamic, we'll end up ignoring this
10228     // attribute.
10229     if (CurInitSeg && var->getInit())
10230       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10231                                                CurInitSegLoc));
10232   }
10233 
10234   // All the following checks are C++ only.
10235   if (!getLangOpts().CPlusPlus) return;
10236 
10237   QualType type = var->getType();
10238   if (type->isDependentType()) return;
10239 
10240   // __block variables might require us to capture a copy-initializer.
10241   if (var->hasAttr<BlocksAttr>()) {
10242     // It's currently invalid to ever have a __block variable with an
10243     // array type; should we diagnose that here?
10244 
10245     // Regardless, we don't want to ignore array nesting when
10246     // constructing this copy.
10247     if (type->isStructureOrClassType()) {
10248       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10249       SourceLocation poi = var->getLocation();
10250       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10251       ExprResult result
10252         = PerformMoveOrCopyInitialization(
10253             InitializedEntity::InitializeBlock(poi, type, false),
10254             var, var->getType(), varRef, /*AllowNRVO=*/true);
10255       if (!result.isInvalid()) {
10256         result = MaybeCreateExprWithCleanups(result);
10257         Expr *init = result.getAs<Expr>();
10258         Context.setBlockVarCopyInits(var, init);
10259       }
10260     }
10261   }
10262 
10263   Expr *Init = var->getInit();
10264   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10265   QualType baseType = Context.getBaseElementType(type);
10266 
10267   if (!var->getDeclContext()->isDependentContext() &&
10268       Init && !Init->isValueDependent()) {
10269     if (IsGlobal && !var->isConstexpr() &&
10270         !getDiagnostics().isIgnored(diag::warn_global_constructor,
10271                                     var->getLocation())) {
10272       // Warn about globals which don't have a constant initializer.  Don't
10273       // warn about globals with a non-trivial destructor because we already
10274       // warned about them.
10275       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10276       if (!(RD && !RD->hasTrivialDestructor()) &&
10277           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
10278         Diag(var->getLocation(), diag::warn_global_constructor)
10279           << Init->getSourceRange();
10280     }
10281 
10282     if (var->isConstexpr()) {
10283       SmallVector<PartialDiagnosticAt, 8> Notes;
10284       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10285         SourceLocation DiagLoc = var->getLocation();
10286         // If the note doesn't add any useful information other than a source
10287         // location, fold it into the primary diagnostic.
10288         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10289               diag::note_invalid_subexpr_in_const_expr) {
10290           DiagLoc = Notes[0].first;
10291           Notes.clear();
10292         }
10293         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10294           << var << Init->getSourceRange();
10295         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10296           Diag(Notes[I].first, Notes[I].second);
10297       }
10298     } else if (var->isUsableInConstantExpressions(Context)) {
10299       // Check whether the initializer of a const variable of integral or
10300       // enumeration type is an ICE now, since we can't tell whether it was
10301       // initialized by a constant expression if we check later.
10302       var->checkInitIsICE();
10303     }
10304   }
10305 
10306   // Require the destructor.
10307   if (const RecordType *recordType = baseType->getAs<RecordType>())
10308     FinalizeVarWithDestructor(var, recordType);
10309 }
10310 
10311 /// \brief Determines if a variable's alignment is dependent.
10312 static bool hasDependentAlignment(VarDecl *VD) {
10313   if (VD->getType()->isDependentType())
10314     return true;
10315   for (auto *I : VD->specific_attrs<AlignedAttr>())
10316     if (I->isAlignmentDependent())
10317       return true;
10318   return false;
10319 }
10320 
10321 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10322 /// any semantic actions necessary after any initializer has been attached.
10323 void
10324 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10325   // Note that we are no longer parsing the initializer for this declaration.
10326   ParsingInitForAutoVars.erase(ThisDecl);
10327 
10328   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10329   if (!VD)
10330     return;
10331 
10332   checkAttributesAfterMerging(*this, *VD);
10333 
10334   // Perform TLS alignment check here after attributes attached to the variable
10335   // which may affect the alignment have been processed. Only perform the check
10336   // if the target has a maximum TLS alignment (zero means no constraints).
10337   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
10338     // Protect the check so that it's not performed on dependent types and
10339     // dependent alignments (we can't determine the alignment in that case).
10340     if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
10341       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
10342       if (Context.getDeclAlign(VD) > MaxAlignChars) {
10343         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
10344           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
10345           << (unsigned)MaxAlignChars.getQuantity();
10346       }
10347     }
10348   }
10349 
10350   // Static locals inherit dll attributes from their function.
10351   if (VD->isStaticLocal()) {
10352     if (FunctionDecl *FD =
10353             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
10354       if (Attr *A = getDLLAttr(FD)) {
10355         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
10356         NewAttr->setInherited(true);
10357         VD->addAttr(NewAttr);
10358       }
10359     }
10360   }
10361 
10362   // Perform check for initializers of device-side global variables.
10363   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
10364   // 7.5). CUDA also allows constant initializers for __constant__ and
10365   // __device__ variables.
10366   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
10367     const Expr *Init = VD->getInit();
10368     const bool IsGlobal = VD->hasGlobalStorage() && !VD->isStaticLocal();
10369     if (Init && IsGlobal &&
10370         (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
10371          VD->hasAttr<CUDASharedAttr>())) {
10372       bool AllowedInit = false;
10373       if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
10374         AllowedInit =
10375             isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
10376       // We'll allow constant initializers even if it's a non-empty
10377       // constructor according to CUDA rules. This deviates from NVCC,
10378       // but allows us to handle things like constexpr constructors.
10379       if (!AllowedInit &&
10380           (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
10381         AllowedInit = VD->getInit()->isConstantInitializer(
10382             Context, VD->getType()->isReferenceType());
10383 
10384       if (!AllowedInit) {
10385         Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
10386                                     ? diag::err_shared_var_init
10387                                     : diag::err_dynamic_var_init)
10388             << Init->getSourceRange();
10389         VD->setInvalidDecl();
10390       }
10391     }
10392   }
10393 
10394   // Grab the dllimport or dllexport attribute off of the VarDecl.
10395   const InheritableAttr *DLLAttr = getDLLAttr(VD);
10396 
10397   // Imported static data members cannot be defined out-of-line.
10398   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
10399     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
10400         VD->isThisDeclarationADefinition()) {
10401       // We allow definitions of dllimport class template static data members
10402       // with a warning.
10403       CXXRecordDecl *Context =
10404         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
10405       bool IsClassTemplateMember =
10406           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
10407           Context->getDescribedClassTemplate();
10408 
10409       Diag(VD->getLocation(),
10410            IsClassTemplateMember
10411                ? diag::warn_attribute_dllimport_static_field_definition
10412                : diag::err_attribute_dllimport_static_field_definition);
10413       Diag(IA->getLocation(), diag::note_attribute);
10414       if (!IsClassTemplateMember)
10415         VD->setInvalidDecl();
10416     }
10417   }
10418 
10419   // dllimport/dllexport variables cannot be thread local, their TLS index
10420   // isn't exported with the variable.
10421   if (DLLAttr && VD->getTLSKind()) {
10422     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
10423     if (F && getDLLAttr(F)) {
10424       assert(VD->isStaticLocal());
10425       // But if this is a static local in a dlimport/dllexport function, the
10426       // function will never be inlined, which means the var would never be
10427       // imported, so having it marked import/export is safe.
10428     } else {
10429       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
10430                                                                     << DLLAttr;
10431       VD->setInvalidDecl();
10432     }
10433   }
10434 
10435   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
10436     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
10437       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
10438       VD->dropAttr<UsedAttr>();
10439     }
10440   }
10441 
10442   const DeclContext *DC = VD->getDeclContext();
10443   // If there's a #pragma GCC visibility in scope, and this isn't a class
10444   // member, set the visibility of this variable.
10445   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
10446     AddPushedVisibilityAttribute(VD);
10447 
10448   // FIXME: Warn on unused templates.
10449   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
10450       !isa<VarTemplatePartialSpecializationDecl>(VD))
10451     MarkUnusedFileScopedDecl(VD);
10452 
10453   // Now we have parsed the initializer and can update the table of magic
10454   // tag values.
10455   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
10456       !VD->getType()->isIntegralOrEnumerationType())
10457     return;
10458 
10459   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
10460     const Expr *MagicValueExpr = VD->getInit();
10461     if (!MagicValueExpr) {
10462       continue;
10463     }
10464     llvm::APSInt MagicValueInt;
10465     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
10466       Diag(I->getRange().getBegin(),
10467            diag::err_type_tag_for_datatype_not_ice)
10468         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10469       continue;
10470     }
10471     if (MagicValueInt.getActiveBits() > 64) {
10472       Diag(I->getRange().getBegin(),
10473            diag::err_type_tag_for_datatype_too_large)
10474         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10475       continue;
10476     }
10477     uint64_t MagicValue = MagicValueInt.getZExtValue();
10478     RegisterTypeTagForDatatype(I->getArgumentKind(),
10479                                MagicValue,
10480                                I->getMatchingCType(),
10481                                I->getLayoutCompatible(),
10482                                I->getMustBeNull());
10483   }
10484 }
10485 
10486 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
10487                                                    ArrayRef<Decl *> Group) {
10488   SmallVector<Decl*, 8> Decls;
10489 
10490   if (DS.isTypeSpecOwned())
10491     Decls.push_back(DS.getRepAsDecl());
10492 
10493   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
10494   for (unsigned i = 0, e = Group.size(); i != e; ++i)
10495     if (Decl *D = Group[i]) {
10496       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
10497         if (!FirstDeclaratorInGroup)
10498           FirstDeclaratorInGroup = DD;
10499       Decls.push_back(D);
10500     }
10501 
10502   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
10503     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
10504       handleTagNumbering(Tag, S);
10505       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
10506           getLangOpts().CPlusPlus)
10507         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
10508     }
10509   }
10510 
10511   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
10512 }
10513 
10514 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
10515 /// group, performing any necessary semantic checking.
10516 Sema::DeclGroupPtrTy
10517 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
10518                            bool TypeMayContainAuto) {
10519   // C++0x [dcl.spec.auto]p7:
10520   //   If the type deduced for the template parameter U is not the same in each
10521   //   deduction, the program is ill-formed.
10522   // FIXME: When initializer-list support is added, a distinction is needed
10523   // between the deduced type U and the deduced type which 'auto' stands for.
10524   //   auto a = 0, b = { 1, 2, 3 };
10525   // is legal because the deduced type U is 'int' in both cases.
10526   if (TypeMayContainAuto && Group.size() > 1) {
10527     QualType Deduced;
10528     CanQualType DeducedCanon;
10529     VarDecl *DeducedDecl = nullptr;
10530     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
10531       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
10532         AutoType *AT = D->getType()->getContainedAutoType();
10533         // Don't reissue diagnostics when instantiating a template.
10534         if (AT && D->isInvalidDecl())
10535           break;
10536         QualType U = AT ? AT->getDeducedType() : QualType();
10537         if (!U.isNull()) {
10538           CanQualType UCanon = Context.getCanonicalType(U);
10539           if (Deduced.isNull()) {
10540             Deduced = U;
10541             DeducedCanon = UCanon;
10542             DeducedDecl = D;
10543           } else if (DeducedCanon != UCanon) {
10544             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
10545                  diag::err_auto_different_deductions)
10546               << (unsigned)AT->getKeyword()
10547               << Deduced << DeducedDecl->getDeclName()
10548               << U << D->getDeclName()
10549               << DeducedDecl->getInit()->getSourceRange()
10550               << D->getInit()->getSourceRange();
10551             D->setInvalidDecl();
10552             break;
10553           }
10554         }
10555       }
10556     }
10557   }
10558 
10559   ActOnDocumentableDecls(Group);
10560 
10561   return DeclGroupPtrTy::make(
10562       DeclGroupRef::Create(Context, Group.data(), Group.size()));
10563 }
10564 
10565 void Sema::ActOnDocumentableDecl(Decl *D) {
10566   ActOnDocumentableDecls(D);
10567 }
10568 
10569 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
10570   // Don't parse the comment if Doxygen diagnostics are ignored.
10571   if (Group.empty() || !Group[0])
10572     return;
10573 
10574   if (Diags.isIgnored(diag::warn_doc_param_not_found,
10575                       Group[0]->getLocation()) &&
10576       Diags.isIgnored(diag::warn_unknown_comment_command_name,
10577                       Group[0]->getLocation()))
10578     return;
10579 
10580   if (Group.size() >= 2) {
10581     // This is a decl group.  Normally it will contain only declarations
10582     // produced from declarator list.  But in case we have any definitions or
10583     // additional declaration references:
10584     //   'typedef struct S {} S;'
10585     //   'typedef struct S *S;'
10586     //   'struct S *pS;'
10587     // FinalizeDeclaratorGroup adds these as separate declarations.
10588     Decl *MaybeTagDecl = Group[0];
10589     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
10590       Group = Group.slice(1);
10591     }
10592   }
10593 
10594   // See if there are any new comments that are not attached to a decl.
10595   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
10596   if (!Comments.empty() &&
10597       !Comments.back()->isAttached()) {
10598     // There is at least one comment that not attached to a decl.
10599     // Maybe it should be attached to one of these decls?
10600     //
10601     // Note that this way we pick up not only comments that precede the
10602     // declaration, but also comments that *follow* the declaration -- thanks to
10603     // the lookahead in the lexer: we've consumed the semicolon and looked
10604     // ahead through comments.
10605     for (unsigned i = 0, e = Group.size(); i != e; ++i)
10606       Context.getCommentForDecl(Group[i], &PP);
10607   }
10608 }
10609 
10610 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
10611 /// to introduce parameters into function prototype scope.
10612 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
10613   const DeclSpec &DS = D.getDeclSpec();
10614 
10615   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
10616 
10617   // C++03 [dcl.stc]p2 also permits 'auto'.
10618   StorageClass SC = SC_None;
10619   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
10620     SC = SC_Register;
10621   } else if (getLangOpts().CPlusPlus &&
10622              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
10623     SC = SC_Auto;
10624   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
10625     Diag(DS.getStorageClassSpecLoc(),
10626          diag::err_invalid_storage_class_in_func_decl);
10627     D.getMutableDeclSpec().ClearStorageClassSpecs();
10628   }
10629 
10630   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
10631     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
10632       << DeclSpec::getSpecifierName(TSCS);
10633   if (DS.isConstexprSpecified())
10634     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
10635       << 0;
10636   if (DS.isConceptSpecified())
10637     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
10638 
10639   DiagnoseFunctionSpecifiers(DS);
10640 
10641   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10642   QualType parmDeclType = TInfo->getType();
10643 
10644   if (getLangOpts().CPlusPlus) {
10645     // Check that there are no default arguments inside the type of this
10646     // parameter.
10647     CheckExtraCXXDefaultArguments(D);
10648 
10649     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
10650     if (D.getCXXScopeSpec().isSet()) {
10651       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
10652         << D.getCXXScopeSpec().getRange();
10653       D.getCXXScopeSpec().clear();
10654     }
10655   }
10656 
10657   // Ensure we have a valid name
10658   IdentifierInfo *II = nullptr;
10659   if (D.hasName()) {
10660     II = D.getIdentifier();
10661     if (!II) {
10662       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
10663         << GetNameForDeclarator(D).getName();
10664       D.setInvalidType(true);
10665     }
10666   }
10667 
10668   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
10669   if (II) {
10670     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
10671                    ForRedeclaration);
10672     LookupName(R, S);
10673     if (R.isSingleResult()) {
10674       NamedDecl *PrevDecl = R.getFoundDecl();
10675       if (PrevDecl->isTemplateParameter()) {
10676         // Maybe we will complain about the shadowed template parameter.
10677         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10678         // Just pretend that we didn't see the previous declaration.
10679         PrevDecl = nullptr;
10680       } else if (S->isDeclScope(PrevDecl)) {
10681         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
10682         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10683 
10684         // Recover by removing the name
10685         II = nullptr;
10686         D.SetIdentifier(nullptr, D.getIdentifierLoc());
10687         D.setInvalidType(true);
10688       }
10689     }
10690   }
10691 
10692   // Temporarily put parameter variables in the translation unit, not
10693   // the enclosing context.  This prevents them from accidentally
10694   // looking like class members in C++.
10695   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
10696                                     D.getLocStart(),
10697                                     D.getIdentifierLoc(), II,
10698                                     parmDeclType, TInfo,
10699                                     SC);
10700 
10701   if (D.isInvalidType())
10702     New->setInvalidDecl();
10703 
10704   assert(S->isFunctionPrototypeScope());
10705   assert(S->getFunctionPrototypeDepth() >= 1);
10706   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
10707                     S->getNextFunctionPrototypeIndex());
10708 
10709   // Add the parameter declaration into this scope.
10710   S->AddDecl(New);
10711   if (II)
10712     IdResolver.AddDecl(New);
10713 
10714   ProcessDeclAttributes(S, New, D);
10715 
10716   if (D.getDeclSpec().isModulePrivateSpecified())
10717     Diag(New->getLocation(), diag::err_module_private_local)
10718       << 1 << New->getDeclName()
10719       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10720       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10721 
10722   if (New->hasAttr<BlocksAttr>()) {
10723     Diag(New->getLocation(), diag::err_block_on_nonlocal);
10724   }
10725   return New;
10726 }
10727 
10728 /// \brief Synthesizes a variable for a parameter arising from a
10729 /// typedef.
10730 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
10731                                               SourceLocation Loc,
10732                                               QualType T) {
10733   /* FIXME: setting StartLoc == Loc.
10734      Would it be worth to modify callers so as to provide proper source
10735      location for the unnamed parameters, embedding the parameter's type? */
10736   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
10737                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
10738                                            SC_None, nullptr);
10739   Param->setImplicit();
10740   return Param;
10741 }
10742 
10743 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
10744                                     ParmVarDecl * const *ParamEnd) {
10745   // Don't diagnose unused-parameter errors in template instantiations; we
10746   // will already have done so in the template itself.
10747   if (!ActiveTemplateInstantiations.empty())
10748     return;
10749 
10750   for (; Param != ParamEnd; ++Param) {
10751     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
10752         !(*Param)->hasAttr<UnusedAttr>()) {
10753       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
10754         << (*Param)->getDeclName();
10755     }
10756   }
10757 }
10758 
10759 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
10760                                                   ParmVarDecl * const *ParamEnd,
10761                                                   QualType ReturnTy,
10762                                                   NamedDecl *D) {
10763   if (LangOpts.NumLargeByValueCopy == 0) // No check.
10764     return;
10765 
10766   // Warn if the return value is pass-by-value and larger than the specified
10767   // threshold.
10768   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
10769     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
10770     if (Size > LangOpts.NumLargeByValueCopy)
10771       Diag(D->getLocation(), diag::warn_return_value_size)
10772           << D->getDeclName() << Size;
10773   }
10774 
10775   // Warn if any parameter is pass-by-value and larger than the specified
10776   // threshold.
10777   for (; Param != ParamEnd; ++Param) {
10778     QualType T = (*Param)->getType();
10779     if (T->isDependentType() || !T.isPODType(Context))
10780       continue;
10781     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
10782     if (Size > LangOpts.NumLargeByValueCopy)
10783       Diag((*Param)->getLocation(), diag::warn_parameter_size)
10784           << (*Param)->getDeclName() << Size;
10785   }
10786 }
10787 
10788 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
10789                                   SourceLocation NameLoc, IdentifierInfo *Name,
10790                                   QualType T, TypeSourceInfo *TSInfo,
10791                                   StorageClass SC) {
10792   // In ARC, infer a lifetime qualifier for appropriate parameter types.
10793   if (getLangOpts().ObjCAutoRefCount &&
10794       T.getObjCLifetime() == Qualifiers::OCL_None &&
10795       T->isObjCLifetimeType()) {
10796 
10797     Qualifiers::ObjCLifetime lifetime;
10798 
10799     // Special cases for arrays:
10800     //   - if it's const, use __unsafe_unretained
10801     //   - otherwise, it's an error
10802     if (T->isArrayType()) {
10803       if (!T.isConstQualified()) {
10804         DelayedDiagnostics.add(
10805             sema::DelayedDiagnostic::makeForbiddenType(
10806             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
10807       }
10808       lifetime = Qualifiers::OCL_ExplicitNone;
10809     } else {
10810       lifetime = T->getObjCARCImplicitLifetime();
10811     }
10812     T = Context.getLifetimeQualifiedType(T, lifetime);
10813   }
10814 
10815   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
10816                                          Context.getAdjustedParameterType(T),
10817                                          TSInfo, SC, nullptr);
10818 
10819   // Parameters can not be abstract class types.
10820   // For record types, this is done by the AbstractClassUsageDiagnoser once
10821   // the class has been completely parsed.
10822   if (!CurContext->isRecord() &&
10823       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
10824                              AbstractParamType))
10825     New->setInvalidDecl();
10826 
10827   // Parameter declarators cannot be interface types. All ObjC objects are
10828   // passed by reference.
10829   if (T->isObjCObjectType()) {
10830     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
10831     Diag(NameLoc,
10832          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
10833       << FixItHint::CreateInsertion(TypeEndLoc, "*");
10834     T = Context.getObjCObjectPointerType(T);
10835     New->setType(T);
10836   }
10837 
10838   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
10839   // duration shall not be qualified by an address-space qualifier."
10840   // Since all parameters have automatic store duration, they can not have
10841   // an address space.
10842   if (T.getAddressSpace() != 0) {
10843     // OpenCL allows function arguments declared to be an array of a type
10844     // to be qualified with an address space.
10845     if (!(getLangOpts().OpenCL && T->isArrayType())) {
10846       Diag(NameLoc, diag::err_arg_with_address_space);
10847       New->setInvalidDecl();
10848     }
10849   }
10850 
10851   // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
10852   // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
10853   if (getLangOpts().OpenCL && T->isPointerType()) {
10854     const QualType PTy = T->getPointeeType();
10855     if (PTy->isImageType() || PTy->isSamplerT() || PTy->isPipeType()) {
10856       Diag(NameLoc, diag::err_opencl_pointer_to_type) << PTy;
10857       New->setInvalidDecl();
10858     }
10859   }
10860 
10861   return New;
10862 }
10863 
10864 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
10865                                            SourceLocation LocAfterDecls) {
10866   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10867 
10868   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
10869   // for a K&R function.
10870   if (!FTI.hasPrototype) {
10871     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
10872       --i;
10873       if (FTI.Params[i].Param == nullptr) {
10874         SmallString<256> Code;
10875         llvm::raw_svector_ostream(Code)
10876             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
10877         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
10878             << FTI.Params[i].Ident
10879             << FixItHint::CreateInsertion(LocAfterDecls, Code);
10880 
10881         // Implicitly declare the argument as type 'int' for lack of a better
10882         // type.
10883         AttributeFactory attrs;
10884         DeclSpec DS(attrs);
10885         const char* PrevSpec; // unused
10886         unsigned DiagID; // unused
10887         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
10888                            DiagID, Context.getPrintingPolicy());
10889         // Use the identifier location for the type source range.
10890         DS.SetRangeStart(FTI.Params[i].IdentLoc);
10891         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
10892         Declarator ParamD(DS, Declarator::KNRTypeListContext);
10893         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
10894         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
10895       }
10896     }
10897   }
10898 }
10899 
10900 Decl *
10901 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
10902                               MultiTemplateParamsArg TemplateParameterLists,
10903                               SkipBodyInfo *SkipBody) {
10904   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
10905   assert(D.isFunctionDeclarator() && "Not a function declarator!");
10906   Scope *ParentScope = FnBodyScope->getParent();
10907 
10908   D.setFunctionDefinitionKind(FDK_Definition);
10909   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
10910   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
10911 }
10912 
10913 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
10914   Consumer.HandleInlineFunctionDefinition(D);
10915 }
10916 
10917 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
10918                              const FunctionDecl*& PossibleZeroParamPrototype) {
10919   // Don't warn about invalid declarations.
10920   if (FD->isInvalidDecl())
10921     return false;
10922 
10923   // Or declarations that aren't global.
10924   if (!FD->isGlobal())
10925     return false;
10926 
10927   // Don't warn about C++ member functions.
10928   if (isa<CXXMethodDecl>(FD))
10929     return false;
10930 
10931   // Don't warn about 'main'.
10932   if (FD->isMain())
10933     return false;
10934 
10935   // Don't warn about inline functions.
10936   if (FD->isInlined())
10937     return false;
10938 
10939   // Don't warn about function templates.
10940   if (FD->getDescribedFunctionTemplate())
10941     return false;
10942 
10943   // Don't warn about function template specializations.
10944   if (FD->isFunctionTemplateSpecialization())
10945     return false;
10946 
10947   // Don't warn for OpenCL kernels.
10948   if (FD->hasAttr<OpenCLKernelAttr>())
10949     return false;
10950 
10951   // Don't warn on explicitly deleted functions.
10952   if (FD->isDeleted())
10953     return false;
10954 
10955   bool MissingPrototype = true;
10956   for (const FunctionDecl *Prev = FD->getPreviousDecl();
10957        Prev; Prev = Prev->getPreviousDecl()) {
10958     // Ignore any declarations that occur in function or method
10959     // scope, because they aren't visible from the header.
10960     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
10961       continue;
10962 
10963     MissingPrototype = !Prev->getType()->isFunctionProtoType();
10964     if (FD->getNumParams() == 0)
10965       PossibleZeroParamPrototype = Prev;
10966     break;
10967   }
10968 
10969   return MissingPrototype;
10970 }
10971 
10972 void
10973 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
10974                                    const FunctionDecl *EffectiveDefinition,
10975                                    SkipBodyInfo *SkipBody) {
10976   // Don't complain if we're in GNU89 mode and the previous definition
10977   // was an extern inline function.
10978   const FunctionDecl *Definition = EffectiveDefinition;
10979   if (!Definition)
10980     if (!FD->isDefined(Definition))
10981       return;
10982 
10983   if (canRedefineFunction(Definition, getLangOpts()))
10984     return;
10985 
10986   // If we don't have a visible definition of the function, and it's inline or
10987   // a template, skip the new definition.
10988   if (SkipBody && !hasVisibleDefinition(Definition) &&
10989       (Definition->getFormalLinkage() == InternalLinkage ||
10990        Definition->isInlined() ||
10991        Definition->getDescribedFunctionTemplate() ||
10992        Definition->getNumTemplateParameterLists())) {
10993     SkipBody->ShouldSkip = true;
10994     if (auto *TD = Definition->getDescribedFunctionTemplate())
10995       makeMergedDefinitionVisible(TD, FD->getLocation());
10996     else
10997       makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
10998                                   FD->getLocation());
10999     return;
11000   }
11001 
11002   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11003       Definition->getStorageClass() == SC_Extern)
11004     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11005         << FD->getDeclName() << getLangOpts().CPlusPlus;
11006   else
11007     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11008 
11009   Diag(Definition->getLocation(), diag::note_previous_definition);
11010   FD->setInvalidDecl();
11011 }
11012 
11013 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11014                                    Sema &S) {
11015   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11016 
11017   LambdaScopeInfo *LSI = S.PushLambdaScope();
11018   LSI->CallOperator = CallOperator;
11019   LSI->Lambda = LambdaClass;
11020   LSI->ReturnType = CallOperator->getReturnType();
11021   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11022 
11023   if (LCD == LCD_None)
11024     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
11025   else if (LCD == LCD_ByCopy)
11026     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
11027   else if (LCD == LCD_ByRef)
11028     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
11029   DeclarationNameInfo DNI = CallOperator->getNameInfo();
11030 
11031   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
11032   LSI->Mutable = !CallOperator->isConst();
11033 
11034   // Add the captures to the LSI so they can be noted as already
11035   // captured within tryCaptureVar.
11036   auto I = LambdaClass->field_begin();
11037   for (const auto &C : LambdaClass->captures()) {
11038     if (C.capturesVariable()) {
11039       VarDecl *VD = C.getCapturedVar();
11040       if (VD->isInitCapture())
11041         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11042       QualType CaptureType = VD->getType();
11043       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11044       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11045           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11046           /*EllipsisLoc*/C.isPackExpansion()
11047                          ? C.getEllipsisLoc() : SourceLocation(),
11048           CaptureType, /*Expr*/ nullptr);
11049 
11050     } else if (C.capturesThis()) {
11051       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11052                               S.getCurrentThisType(), /*Expr*/ nullptr,
11053                               C.getCaptureKind() == LCK_StarThis);
11054     } else {
11055       LSI->addVLATypeCapture(C.getLocation(), I->getType());
11056     }
11057     ++I;
11058   }
11059 }
11060 
11061 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
11062                                     SkipBodyInfo *SkipBody) {
11063   // Clear the last template instantiation error context.
11064   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
11065 
11066   if (!D)
11067     return D;
11068   FunctionDecl *FD = nullptr;
11069 
11070   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
11071     FD = FunTmpl->getTemplatedDecl();
11072   else
11073     FD = cast<FunctionDecl>(D);
11074 
11075   // See if this is a redefinition.
11076   if (!FD->isLateTemplateParsed()) {
11077     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
11078 
11079     // If we're skipping the body, we're done. Don't enter the scope.
11080     if (SkipBody && SkipBody->ShouldSkip)
11081       return D;
11082   }
11083 
11084   // If we are instantiating a generic lambda call operator, push
11085   // a LambdaScopeInfo onto the function stack.  But use the information
11086   // that's already been calculated (ActOnLambdaExpr) to prime the current
11087   // LambdaScopeInfo.
11088   // When the template operator is being specialized, the LambdaScopeInfo,
11089   // has to be properly restored so that tryCaptureVariable doesn't try
11090   // and capture any new variables. In addition when calculating potential
11091   // captures during transformation of nested lambdas, it is necessary to
11092   // have the LSI properly restored.
11093   if (isGenericLambdaCallOperatorSpecialization(FD)) {
11094     assert(ActiveTemplateInstantiations.size() &&
11095       "There should be an active template instantiation on the stack "
11096       "when instantiating a generic lambda!");
11097     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
11098   }
11099   else
11100     // Enter a new function scope
11101     PushFunctionScope();
11102 
11103   // Builtin functions cannot be defined.
11104   if (unsigned BuiltinID = FD->getBuiltinID()) {
11105     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
11106         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
11107       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
11108       FD->setInvalidDecl();
11109     }
11110   }
11111 
11112   // The return type of a function definition must be complete
11113   // (C99 6.9.1p3, C++ [dcl.fct]p6).
11114   QualType ResultType = FD->getReturnType();
11115   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
11116       !FD->isInvalidDecl() &&
11117       RequireCompleteType(FD->getLocation(), ResultType,
11118                           diag::err_func_def_incomplete_result))
11119     FD->setInvalidDecl();
11120 
11121   if (FnBodyScope)
11122     PushDeclContext(FnBodyScope, FD);
11123 
11124   // Check the validity of our function parameters
11125   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
11126                            /*CheckParameterNames=*/true);
11127 
11128   // Introduce our parameters into the function scope
11129   for (auto Param : FD->params()) {
11130     Param->setOwningFunction(FD);
11131 
11132     // If this has an identifier, add it to the scope stack.
11133     if (Param->getIdentifier() && FnBodyScope) {
11134       CheckShadow(FnBodyScope, Param);
11135 
11136       PushOnScopeChains(Param, FnBodyScope);
11137     }
11138   }
11139 
11140   // If we had any tags defined in the function prototype,
11141   // introduce them into the function scope.
11142   if (FnBodyScope) {
11143     for (ArrayRef<NamedDecl *>::iterator
11144              I = FD->getDeclsInPrototypeScope().begin(),
11145              E = FD->getDeclsInPrototypeScope().end();
11146          I != E; ++I) {
11147       NamedDecl *D = *I;
11148 
11149       // Some of these decls (like enums) may have been pinned to the
11150       // translation unit for lack of a real context earlier. If so, remove
11151       // from the translation unit and reattach to the current context.
11152       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
11153         // Is the decl actually in the context?
11154         if (Context.getTranslationUnitDecl()->containsDecl(D))
11155           Context.getTranslationUnitDecl()->removeDecl(D);
11156         // Either way, reassign the lexical decl context to our FunctionDecl.
11157         D->setLexicalDeclContext(CurContext);
11158       }
11159 
11160       // If the decl has a non-null name, make accessible in the current scope.
11161       if (!D->getName().empty())
11162         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
11163 
11164       // Similarly, dive into enums and fish their constants out, making them
11165       // accessible in this scope.
11166       if (auto *ED = dyn_cast<EnumDecl>(D)) {
11167         for (auto *EI : ED->enumerators())
11168           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
11169       }
11170     }
11171   }
11172 
11173   // Ensure that the function's exception specification is instantiated.
11174   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
11175     ResolveExceptionSpec(D->getLocation(), FPT);
11176 
11177   // dllimport cannot be applied to non-inline function definitions.
11178   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
11179       !FD->isTemplateInstantiation()) {
11180     assert(!FD->hasAttr<DLLExportAttr>());
11181     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
11182     FD->setInvalidDecl();
11183     return D;
11184   }
11185   // We want to attach documentation to original Decl (which might be
11186   // a function template).
11187   ActOnDocumentableDecl(D);
11188   if (getCurLexicalContext()->isObjCContainer() &&
11189       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
11190       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
11191     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
11192 
11193   return D;
11194 }
11195 
11196 /// \brief Given the set of return statements within a function body,
11197 /// compute the variables that are subject to the named return value
11198 /// optimization.
11199 ///
11200 /// Each of the variables that is subject to the named return value
11201 /// optimization will be marked as NRVO variables in the AST, and any
11202 /// return statement that has a marked NRVO variable as its NRVO candidate can
11203 /// use the named return value optimization.
11204 ///
11205 /// This function applies a very simplistic algorithm for NRVO: if every return
11206 /// statement in the scope of a variable has the same NRVO candidate, that
11207 /// candidate is an NRVO variable.
11208 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
11209   ReturnStmt **Returns = Scope->Returns.data();
11210 
11211   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
11212     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
11213       if (!NRVOCandidate->isNRVOVariable())
11214         Returns[I]->setNRVOCandidate(nullptr);
11215     }
11216   }
11217 }
11218 
11219 bool Sema::canDelayFunctionBody(const Declarator &D) {
11220   // We can't delay parsing the body of a constexpr function template (yet).
11221   if (D.getDeclSpec().isConstexprSpecified())
11222     return false;
11223 
11224   // We can't delay parsing the body of a function template with a deduced
11225   // return type (yet).
11226   if (D.getDeclSpec().containsPlaceholderType()) {
11227     // If the placeholder introduces a non-deduced trailing return type,
11228     // we can still delay parsing it.
11229     if (D.getNumTypeObjects()) {
11230       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11231       if (Outer.Kind == DeclaratorChunk::Function &&
11232           Outer.Fun.hasTrailingReturnType()) {
11233         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11234         return Ty.isNull() || !Ty->isUndeducedType();
11235       }
11236     }
11237     return false;
11238   }
11239 
11240   return true;
11241 }
11242 
11243 bool Sema::canSkipFunctionBody(Decl *D) {
11244   // We cannot skip the body of a function (or function template) which is
11245   // constexpr, since we may need to evaluate its body in order to parse the
11246   // rest of the file.
11247   // We cannot skip the body of a function with an undeduced return type,
11248   // because any callers of that function need to know the type.
11249   if (const FunctionDecl *FD = D->getAsFunction())
11250     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11251       return false;
11252   return Consumer.shouldSkipFunctionBody(D);
11253 }
11254 
11255 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11256   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11257     FD->setHasSkippedBody();
11258   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11259     MD->setHasSkippedBody();
11260   return ActOnFinishFunctionBody(Decl, nullptr);
11261 }
11262 
11263 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11264   return ActOnFinishFunctionBody(D, BodyArg, false);
11265 }
11266 
11267 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
11268                                     bool IsInstantiation) {
11269   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
11270 
11271   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11272   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
11273 
11274   if (getLangOpts().Coroutines && !getCurFunction()->CoroutineStmts.empty())
11275     CheckCompletedCoroutineBody(FD, Body);
11276 
11277   if (FD) {
11278     FD->setBody(Body);
11279 
11280     if (getLangOpts().CPlusPlus14) {
11281       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
11282           FD->getReturnType()->isUndeducedType()) {
11283         // If the function has a deduced result type but contains no 'return'
11284         // statements, the result type as written must be exactly 'auto', and
11285         // the deduced result type is 'void'.
11286         if (!FD->getReturnType()->getAs<AutoType>()) {
11287           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
11288               << FD->getReturnType();
11289           FD->setInvalidDecl();
11290         } else {
11291           // Substitute 'void' for the 'auto' in the type.
11292           TypeLoc ResultType = getReturnTypeLoc(FD);
11293           Context.adjustDeducedFunctionResultType(
11294               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
11295         }
11296       }
11297     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
11298       // In C++11, we don't use 'auto' deduction rules for lambda call
11299       // operators because we don't support return type deduction.
11300       auto *LSI = getCurLambda();
11301       if (LSI->HasImplicitReturnType) {
11302         deduceClosureReturnType(*LSI);
11303 
11304         // C++11 [expr.prim.lambda]p4:
11305         //   [...] if there are no return statements in the compound-statement
11306         //   [the deduced type is] the type void
11307         QualType RetType =
11308             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
11309 
11310         // Update the return type to the deduced type.
11311         const FunctionProtoType *Proto =
11312             FD->getType()->getAs<FunctionProtoType>();
11313         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
11314                                             Proto->getExtProtoInfo()));
11315       }
11316     }
11317 
11318     // The only way to be included in UndefinedButUsed is if there is an
11319     // ODR use before the definition. Avoid the expensive map lookup if this
11320     // is the first declaration.
11321     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
11322       if (!FD->isExternallyVisible())
11323         UndefinedButUsed.erase(FD);
11324       else if (FD->isInlined() &&
11325                !LangOpts.GNUInline &&
11326                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
11327         UndefinedButUsed.erase(FD);
11328     }
11329 
11330     // If the function implicitly returns zero (like 'main') or is naked,
11331     // don't complain about missing return statements.
11332     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
11333       WP.disableCheckFallThrough();
11334 
11335     // MSVC permits the use of pure specifier (=0) on function definition,
11336     // defined at class scope, warn about this non-standard construct.
11337     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
11338       Diag(FD->getLocation(), diag::ext_pure_function_definition);
11339 
11340     if (!FD->isInvalidDecl()) {
11341       // Don't diagnose unused parameters of defaulted or deleted functions.
11342       if (!FD->isDeleted() && !FD->isDefaulted())
11343         DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
11344       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
11345                                              FD->getReturnType(), FD);
11346 
11347       // If this is a structor, we need a vtable.
11348       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
11349         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
11350       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
11351         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
11352 
11353       // Try to apply the named return value optimization. We have to check
11354       // if we can do this here because lambdas keep return statements around
11355       // to deduce an implicit return type.
11356       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
11357           !FD->isDependentContext())
11358         computeNRVO(Body, getCurFunction());
11359     }
11360 
11361     // GNU warning -Wmissing-prototypes:
11362     //   Warn if a global function is defined without a previous
11363     //   prototype declaration. This warning is issued even if the
11364     //   definition itself provides a prototype. The aim is to detect
11365     //   global functions that fail to be declared in header files.
11366     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
11367     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
11368       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
11369 
11370       if (PossibleZeroParamPrototype) {
11371         // We found a declaration that is not a prototype,
11372         // but that could be a zero-parameter prototype
11373         if (TypeSourceInfo *TI =
11374                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
11375           TypeLoc TL = TI->getTypeLoc();
11376           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
11377             Diag(PossibleZeroParamPrototype->getLocation(),
11378                  diag::note_declaration_not_a_prototype)
11379                 << PossibleZeroParamPrototype
11380                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
11381         }
11382       }
11383     }
11384 
11385     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11386       const CXXMethodDecl *KeyFunction;
11387       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
11388           MD->isVirtual() &&
11389           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
11390           MD == KeyFunction->getCanonicalDecl()) {
11391         // Update the key-function state if necessary for this ABI.
11392         if (FD->isInlined() &&
11393             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11394           Context.setNonKeyFunction(MD);
11395 
11396           // If the newly-chosen key function is already defined, then we
11397           // need to mark the vtable as used retroactively.
11398           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
11399           const FunctionDecl *Definition;
11400           if (KeyFunction && KeyFunction->isDefined(Definition))
11401             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
11402         } else {
11403           // We just defined they key function; mark the vtable as used.
11404           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
11405         }
11406       }
11407     }
11408 
11409     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
11410            "Function parsing confused");
11411   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
11412     assert(MD == getCurMethodDecl() && "Method parsing confused");
11413     MD->setBody(Body);
11414     if (!MD->isInvalidDecl()) {
11415       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
11416       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
11417                                              MD->getReturnType(), MD);
11418 
11419       if (Body)
11420         computeNRVO(Body, getCurFunction());
11421     }
11422     if (getCurFunction()->ObjCShouldCallSuper) {
11423       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
11424         << MD->getSelector().getAsString();
11425       getCurFunction()->ObjCShouldCallSuper = false;
11426     }
11427     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
11428       const ObjCMethodDecl *InitMethod = nullptr;
11429       bool isDesignated =
11430           MD->isDesignatedInitializerForTheInterface(&InitMethod);
11431       assert(isDesignated && InitMethod);
11432       (void)isDesignated;
11433 
11434       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
11435         auto IFace = MD->getClassInterface();
11436         if (!IFace)
11437           return false;
11438         auto SuperD = IFace->getSuperClass();
11439         if (!SuperD)
11440           return false;
11441         return SuperD->getIdentifier() ==
11442             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
11443       };
11444       // Don't issue this warning for unavailable inits or direct subclasses
11445       // of NSObject.
11446       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
11447         Diag(MD->getLocation(),
11448              diag::warn_objc_designated_init_missing_super_call);
11449         Diag(InitMethod->getLocation(),
11450              diag::note_objc_designated_init_marked_here);
11451       }
11452       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
11453     }
11454     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
11455       // Don't issue this warning for unavaialable inits.
11456       if (!MD->isUnavailable())
11457         Diag(MD->getLocation(),
11458              diag::warn_objc_secondary_init_missing_init_call);
11459       getCurFunction()->ObjCWarnForNoInitDelegation = false;
11460     }
11461   } else {
11462     return nullptr;
11463   }
11464 
11465   assert(!getCurFunction()->ObjCShouldCallSuper &&
11466          "This should only be set for ObjC methods, which should have been "
11467          "handled in the block above.");
11468 
11469   // Verify and clean out per-function state.
11470   if (Body && (!FD || !FD->isDefaulted())) {
11471     // C++ constructors that have function-try-blocks can't have return
11472     // statements in the handlers of that block. (C++ [except.handle]p14)
11473     // Verify this.
11474     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
11475       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
11476 
11477     // Verify that gotos and switch cases don't jump into scopes illegally.
11478     if (getCurFunction()->NeedsScopeChecking() &&
11479         !PP.isCodeCompletionEnabled())
11480       DiagnoseInvalidJumps(Body);
11481 
11482     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
11483       if (!Destructor->getParent()->isDependentType())
11484         CheckDestructor(Destructor);
11485 
11486       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11487                                              Destructor->getParent());
11488     }
11489 
11490     // If any errors have occurred, clear out any temporaries that may have
11491     // been leftover. This ensures that these temporaries won't be picked up for
11492     // deletion in some later function.
11493     if (getDiagnostics().hasErrorOccurred() ||
11494         getDiagnostics().getSuppressAllDiagnostics()) {
11495       DiscardCleanupsInEvaluationContext();
11496     }
11497     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
11498         !isa<FunctionTemplateDecl>(dcl)) {
11499       // Since the body is valid, issue any analysis-based warnings that are
11500       // enabled.
11501       ActivePolicy = &WP;
11502     }
11503 
11504     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
11505         (!CheckConstexprFunctionDecl(FD) ||
11506          !CheckConstexprFunctionBody(FD, Body)))
11507       FD->setInvalidDecl();
11508 
11509     if (FD && FD->hasAttr<NakedAttr>()) {
11510       for (const Stmt *S : Body->children()) {
11511         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
11512           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
11513           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
11514           FD->setInvalidDecl();
11515           break;
11516         }
11517       }
11518     }
11519 
11520     assert(ExprCleanupObjects.size() ==
11521                ExprEvalContexts.back().NumCleanupObjects &&
11522            "Leftover temporaries in function");
11523     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
11524     assert(MaybeODRUseExprs.empty() &&
11525            "Leftover expressions for odr-use checking");
11526   }
11527 
11528   if (!IsInstantiation)
11529     PopDeclContext();
11530 
11531   PopFunctionScopeInfo(ActivePolicy, dcl);
11532   // If any errors have occurred, clear out any temporaries that may have
11533   // been leftover. This ensures that these temporaries won't be picked up for
11534   // deletion in some later function.
11535   if (getDiagnostics().hasErrorOccurred()) {
11536     DiscardCleanupsInEvaluationContext();
11537   }
11538 
11539   return dcl;
11540 }
11541 
11542 /// When we finish delayed parsing of an attribute, we must attach it to the
11543 /// relevant Decl.
11544 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
11545                                        ParsedAttributes &Attrs) {
11546   // Always attach attributes to the underlying decl.
11547   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
11548     D = TD->getTemplatedDecl();
11549   ProcessDeclAttributeList(S, D, Attrs.getList());
11550 
11551   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
11552     if (Method->isStatic())
11553       checkThisInStaticMemberFunctionAttributes(Method);
11554 }
11555 
11556 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
11557 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
11558 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
11559                                           IdentifierInfo &II, Scope *S) {
11560   // Before we produce a declaration for an implicitly defined
11561   // function, see whether there was a locally-scoped declaration of
11562   // this name as a function or variable. If so, use that
11563   // (non-visible) declaration, and complain about it.
11564   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
11565     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
11566     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
11567     return ExternCPrev;
11568   }
11569 
11570   // Extension in C99.  Legal in C90, but warn about it.
11571   unsigned diag_id;
11572   if (II.getName().startswith("__builtin_"))
11573     diag_id = diag::warn_builtin_unknown;
11574   else if (getLangOpts().C99)
11575     diag_id = diag::ext_implicit_function_decl;
11576   else
11577     diag_id = diag::warn_implicit_function_decl;
11578   Diag(Loc, diag_id) << &II;
11579 
11580   // Because typo correction is expensive, only do it if the implicit
11581   // function declaration is going to be treated as an error.
11582   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
11583     TypoCorrection Corrected;
11584     if (S &&
11585         (Corrected = CorrectTypo(
11586              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
11587              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
11588       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
11589                    /*ErrorRecovery*/false);
11590   }
11591 
11592   // Set a Declarator for the implicit definition: int foo();
11593   const char *Dummy;
11594   AttributeFactory attrFactory;
11595   DeclSpec DS(attrFactory);
11596   unsigned DiagID;
11597   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
11598                                   Context.getPrintingPolicy());
11599   (void)Error; // Silence warning.
11600   assert(!Error && "Error setting up implicit decl!");
11601   SourceLocation NoLoc;
11602   Declarator D(DS, Declarator::BlockContext);
11603   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
11604                                              /*IsAmbiguous=*/false,
11605                                              /*LParenLoc=*/NoLoc,
11606                                              /*Params=*/nullptr,
11607                                              /*NumParams=*/0,
11608                                              /*EllipsisLoc=*/NoLoc,
11609                                              /*RParenLoc=*/NoLoc,
11610                                              /*TypeQuals=*/0,
11611                                              /*RefQualifierIsLvalueRef=*/true,
11612                                              /*RefQualifierLoc=*/NoLoc,
11613                                              /*ConstQualifierLoc=*/NoLoc,
11614                                              /*VolatileQualifierLoc=*/NoLoc,
11615                                              /*RestrictQualifierLoc=*/NoLoc,
11616                                              /*MutableLoc=*/NoLoc,
11617                                              EST_None,
11618                                              /*ESpecRange=*/SourceRange(),
11619                                              /*Exceptions=*/nullptr,
11620                                              /*ExceptionRanges=*/nullptr,
11621                                              /*NumExceptions=*/0,
11622                                              /*NoexceptExpr=*/nullptr,
11623                                              /*ExceptionSpecTokens=*/nullptr,
11624                                              Loc, Loc, D),
11625                 DS.getAttributes(),
11626                 SourceLocation());
11627   D.SetIdentifier(&II, Loc);
11628 
11629   // Insert this function into translation-unit scope.
11630 
11631   DeclContext *PrevDC = CurContext;
11632   CurContext = Context.getTranslationUnitDecl();
11633 
11634   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
11635   FD->setImplicit();
11636 
11637   CurContext = PrevDC;
11638 
11639   AddKnownFunctionAttributes(FD);
11640 
11641   return FD;
11642 }
11643 
11644 /// \brief Adds any function attributes that we know a priori based on
11645 /// the declaration of this function.
11646 ///
11647 /// These attributes can apply both to implicitly-declared builtins
11648 /// (like __builtin___printf_chk) or to library-declared functions
11649 /// like NSLog or printf.
11650 ///
11651 /// We need to check for duplicate attributes both here and where user-written
11652 /// attributes are applied to declarations.
11653 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
11654   if (FD->isInvalidDecl())
11655     return;
11656 
11657   // If this is a built-in function, map its builtin attributes to
11658   // actual attributes.
11659   if (unsigned BuiltinID = FD->getBuiltinID()) {
11660     // Handle printf-formatting attributes.
11661     unsigned FormatIdx;
11662     bool HasVAListArg;
11663     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
11664       if (!FD->hasAttr<FormatAttr>()) {
11665         const char *fmt = "printf";
11666         unsigned int NumParams = FD->getNumParams();
11667         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
11668             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
11669           fmt = "NSString";
11670         FD->addAttr(FormatAttr::CreateImplicit(Context,
11671                                                &Context.Idents.get(fmt),
11672                                                FormatIdx+1,
11673                                                HasVAListArg ? 0 : FormatIdx+2,
11674                                                FD->getLocation()));
11675       }
11676     }
11677     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
11678                                              HasVAListArg)) {
11679      if (!FD->hasAttr<FormatAttr>())
11680        FD->addAttr(FormatAttr::CreateImplicit(Context,
11681                                               &Context.Idents.get("scanf"),
11682                                               FormatIdx+1,
11683                                               HasVAListArg ? 0 : FormatIdx+2,
11684                                               FD->getLocation()));
11685     }
11686 
11687     // Mark const if we don't care about errno and that is the only
11688     // thing preventing the function from being const. This allows
11689     // IRgen to use LLVM intrinsics for such functions.
11690     if (!getLangOpts().MathErrno &&
11691         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
11692       if (!FD->hasAttr<ConstAttr>())
11693         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11694     }
11695 
11696     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
11697         !FD->hasAttr<ReturnsTwiceAttr>())
11698       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
11699                                          FD->getLocation()));
11700     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
11701       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11702     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
11703       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11704     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
11705         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
11706       // Add the appropriate attribute, depending on the CUDA compilation mode
11707       // and which target the builtin belongs to. For example, during host
11708       // compilation, aux builtins are __device__, while the rest are __host__.
11709       if (getLangOpts().CUDAIsDevice !=
11710           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
11711         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
11712       else
11713         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
11714     }
11715   }
11716 
11717   // If C++ exceptions are enabled but we are told extern "C" functions cannot
11718   // throw, add an implicit nothrow attribute to any extern "C" function we come
11719   // across.
11720   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
11721       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
11722     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
11723     if (!FPT || FPT->getExceptionSpecType() == EST_None)
11724       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11725   }
11726 
11727   IdentifierInfo *Name = FD->getIdentifier();
11728   if (!Name)
11729     return;
11730   if ((!getLangOpts().CPlusPlus &&
11731        FD->getDeclContext()->isTranslationUnit()) ||
11732       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
11733        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
11734        LinkageSpecDecl::lang_c)) {
11735     // Okay: this could be a libc/libm/Objective-C function we know
11736     // about.
11737   } else
11738     return;
11739 
11740   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
11741     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
11742     // target-specific builtins, perhaps?
11743     if (!FD->hasAttr<FormatAttr>())
11744       FD->addAttr(FormatAttr::CreateImplicit(Context,
11745                                              &Context.Idents.get("printf"), 2,
11746                                              Name->isStr("vasprintf") ? 0 : 3,
11747                                              FD->getLocation()));
11748   }
11749 
11750   if (Name->isStr("__CFStringMakeConstantString")) {
11751     // We already have a __builtin___CFStringMakeConstantString,
11752     // but builds that use -fno-constant-cfstrings don't go through that.
11753     if (!FD->hasAttr<FormatArgAttr>())
11754       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
11755                                                 FD->getLocation()));
11756   }
11757 }
11758 
11759 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
11760                                     TypeSourceInfo *TInfo) {
11761   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
11762   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
11763 
11764   if (!TInfo) {
11765     assert(D.isInvalidType() && "no declarator info for valid type");
11766     TInfo = Context.getTrivialTypeSourceInfo(T);
11767   }
11768 
11769   // Scope manipulation handled by caller.
11770   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
11771                                            D.getLocStart(),
11772                                            D.getIdentifierLoc(),
11773                                            D.getIdentifier(),
11774                                            TInfo);
11775 
11776   // Bail out immediately if we have an invalid declaration.
11777   if (D.isInvalidType()) {
11778     NewTD->setInvalidDecl();
11779     return NewTD;
11780   }
11781 
11782   if (D.getDeclSpec().isModulePrivateSpecified()) {
11783     if (CurContext->isFunctionOrMethod())
11784       Diag(NewTD->getLocation(), diag::err_module_private_local)
11785         << 2 << NewTD->getDeclName()
11786         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11787         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11788     else
11789       NewTD->setModulePrivate();
11790   }
11791 
11792   // C++ [dcl.typedef]p8:
11793   //   If the typedef declaration defines an unnamed class (or
11794   //   enum), the first typedef-name declared by the declaration
11795   //   to be that class type (or enum type) is used to denote the
11796   //   class type (or enum type) for linkage purposes only.
11797   // We need to check whether the type was declared in the declaration.
11798   switch (D.getDeclSpec().getTypeSpecType()) {
11799   case TST_enum:
11800   case TST_struct:
11801   case TST_interface:
11802   case TST_union:
11803   case TST_class: {
11804     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
11805     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
11806     break;
11807   }
11808 
11809   default:
11810     break;
11811   }
11812 
11813   return NewTD;
11814 }
11815 
11816 /// \brief Check that this is a valid underlying type for an enum declaration.
11817 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
11818   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
11819   QualType T = TI->getType();
11820 
11821   if (T->isDependentType())
11822     return false;
11823 
11824   if (const BuiltinType *BT = T->getAs<BuiltinType>())
11825     if (BT->isInteger())
11826       return false;
11827 
11828   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
11829   return true;
11830 }
11831 
11832 /// Check whether this is a valid redeclaration of a previous enumeration.
11833 /// \return true if the redeclaration was invalid.
11834 bool Sema::CheckEnumRedeclaration(
11835     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
11836     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
11837   bool IsFixed = !EnumUnderlyingTy.isNull();
11838 
11839   if (IsScoped != Prev->isScoped()) {
11840     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
11841       << Prev->isScoped();
11842     Diag(Prev->getLocation(), diag::note_previous_declaration);
11843     return true;
11844   }
11845 
11846   if (IsFixed && Prev->isFixed()) {
11847     if (!EnumUnderlyingTy->isDependentType() &&
11848         !Prev->getIntegerType()->isDependentType() &&
11849         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
11850                                         Prev->getIntegerType())) {
11851       // TODO: Highlight the underlying type of the redeclaration.
11852       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
11853         << EnumUnderlyingTy << Prev->getIntegerType();
11854       Diag(Prev->getLocation(), diag::note_previous_declaration)
11855           << Prev->getIntegerTypeRange();
11856       return true;
11857     }
11858   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
11859     ;
11860   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
11861     ;
11862   } else if (IsFixed != Prev->isFixed()) {
11863     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
11864       << Prev->isFixed();
11865     Diag(Prev->getLocation(), diag::note_previous_declaration);
11866     return true;
11867   }
11868 
11869   return false;
11870 }
11871 
11872 /// \brief Get diagnostic %select index for tag kind for
11873 /// redeclaration diagnostic message.
11874 /// WARNING: Indexes apply to particular diagnostics only!
11875 ///
11876 /// \returns diagnostic %select index.
11877 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
11878   switch (Tag) {
11879   case TTK_Struct: return 0;
11880   case TTK_Interface: return 1;
11881   case TTK_Class:  return 2;
11882   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
11883   }
11884 }
11885 
11886 /// \brief Determine if tag kind is a class-key compatible with
11887 /// class for redeclaration (class, struct, or __interface).
11888 ///
11889 /// \returns true iff the tag kind is compatible.
11890 static bool isClassCompatTagKind(TagTypeKind Tag)
11891 {
11892   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
11893 }
11894 
11895 /// \brief Determine whether a tag with a given kind is acceptable
11896 /// as a redeclaration of the given tag declaration.
11897 ///
11898 /// \returns true if the new tag kind is acceptable, false otherwise.
11899 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
11900                                         TagTypeKind NewTag, bool isDefinition,
11901                                         SourceLocation NewTagLoc,
11902                                         const IdentifierInfo *Name) {
11903   // C++ [dcl.type.elab]p3:
11904   //   The class-key or enum keyword present in the
11905   //   elaborated-type-specifier shall agree in kind with the
11906   //   declaration to which the name in the elaborated-type-specifier
11907   //   refers. This rule also applies to the form of
11908   //   elaborated-type-specifier that declares a class-name or
11909   //   friend class since it can be construed as referring to the
11910   //   definition of the class. Thus, in any
11911   //   elaborated-type-specifier, the enum keyword shall be used to
11912   //   refer to an enumeration (7.2), the union class-key shall be
11913   //   used to refer to a union (clause 9), and either the class or
11914   //   struct class-key shall be used to refer to a class (clause 9)
11915   //   declared using the class or struct class-key.
11916   TagTypeKind OldTag = Previous->getTagKind();
11917   if (!isDefinition || !isClassCompatTagKind(NewTag))
11918     if (OldTag == NewTag)
11919       return true;
11920 
11921   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
11922     // Warn about the struct/class tag mismatch.
11923     bool isTemplate = false;
11924     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
11925       isTemplate = Record->getDescribedClassTemplate();
11926 
11927     if (!ActiveTemplateInstantiations.empty()) {
11928       // In a template instantiation, do not offer fix-its for tag mismatches
11929       // since they usually mess up the template instead of fixing the problem.
11930       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11931         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11932         << getRedeclDiagFromTagKind(OldTag);
11933       return true;
11934     }
11935 
11936     if (isDefinition) {
11937       // On definitions, check previous tags and issue a fix-it for each
11938       // one that doesn't match the current tag.
11939       if (Previous->getDefinition()) {
11940         // Don't suggest fix-its for redefinitions.
11941         return true;
11942       }
11943 
11944       bool previousMismatch = false;
11945       for (auto I : Previous->redecls()) {
11946         if (I->getTagKind() != NewTag) {
11947           if (!previousMismatch) {
11948             previousMismatch = true;
11949             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
11950               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11951               << getRedeclDiagFromTagKind(I->getTagKind());
11952           }
11953           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
11954             << getRedeclDiagFromTagKind(NewTag)
11955             << FixItHint::CreateReplacement(I->getInnerLocStart(),
11956                  TypeWithKeyword::getTagTypeKindName(NewTag));
11957         }
11958       }
11959       return true;
11960     }
11961 
11962     // Check for a previous definition.  If current tag and definition
11963     // are same type, do nothing.  If no definition, but disagree with
11964     // with previous tag type, give a warning, but no fix-it.
11965     const TagDecl *Redecl = Previous->getDefinition() ?
11966                             Previous->getDefinition() : Previous;
11967     if (Redecl->getTagKind() == NewTag) {
11968       return true;
11969     }
11970 
11971     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11972       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11973       << getRedeclDiagFromTagKind(OldTag);
11974     Diag(Redecl->getLocation(), diag::note_previous_use);
11975 
11976     // If there is a previous definition, suggest a fix-it.
11977     if (Previous->getDefinition()) {
11978         Diag(NewTagLoc, diag::note_struct_class_suggestion)
11979           << getRedeclDiagFromTagKind(Redecl->getTagKind())
11980           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
11981                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
11982     }
11983 
11984     return true;
11985   }
11986   return false;
11987 }
11988 
11989 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
11990 /// from an outer enclosing namespace or file scope inside a friend declaration.
11991 /// This should provide the commented out code in the following snippet:
11992 ///   namespace N {
11993 ///     struct X;
11994 ///     namespace M {
11995 ///       struct Y { friend struct /*N::*/ X; };
11996 ///     }
11997 ///   }
11998 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
11999                                          SourceLocation NameLoc) {
12000   // While the decl is in a namespace, do repeated lookup of that name and see
12001   // if we get the same namespace back.  If we do not, continue until
12002   // translation unit scope, at which point we have a fully qualified NNS.
12003   SmallVector<IdentifierInfo *, 4> Namespaces;
12004   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12005   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
12006     // This tag should be declared in a namespace, which can only be enclosed by
12007     // other namespaces.  Bail if there's an anonymous namespace in the chain.
12008     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
12009     if (!Namespace || Namespace->isAnonymousNamespace())
12010       return FixItHint();
12011     IdentifierInfo *II = Namespace->getIdentifier();
12012     Namespaces.push_back(II);
12013     NamedDecl *Lookup = SemaRef.LookupSingleName(
12014         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
12015     if (Lookup == Namespace)
12016       break;
12017   }
12018 
12019   // Once we have all the namespaces, reverse them to go outermost first, and
12020   // build an NNS.
12021   SmallString<64> Insertion;
12022   llvm::raw_svector_ostream OS(Insertion);
12023   if (DC->isTranslationUnit())
12024     OS << "::";
12025   std::reverse(Namespaces.begin(), Namespaces.end());
12026   for (auto *II : Namespaces)
12027     OS << II->getName() << "::";
12028   return FixItHint::CreateInsertion(NameLoc, Insertion);
12029 }
12030 
12031 /// \brief Determine whether a tag originally declared in context \p OldDC can
12032 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
12033 /// found a declaration in \p OldDC as a previous decl, perhaps through a
12034 /// using-declaration).
12035 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
12036                                          DeclContext *NewDC) {
12037   OldDC = OldDC->getRedeclContext();
12038   NewDC = NewDC->getRedeclContext();
12039 
12040   if (OldDC->Equals(NewDC))
12041     return true;
12042 
12043   // In MSVC mode, we allow a redeclaration if the contexts are related (either
12044   // encloses the other).
12045   if (S.getLangOpts().MSVCCompat &&
12046       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
12047     return true;
12048 
12049   return false;
12050 }
12051 
12052 /// Find the DeclContext in which a tag is implicitly declared if we see an
12053 /// elaborated type specifier in the specified context, and lookup finds
12054 /// nothing.
12055 static DeclContext *getTagInjectionContext(DeclContext *DC) {
12056   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
12057     DC = DC->getParent();
12058   return DC;
12059 }
12060 
12061 /// Find the Scope in which a tag is implicitly declared if we see an
12062 /// elaborated type specifier in the specified context, and lookup finds
12063 /// nothing.
12064 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
12065   while (S->isClassScope() ||
12066          (LangOpts.CPlusPlus &&
12067           S->isFunctionPrototypeScope()) ||
12068          ((S->getFlags() & Scope::DeclScope) == 0) ||
12069          (S->getEntity() && S->getEntity()->isTransparentContext()))
12070     S = S->getParent();
12071   return S;
12072 }
12073 
12074 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
12075 /// former case, Name will be non-null.  In the later case, Name will be null.
12076 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
12077 /// reference/declaration/definition of a tag.
12078 ///
12079 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
12080 /// trailing-type-specifier) other than one in an alias-declaration.
12081 ///
12082 /// \param SkipBody If non-null, will be set to indicate if the caller should
12083 /// skip the definition of this tag and treat it as if it were a declaration.
12084 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12085                      SourceLocation KWLoc, CXXScopeSpec &SS,
12086                      IdentifierInfo *Name, SourceLocation NameLoc,
12087                      AttributeList *Attr, AccessSpecifier AS,
12088                      SourceLocation ModulePrivateLoc,
12089                      MultiTemplateParamsArg TemplateParameterLists,
12090                      bool &OwnedDecl, bool &IsDependent,
12091                      SourceLocation ScopedEnumKWLoc,
12092                      bool ScopedEnumUsesClassTag,
12093                      TypeResult UnderlyingType,
12094                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
12095   // If this is not a definition, it must have a name.
12096   IdentifierInfo *OrigName = Name;
12097   assert((Name != nullptr || TUK == TUK_Definition) &&
12098          "Nameless record must be a definition!");
12099   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
12100 
12101   OwnedDecl = false;
12102   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12103   bool ScopedEnum = ScopedEnumKWLoc.isValid();
12104 
12105   // FIXME: Check explicit specializations more carefully.
12106   bool isExplicitSpecialization = false;
12107   bool Invalid = false;
12108 
12109   // We only need to do this matching if we have template parameters
12110   // or a scope specifier, which also conveniently avoids this work
12111   // for non-C++ cases.
12112   if (TemplateParameterLists.size() > 0 ||
12113       (SS.isNotEmpty() && TUK != TUK_Reference)) {
12114     if (TemplateParameterList *TemplateParams =
12115             MatchTemplateParametersToScopeSpecifier(
12116                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
12117                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
12118       if (Kind == TTK_Enum) {
12119         Diag(KWLoc, diag::err_enum_template);
12120         return nullptr;
12121       }
12122 
12123       if (TemplateParams->size() > 0) {
12124         // This is a declaration or definition of a class template (which may
12125         // be a member of another template).
12126 
12127         if (Invalid)
12128           return nullptr;
12129 
12130         OwnedDecl = false;
12131         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
12132                                                SS, Name, NameLoc, Attr,
12133                                                TemplateParams, AS,
12134                                                ModulePrivateLoc,
12135                                                /*FriendLoc*/SourceLocation(),
12136                                                TemplateParameterLists.size()-1,
12137                                                TemplateParameterLists.data(),
12138                                                SkipBody);
12139         return Result.get();
12140       } else {
12141         // The "template<>" header is extraneous.
12142         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12143           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12144         isExplicitSpecialization = true;
12145       }
12146     }
12147   }
12148 
12149   // Figure out the underlying type if this a enum declaration. We need to do
12150   // this early, because it's needed to detect if this is an incompatible
12151   // redeclaration.
12152   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
12153   bool EnumUnderlyingIsImplicit = false;
12154 
12155   if (Kind == TTK_Enum) {
12156     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
12157       // No underlying type explicitly specified, or we failed to parse the
12158       // type, default to int.
12159       EnumUnderlying = Context.IntTy.getTypePtr();
12160     else if (UnderlyingType.get()) {
12161       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
12162       // integral type; any cv-qualification is ignored.
12163       TypeSourceInfo *TI = nullptr;
12164       GetTypeFromParser(UnderlyingType.get(), &TI);
12165       EnumUnderlying = TI;
12166 
12167       if (CheckEnumUnderlyingType(TI))
12168         // Recover by falling back to int.
12169         EnumUnderlying = Context.IntTy.getTypePtr();
12170 
12171       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
12172                                           UPPC_FixedUnderlyingType))
12173         EnumUnderlying = Context.IntTy.getTypePtr();
12174 
12175     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12176       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
12177         // Microsoft enums are always of int type.
12178         EnumUnderlying = Context.IntTy.getTypePtr();
12179         EnumUnderlyingIsImplicit = true;
12180       }
12181     }
12182   }
12183 
12184   DeclContext *SearchDC = CurContext;
12185   DeclContext *DC = CurContext;
12186   bool isStdBadAlloc = false;
12187 
12188   RedeclarationKind Redecl = ForRedeclaration;
12189   if (TUK == TUK_Friend || TUK == TUK_Reference)
12190     Redecl = NotForRedeclaration;
12191 
12192   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
12193   if (Name && SS.isNotEmpty()) {
12194     // We have a nested-name tag ('struct foo::bar').
12195 
12196     // Check for invalid 'foo::'.
12197     if (SS.isInvalid()) {
12198       Name = nullptr;
12199       goto CreateNewDecl;
12200     }
12201 
12202     // If this is a friend or a reference to a class in a dependent
12203     // context, don't try to make a decl for it.
12204     if (TUK == TUK_Friend || TUK == TUK_Reference) {
12205       DC = computeDeclContext(SS, false);
12206       if (!DC) {
12207         IsDependent = true;
12208         return nullptr;
12209       }
12210     } else {
12211       DC = computeDeclContext(SS, true);
12212       if (!DC) {
12213         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
12214           << SS.getRange();
12215         return nullptr;
12216       }
12217     }
12218 
12219     if (RequireCompleteDeclContext(SS, DC))
12220       return nullptr;
12221 
12222     SearchDC = DC;
12223     // Look-up name inside 'foo::'.
12224     LookupQualifiedName(Previous, DC);
12225 
12226     if (Previous.isAmbiguous())
12227       return nullptr;
12228 
12229     if (Previous.empty()) {
12230       // Name lookup did not find anything. However, if the
12231       // nested-name-specifier refers to the current instantiation,
12232       // and that current instantiation has any dependent base
12233       // classes, we might find something at instantiation time: treat
12234       // this as a dependent elaborated-type-specifier.
12235       // But this only makes any sense for reference-like lookups.
12236       if (Previous.wasNotFoundInCurrentInstantiation() &&
12237           (TUK == TUK_Reference || TUK == TUK_Friend)) {
12238         IsDependent = true;
12239         return nullptr;
12240       }
12241 
12242       // A tag 'foo::bar' must already exist.
12243       Diag(NameLoc, diag::err_not_tag_in_scope)
12244         << Kind << Name << DC << SS.getRange();
12245       Name = nullptr;
12246       Invalid = true;
12247       goto CreateNewDecl;
12248     }
12249   } else if (Name) {
12250     // C++14 [class.mem]p14:
12251     //   If T is the name of a class, then each of the following shall have a
12252     //   name different from T:
12253     //    -- every member of class T that is itself a type
12254     if (TUK != TUK_Reference && TUK != TUK_Friend &&
12255         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
12256       return nullptr;
12257 
12258     // If this is a named struct, check to see if there was a previous forward
12259     // declaration or definition.
12260     // FIXME: We're looking into outer scopes here, even when we
12261     // shouldn't be. Doing so can result in ambiguities that we
12262     // shouldn't be diagnosing.
12263     LookupName(Previous, S);
12264 
12265     // When declaring or defining a tag, ignore ambiguities introduced
12266     // by types using'ed into this scope.
12267     if (Previous.isAmbiguous() &&
12268         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
12269       LookupResult::Filter F = Previous.makeFilter();
12270       while (F.hasNext()) {
12271         NamedDecl *ND = F.next();
12272         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
12273           F.erase();
12274       }
12275       F.done();
12276     }
12277 
12278     // C++11 [namespace.memdef]p3:
12279     //   If the name in a friend declaration is neither qualified nor
12280     //   a template-id and the declaration is a function or an
12281     //   elaborated-type-specifier, the lookup to determine whether
12282     //   the entity has been previously declared shall not consider
12283     //   any scopes outside the innermost enclosing namespace.
12284     //
12285     // MSVC doesn't implement the above rule for types, so a friend tag
12286     // declaration may be a redeclaration of a type declared in an enclosing
12287     // scope.  They do implement this rule for friend functions.
12288     //
12289     // Does it matter that this should be by scope instead of by
12290     // semantic context?
12291     if (!Previous.empty() && TUK == TUK_Friend) {
12292       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
12293       LookupResult::Filter F = Previous.makeFilter();
12294       bool FriendSawTagOutsideEnclosingNamespace = false;
12295       while (F.hasNext()) {
12296         NamedDecl *ND = F.next();
12297         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12298         if (DC->isFileContext() &&
12299             !EnclosingNS->Encloses(ND->getDeclContext())) {
12300           if (getLangOpts().MSVCCompat)
12301             FriendSawTagOutsideEnclosingNamespace = true;
12302           else
12303             F.erase();
12304         }
12305       }
12306       F.done();
12307 
12308       // Diagnose this MSVC extension in the easy case where lookup would have
12309       // unambiguously found something outside the enclosing namespace.
12310       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
12311         NamedDecl *ND = Previous.getFoundDecl();
12312         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
12313             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
12314       }
12315     }
12316 
12317     // Note:  there used to be some attempt at recovery here.
12318     if (Previous.isAmbiguous())
12319       return nullptr;
12320 
12321     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
12322       // FIXME: This makes sure that we ignore the contexts associated
12323       // with C structs, unions, and enums when looking for a matching
12324       // tag declaration or definition. See the similar lookup tweak
12325       // in Sema::LookupName; is there a better way to deal with this?
12326       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
12327         SearchDC = SearchDC->getParent();
12328     }
12329   }
12330 
12331   if (Previous.isSingleResult() &&
12332       Previous.getFoundDecl()->isTemplateParameter()) {
12333     // Maybe we will complain about the shadowed template parameter.
12334     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
12335     // Just pretend that we didn't see the previous declaration.
12336     Previous.clear();
12337   }
12338 
12339   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
12340       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
12341     // This is a declaration of or a reference to "std::bad_alloc".
12342     isStdBadAlloc = true;
12343 
12344     if (Previous.empty() && StdBadAlloc) {
12345       // std::bad_alloc has been implicitly declared (but made invisible to
12346       // name lookup). Fill in this implicit declaration as the previous
12347       // declaration, so that the declarations get chained appropriately.
12348       Previous.addDecl(getStdBadAlloc());
12349     }
12350   }
12351 
12352   // If we didn't find a previous declaration, and this is a reference
12353   // (or friend reference), move to the correct scope.  In C++, we
12354   // also need to do a redeclaration lookup there, just in case
12355   // there's a shadow friend decl.
12356   if (Name && Previous.empty() &&
12357       (TUK == TUK_Reference || TUK == TUK_Friend)) {
12358     if (Invalid) goto CreateNewDecl;
12359     assert(SS.isEmpty());
12360 
12361     if (TUK == TUK_Reference) {
12362       // C++ [basic.scope.pdecl]p5:
12363       //   -- for an elaborated-type-specifier of the form
12364       //
12365       //          class-key identifier
12366       //
12367       //      if the elaborated-type-specifier is used in the
12368       //      decl-specifier-seq or parameter-declaration-clause of a
12369       //      function defined in namespace scope, the identifier is
12370       //      declared as a class-name in the namespace that contains
12371       //      the declaration; otherwise, except as a friend
12372       //      declaration, the identifier is declared in the smallest
12373       //      non-class, non-function-prototype scope that contains the
12374       //      declaration.
12375       //
12376       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
12377       // C structs and unions.
12378       //
12379       // It is an error in C++ to declare (rather than define) an enum
12380       // type, including via an elaborated type specifier.  We'll
12381       // diagnose that later; for now, declare the enum in the same
12382       // scope as we would have picked for any other tag type.
12383       //
12384       // GNU C also supports this behavior as part of its incomplete
12385       // enum types extension, while GNU C++ does not.
12386       //
12387       // Find the context where we'll be declaring the tag.
12388       // FIXME: We would like to maintain the current DeclContext as the
12389       // lexical context,
12390       SearchDC = getTagInjectionContext(SearchDC);
12391 
12392       // Find the scope where we'll be declaring the tag.
12393       S = getTagInjectionScope(S, getLangOpts());
12394     } else {
12395       assert(TUK == TUK_Friend);
12396       // C++ [namespace.memdef]p3:
12397       //   If a friend declaration in a non-local class first declares a
12398       //   class or function, the friend class or function is a member of
12399       //   the innermost enclosing namespace.
12400       SearchDC = SearchDC->getEnclosingNamespaceContext();
12401     }
12402 
12403     // In C++, we need to do a redeclaration lookup to properly
12404     // diagnose some problems.
12405     // FIXME: redeclaration lookup is also used (with and without C++) to find a
12406     // hidden declaration so that we don't get ambiguity errors when using a
12407     // type declared by an elaborated-type-specifier.  In C that is not correct
12408     // and we should instead merge compatible types found by lookup.
12409     if (getLangOpts().CPlusPlus) {
12410       Previous.setRedeclarationKind(ForRedeclaration);
12411       LookupQualifiedName(Previous, SearchDC);
12412     } else {
12413       Previous.setRedeclarationKind(ForRedeclaration);
12414       LookupName(Previous, S);
12415     }
12416   }
12417 
12418   // If we have a known previous declaration to use, then use it.
12419   if (Previous.empty() && SkipBody && SkipBody->Previous)
12420     Previous.addDecl(SkipBody->Previous);
12421 
12422   if (!Previous.empty()) {
12423     NamedDecl *PrevDecl = Previous.getFoundDecl();
12424     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
12425 
12426     // It's okay to have a tag decl in the same scope as a typedef
12427     // which hides a tag decl in the same scope.  Finding this
12428     // insanity with a redeclaration lookup can only actually happen
12429     // in C++.
12430     //
12431     // This is also okay for elaborated-type-specifiers, which is
12432     // technically forbidden by the current standard but which is
12433     // okay according to the likely resolution of an open issue;
12434     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
12435     if (getLangOpts().CPlusPlus) {
12436       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12437         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
12438           TagDecl *Tag = TT->getDecl();
12439           if (Tag->getDeclName() == Name &&
12440               Tag->getDeclContext()->getRedeclContext()
12441                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
12442             PrevDecl = Tag;
12443             Previous.clear();
12444             Previous.addDecl(Tag);
12445             Previous.resolveKind();
12446           }
12447         }
12448       }
12449     }
12450 
12451     // If this is a redeclaration of a using shadow declaration, it must
12452     // declare a tag in the same context. In MSVC mode, we allow a
12453     // redefinition if either context is within the other.
12454     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
12455       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
12456       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
12457           isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
12458           !(OldTag && isAcceptableTagRedeclContext(
12459                           *this, OldTag->getDeclContext(), SearchDC))) {
12460         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
12461         Diag(Shadow->getTargetDecl()->getLocation(),
12462              diag::note_using_decl_target);
12463         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
12464             << 0;
12465         // Recover by ignoring the old declaration.
12466         Previous.clear();
12467         goto CreateNewDecl;
12468       }
12469     }
12470 
12471     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
12472       // If this is a use of a previous tag, or if the tag is already declared
12473       // in the same scope (so that the definition/declaration completes or
12474       // rementions the tag), reuse the decl.
12475       if (TUK == TUK_Reference || TUK == TUK_Friend ||
12476           isDeclInScope(DirectPrevDecl, SearchDC, S,
12477                         SS.isNotEmpty() || isExplicitSpecialization)) {
12478         // Make sure that this wasn't declared as an enum and now used as a
12479         // struct or something similar.
12480         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
12481                                           TUK == TUK_Definition, KWLoc,
12482                                           Name)) {
12483           bool SafeToContinue
12484             = (PrevTagDecl->getTagKind() != TTK_Enum &&
12485                Kind != TTK_Enum);
12486           if (SafeToContinue)
12487             Diag(KWLoc, diag::err_use_with_wrong_tag)
12488               << Name
12489               << FixItHint::CreateReplacement(SourceRange(KWLoc),
12490                                               PrevTagDecl->getKindName());
12491           else
12492             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
12493           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
12494 
12495           if (SafeToContinue)
12496             Kind = PrevTagDecl->getTagKind();
12497           else {
12498             // Recover by making this an anonymous redefinition.
12499             Name = nullptr;
12500             Previous.clear();
12501             Invalid = true;
12502           }
12503         }
12504 
12505         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
12506           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
12507 
12508           // If this is an elaborated-type-specifier for a scoped enumeration,
12509           // the 'class' keyword is not necessary and not permitted.
12510           if (TUK == TUK_Reference || TUK == TUK_Friend) {
12511             if (ScopedEnum)
12512               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
12513                 << PrevEnum->isScoped()
12514                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
12515             return PrevTagDecl;
12516           }
12517 
12518           QualType EnumUnderlyingTy;
12519           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12520             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
12521           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
12522             EnumUnderlyingTy = QualType(T, 0);
12523 
12524           // All conflicts with previous declarations are recovered by
12525           // returning the previous declaration, unless this is a definition,
12526           // in which case we want the caller to bail out.
12527           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
12528                                      ScopedEnum, EnumUnderlyingTy,
12529                                      EnumUnderlyingIsImplicit, PrevEnum))
12530             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
12531         }
12532 
12533         // C++11 [class.mem]p1:
12534         //   A member shall not be declared twice in the member-specification,
12535         //   except that a nested class or member class template can be declared
12536         //   and then later defined.
12537         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
12538             S->isDeclScope(PrevDecl)) {
12539           Diag(NameLoc, diag::ext_member_redeclared);
12540           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
12541         }
12542 
12543         if (!Invalid) {
12544           // If this is a use, just return the declaration we found, unless
12545           // we have attributes.
12546           if (TUK == TUK_Reference || TUK == TUK_Friend) {
12547             if (Attr) {
12548               // FIXME: Diagnose these attributes. For now, we create a new
12549               // declaration to hold them.
12550             } else if (TUK == TUK_Reference &&
12551                        (PrevTagDecl->getFriendObjectKind() ==
12552                             Decl::FOK_Undeclared ||
12553                         PP.getModuleContainingLocation(
12554                             PrevDecl->getLocation()) !=
12555                             PP.getModuleContainingLocation(KWLoc)) &&
12556                        SS.isEmpty()) {
12557               // This declaration is a reference to an existing entity, but
12558               // has different visibility from that entity: it either makes
12559               // a friend visible or it makes a type visible in a new module.
12560               // In either case, create a new declaration. We only do this if
12561               // the declaration would have meant the same thing if no prior
12562               // declaration were found, that is, if it was found in the same
12563               // scope where we would have injected a declaration.
12564               if (!getTagInjectionContext(CurContext)->getRedeclContext()
12565                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
12566                 return PrevTagDecl;
12567               // This is in the injected scope, create a new declaration in
12568               // that scope.
12569               S = getTagInjectionScope(S, getLangOpts());
12570             } else {
12571               return PrevTagDecl;
12572             }
12573           }
12574 
12575           // Diagnose attempts to redefine a tag.
12576           if (TUK == TUK_Definition) {
12577             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
12578               // If we're defining a specialization and the previous definition
12579               // is from an implicit instantiation, don't emit an error
12580               // here; we'll catch this in the general case below.
12581               bool IsExplicitSpecializationAfterInstantiation = false;
12582               if (isExplicitSpecialization) {
12583                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
12584                   IsExplicitSpecializationAfterInstantiation =
12585                     RD->getTemplateSpecializationKind() !=
12586                     TSK_ExplicitSpecialization;
12587                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
12588                   IsExplicitSpecializationAfterInstantiation =
12589                     ED->getTemplateSpecializationKind() !=
12590                     TSK_ExplicitSpecialization;
12591               }
12592 
12593               NamedDecl *Hidden = nullptr;
12594               if (SkipBody && getLangOpts().CPlusPlus &&
12595                   !hasVisibleDefinition(Def, &Hidden)) {
12596                 // There is a definition of this tag, but it is not visible. We
12597                 // explicitly make use of C++'s one definition rule here, and
12598                 // assume that this definition is identical to the hidden one
12599                 // we already have. Make the existing definition visible and
12600                 // use it in place of this one.
12601                 SkipBody->ShouldSkip = true;
12602                 makeMergedDefinitionVisible(Hidden, KWLoc);
12603                 return Def;
12604               } else if (!IsExplicitSpecializationAfterInstantiation) {
12605                 // A redeclaration in function prototype scope in C isn't
12606                 // visible elsewhere, so merely issue a warning.
12607                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
12608                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
12609                 else
12610                   Diag(NameLoc, diag::err_redefinition) << Name;
12611                 Diag(Def->getLocation(), diag::note_previous_definition);
12612                 // If this is a redefinition, recover by making this
12613                 // struct be anonymous, which will make any later
12614                 // references get the previous definition.
12615                 Name = nullptr;
12616                 Previous.clear();
12617                 Invalid = true;
12618               }
12619             } else {
12620               // If the type is currently being defined, complain
12621               // about a nested redefinition.
12622               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
12623               if (TD->isBeingDefined()) {
12624                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
12625                 Diag(PrevTagDecl->getLocation(),
12626                      diag::note_previous_definition);
12627                 Name = nullptr;
12628                 Previous.clear();
12629                 Invalid = true;
12630               }
12631             }
12632 
12633             // Okay, this is definition of a previously declared or referenced
12634             // tag. We're going to create a new Decl for it.
12635           }
12636 
12637           // Okay, we're going to make a redeclaration.  If this is some kind
12638           // of reference, make sure we build the redeclaration in the same DC
12639           // as the original, and ignore the current access specifier.
12640           if (TUK == TUK_Friend || TUK == TUK_Reference) {
12641             SearchDC = PrevTagDecl->getDeclContext();
12642             AS = AS_none;
12643           }
12644         }
12645         // If we get here we have (another) forward declaration or we
12646         // have a definition.  Just create a new decl.
12647 
12648       } else {
12649         // If we get here, this is a definition of a new tag type in a nested
12650         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
12651         // new decl/type.  We set PrevDecl to NULL so that the entities
12652         // have distinct types.
12653         Previous.clear();
12654       }
12655       // If we get here, we're going to create a new Decl. If PrevDecl
12656       // is non-NULL, it's a definition of the tag declared by
12657       // PrevDecl. If it's NULL, we have a new definition.
12658 
12659     // Otherwise, PrevDecl is not a tag, but was found with tag
12660     // lookup.  This is only actually possible in C++, where a few
12661     // things like templates still live in the tag namespace.
12662     } else {
12663       // Use a better diagnostic if an elaborated-type-specifier
12664       // found the wrong kind of type on the first
12665       // (non-redeclaration) lookup.
12666       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
12667           !Previous.isForRedeclaration()) {
12668         unsigned Kind = 0;
12669         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12670         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12671         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12672         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
12673         Diag(PrevDecl->getLocation(), diag::note_declared_at);
12674         Invalid = true;
12675 
12676       // Otherwise, only diagnose if the declaration is in scope.
12677       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
12678                                 SS.isNotEmpty() || isExplicitSpecialization)) {
12679         // do nothing
12680 
12681       // Diagnose implicit declarations introduced by elaborated types.
12682       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
12683         unsigned Kind = 0;
12684         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12685         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12686         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12687         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
12688         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12689         Invalid = true;
12690 
12691       // Otherwise it's a declaration.  Call out a particularly common
12692       // case here.
12693       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12694         unsigned Kind = 0;
12695         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
12696         Diag(NameLoc, diag::err_tag_definition_of_typedef)
12697           << Name << Kind << TND->getUnderlyingType();
12698         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12699         Invalid = true;
12700 
12701       // Otherwise, diagnose.
12702       } else {
12703         // The tag name clashes with something else in the target scope,
12704         // issue an error and recover by making this tag be anonymous.
12705         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
12706         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12707         Name = nullptr;
12708         Invalid = true;
12709       }
12710 
12711       // The existing declaration isn't relevant to us; we're in a
12712       // new scope, so clear out the previous declaration.
12713       Previous.clear();
12714     }
12715   }
12716 
12717 CreateNewDecl:
12718 
12719   TagDecl *PrevDecl = nullptr;
12720   if (Previous.isSingleResult())
12721     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
12722 
12723   // If there is an identifier, use the location of the identifier as the
12724   // location of the decl, otherwise use the location of the struct/union
12725   // keyword.
12726   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
12727 
12728   // Otherwise, create a new declaration. If there is a previous
12729   // declaration of the same entity, the two will be linked via
12730   // PrevDecl.
12731   TagDecl *New;
12732 
12733   bool IsForwardReference = false;
12734   if (Kind == TTK_Enum) {
12735     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12736     // enum X { A, B, C } D;    D should chain to X.
12737     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
12738                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
12739                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
12740     // If this is an undefined enum, warn.
12741     if (TUK != TUK_Definition && !Invalid) {
12742       TagDecl *Def;
12743       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
12744           cast<EnumDecl>(New)->isFixed()) {
12745         // C++0x: 7.2p2: opaque-enum-declaration.
12746         // Conflicts are diagnosed above. Do nothing.
12747       }
12748       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
12749         Diag(Loc, diag::ext_forward_ref_enum_def)
12750           << New;
12751         Diag(Def->getLocation(), diag::note_previous_definition);
12752       } else {
12753         unsigned DiagID = diag::ext_forward_ref_enum;
12754         if (getLangOpts().MSVCCompat)
12755           DiagID = diag::ext_ms_forward_ref_enum;
12756         else if (getLangOpts().CPlusPlus)
12757           DiagID = diag::err_forward_ref_enum;
12758         Diag(Loc, DiagID);
12759 
12760         // If this is a forward-declared reference to an enumeration, make a
12761         // note of it; we won't actually be introducing the declaration into
12762         // the declaration context.
12763         if (TUK == TUK_Reference)
12764           IsForwardReference = true;
12765       }
12766     }
12767 
12768     if (EnumUnderlying) {
12769       EnumDecl *ED = cast<EnumDecl>(New);
12770       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12771         ED->setIntegerTypeSourceInfo(TI);
12772       else
12773         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
12774       ED->setPromotionType(ED->getIntegerType());
12775     }
12776   } else {
12777     // struct/union/class
12778 
12779     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12780     // struct X { int A; } D;    D should chain to X.
12781     if (getLangOpts().CPlusPlus) {
12782       // FIXME: Look for a way to use RecordDecl for simple structs.
12783       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12784                                   cast_or_null<CXXRecordDecl>(PrevDecl));
12785 
12786       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
12787         StdBadAlloc = cast<CXXRecordDecl>(New);
12788     } else
12789       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12790                                cast_or_null<RecordDecl>(PrevDecl));
12791   }
12792 
12793   // C++11 [dcl.type]p3:
12794   //   A type-specifier-seq shall not define a class or enumeration [...].
12795   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
12796     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
12797       << Context.getTagDeclType(New);
12798     Invalid = true;
12799   }
12800 
12801   // Maybe add qualifier info.
12802   if (SS.isNotEmpty()) {
12803     if (SS.isSet()) {
12804       // If this is either a declaration or a definition, check the
12805       // nested-name-specifier against the current context. We don't do this
12806       // for explicit specializations, because they have similar checking
12807       // (with more specific diagnostics) in the call to
12808       // CheckMemberSpecialization, below.
12809       if (!isExplicitSpecialization &&
12810           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
12811           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
12812         Invalid = true;
12813 
12814       New->setQualifierInfo(SS.getWithLocInContext(Context));
12815       if (TemplateParameterLists.size() > 0) {
12816         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
12817       }
12818     }
12819     else
12820       Invalid = true;
12821   }
12822 
12823   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
12824     // Add alignment attributes if necessary; these attributes are checked when
12825     // the ASTContext lays out the structure.
12826     //
12827     // It is important for implementing the correct semantics that this
12828     // happen here (in act on tag decl). The #pragma pack stack is
12829     // maintained as a result of parser callbacks which can occur at
12830     // many points during the parsing of a struct declaration (because
12831     // the #pragma tokens are effectively skipped over during the
12832     // parsing of the struct).
12833     if (TUK == TUK_Definition) {
12834       AddAlignmentAttributesForRecord(RD);
12835       AddMsStructLayoutForRecord(RD);
12836     }
12837   }
12838 
12839   if (ModulePrivateLoc.isValid()) {
12840     if (isExplicitSpecialization)
12841       Diag(New->getLocation(), diag::err_module_private_specialization)
12842         << 2
12843         << FixItHint::CreateRemoval(ModulePrivateLoc);
12844     // __module_private__ does not apply to local classes. However, we only
12845     // diagnose this as an error when the declaration specifiers are
12846     // freestanding. Here, we just ignore the __module_private__.
12847     else if (!SearchDC->isFunctionOrMethod())
12848       New->setModulePrivate();
12849   }
12850 
12851   // If this is a specialization of a member class (of a class template),
12852   // check the specialization.
12853   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
12854     Invalid = true;
12855 
12856   // If we're declaring or defining a tag in function prototype scope in C,
12857   // note that this type can only be used within the function and add it to
12858   // the list of decls to inject into the function definition scope.
12859   if ((Name || Kind == TTK_Enum) &&
12860       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
12861     if (getLangOpts().CPlusPlus) {
12862       // C++ [dcl.fct]p6:
12863       //   Types shall not be defined in return or parameter types.
12864       if (TUK == TUK_Definition && !IsTypeSpecifier) {
12865         Diag(Loc, diag::err_type_defined_in_param_type)
12866             << Name;
12867         Invalid = true;
12868       }
12869     } else if (!PrevDecl) {
12870       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
12871     }
12872     DeclsInPrototypeScope.push_back(New);
12873   }
12874 
12875   if (Invalid)
12876     New->setInvalidDecl();
12877 
12878   if (Attr)
12879     ProcessDeclAttributeList(S, New, Attr);
12880 
12881   // Set the lexical context. If the tag has a C++ scope specifier, the
12882   // lexical context will be different from the semantic context.
12883   New->setLexicalDeclContext(CurContext);
12884 
12885   // Mark this as a friend decl if applicable.
12886   // In Microsoft mode, a friend declaration also acts as a forward
12887   // declaration so we always pass true to setObjectOfFriendDecl to make
12888   // the tag name visible.
12889   if (TUK == TUK_Friend)
12890     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
12891 
12892   // Set the access specifier.
12893   if (!Invalid && SearchDC->isRecord())
12894     SetMemberAccessSpecifier(New, PrevDecl, AS);
12895 
12896   if (TUK == TUK_Definition)
12897     New->startDefinition();
12898 
12899   // If this has an identifier, add it to the scope stack.
12900   if (TUK == TUK_Friend) {
12901     // We might be replacing an existing declaration in the lookup tables;
12902     // if so, borrow its access specifier.
12903     if (PrevDecl)
12904       New->setAccess(PrevDecl->getAccess());
12905 
12906     DeclContext *DC = New->getDeclContext()->getRedeclContext();
12907     DC->makeDeclVisibleInContext(New);
12908     if (Name) // can be null along some error paths
12909       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12910         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
12911   } else if (Name) {
12912     S = getNonFieldDeclScope(S);
12913     PushOnScopeChains(New, S, !IsForwardReference);
12914     if (IsForwardReference)
12915       SearchDC->makeDeclVisibleInContext(New);
12916   } else {
12917     CurContext->addDecl(New);
12918   }
12919 
12920   // If this is the C FILE type, notify the AST context.
12921   if (IdentifierInfo *II = New->getIdentifier())
12922     if (!New->isInvalidDecl() &&
12923         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
12924         II->isStr("FILE"))
12925       Context.setFILEDecl(New);
12926 
12927   if (PrevDecl)
12928     mergeDeclAttributes(New, PrevDecl);
12929 
12930   // If there's a #pragma GCC visibility in scope, set the visibility of this
12931   // record.
12932   AddPushedVisibilityAttribute(New);
12933 
12934   OwnedDecl = true;
12935   // In C++, don't return an invalid declaration. We can't recover well from
12936   // the cases where we make the type anonymous.
12937   return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
12938 }
12939 
12940 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
12941   AdjustDeclIfTemplate(TagD);
12942   TagDecl *Tag = cast<TagDecl>(TagD);
12943 
12944   // Enter the tag context.
12945   PushDeclContext(S, Tag);
12946 
12947   ActOnDocumentableDecl(TagD);
12948 
12949   // If there's a #pragma GCC visibility in scope, set the visibility of this
12950   // record.
12951   AddPushedVisibilityAttribute(Tag);
12952 }
12953 
12954 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
12955   assert(isa<ObjCContainerDecl>(IDecl) &&
12956          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
12957   DeclContext *OCD = cast<DeclContext>(IDecl);
12958   assert(getContainingDC(OCD) == CurContext &&
12959       "The next DeclContext should be lexically contained in the current one.");
12960   CurContext = OCD;
12961   return IDecl;
12962 }
12963 
12964 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
12965                                            SourceLocation FinalLoc,
12966                                            bool IsFinalSpelledSealed,
12967                                            SourceLocation LBraceLoc) {
12968   AdjustDeclIfTemplate(TagD);
12969   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
12970 
12971   FieldCollector->StartClass();
12972 
12973   if (!Record->getIdentifier())
12974     return;
12975 
12976   if (FinalLoc.isValid())
12977     Record->addAttr(new (Context)
12978                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
12979 
12980   // C++ [class]p2:
12981   //   [...] The class-name is also inserted into the scope of the
12982   //   class itself; this is known as the injected-class-name. For
12983   //   purposes of access checking, the injected-class-name is treated
12984   //   as if it were a public member name.
12985   CXXRecordDecl *InjectedClassName
12986     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
12987                             Record->getLocStart(), Record->getLocation(),
12988                             Record->getIdentifier(),
12989                             /*PrevDecl=*/nullptr,
12990                             /*DelayTypeCreation=*/true);
12991   Context.getTypeDeclType(InjectedClassName, Record);
12992   InjectedClassName->setImplicit();
12993   InjectedClassName->setAccess(AS_public);
12994   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
12995       InjectedClassName->setDescribedClassTemplate(Template);
12996   PushOnScopeChains(InjectedClassName, S);
12997   assert(InjectedClassName->isInjectedClassName() &&
12998          "Broken injected-class-name");
12999 }
13000 
13001 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
13002                                     SourceLocation RBraceLoc) {
13003   AdjustDeclIfTemplate(TagD);
13004   TagDecl *Tag = cast<TagDecl>(TagD);
13005   Tag->setRBraceLoc(RBraceLoc);
13006 
13007   // Make sure we "complete" the definition even it is invalid.
13008   if (Tag->isBeingDefined()) {
13009     assert(Tag->isInvalidDecl() && "We should already have completed it");
13010     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13011       RD->completeDefinition();
13012   }
13013 
13014   if (isa<CXXRecordDecl>(Tag))
13015     FieldCollector->FinishClass();
13016 
13017   // Exit this scope of this tag's definition.
13018   PopDeclContext();
13019 
13020   if (getCurLexicalContext()->isObjCContainer() &&
13021       Tag->getDeclContext()->isFileContext())
13022     Tag->setTopLevelDeclInObjCContainer();
13023 
13024   // Notify the consumer that we've defined a tag.
13025   if (!Tag->isInvalidDecl())
13026     Consumer.HandleTagDeclDefinition(Tag);
13027 }
13028 
13029 void Sema::ActOnObjCContainerFinishDefinition() {
13030   // Exit this scope of this interface definition.
13031   PopDeclContext();
13032 }
13033 
13034 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
13035   assert(DC == CurContext && "Mismatch of container contexts");
13036   OriginalLexicalContext = DC;
13037   ActOnObjCContainerFinishDefinition();
13038 }
13039 
13040 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
13041   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
13042   OriginalLexicalContext = nullptr;
13043 }
13044 
13045 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
13046   AdjustDeclIfTemplate(TagD);
13047   TagDecl *Tag = cast<TagDecl>(TagD);
13048   Tag->setInvalidDecl();
13049 
13050   // Make sure we "complete" the definition even it is invalid.
13051   if (Tag->isBeingDefined()) {
13052     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13053       RD->completeDefinition();
13054   }
13055 
13056   // We're undoing ActOnTagStartDefinition here, not
13057   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
13058   // the FieldCollector.
13059 
13060   PopDeclContext();
13061 }
13062 
13063 // Note that FieldName may be null for anonymous bitfields.
13064 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
13065                                 IdentifierInfo *FieldName,
13066                                 QualType FieldTy, bool IsMsStruct,
13067                                 Expr *BitWidth, bool *ZeroWidth) {
13068   // Default to true; that shouldn't confuse checks for emptiness
13069   if (ZeroWidth)
13070     *ZeroWidth = true;
13071 
13072   // C99 6.7.2.1p4 - verify the field type.
13073   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
13074   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
13075     // Handle incomplete types with specific error.
13076     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
13077       return ExprError();
13078     if (FieldName)
13079       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
13080         << FieldName << FieldTy << BitWidth->getSourceRange();
13081     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
13082       << FieldTy << BitWidth->getSourceRange();
13083   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
13084                                              UPPC_BitFieldWidth))
13085     return ExprError();
13086 
13087   // If the bit-width is type- or value-dependent, don't try to check
13088   // it now.
13089   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
13090     return BitWidth;
13091 
13092   llvm::APSInt Value;
13093   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
13094   if (ICE.isInvalid())
13095     return ICE;
13096   BitWidth = ICE.get();
13097 
13098   if (Value != 0 && ZeroWidth)
13099     *ZeroWidth = false;
13100 
13101   // Zero-width bitfield is ok for anonymous field.
13102   if (Value == 0 && FieldName)
13103     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
13104 
13105   if (Value.isSigned() && Value.isNegative()) {
13106     if (FieldName)
13107       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
13108                << FieldName << Value.toString(10);
13109     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
13110       << Value.toString(10);
13111   }
13112 
13113   if (!FieldTy->isDependentType()) {
13114     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
13115     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
13116     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
13117 
13118     // Over-wide bitfields are an error in C or when using the MSVC bitfield
13119     // ABI.
13120     bool CStdConstraintViolation =
13121         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
13122     bool MSBitfieldViolation =
13123         Value.ugt(TypeStorageSize) &&
13124         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
13125     if (CStdConstraintViolation || MSBitfieldViolation) {
13126       unsigned DiagWidth =
13127           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
13128       if (FieldName)
13129         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
13130                << FieldName << (unsigned)Value.getZExtValue()
13131                << !CStdConstraintViolation << DiagWidth;
13132 
13133       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
13134              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
13135              << DiagWidth;
13136     }
13137 
13138     // Warn on types where the user might conceivably expect to get all
13139     // specified bits as value bits: that's all integral types other than
13140     // 'bool'.
13141     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
13142       if (FieldName)
13143         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
13144             << FieldName << (unsigned)Value.getZExtValue()
13145             << (unsigned)TypeWidth;
13146       else
13147         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
13148             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
13149     }
13150   }
13151 
13152   return BitWidth;
13153 }
13154 
13155 /// ActOnField - Each field of a C struct/union is passed into this in order
13156 /// to create a FieldDecl object for it.
13157 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
13158                        Declarator &D, Expr *BitfieldWidth) {
13159   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
13160                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
13161                                /*InitStyle=*/ICIS_NoInit, AS_public);
13162   return Res;
13163 }
13164 
13165 /// HandleField - Analyze a field of a C struct or a C++ data member.
13166 ///
13167 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
13168                              SourceLocation DeclStart,
13169                              Declarator &D, Expr *BitWidth,
13170                              InClassInitStyle InitStyle,
13171                              AccessSpecifier AS) {
13172   IdentifierInfo *II = D.getIdentifier();
13173   SourceLocation Loc = DeclStart;
13174   if (II) Loc = D.getIdentifierLoc();
13175 
13176   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13177   QualType T = TInfo->getType();
13178   if (getLangOpts().CPlusPlus) {
13179     CheckExtraCXXDefaultArguments(D);
13180 
13181     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13182                                         UPPC_DataMemberType)) {
13183       D.setInvalidType();
13184       T = Context.IntTy;
13185       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13186     }
13187   }
13188 
13189   // TR 18037 does not allow fields to be declared with address spaces.
13190   if (T.getQualifiers().hasAddressSpace()) {
13191     Diag(Loc, diag::err_field_with_address_space);
13192     D.setInvalidType();
13193   }
13194 
13195   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
13196   // used as structure or union field: image, sampler, event or block types.
13197   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
13198                           T->isSamplerT() || T->isBlockPointerType())) {
13199     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
13200     D.setInvalidType();
13201   }
13202 
13203   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13204 
13205   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13206     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13207          diag::err_invalid_thread)
13208       << DeclSpec::getSpecifierName(TSCS);
13209 
13210   // Check to see if this name was declared as a member previously
13211   NamedDecl *PrevDecl = nullptr;
13212   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13213   LookupName(Previous, S);
13214   switch (Previous.getResultKind()) {
13215     case LookupResult::Found:
13216     case LookupResult::FoundUnresolvedValue:
13217       PrevDecl = Previous.getAsSingle<NamedDecl>();
13218       break;
13219 
13220     case LookupResult::FoundOverloaded:
13221       PrevDecl = Previous.getRepresentativeDecl();
13222       break;
13223 
13224     case LookupResult::NotFound:
13225     case LookupResult::NotFoundInCurrentInstantiation:
13226     case LookupResult::Ambiguous:
13227       break;
13228   }
13229   Previous.suppressDiagnostics();
13230 
13231   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13232     // Maybe we will complain about the shadowed template parameter.
13233     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13234     // Just pretend that we didn't see the previous declaration.
13235     PrevDecl = nullptr;
13236   }
13237 
13238   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13239     PrevDecl = nullptr;
13240 
13241   bool Mutable
13242     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
13243   SourceLocation TSSL = D.getLocStart();
13244   FieldDecl *NewFD
13245     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
13246                      TSSL, AS, PrevDecl, &D);
13247 
13248   if (NewFD->isInvalidDecl())
13249     Record->setInvalidDecl();
13250 
13251   if (D.getDeclSpec().isModulePrivateSpecified())
13252     NewFD->setModulePrivate();
13253 
13254   if (NewFD->isInvalidDecl() && PrevDecl) {
13255     // Don't introduce NewFD into scope; there's already something
13256     // with the same name in the same scope.
13257   } else if (II) {
13258     PushOnScopeChains(NewFD, S);
13259   } else
13260     Record->addDecl(NewFD);
13261 
13262   return NewFD;
13263 }
13264 
13265 /// \brief Build a new FieldDecl and check its well-formedness.
13266 ///
13267 /// This routine builds a new FieldDecl given the fields name, type,
13268 /// record, etc. \p PrevDecl should refer to any previous declaration
13269 /// with the same name and in the same scope as the field to be
13270 /// created.
13271 ///
13272 /// \returns a new FieldDecl.
13273 ///
13274 /// \todo The Declarator argument is a hack. It will be removed once
13275 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
13276                                 TypeSourceInfo *TInfo,
13277                                 RecordDecl *Record, SourceLocation Loc,
13278                                 bool Mutable, Expr *BitWidth,
13279                                 InClassInitStyle InitStyle,
13280                                 SourceLocation TSSL,
13281                                 AccessSpecifier AS, NamedDecl *PrevDecl,
13282                                 Declarator *D) {
13283   IdentifierInfo *II = Name.getAsIdentifierInfo();
13284   bool InvalidDecl = false;
13285   if (D) InvalidDecl = D->isInvalidType();
13286 
13287   // If we receive a broken type, recover by assuming 'int' and
13288   // marking this declaration as invalid.
13289   if (T.isNull()) {
13290     InvalidDecl = true;
13291     T = Context.IntTy;
13292   }
13293 
13294   QualType EltTy = Context.getBaseElementType(T);
13295   if (!EltTy->isDependentType()) {
13296     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
13297       // Fields of incomplete type force their record to be invalid.
13298       Record->setInvalidDecl();
13299       InvalidDecl = true;
13300     } else {
13301       NamedDecl *Def;
13302       EltTy->isIncompleteType(&Def);
13303       if (Def && Def->isInvalidDecl()) {
13304         Record->setInvalidDecl();
13305         InvalidDecl = true;
13306       }
13307     }
13308   }
13309 
13310   // OpenCL v1.2 s6.9.c: bitfields are not supported.
13311   if (BitWidth && getLangOpts().OpenCL) {
13312     Diag(Loc, diag::err_opencl_bitfields);
13313     InvalidDecl = true;
13314   }
13315 
13316   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13317   // than a variably modified type.
13318   if (!InvalidDecl && T->isVariablyModifiedType()) {
13319     bool SizeIsNegative;
13320     llvm::APSInt Oversized;
13321 
13322     TypeSourceInfo *FixedTInfo =
13323       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
13324                                                     SizeIsNegative,
13325                                                     Oversized);
13326     if (FixedTInfo) {
13327       Diag(Loc, diag::warn_illegal_constant_array_size);
13328       TInfo = FixedTInfo;
13329       T = FixedTInfo->getType();
13330     } else {
13331       if (SizeIsNegative)
13332         Diag(Loc, diag::err_typecheck_negative_array_size);
13333       else if (Oversized.getBoolValue())
13334         Diag(Loc, diag::err_array_too_large)
13335           << Oversized.toString(10);
13336       else
13337         Diag(Loc, diag::err_typecheck_field_variable_size);
13338       InvalidDecl = true;
13339     }
13340   }
13341 
13342   // Fields can not have abstract class types
13343   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
13344                                              diag::err_abstract_type_in_decl,
13345                                              AbstractFieldType))
13346     InvalidDecl = true;
13347 
13348   bool ZeroWidth = false;
13349   if (InvalidDecl)
13350     BitWidth = nullptr;
13351   // If this is declared as a bit-field, check the bit-field.
13352   if (BitWidth) {
13353     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
13354                               &ZeroWidth).get();
13355     if (!BitWidth) {
13356       InvalidDecl = true;
13357       BitWidth = nullptr;
13358       ZeroWidth = false;
13359     }
13360   }
13361 
13362   // Check that 'mutable' is consistent with the type of the declaration.
13363   if (!InvalidDecl && Mutable) {
13364     unsigned DiagID = 0;
13365     if (T->isReferenceType())
13366       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
13367                                         : diag::err_mutable_reference;
13368     else if (T.isConstQualified())
13369       DiagID = diag::err_mutable_const;
13370 
13371     if (DiagID) {
13372       SourceLocation ErrLoc = Loc;
13373       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
13374         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
13375       Diag(ErrLoc, DiagID);
13376       if (DiagID != diag::ext_mutable_reference) {
13377         Mutable = false;
13378         InvalidDecl = true;
13379       }
13380     }
13381   }
13382 
13383   // C++11 [class.union]p8 (DR1460):
13384   //   At most one variant member of a union may have a
13385   //   brace-or-equal-initializer.
13386   if (InitStyle != ICIS_NoInit)
13387     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
13388 
13389   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
13390                                        BitWidth, Mutable, InitStyle);
13391   if (InvalidDecl)
13392     NewFD->setInvalidDecl();
13393 
13394   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
13395     Diag(Loc, diag::err_duplicate_member) << II;
13396     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13397     NewFD->setInvalidDecl();
13398   }
13399 
13400   if (!InvalidDecl && getLangOpts().CPlusPlus) {
13401     if (Record->isUnion()) {
13402       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13403         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
13404         if (RDecl->getDefinition()) {
13405           // C++ [class.union]p1: An object of a class with a non-trivial
13406           // constructor, a non-trivial copy constructor, a non-trivial
13407           // destructor, or a non-trivial copy assignment operator
13408           // cannot be a member of a union, nor can an array of such
13409           // objects.
13410           if (CheckNontrivialField(NewFD))
13411             NewFD->setInvalidDecl();
13412         }
13413       }
13414 
13415       // C++ [class.union]p1: If a union contains a member of reference type,
13416       // the program is ill-formed, except when compiling with MSVC extensions
13417       // enabled.
13418       if (EltTy->isReferenceType()) {
13419         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
13420                                     diag::ext_union_member_of_reference_type :
13421                                     diag::err_union_member_of_reference_type)
13422           << NewFD->getDeclName() << EltTy;
13423         if (!getLangOpts().MicrosoftExt)
13424           NewFD->setInvalidDecl();
13425       }
13426     }
13427   }
13428 
13429   // FIXME: We need to pass in the attributes given an AST
13430   // representation, not a parser representation.
13431   if (D) {
13432     // FIXME: The current scope is almost... but not entirely... correct here.
13433     ProcessDeclAttributes(getCurScope(), NewFD, *D);
13434 
13435     if (NewFD->hasAttrs())
13436       CheckAlignasUnderalignment(NewFD);
13437   }
13438 
13439   // In auto-retain/release, infer strong retension for fields of
13440   // retainable type.
13441   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
13442     NewFD->setInvalidDecl();
13443 
13444   if (T.isObjCGCWeak())
13445     Diag(Loc, diag::warn_attribute_weak_on_field);
13446 
13447   NewFD->setAccess(AS);
13448   return NewFD;
13449 }
13450 
13451 bool Sema::CheckNontrivialField(FieldDecl *FD) {
13452   assert(FD);
13453   assert(getLangOpts().CPlusPlus && "valid check only for C++");
13454 
13455   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
13456     return false;
13457 
13458   QualType EltTy = Context.getBaseElementType(FD->getType());
13459   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13460     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
13461     if (RDecl->getDefinition()) {
13462       // We check for copy constructors before constructors
13463       // because otherwise we'll never get complaints about
13464       // copy constructors.
13465 
13466       CXXSpecialMember member = CXXInvalid;
13467       // We're required to check for any non-trivial constructors. Since the
13468       // implicit default constructor is suppressed if there are any
13469       // user-declared constructors, we just need to check that there is a
13470       // trivial default constructor and a trivial copy constructor. (We don't
13471       // worry about move constructors here, since this is a C++98 check.)
13472       if (RDecl->hasNonTrivialCopyConstructor())
13473         member = CXXCopyConstructor;
13474       else if (!RDecl->hasTrivialDefaultConstructor())
13475         member = CXXDefaultConstructor;
13476       else if (RDecl->hasNonTrivialCopyAssignment())
13477         member = CXXCopyAssignment;
13478       else if (RDecl->hasNonTrivialDestructor())
13479         member = CXXDestructor;
13480 
13481       if (member != CXXInvalid) {
13482         if (!getLangOpts().CPlusPlus11 &&
13483             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
13484           // Objective-C++ ARC: it is an error to have a non-trivial field of
13485           // a union. However, system headers in Objective-C programs
13486           // occasionally have Objective-C lifetime objects within unions,
13487           // and rather than cause the program to fail, we make those
13488           // members unavailable.
13489           SourceLocation Loc = FD->getLocation();
13490           if (getSourceManager().isInSystemHeader(Loc)) {
13491             if (!FD->hasAttr<UnavailableAttr>())
13492               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13493                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
13494             return false;
13495           }
13496         }
13497 
13498         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
13499                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
13500                diag::err_illegal_union_or_anon_struct_member)
13501           << FD->getParent()->isUnion() << FD->getDeclName() << member;
13502         DiagnoseNontrivial(RDecl, member);
13503         return !getLangOpts().CPlusPlus11;
13504       }
13505     }
13506   }
13507 
13508   return false;
13509 }
13510 
13511 /// TranslateIvarVisibility - Translate visibility from a token ID to an
13512 ///  AST enum value.
13513 static ObjCIvarDecl::AccessControl
13514 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
13515   switch (ivarVisibility) {
13516   default: llvm_unreachable("Unknown visitibility kind");
13517   case tok::objc_private: return ObjCIvarDecl::Private;
13518   case tok::objc_public: return ObjCIvarDecl::Public;
13519   case tok::objc_protected: return ObjCIvarDecl::Protected;
13520   case tok::objc_package: return ObjCIvarDecl::Package;
13521   }
13522 }
13523 
13524 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
13525 /// in order to create an IvarDecl object for it.
13526 Decl *Sema::ActOnIvar(Scope *S,
13527                                 SourceLocation DeclStart,
13528                                 Declarator &D, Expr *BitfieldWidth,
13529                                 tok::ObjCKeywordKind Visibility) {
13530 
13531   IdentifierInfo *II = D.getIdentifier();
13532   Expr *BitWidth = (Expr*)BitfieldWidth;
13533   SourceLocation Loc = DeclStart;
13534   if (II) Loc = D.getIdentifierLoc();
13535 
13536   // FIXME: Unnamed fields can be handled in various different ways, for
13537   // example, unnamed unions inject all members into the struct namespace!
13538 
13539   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13540   QualType T = TInfo->getType();
13541 
13542   if (BitWidth) {
13543     // 6.7.2.1p3, 6.7.2.1p4
13544     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
13545     if (!BitWidth)
13546       D.setInvalidType();
13547   } else {
13548     // Not a bitfield.
13549 
13550     // validate II.
13551 
13552   }
13553   if (T->isReferenceType()) {
13554     Diag(Loc, diag::err_ivar_reference_type);
13555     D.setInvalidType();
13556   }
13557   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13558   // than a variably modified type.
13559   else if (T->isVariablyModifiedType()) {
13560     Diag(Loc, diag::err_typecheck_ivar_variable_size);
13561     D.setInvalidType();
13562   }
13563 
13564   // Get the visibility (access control) for this ivar.
13565   ObjCIvarDecl::AccessControl ac =
13566     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
13567                                         : ObjCIvarDecl::None;
13568   // Must set ivar's DeclContext to its enclosing interface.
13569   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
13570   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
13571     return nullptr;
13572   ObjCContainerDecl *EnclosingContext;
13573   if (ObjCImplementationDecl *IMPDecl =
13574       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13575     if (LangOpts.ObjCRuntime.isFragile()) {
13576     // Case of ivar declared in an implementation. Context is that of its class.
13577       EnclosingContext = IMPDecl->getClassInterface();
13578       assert(EnclosingContext && "Implementation has no class interface!");
13579     }
13580     else
13581       EnclosingContext = EnclosingDecl;
13582   } else {
13583     if (ObjCCategoryDecl *CDecl =
13584         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13585       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
13586         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
13587         return nullptr;
13588       }
13589     }
13590     EnclosingContext = EnclosingDecl;
13591   }
13592 
13593   // Construct the decl.
13594   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
13595                                              DeclStart, Loc, II, T,
13596                                              TInfo, ac, (Expr *)BitfieldWidth);
13597 
13598   if (II) {
13599     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
13600                                            ForRedeclaration);
13601     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
13602         && !isa<TagDecl>(PrevDecl)) {
13603       Diag(Loc, diag::err_duplicate_member) << II;
13604       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13605       NewID->setInvalidDecl();
13606     }
13607   }
13608 
13609   // Process attributes attached to the ivar.
13610   ProcessDeclAttributes(S, NewID, D);
13611 
13612   if (D.isInvalidType())
13613     NewID->setInvalidDecl();
13614 
13615   // In ARC, infer 'retaining' for ivars of retainable type.
13616   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
13617     NewID->setInvalidDecl();
13618 
13619   if (D.getDeclSpec().isModulePrivateSpecified())
13620     NewID->setModulePrivate();
13621 
13622   if (II) {
13623     // FIXME: When interfaces are DeclContexts, we'll need to add
13624     // these to the interface.
13625     S->AddDecl(NewID);
13626     IdResolver.AddDecl(NewID);
13627   }
13628 
13629   if (LangOpts.ObjCRuntime.isNonFragile() &&
13630       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
13631     Diag(Loc, diag::warn_ivars_in_interface);
13632 
13633   return NewID;
13634 }
13635 
13636 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
13637 /// class and class extensions. For every class \@interface and class
13638 /// extension \@interface, if the last ivar is a bitfield of any type,
13639 /// then add an implicit `char :0` ivar to the end of that interface.
13640 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
13641                              SmallVectorImpl<Decl *> &AllIvarDecls) {
13642   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
13643     return;
13644 
13645   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
13646   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
13647 
13648   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
13649     return;
13650   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
13651   if (!ID) {
13652     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
13653       if (!CD->IsClassExtension())
13654         return;
13655     }
13656     // No need to add this to end of @implementation.
13657     else
13658       return;
13659   }
13660   // All conditions are met. Add a new bitfield to the tail end of ivars.
13661   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
13662   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
13663 
13664   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
13665                               DeclLoc, DeclLoc, nullptr,
13666                               Context.CharTy,
13667                               Context.getTrivialTypeSourceInfo(Context.CharTy,
13668                                                                DeclLoc),
13669                               ObjCIvarDecl::Private, BW,
13670                               true);
13671   AllIvarDecls.push_back(Ivar);
13672 }
13673 
13674 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
13675                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
13676                        SourceLocation RBrac, AttributeList *Attr) {
13677   assert(EnclosingDecl && "missing record or interface decl");
13678 
13679   // If this is an Objective-C @implementation or category and we have
13680   // new fields here we should reset the layout of the interface since
13681   // it will now change.
13682   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
13683     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
13684     switch (DC->getKind()) {
13685     default: break;
13686     case Decl::ObjCCategory:
13687       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
13688       break;
13689     case Decl::ObjCImplementation:
13690       Context.
13691         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
13692       break;
13693     }
13694   }
13695 
13696   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
13697 
13698   // Start counting up the number of named members; make sure to include
13699   // members of anonymous structs and unions in the total.
13700   unsigned NumNamedMembers = 0;
13701   if (Record) {
13702     for (const auto *I : Record->decls()) {
13703       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
13704         if (IFD->getDeclName())
13705           ++NumNamedMembers;
13706     }
13707   }
13708 
13709   // Verify that all the fields are okay.
13710   SmallVector<FieldDecl*, 32> RecFields;
13711 
13712   bool ARCErrReported = false;
13713   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
13714        i != end; ++i) {
13715     FieldDecl *FD = cast<FieldDecl>(*i);
13716 
13717     // Get the type for the field.
13718     const Type *FDTy = FD->getType().getTypePtr();
13719 
13720     if (!FD->isAnonymousStructOrUnion()) {
13721       // Remember all fields written by the user.
13722       RecFields.push_back(FD);
13723     }
13724 
13725     // If the field is already invalid for some reason, don't emit more
13726     // diagnostics about it.
13727     if (FD->isInvalidDecl()) {
13728       EnclosingDecl->setInvalidDecl();
13729       continue;
13730     }
13731 
13732     // C99 6.7.2.1p2:
13733     //   A structure or union shall not contain a member with
13734     //   incomplete or function type (hence, a structure shall not
13735     //   contain an instance of itself, but may contain a pointer to
13736     //   an instance of itself), except that the last member of a
13737     //   structure with more than one named member may have incomplete
13738     //   array type; such a structure (and any union containing,
13739     //   possibly recursively, a member that is such a structure)
13740     //   shall not be a member of a structure or an element of an
13741     //   array.
13742     if (FDTy->isFunctionType()) {
13743       // Field declared as a function.
13744       Diag(FD->getLocation(), diag::err_field_declared_as_function)
13745         << FD->getDeclName();
13746       FD->setInvalidDecl();
13747       EnclosingDecl->setInvalidDecl();
13748       continue;
13749     } else if (FDTy->isIncompleteArrayType() && Record &&
13750                ((i + 1 == Fields.end() && !Record->isUnion()) ||
13751                 ((getLangOpts().MicrosoftExt ||
13752                   getLangOpts().CPlusPlus) &&
13753                  (i + 1 == Fields.end() || Record->isUnion())))) {
13754       // Flexible array member.
13755       // Microsoft and g++ is more permissive regarding flexible array.
13756       // It will accept flexible array in union and also
13757       // as the sole element of a struct/class.
13758       unsigned DiagID = 0;
13759       if (Record->isUnion())
13760         DiagID = getLangOpts().MicrosoftExt
13761                      ? diag::ext_flexible_array_union_ms
13762                      : getLangOpts().CPlusPlus
13763                            ? diag::ext_flexible_array_union_gnu
13764                            : diag::err_flexible_array_union;
13765       else if (Fields.size() == 1)
13766         DiagID = getLangOpts().MicrosoftExt
13767                      ? diag::ext_flexible_array_empty_aggregate_ms
13768                      : getLangOpts().CPlusPlus
13769                            ? diag::ext_flexible_array_empty_aggregate_gnu
13770                            : NumNamedMembers < 1
13771                                  ? diag::err_flexible_array_empty_aggregate
13772                                  : 0;
13773 
13774       if (DiagID)
13775         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
13776                                         << Record->getTagKind();
13777       // While the layout of types that contain virtual bases is not specified
13778       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
13779       // virtual bases after the derived members.  This would make a flexible
13780       // array member declared at the end of an object not adjacent to the end
13781       // of the type.
13782       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
13783         if (RD->getNumVBases() != 0)
13784           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
13785             << FD->getDeclName() << Record->getTagKind();
13786       if (!getLangOpts().C99)
13787         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
13788           << FD->getDeclName() << Record->getTagKind();
13789 
13790       // If the element type has a non-trivial destructor, we would not
13791       // implicitly destroy the elements, so disallow it for now.
13792       //
13793       // FIXME: GCC allows this. We should probably either implicitly delete
13794       // the destructor of the containing class, or just allow this.
13795       QualType BaseElem = Context.getBaseElementType(FD->getType());
13796       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
13797         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
13798           << FD->getDeclName() << FD->getType();
13799         FD->setInvalidDecl();
13800         EnclosingDecl->setInvalidDecl();
13801         continue;
13802       }
13803       // Okay, we have a legal flexible array member at the end of the struct.
13804       Record->setHasFlexibleArrayMember(true);
13805     } else if (!FDTy->isDependentType() &&
13806                RequireCompleteType(FD->getLocation(), FD->getType(),
13807                                    diag::err_field_incomplete)) {
13808       // Incomplete type
13809       FD->setInvalidDecl();
13810       EnclosingDecl->setInvalidDecl();
13811       continue;
13812     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
13813       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
13814         // A type which contains a flexible array member is considered to be a
13815         // flexible array member.
13816         Record->setHasFlexibleArrayMember(true);
13817         if (!Record->isUnion()) {
13818           // If this is a struct/class and this is not the last element, reject
13819           // it.  Note that GCC supports variable sized arrays in the middle of
13820           // structures.
13821           if (i + 1 != Fields.end())
13822             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
13823               << FD->getDeclName() << FD->getType();
13824           else {
13825             // We support flexible arrays at the end of structs in
13826             // other structs as an extension.
13827             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
13828               << FD->getDeclName();
13829           }
13830         }
13831       }
13832       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
13833           RequireNonAbstractType(FD->getLocation(), FD->getType(),
13834                                  diag::err_abstract_type_in_decl,
13835                                  AbstractIvarType)) {
13836         // Ivars can not have abstract class types
13837         FD->setInvalidDecl();
13838       }
13839       if (Record && FDTTy->getDecl()->hasObjectMember())
13840         Record->setHasObjectMember(true);
13841       if (Record && FDTTy->getDecl()->hasVolatileMember())
13842         Record->setHasVolatileMember(true);
13843     } else if (FDTy->isObjCObjectType()) {
13844       /// A field cannot be an Objective-c object
13845       Diag(FD->getLocation(), diag::err_statically_allocated_object)
13846         << FixItHint::CreateInsertion(FD->getLocation(), "*");
13847       QualType T = Context.getObjCObjectPointerType(FD->getType());
13848       FD->setType(T);
13849     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
13850                (!getLangOpts().CPlusPlus || Record->isUnion())) {
13851       // It's an error in ARC if a field has lifetime.
13852       // We don't want to report this in a system header, though,
13853       // so we just make the field unavailable.
13854       // FIXME: that's really not sufficient; we need to make the type
13855       // itself invalid to, say, initialize or copy.
13856       QualType T = FD->getType();
13857       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
13858       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
13859         SourceLocation loc = FD->getLocation();
13860         if (getSourceManager().isInSystemHeader(loc)) {
13861           if (!FD->hasAttr<UnavailableAttr>()) {
13862             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13863                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
13864           }
13865         } else {
13866           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
13867             << T->isBlockPointerType() << Record->getTagKind();
13868         }
13869         ARCErrReported = true;
13870       }
13871     } else if (getLangOpts().ObjC1 &&
13872                getLangOpts().getGC() != LangOptions::NonGC &&
13873                Record && !Record->hasObjectMember()) {
13874       if (FD->getType()->isObjCObjectPointerType() ||
13875           FD->getType().isObjCGCStrong())
13876         Record->setHasObjectMember(true);
13877       else if (Context.getAsArrayType(FD->getType())) {
13878         QualType BaseType = Context.getBaseElementType(FD->getType());
13879         if (BaseType->isRecordType() &&
13880             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
13881           Record->setHasObjectMember(true);
13882         else if (BaseType->isObjCObjectPointerType() ||
13883                  BaseType.isObjCGCStrong())
13884                Record->setHasObjectMember(true);
13885       }
13886     }
13887     if (Record && FD->getType().isVolatileQualified())
13888       Record->setHasVolatileMember(true);
13889     // Keep track of the number of named members.
13890     if (FD->getIdentifier())
13891       ++NumNamedMembers;
13892   }
13893 
13894   // Okay, we successfully defined 'Record'.
13895   if (Record) {
13896     bool Completed = false;
13897     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
13898       if (!CXXRecord->isInvalidDecl()) {
13899         // Set access bits correctly on the directly-declared conversions.
13900         for (CXXRecordDecl::conversion_iterator
13901                I = CXXRecord->conversion_begin(),
13902                E = CXXRecord->conversion_end(); I != E; ++I)
13903           I.setAccess((*I)->getAccess());
13904       }
13905 
13906       if (!CXXRecord->isDependentType()) {
13907         if (CXXRecord->hasUserDeclaredDestructor()) {
13908           // Adjust user-defined destructor exception spec.
13909           if (getLangOpts().CPlusPlus11)
13910             AdjustDestructorExceptionSpec(CXXRecord,
13911                                           CXXRecord->getDestructor());
13912         }
13913 
13914         if (!CXXRecord->isInvalidDecl()) {
13915           // Add any implicitly-declared members to this class.
13916           AddImplicitlyDeclaredMembersToClass(CXXRecord);
13917 
13918           // If we have virtual base classes, we may end up finding multiple
13919           // final overriders for a given virtual function. Check for this
13920           // problem now.
13921           if (CXXRecord->getNumVBases()) {
13922             CXXFinalOverriderMap FinalOverriders;
13923             CXXRecord->getFinalOverriders(FinalOverriders);
13924 
13925             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
13926                                              MEnd = FinalOverriders.end();
13927                  M != MEnd; ++M) {
13928               for (OverridingMethods::iterator SO = M->second.begin(),
13929                                             SOEnd = M->second.end();
13930                    SO != SOEnd; ++SO) {
13931                 assert(SO->second.size() > 0 &&
13932                        "Virtual function without overridding functions?");
13933                 if (SO->second.size() == 1)
13934                   continue;
13935 
13936                 // C++ [class.virtual]p2:
13937                 //   In a derived class, if a virtual member function of a base
13938                 //   class subobject has more than one final overrider the
13939                 //   program is ill-formed.
13940                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
13941                   << (const NamedDecl *)M->first << Record;
13942                 Diag(M->first->getLocation(),
13943                      diag::note_overridden_virtual_function);
13944                 for (OverridingMethods::overriding_iterator
13945                           OM = SO->second.begin(),
13946                        OMEnd = SO->second.end();
13947                      OM != OMEnd; ++OM)
13948                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
13949                     << (const NamedDecl *)M->first << OM->Method->getParent();
13950 
13951                 Record->setInvalidDecl();
13952               }
13953             }
13954             CXXRecord->completeDefinition(&FinalOverriders);
13955             Completed = true;
13956           }
13957         }
13958       }
13959     }
13960 
13961     if (!Completed)
13962       Record->completeDefinition();
13963 
13964     if (Record->hasAttrs()) {
13965       CheckAlignasUnderalignment(Record);
13966 
13967       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
13968         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
13969                                            IA->getRange(), IA->getBestCase(),
13970                                            IA->getSemanticSpelling());
13971     }
13972 
13973     // Check if the structure/union declaration is a type that can have zero
13974     // size in C. For C this is a language extension, for C++ it may cause
13975     // compatibility problems.
13976     bool CheckForZeroSize;
13977     if (!getLangOpts().CPlusPlus) {
13978       CheckForZeroSize = true;
13979     } else {
13980       // For C++ filter out types that cannot be referenced in C code.
13981       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
13982       CheckForZeroSize =
13983           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
13984           !CXXRecord->isDependentType() &&
13985           CXXRecord->isCLike();
13986     }
13987     if (CheckForZeroSize) {
13988       bool ZeroSize = true;
13989       bool IsEmpty = true;
13990       unsigned NonBitFields = 0;
13991       for (RecordDecl::field_iterator I = Record->field_begin(),
13992                                       E = Record->field_end();
13993            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
13994         IsEmpty = false;
13995         if (I->isUnnamedBitfield()) {
13996           if (I->getBitWidthValue(Context) > 0)
13997             ZeroSize = false;
13998         } else {
13999           ++NonBitFields;
14000           QualType FieldType = I->getType();
14001           if (FieldType->isIncompleteType() ||
14002               !Context.getTypeSizeInChars(FieldType).isZero())
14003             ZeroSize = false;
14004         }
14005       }
14006 
14007       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
14008       // allowed in C++, but warn if its declaration is inside
14009       // extern "C" block.
14010       if (ZeroSize) {
14011         Diag(RecLoc, getLangOpts().CPlusPlus ?
14012                          diag::warn_zero_size_struct_union_in_extern_c :
14013                          diag::warn_zero_size_struct_union_compat)
14014           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
14015       }
14016 
14017       // Structs without named members are extension in C (C99 6.7.2.1p7),
14018       // but are accepted by GCC.
14019       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
14020         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
14021                                diag::ext_no_named_members_in_struct_union)
14022           << Record->isUnion();
14023       }
14024     }
14025   } else {
14026     ObjCIvarDecl **ClsFields =
14027       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
14028     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
14029       ID->setEndOfDefinitionLoc(RBrac);
14030       // Add ivar's to class's DeclContext.
14031       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14032         ClsFields[i]->setLexicalDeclContext(ID);
14033         ID->addDecl(ClsFields[i]);
14034       }
14035       // Must enforce the rule that ivars in the base classes may not be
14036       // duplicates.
14037       if (ID->getSuperClass())
14038         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
14039     } else if (ObjCImplementationDecl *IMPDecl =
14040                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14041       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
14042       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
14043         // Ivar declared in @implementation never belongs to the implementation.
14044         // Only it is in implementation's lexical context.
14045         ClsFields[I]->setLexicalDeclContext(IMPDecl);
14046       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
14047       IMPDecl->setIvarLBraceLoc(LBrac);
14048       IMPDecl->setIvarRBraceLoc(RBrac);
14049     } else if (ObjCCategoryDecl *CDecl =
14050                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14051       // case of ivars in class extension; all other cases have been
14052       // reported as errors elsewhere.
14053       // FIXME. Class extension does not have a LocEnd field.
14054       // CDecl->setLocEnd(RBrac);
14055       // Add ivar's to class extension's DeclContext.
14056       // Diagnose redeclaration of private ivars.
14057       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
14058       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14059         if (IDecl) {
14060           if (const ObjCIvarDecl *ClsIvar =
14061               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
14062             Diag(ClsFields[i]->getLocation(),
14063                  diag::err_duplicate_ivar_declaration);
14064             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
14065             continue;
14066           }
14067           for (const auto *Ext : IDecl->known_extensions()) {
14068             if (const ObjCIvarDecl *ClsExtIvar
14069                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
14070               Diag(ClsFields[i]->getLocation(),
14071                    diag::err_duplicate_ivar_declaration);
14072               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
14073               continue;
14074             }
14075           }
14076         }
14077         ClsFields[i]->setLexicalDeclContext(CDecl);
14078         CDecl->addDecl(ClsFields[i]);
14079       }
14080       CDecl->setIvarLBraceLoc(LBrac);
14081       CDecl->setIvarRBraceLoc(RBrac);
14082     }
14083   }
14084 
14085   if (Attr)
14086     ProcessDeclAttributeList(S, Record, Attr);
14087 }
14088 
14089 /// \brief Determine whether the given integral value is representable within
14090 /// the given type T.
14091 static bool isRepresentableIntegerValue(ASTContext &Context,
14092                                         llvm::APSInt &Value,
14093                                         QualType T) {
14094   assert(T->isIntegralType(Context) && "Integral type required!");
14095   unsigned BitWidth = Context.getIntWidth(T);
14096 
14097   if (Value.isUnsigned() || Value.isNonNegative()) {
14098     if (T->isSignedIntegerOrEnumerationType())
14099       --BitWidth;
14100     return Value.getActiveBits() <= BitWidth;
14101   }
14102   return Value.getMinSignedBits() <= BitWidth;
14103 }
14104 
14105 // \brief Given an integral type, return the next larger integral type
14106 // (or a NULL type of no such type exists).
14107 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
14108   // FIXME: Int128/UInt128 support, which also needs to be introduced into
14109   // enum checking below.
14110   assert(T->isIntegralType(Context) && "Integral type required!");
14111   const unsigned NumTypes = 4;
14112   QualType SignedIntegralTypes[NumTypes] = {
14113     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
14114   };
14115   QualType UnsignedIntegralTypes[NumTypes] = {
14116     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
14117     Context.UnsignedLongLongTy
14118   };
14119 
14120   unsigned BitWidth = Context.getTypeSize(T);
14121   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
14122                                                         : UnsignedIntegralTypes;
14123   for (unsigned I = 0; I != NumTypes; ++I)
14124     if (Context.getTypeSize(Types[I]) > BitWidth)
14125       return Types[I];
14126 
14127   return QualType();
14128 }
14129 
14130 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
14131                                           EnumConstantDecl *LastEnumConst,
14132                                           SourceLocation IdLoc,
14133                                           IdentifierInfo *Id,
14134                                           Expr *Val) {
14135   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14136   llvm::APSInt EnumVal(IntWidth);
14137   QualType EltTy;
14138 
14139   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
14140     Val = nullptr;
14141 
14142   if (Val)
14143     Val = DefaultLvalueConversion(Val).get();
14144 
14145   if (Val) {
14146     if (Enum->isDependentType() || Val->isTypeDependent())
14147       EltTy = Context.DependentTy;
14148     else {
14149       SourceLocation ExpLoc;
14150       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
14151           !getLangOpts().MSVCCompat) {
14152         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
14153         // constant-expression in the enumerator-definition shall be a converted
14154         // constant expression of the underlying type.
14155         EltTy = Enum->getIntegerType();
14156         ExprResult Converted =
14157           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
14158                                            CCEK_Enumerator);
14159         if (Converted.isInvalid())
14160           Val = nullptr;
14161         else
14162           Val = Converted.get();
14163       } else if (!Val->isValueDependent() &&
14164                  !(Val = VerifyIntegerConstantExpression(Val,
14165                                                          &EnumVal).get())) {
14166         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
14167       } else {
14168         if (Enum->isFixed()) {
14169           EltTy = Enum->getIntegerType();
14170 
14171           // In Obj-C and Microsoft mode, require the enumeration value to be
14172           // representable in the underlying type of the enumeration. In C++11,
14173           // we perform a non-narrowing conversion as part of converted constant
14174           // expression checking.
14175           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14176             if (getLangOpts().MSVCCompat) {
14177               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
14178               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
14179             } else
14180               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
14181           } else
14182             Val = ImpCastExprToType(Val, EltTy,
14183                                     EltTy->isBooleanType() ?
14184                                     CK_IntegralToBoolean : CK_IntegralCast)
14185                     .get();
14186         } else if (getLangOpts().CPlusPlus) {
14187           // C++11 [dcl.enum]p5:
14188           //   If the underlying type is not fixed, the type of each enumerator
14189           //   is the type of its initializing value:
14190           //     - If an initializer is specified for an enumerator, the
14191           //       initializing value has the same type as the expression.
14192           EltTy = Val->getType();
14193         } else {
14194           // C99 6.7.2.2p2:
14195           //   The expression that defines the value of an enumeration constant
14196           //   shall be an integer constant expression that has a value
14197           //   representable as an int.
14198 
14199           // Complain if the value is not representable in an int.
14200           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
14201             Diag(IdLoc, diag::ext_enum_value_not_int)
14202               << EnumVal.toString(10) << Val->getSourceRange()
14203               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
14204           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
14205             // Force the type of the expression to 'int'.
14206             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
14207           }
14208           EltTy = Val->getType();
14209         }
14210       }
14211     }
14212   }
14213 
14214   if (!Val) {
14215     if (Enum->isDependentType())
14216       EltTy = Context.DependentTy;
14217     else if (!LastEnumConst) {
14218       // C++0x [dcl.enum]p5:
14219       //   If the underlying type is not fixed, the type of each enumerator
14220       //   is the type of its initializing value:
14221       //     - If no initializer is specified for the first enumerator, the
14222       //       initializing value has an unspecified integral type.
14223       //
14224       // GCC uses 'int' for its unspecified integral type, as does
14225       // C99 6.7.2.2p3.
14226       if (Enum->isFixed()) {
14227         EltTy = Enum->getIntegerType();
14228       }
14229       else {
14230         EltTy = Context.IntTy;
14231       }
14232     } else {
14233       // Assign the last value + 1.
14234       EnumVal = LastEnumConst->getInitVal();
14235       ++EnumVal;
14236       EltTy = LastEnumConst->getType();
14237 
14238       // Check for overflow on increment.
14239       if (EnumVal < LastEnumConst->getInitVal()) {
14240         // C++0x [dcl.enum]p5:
14241         //   If the underlying type is not fixed, the type of each enumerator
14242         //   is the type of its initializing value:
14243         //
14244         //     - Otherwise the type of the initializing value is the same as
14245         //       the type of the initializing value of the preceding enumerator
14246         //       unless the incremented value is not representable in that type,
14247         //       in which case the type is an unspecified integral type
14248         //       sufficient to contain the incremented value. If no such type
14249         //       exists, the program is ill-formed.
14250         QualType T = getNextLargerIntegralType(Context, EltTy);
14251         if (T.isNull() || Enum->isFixed()) {
14252           // There is no integral type larger enough to represent this
14253           // value. Complain, then allow the value to wrap around.
14254           EnumVal = LastEnumConst->getInitVal();
14255           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
14256           ++EnumVal;
14257           if (Enum->isFixed())
14258             // When the underlying type is fixed, this is ill-formed.
14259             Diag(IdLoc, diag::err_enumerator_wrapped)
14260               << EnumVal.toString(10)
14261               << EltTy;
14262           else
14263             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
14264               << EnumVal.toString(10);
14265         } else {
14266           EltTy = T;
14267         }
14268 
14269         // Retrieve the last enumerator's value, extent that type to the
14270         // type that is supposed to be large enough to represent the incremented
14271         // value, then increment.
14272         EnumVal = LastEnumConst->getInitVal();
14273         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14274         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
14275         ++EnumVal;
14276 
14277         // If we're not in C++, diagnose the overflow of enumerator values,
14278         // which in C99 means that the enumerator value is not representable in
14279         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
14280         // permits enumerator values that are representable in some larger
14281         // integral type.
14282         if (!getLangOpts().CPlusPlus && !T.isNull())
14283           Diag(IdLoc, diag::warn_enum_value_overflow);
14284       } else if (!getLangOpts().CPlusPlus &&
14285                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14286         // Enforce C99 6.7.2.2p2 even when we compute the next value.
14287         Diag(IdLoc, diag::ext_enum_value_not_int)
14288           << EnumVal.toString(10) << 1;
14289       }
14290     }
14291   }
14292 
14293   if (!EltTy->isDependentType()) {
14294     // Make the enumerator value match the signedness and size of the
14295     // enumerator's type.
14296     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
14297     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14298   }
14299 
14300   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
14301                                   Val, EnumVal);
14302 }
14303 
14304 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
14305                                                 SourceLocation IILoc) {
14306   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
14307       !getLangOpts().CPlusPlus)
14308     return SkipBodyInfo();
14309 
14310   // We have an anonymous enum definition. Look up the first enumerator to
14311   // determine if we should merge the definition with an existing one and
14312   // skip the body.
14313   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
14314                                          ForRedeclaration);
14315   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
14316   if (!PrevECD)
14317     return SkipBodyInfo();
14318 
14319   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
14320   NamedDecl *Hidden;
14321   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
14322     SkipBodyInfo Skip;
14323     Skip.Previous = Hidden;
14324     return Skip;
14325   }
14326 
14327   return SkipBodyInfo();
14328 }
14329 
14330 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
14331                               SourceLocation IdLoc, IdentifierInfo *Id,
14332                               AttributeList *Attr,
14333                               SourceLocation EqualLoc, Expr *Val) {
14334   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
14335   EnumConstantDecl *LastEnumConst =
14336     cast_or_null<EnumConstantDecl>(lastEnumConst);
14337 
14338   // The scope passed in may not be a decl scope.  Zip up the scope tree until
14339   // we find one that is.
14340   S = getNonFieldDeclScope(S);
14341 
14342   // Verify that there isn't already something declared with this name in this
14343   // scope.
14344   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
14345                                          ForRedeclaration);
14346   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14347     // Maybe we will complain about the shadowed template parameter.
14348     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
14349     // Just pretend that we didn't see the previous declaration.
14350     PrevDecl = nullptr;
14351   }
14352 
14353   // C++ [class.mem]p15:
14354   // If T is the name of a class, then each of the following shall have a name
14355   // different from T:
14356   // - every enumerator of every member of class T that is an unscoped
14357   // enumerated type
14358   if (!TheEnumDecl->isScoped())
14359     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
14360                             DeclarationNameInfo(Id, IdLoc));
14361 
14362   EnumConstantDecl *New =
14363     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
14364   if (!New)
14365     return nullptr;
14366 
14367   if (PrevDecl) {
14368     // When in C++, we may get a TagDecl with the same name; in this case the
14369     // enum constant will 'hide' the tag.
14370     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
14371            "Received TagDecl when not in C++!");
14372     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
14373         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
14374       if (isa<EnumConstantDecl>(PrevDecl))
14375         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
14376       else
14377         Diag(IdLoc, diag::err_redefinition) << Id;
14378       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14379       return nullptr;
14380     }
14381   }
14382 
14383   // Process attributes.
14384   if (Attr) ProcessDeclAttributeList(S, New, Attr);
14385 
14386   // Register this decl in the current scope stack.
14387   New->setAccess(TheEnumDecl->getAccess());
14388   PushOnScopeChains(New, S);
14389 
14390   ActOnDocumentableDecl(New);
14391 
14392   return New;
14393 }
14394 
14395 // Returns true when the enum initial expression does not trigger the
14396 // duplicate enum warning.  A few common cases are exempted as follows:
14397 // Element2 = Element1
14398 // Element2 = Element1 + 1
14399 // Element2 = Element1 - 1
14400 // Where Element2 and Element1 are from the same enum.
14401 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
14402   Expr *InitExpr = ECD->getInitExpr();
14403   if (!InitExpr)
14404     return true;
14405   InitExpr = InitExpr->IgnoreImpCasts();
14406 
14407   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
14408     if (!BO->isAdditiveOp())
14409       return true;
14410     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
14411     if (!IL)
14412       return true;
14413     if (IL->getValue() != 1)
14414       return true;
14415 
14416     InitExpr = BO->getLHS();
14417   }
14418 
14419   // This checks if the elements are from the same enum.
14420   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
14421   if (!DRE)
14422     return true;
14423 
14424   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
14425   if (!EnumConstant)
14426     return true;
14427 
14428   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
14429       Enum)
14430     return true;
14431 
14432   return false;
14433 }
14434 
14435 namespace {
14436 struct DupKey {
14437   int64_t val;
14438   bool isTombstoneOrEmptyKey;
14439   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
14440     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
14441 };
14442 
14443 static DupKey GetDupKey(const llvm::APSInt& Val) {
14444   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
14445                 false);
14446 }
14447 
14448 struct DenseMapInfoDupKey {
14449   static DupKey getEmptyKey() { return DupKey(0, true); }
14450   static DupKey getTombstoneKey() { return DupKey(1, true); }
14451   static unsigned getHashValue(const DupKey Key) {
14452     return (unsigned)(Key.val * 37);
14453   }
14454   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
14455     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
14456            LHS.val == RHS.val;
14457   }
14458 };
14459 } // end anonymous namespace
14460 
14461 // Emits a warning when an element is implicitly set a value that
14462 // a previous element has already been set to.
14463 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
14464                                         EnumDecl *Enum,
14465                                         QualType EnumType) {
14466   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
14467     return;
14468   // Avoid anonymous enums
14469   if (!Enum->getIdentifier())
14470     return;
14471 
14472   // Only check for small enums.
14473   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
14474     return;
14475 
14476   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
14477   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
14478 
14479   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
14480   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
14481           ValueToVectorMap;
14482 
14483   DuplicatesVector DupVector;
14484   ValueToVectorMap EnumMap;
14485 
14486   // Populate the EnumMap with all values represented by enum constants without
14487   // an initialier.
14488   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14489     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
14490 
14491     // Null EnumConstantDecl means a previous diagnostic has been emitted for
14492     // this constant.  Skip this enum since it may be ill-formed.
14493     if (!ECD) {
14494       return;
14495     }
14496 
14497     if (ECD->getInitExpr())
14498       continue;
14499 
14500     DupKey Key = GetDupKey(ECD->getInitVal());
14501     DeclOrVector &Entry = EnumMap[Key];
14502 
14503     // First time encountering this value.
14504     if (Entry.isNull())
14505       Entry = ECD;
14506   }
14507 
14508   // Create vectors for any values that has duplicates.
14509   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14510     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
14511     if (!ValidDuplicateEnum(ECD, Enum))
14512       continue;
14513 
14514     DupKey Key = GetDupKey(ECD->getInitVal());
14515 
14516     DeclOrVector& Entry = EnumMap[Key];
14517     if (Entry.isNull())
14518       continue;
14519 
14520     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
14521       // Ensure constants are different.
14522       if (D == ECD)
14523         continue;
14524 
14525       // Create new vector and push values onto it.
14526       ECDVector *Vec = new ECDVector();
14527       Vec->push_back(D);
14528       Vec->push_back(ECD);
14529 
14530       // Update entry to point to the duplicates vector.
14531       Entry = Vec;
14532 
14533       // Store the vector somewhere we can consult later for quick emission of
14534       // diagnostics.
14535       DupVector.push_back(Vec);
14536       continue;
14537     }
14538 
14539     ECDVector *Vec = Entry.get<ECDVector*>();
14540     // Make sure constants are not added more than once.
14541     if (*Vec->begin() == ECD)
14542       continue;
14543 
14544     Vec->push_back(ECD);
14545   }
14546 
14547   // Emit diagnostics.
14548   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
14549                                   DupVectorEnd = DupVector.end();
14550        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
14551     ECDVector *Vec = *DupVectorIter;
14552     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
14553 
14554     // Emit warning for one enum constant.
14555     ECDVector::iterator I = Vec->begin();
14556     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
14557       << (*I)->getName() << (*I)->getInitVal().toString(10)
14558       << (*I)->getSourceRange();
14559     ++I;
14560 
14561     // Emit one note for each of the remaining enum constants with
14562     // the same value.
14563     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
14564       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
14565         << (*I)->getName() << (*I)->getInitVal().toString(10)
14566         << (*I)->getSourceRange();
14567     delete Vec;
14568   }
14569 }
14570 
14571 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
14572                              bool AllowMask) const {
14573   assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
14574   assert(ED->isCompleteDefinition() && "expected enum definition");
14575 
14576   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
14577   llvm::APInt &FlagBits = R.first->second;
14578 
14579   if (R.second) {
14580     for (auto *E : ED->enumerators()) {
14581       const auto &EVal = E->getInitVal();
14582       // Only single-bit enumerators introduce new flag values.
14583       if (EVal.isPowerOf2())
14584         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
14585     }
14586   }
14587 
14588   // A value is in a flag enum if either its bits are a subset of the enum's
14589   // flag bits (the first condition) or we are allowing masks and the same is
14590   // true of its complement (the second condition). When masks are allowed, we
14591   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
14592   //
14593   // While it's true that any value could be used as a mask, the assumption is
14594   // that a mask will have all of the insignificant bits set. Anything else is
14595   // likely a logic error.
14596   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
14597   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
14598 }
14599 
14600 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
14601                          SourceLocation RBraceLoc, Decl *EnumDeclX,
14602                          ArrayRef<Decl *> Elements,
14603                          Scope *S, AttributeList *Attr) {
14604   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
14605   QualType EnumType = Context.getTypeDeclType(Enum);
14606 
14607   if (Attr)
14608     ProcessDeclAttributeList(S, Enum, Attr);
14609 
14610   if (Enum->isDependentType()) {
14611     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14612       EnumConstantDecl *ECD =
14613         cast_or_null<EnumConstantDecl>(Elements[i]);
14614       if (!ECD) continue;
14615 
14616       ECD->setType(EnumType);
14617     }
14618 
14619     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
14620     return;
14621   }
14622 
14623   // TODO: If the result value doesn't fit in an int, it must be a long or long
14624   // long value.  ISO C does not support this, but GCC does as an extension,
14625   // emit a warning.
14626   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14627   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
14628   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
14629 
14630   // Verify that all the values are okay, compute the size of the values, and
14631   // reverse the list.
14632   unsigned NumNegativeBits = 0;
14633   unsigned NumPositiveBits = 0;
14634 
14635   // Keep track of whether all elements have type int.
14636   bool AllElementsInt = true;
14637 
14638   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14639     EnumConstantDecl *ECD =
14640       cast_or_null<EnumConstantDecl>(Elements[i]);
14641     if (!ECD) continue;  // Already issued a diagnostic.
14642 
14643     const llvm::APSInt &InitVal = ECD->getInitVal();
14644 
14645     // Keep track of the size of positive and negative values.
14646     if (InitVal.isUnsigned() || InitVal.isNonNegative())
14647       NumPositiveBits = std::max(NumPositiveBits,
14648                                  (unsigned)InitVal.getActiveBits());
14649     else
14650       NumNegativeBits = std::max(NumNegativeBits,
14651                                  (unsigned)InitVal.getMinSignedBits());
14652 
14653     // Keep track of whether every enum element has type int (very commmon).
14654     if (AllElementsInt)
14655       AllElementsInt = ECD->getType() == Context.IntTy;
14656   }
14657 
14658   // Figure out the type that should be used for this enum.
14659   QualType BestType;
14660   unsigned BestWidth;
14661 
14662   // C++0x N3000 [conv.prom]p3:
14663   //   An rvalue of an unscoped enumeration type whose underlying
14664   //   type is not fixed can be converted to an rvalue of the first
14665   //   of the following types that can represent all the values of
14666   //   the enumeration: int, unsigned int, long int, unsigned long
14667   //   int, long long int, or unsigned long long int.
14668   // C99 6.4.4.3p2:
14669   //   An identifier declared as an enumeration constant has type int.
14670   // The C99 rule is modified by a gcc extension
14671   QualType BestPromotionType;
14672 
14673   bool Packed = Enum->hasAttr<PackedAttr>();
14674   // -fshort-enums is the equivalent to specifying the packed attribute on all
14675   // enum definitions.
14676   if (LangOpts.ShortEnums)
14677     Packed = true;
14678 
14679   if (Enum->isFixed()) {
14680     BestType = Enum->getIntegerType();
14681     if (BestType->isPromotableIntegerType())
14682       BestPromotionType = Context.getPromotedIntegerType(BestType);
14683     else
14684       BestPromotionType = BestType;
14685 
14686     BestWidth = Context.getIntWidth(BestType);
14687   }
14688   else if (NumNegativeBits) {
14689     // If there is a negative value, figure out the smallest integer type (of
14690     // int/long/longlong) that fits.
14691     // If it's packed, check also if it fits a char or a short.
14692     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
14693       BestType = Context.SignedCharTy;
14694       BestWidth = CharWidth;
14695     } else if (Packed && NumNegativeBits <= ShortWidth &&
14696                NumPositiveBits < ShortWidth) {
14697       BestType = Context.ShortTy;
14698       BestWidth = ShortWidth;
14699     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
14700       BestType = Context.IntTy;
14701       BestWidth = IntWidth;
14702     } else {
14703       BestWidth = Context.getTargetInfo().getLongWidth();
14704 
14705       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
14706         BestType = Context.LongTy;
14707       } else {
14708         BestWidth = Context.getTargetInfo().getLongLongWidth();
14709 
14710         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
14711           Diag(Enum->getLocation(), diag::ext_enum_too_large);
14712         BestType = Context.LongLongTy;
14713       }
14714     }
14715     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
14716   } else {
14717     // If there is no negative value, figure out the smallest type that fits
14718     // all of the enumerator values.
14719     // If it's packed, check also if it fits a char or a short.
14720     if (Packed && NumPositiveBits <= CharWidth) {
14721       BestType = Context.UnsignedCharTy;
14722       BestPromotionType = Context.IntTy;
14723       BestWidth = CharWidth;
14724     } else if (Packed && NumPositiveBits <= ShortWidth) {
14725       BestType = Context.UnsignedShortTy;
14726       BestPromotionType = Context.IntTy;
14727       BestWidth = ShortWidth;
14728     } else if (NumPositiveBits <= IntWidth) {
14729       BestType = Context.UnsignedIntTy;
14730       BestWidth = IntWidth;
14731       BestPromotionType
14732         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14733                            ? Context.UnsignedIntTy : Context.IntTy;
14734     } else if (NumPositiveBits <=
14735                (BestWidth = Context.getTargetInfo().getLongWidth())) {
14736       BestType = Context.UnsignedLongTy;
14737       BestPromotionType
14738         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14739                            ? Context.UnsignedLongTy : Context.LongTy;
14740     } else {
14741       BestWidth = Context.getTargetInfo().getLongLongWidth();
14742       assert(NumPositiveBits <= BestWidth &&
14743              "How could an initializer get larger than ULL?");
14744       BestType = Context.UnsignedLongLongTy;
14745       BestPromotionType
14746         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14747                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
14748     }
14749   }
14750 
14751   // Loop over all of the enumerator constants, changing their types to match
14752   // the type of the enum if needed.
14753   for (auto *D : Elements) {
14754     auto *ECD = cast_or_null<EnumConstantDecl>(D);
14755     if (!ECD) continue;  // Already issued a diagnostic.
14756 
14757     // Standard C says the enumerators have int type, but we allow, as an
14758     // extension, the enumerators to be larger than int size.  If each
14759     // enumerator value fits in an int, type it as an int, otherwise type it the
14760     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
14761     // that X has type 'int', not 'unsigned'.
14762 
14763     // Determine whether the value fits into an int.
14764     llvm::APSInt InitVal = ECD->getInitVal();
14765 
14766     // If it fits into an integer type, force it.  Otherwise force it to match
14767     // the enum decl type.
14768     QualType NewTy;
14769     unsigned NewWidth;
14770     bool NewSign;
14771     if (!getLangOpts().CPlusPlus &&
14772         !Enum->isFixed() &&
14773         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
14774       NewTy = Context.IntTy;
14775       NewWidth = IntWidth;
14776       NewSign = true;
14777     } else if (ECD->getType() == BestType) {
14778       // Already the right type!
14779       if (getLangOpts().CPlusPlus)
14780         // C++ [dcl.enum]p4: Following the closing brace of an
14781         // enum-specifier, each enumerator has the type of its
14782         // enumeration.
14783         ECD->setType(EnumType);
14784       continue;
14785     } else {
14786       NewTy = BestType;
14787       NewWidth = BestWidth;
14788       NewSign = BestType->isSignedIntegerOrEnumerationType();
14789     }
14790 
14791     // Adjust the APSInt value.
14792     InitVal = InitVal.extOrTrunc(NewWidth);
14793     InitVal.setIsSigned(NewSign);
14794     ECD->setInitVal(InitVal);
14795 
14796     // Adjust the Expr initializer and type.
14797     if (ECD->getInitExpr() &&
14798         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
14799       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
14800                                                 CK_IntegralCast,
14801                                                 ECD->getInitExpr(),
14802                                                 /*base paths*/ nullptr,
14803                                                 VK_RValue));
14804     if (getLangOpts().CPlusPlus)
14805       // C++ [dcl.enum]p4: Following the closing brace of an
14806       // enum-specifier, each enumerator has the type of its
14807       // enumeration.
14808       ECD->setType(EnumType);
14809     else
14810       ECD->setType(NewTy);
14811   }
14812 
14813   Enum->completeDefinition(BestType, BestPromotionType,
14814                            NumPositiveBits, NumNegativeBits);
14815 
14816   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
14817 
14818   if (Enum->hasAttr<FlagEnumAttr>()) {
14819     for (Decl *D : Elements) {
14820       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
14821       if (!ECD) continue;  // Already issued a diagnostic.
14822 
14823       llvm::APSInt InitVal = ECD->getInitVal();
14824       if (InitVal != 0 && !InitVal.isPowerOf2() &&
14825           !IsValueInFlagEnum(Enum, InitVal, true))
14826         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
14827           << ECD << Enum;
14828     }
14829   }
14830 
14831   // Now that the enum type is defined, ensure it's not been underaligned.
14832   if (Enum->hasAttrs())
14833     CheckAlignasUnderalignment(Enum);
14834 }
14835 
14836 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
14837                                   SourceLocation StartLoc,
14838                                   SourceLocation EndLoc) {
14839   StringLiteral *AsmString = cast<StringLiteral>(expr);
14840 
14841   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
14842                                                    AsmString, StartLoc,
14843                                                    EndLoc);
14844   CurContext->addDecl(New);
14845   return New;
14846 }
14847 
14848 static void checkModuleImportContext(Sema &S, Module *M,
14849                                      SourceLocation ImportLoc, DeclContext *DC,
14850                                      bool FromInclude = false) {
14851   SourceLocation ExternCLoc;
14852 
14853   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
14854     switch (LSD->getLanguage()) {
14855     case LinkageSpecDecl::lang_c:
14856       if (ExternCLoc.isInvalid())
14857         ExternCLoc = LSD->getLocStart();
14858       break;
14859     case LinkageSpecDecl::lang_cxx:
14860       break;
14861     }
14862     DC = LSD->getParent();
14863   }
14864 
14865   while (isa<LinkageSpecDecl>(DC))
14866     DC = DC->getParent();
14867 
14868   if (!isa<TranslationUnitDecl>(DC)) {
14869     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
14870                           ? diag::ext_module_import_not_at_top_level_noop
14871                           : diag::err_module_import_not_at_top_level_fatal)
14872         << M->getFullModuleName() << DC;
14873     S.Diag(cast<Decl>(DC)->getLocStart(),
14874            diag::note_module_import_not_at_top_level) << DC;
14875   } else if (!M->IsExternC && ExternCLoc.isValid()) {
14876     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
14877       << M->getFullModuleName();
14878     S.Diag(ExternCLoc, diag::note_module_import_in_extern_c);
14879   }
14880 }
14881 
14882 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) {
14883   return checkModuleImportContext(*this, M, ImportLoc, CurContext);
14884 }
14885 
14886 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
14887                                    SourceLocation ImportLoc,
14888                                    ModuleIdPath Path) {
14889   Module *Mod =
14890       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
14891                                    /*IsIncludeDirective=*/false);
14892   if (!Mod)
14893     return true;
14894 
14895   VisibleModules.setVisible(Mod, ImportLoc);
14896 
14897   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
14898 
14899   // FIXME: we should support importing a submodule within a different submodule
14900   // of the same top-level module. Until we do, make it an error rather than
14901   // silently ignoring the import.
14902   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
14903     Diag(ImportLoc, getLangOpts().CompilingModule
14904                         ? diag::err_module_self_import
14905                         : diag::err_module_import_in_implementation)
14906         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
14907 
14908   SmallVector<SourceLocation, 2> IdentifierLocs;
14909   Module *ModCheck = Mod;
14910   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
14911     // If we've run out of module parents, just drop the remaining identifiers.
14912     // We need the length to be consistent.
14913     if (!ModCheck)
14914       break;
14915     ModCheck = ModCheck->Parent;
14916 
14917     IdentifierLocs.push_back(Path[I].second);
14918   }
14919 
14920   ImportDecl *Import = ImportDecl::Create(Context,
14921                                           Context.getTranslationUnitDecl(),
14922                                           AtLoc.isValid()? AtLoc : ImportLoc,
14923                                           Mod, IdentifierLocs);
14924   Context.getTranslationUnitDecl()->addDecl(Import);
14925   return Import;
14926 }
14927 
14928 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
14929   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
14930 
14931   // Determine whether we're in the #include buffer for a module. The #includes
14932   // in that buffer do not qualify as module imports; they're just an
14933   // implementation detail of us building the module.
14934   //
14935   // FIXME: Should we even get ActOnModuleInclude calls for those?
14936   bool IsInModuleIncludes =
14937       TUKind == TU_Module &&
14938       getSourceManager().isWrittenInMainFile(DirectiveLoc);
14939 
14940   // Similarly, if we're in the implementation of a module, don't
14941   // synthesize an illegal module import. FIXME: Why not?
14942   bool ShouldAddImport =
14943       !IsInModuleIncludes &&
14944       (getLangOpts().CompilingModule ||
14945        getLangOpts().CurrentModule.empty() ||
14946        getLangOpts().CurrentModule != Mod->getTopLevelModuleName());
14947 
14948   // If this module import was due to an inclusion directive, create an
14949   // implicit import declaration to capture it in the AST.
14950   if (ShouldAddImport) {
14951     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
14952     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
14953                                                      DirectiveLoc, Mod,
14954                                                      DirectiveLoc);
14955     TU->addDecl(ImportD);
14956     Consumer.HandleImplicitImportDecl(ImportD);
14957   }
14958 
14959   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
14960   VisibleModules.setVisible(Mod, DirectiveLoc);
14961 }
14962 
14963 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
14964   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14965 
14966   if (getLangOpts().ModulesLocalVisibility)
14967     VisibleModulesStack.push_back(std::move(VisibleModules));
14968   VisibleModules.setVisible(Mod, DirectiveLoc);
14969 }
14970 
14971 void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) {
14972   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14973 
14974   if (getLangOpts().ModulesLocalVisibility) {
14975     VisibleModules = std::move(VisibleModulesStack.back());
14976     VisibleModulesStack.pop_back();
14977     VisibleModules.setVisible(Mod, DirectiveLoc);
14978     // Leaving a module hides namespace names, so our visible namespace cache
14979     // is now out of date.
14980     VisibleNamespaceCache.clear();
14981   }
14982 }
14983 
14984 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
14985                                                       Module *Mod) {
14986   // Bail if we're not allowed to implicitly import a module here.
14987   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
14988     return;
14989 
14990   // Create the implicit import declaration.
14991   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
14992   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
14993                                                    Loc, Mod, Loc);
14994   TU->addDecl(ImportD);
14995   Consumer.HandleImplicitImportDecl(ImportD);
14996 
14997   // Make the module visible.
14998   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
14999   VisibleModules.setVisible(Mod, Loc);
15000 }
15001 
15002 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
15003                                       IdentifierInfo* AliasName,
15004                                       SourceLocation PragmaLoc,
15005                                       SourceLocation NameLoc,
15006                                       SourceLocation AliasNameLoc) {
15007   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
15008                                          LookupOrdinaryName);
15009   AsmLabelAttr *Attr =
15010       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
15011 
15012   // If a declaration that:
15013   // 1) declares a function or a variable
15014   // 2) has external linkage
15015   // already exists, add a label attribute to it.
15016   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15017     if (isDeclExternC(PrevDecl))
15018       PrevDecl->addAttr(Attr);
15019     else
15020       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
15021           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
15022   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
15023   } else
15024     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
15025 }
15026 
15027 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
15028                              SourceLocation PragmaLoc,
15029                              SourceLocation NameLoc) {
15030   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
15031 
15032   if (PrevDecl) {
15033     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
15034   } else {
15035     (void)WeakUndeclaredIdentifiers.insert(
15036       std::pair<IdentifierInfo*,WeakInfo>
15037         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
15038   }
15039 }
15040 
15041 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
15042                                 IdentifierInfo* AliasName,
15043                                 SourceLocation PragmaLoc,
15044                                 SourceLocation NameLoc,
15045                                 SourceLocation AliasNameLoc) {
15046   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
15047                                     LookupOrdinaryName);
15048   WeakInfo W = WeakInfo(Name, NameLoc);
15049 
15050   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15051     if (!PrevDecl->hasAttr<AliasAttr>())
15052       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
15053         DeclApplyPragmaWeak(TUScope, ND, W);
15054   } else {
15055     (void)WeakUndeclaredIdentifiers.insert(
15056       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
15057   }
15058 }
15059 
15060 Decl *Sema::getObjCDeclContext() const {
15061   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
15062 }
15063 
15064 AvailabilityResult Sema::getCurContextAvailability() const {
15065   const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
15066   if (!D)
15067     return AR_Available;
15068 
15069   // If we are within an Objective-C method, we should consult
15070   // both the availability of the method as well as the
15071   // enclosing class.  If the class is (say) deprecated,
15072   // the entire method is considered deprecated from the
15073   // purpose of checking if the current context is deprecated.
15074   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
15075     AvailabilityResult R = MD->getAvailability();
15076     if (R != AR_Available)
15077       return R;
15078     D = MD->getClassInterface();
15079   }
15080   // If we are within an Objective-c @implementation, it
15081   // gets the same availability context as the @interface.
15082   else if (const ObjCImplementationDecl *ID =
15083             dyn_cast<ObjCImplementationDecl>(D)) {
15084     D = ID->getClassInterface();
15085   }
15086   // Recover from user error.
15087   return D ? D->getAvailability() : AR_Available;
15088 }
15089