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___float128:
112   case tok::kw_wchar_t:
113   case tok::kw_bool:
114   case tok::kw___underlying_type:
115   case tok::kw___auto_type:
116     return true;
117 
118   case tok::annot_typename:
119   case tok::kw_char16_t:
120   case tok::kw_char32_t:
121   case tok::kw_typeof:
122   case tok::annot_decltype:
123   case tok::kw_decltype:
124     return getLangOpts().CPlusPlus;
125 
126   default:
127     break;
128   }
129 
130   return false;
131 }
132 
133 namespace {
134 enum class UnqualifiedTypeNameLookupResult {
135   NotFound,
136   FoundNonType,
137   FoundType
138 };
139 } // end anonymous namespace
140 
141 /// \brief Tries to perform unqualified lookup of the type decls in bases for
142 /// dependent class.
143 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
144 /// type decl, \a FoundType if only type decls are found.
145 static UnqualifiedTypeNameLookupResult
146 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
147                                 SourceLocation NameLoc,
148                                 const CXXRecordDecl *RD) {
149   if (!RD->hasDefinition())
150     return UnqualifiedTypeNameLookupResult::NotFound;
151   // Look for type decls in base classes.
152   UnqualifiedTypeNameLookupResult FoundTypeDecl =
153       UnqualifiedTypeNameLookupResult::NotFound;
154   for (const auto &Base : RD->bases()) {
155     const CXXRecordDecl *BaseRD = nullptr;
156     if (auto *BaseTT = Base.getType()->getAs<TagType>())
157       BaseRD = BaseTT->getAsCXXRecordDecl();
158     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
159       // Look for type decls in dependent base classes that have known primary
160       // templates.
161       if (!TST || !TST->isDependentType())
162         continue;
163       auto *TD = TST->getTemplateName().getAsTemplateDecl();
164       if (!TD)
165         continue;
166       auto *BasePrimaryTemplate =
167           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
168       if (!BasePrimaryTemplate)
169         continue;
170       BaseRD = BasePrimaryTemplate;
171     }
172     if (BaseRD) {
173       for (NamedDecl *ND : BaseRD->lookup(&II)) {
174         if (!isa<TypeDecl>(ND))
175           return UnqualifiedTypeNameLookupResult::FoundNonType;
176         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
177       }
178       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
179         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
180         case UnqualifiedTypeNameLookupResult::FoundNonType:
181           return UnqualifiedTypeNameLookupResult::FoundNonType;
182         case UnqualifiedTypeNameLookupResult::FoundType:
183           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
184           break;
185         case UnqualifiedTypeNameLookupResult::NotFound:
186           break;
187         }
188       }
189     }
190   }
191 
192   return FoundTypeDecl;
193 }
194 
195 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
196                                                       const IdentifierInfo &II,
197                                                       SourceLocation NameLoc) {
198   // Lookup in the parent class template context, if any.
199   const CXXRecordDecl *RD = nullptr;
200   UnqualifiedTypeNameLookupResult FoundTypeDecl =
201       UnqualifiedTypeNameLookupResult::NotFound;
202   for (DeclContext *DC = S.CurContext;
203        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
204        DC = DC->getParent()) {
205     // Look for type decls in dependent base classes that have known primary
206     // templates.
207     RD = dyn_cast<CXXRecordDecl>(DC);
208     if (RD && RD->getDescribedClassTemplate())
209       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
210   }
211   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
212     return nullptr;
213 
214   // We found some types in dependent base classes.  Recover as if the user
215   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
216   // lookup during template instantiation.
217   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
218 
219   ASTContext &Context = S.Context;
220   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
221                                           cast<Type>(Context.getRecordType(RD)));
222   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
223 
224   CXXScopeSpec SS;
225   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
226 
227   TypeLocBuilder Builder;
228   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
229   DepTL.setNameLoc(NameLoc);
230   DepTL.setElaboratedKeywordLoc(SourceLocation());
231   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
232   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
233 }
234 
235 /// \brief If the identifier refers to a type name within this scope,
236 /// return the declaration of that type.
237 ///
238 /// This routine performs ordinary name lookup of the identifier II
239 /// within the given scope, with optional C++ scope specifier SS, to
240 /// determine whether the name refers to a type. If so, returns an
241 /// opaque pointer (actually a QualType) corresponding to that
242 /// type. Otherwise, returns NULL.
243 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
244                              Scope *S, CXXScopeSpec *SS,
245                              bool isClassName, bool HasTrailingDot,
246                              ParsedType ObjectTypePtr,
247                              bool IsCtorOrDtorName,
248                              bool WantNontrivialTypeSourceInfo,
249                              IdentifierInfo **CorrectedII) {
250   // Determine where we will perform name lookup.
251   DeclContext *LookupCtx = nullptr;
252   if (ObjectTypePtr) {
253     QualType ObjectType = ObjectTypePtr.get();
254     if (ObjectType->isRecordType())
255       LookupCtx = computeDeclContext(ObjectType);
256   } else if (SS && SS->isNotEmpty()) {
257     LookupCtx = computeDeclContext(*SS, false);
258 
259     if (!LookupCtx) {
260       if (isDependentScopeSpecifier(*SS)) {
261         // C++ [temp.res]p3:
262         //   A qualified-id that refers to a type and in which the
263         //   nested-name-specifier depends on a template-parameter (14.6.2)
264         //   shall be prefixed by the keyword typename to indicate that the
265         //   qualified-id denotes a type, forming an
266         //   elaborated-type-specifier (7.1.5.3).
267         //
268         // We therefore do not perform any name lookup if the result would
269         // refer to a member of an unknown specialization.
270         if (!isClassName && !IsCtorOrDtorName)
271           return nullptr;
272 
273         // We know from the grammar that this name refers to a type,
274         // so build a dependent node to describe the type.
275         if (WantNontrivialTypeSourceInfo)
276           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
277 
278         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
279         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
280                                        II, NameLoc);
281         return ParsedType::make(T);
282       }
283 
284       return nullptr;
285     }
286 
287     if (!LookupCtx->isDependentContext() &&
288         RequireCompleteDeclContext(*SS, LookupCtx))
289       return nullptr;
290   }
291 
292   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
293   // lookup for class-names.
294   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
295                                       LookupOrdinaryName;
296   LookupResult Result(*this, &II, NameLoc, Kind);
297   if (LookupCtx) {
298     // Perform "qualified" name lookup into the declaration context we
299     // computed, which is either the type of the base of a member access
300     // expression or the declaration context associated with a prior
301     // nested-name-specifier.
302     LookupQualifiedName(Result, LookupCtx);
303 
304     if (ObjectTypePtr && Result.empty()) {
305       // C++ [basic.lookup.classref]p3:
306       //   If the unqualified-id is ~type-name, the type-name is looked up
307       //   in the context of the entire postfix-expression. If the type T of
308       //   the object expression is of a class type C, the type-name is also
309       //   looked up in the scope of class C. At least one of the lookups shall
310       //   find a name that refers to (possibly cv-qualified) T.
311       LookupName(Result, S);
312     }
313   } else {
314     // Perform unqualified name lookup.
315     LookupName(Result, S);
316 
317     // For unqualified lookup in a class template in MSVC mode, look into
318     // dependent base classes where the primary class template is known.
319     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
320       if (ParsedType TypeInBase =
321               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
322         return TypeInBase;
323     }
324   }
325 
326   NamedDecl *IIDecl = nullptr;
327   switch (Result.getResultKind()) {
328   case LookupResult::NotFound:
329   case LookupResult::NotFoundInCurrentInstantiation:
330     if (CorrectedII) {
331       TypoCorrection Correction = CorrectTypo(
332           Result.getLookupNameInfo(), Kind, S, SS,
333           llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
334           CTK_ErrorRecovery);
335       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
336       TemplateTy Template;
337       bool MemberOfUnknownSpecialization;
338       UnqualifiedId TemplateName;
339       TemplateName.setIdentifier(NewII, NameLoc);
340       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
341       CXXScopeSpec NewSS, *NewSSPtr = SS;
342       if (SS && NNS) {
343         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
344         NewSSPtr = &NewSS;
345       }
346       if (Correction && (NNS || NewII != &II) &&
347           // Ignore a correction to a template type as the to-be-corrected
348           // identifier is not a template (typo correction for template names
349           // is handled elsewhere).
350           !(getLangOpts().CPlusPlus && NewSSPtr &&
351             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
352                            Template, MemberOfUnknownSpecialization))) {
353         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
354                                     isClassName, HasTrailingDot, ObjectTypePtr,
355                                     IsCtorOrDtorName,
356                                     WantNontrivialTypeSourceInfo);
357         if (Ty) {
358           diagnoseTypo(Correction,
359                        PDiag(diag::err_unknown_type_or_class_name_suggest)
360                          << Result.getLookupName() << isClassName);
361           if (SS && NNS)
362             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
363           *CorrectedII = NewII;
364           return Ty;
365         }
366       }
367     }
368     // If typo correction failed or was not performed, fall through
369   case LookupResult::FoundOverloaded:
370   case LookupResult::FoundUnresolvedValue:
371     Result.suppressDiagnostics();
372     return nullptr;
373 
374   case LookupResult::Ambiguous:
375     // Recover from type-hiding ambiguities by hiding the type.  We'll
376     // do the lookup again when looking for an object, and we can
377     // diagnose the error then.  If we don't do this, then the error
378     // about hiding the type will be immediately followed by an error
379     // that only makes sense if the identifier was treated like a type.
380     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
381       Result.suppressDiagnostics();
382       return nullptr;
383     }
384 
385     // Look to see if we have a type anywhere in the list of results.
386     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
387          Res != ResEnd; ++Res) {
388       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
389         if (!IIDecl ||
390             (*Res)->getLocation().getRawEncoding() <
391               IIDecl->getLocation().getRawEncoding())
392           IIDecl = *Res;
393       }
394     }
395 
396     if (!IIDecl) {
397       // None of the entities we found is a type, so there is no way
398       // to even assume that the result is a type. In this case, don't
399       // complain about the ambiguity. The parser will either try to
400       // perform this lookup again (e.g., as an object name), which
401       // will produce the ambiguity, or will complain that it expected
402       // a type name.
403       Result.suppressDiagnostics();
404       return nullptr;
405     }
406 
407     // We found a type within the ambiguous lookup; diagnose the
408     // ambiguity and then return that type. This might be the right
409     // answer, or it might not be, but it suppresses any attempt to
410     // perform the name lookup again.
411     break;
412 
413   case LookupResult::Found:
414     IIDecl = Result.getFoundDecl();
415     break;
416   }
417 
418   assert(IIDecl && "Didn't find decl");
419 
420   QualType T;
421   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
422     DiagnoseUseOfDecl(IIDecl, NameLoc);
423 
424     T = Context.getTypeDeclType(TD);
425     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
426 
427     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
428     // constructor or destructor name (in such a case, the scope specifier
429     // will be attached to the enclosing Expr or Decl node).
430     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
431       if (WantNontrivialTypeSourceInfo) {
432         // Construct a type with type-source information.
433         TypeLocBuilder Builder;
434         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
435 
436         T = getElaboratedType(ETK_None, *SS, T);
437         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
438         ElabTL.setElaboratedKeywordLoc(SourceLocation());
439         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
440         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
441       } else {
442         T = getElaboratedType(ETK_None, *SS, T);
443       }
444     }
445   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
446     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
447     if (!HasTrailingDot)
448       T = Context.getObjCInterfaceType(IDecl);
449   }
450 
451   if (T.isNull()) {
452     // If it's not plausibly a type, suppress diagnostics.
453     Result.suppressDiagnostics();
454     return nullptr;
455   }
456   return ParsedType::make(T);
457 }
458 
459 // Builds a fake NNS for the given decl context.
460 static NestedNameSpecifier *
461 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
462   for (;; DC = DC->getLookupParent()) {
463     DC = DC->getPrimaryContext();
464     auto *ND = dyn_cast<NamespaceDecl>(DC);
465     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
466       return NestedNameSpecifier::Create(Context, nullptr, ND);
467     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
468       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
469                                          RD->getTypeForDecl());
470     else if (isa<TranslationUnitDecl>(DC))
471       return NestedNameSpecifier::GlobalSpecifier(Context);
472   }
473   llvm_unreachable("something isn't in TU scope?");
474 }
475 
476 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
477                                                 SourceLocation NameLoc) {
478   // Accepting an undeclared identifier as a default argument for a template
479   // type parameter is a Microsoft extension.
480   Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
481 
482   // Build a fake DependentNameType that will perform lookup into CurContext at
483   // instantiation time.  The name specifier isn't dependent, so template
484   // instantiation won't transform it.  It will retry the lookup, however.
485   NestedNameSpecifier *NNS =
486       synthesizeCurrentNestedNameSpecifier(Context, CurContext);
487   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
488 
489   // Build type location information.  We synthesized the qualifier, so we have
490   // to build a fake NestedNameSpecifierLoc.
491   NestedNameSpecifierLocBuilder NNSLocBuilder;
492   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
493   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
494 
495   TypeLocBuilder Builder;
496   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
497   DepTL.setNameLoc(NameLoc);
498   DepTL.setElaboratedKeywordLoc(SourceLocation());
499   DepTL.setQualifierLoc(QualifierLoc);
500   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
501 }
502 
503 /// isTagName() - This method is called *for error recovery purposes only*
504 /// to determine if the specified name is a valid tag name ("struct foo").  If
505 /// so, this returns the TST for the tag corresponding to it (TST_enum,
506 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
507 /// cases in C where the user forgot to specify the tag.
508 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
509   // Do a tag name lookup in this scope.
510   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
511   LookupName(R, S, false);
512   R.suppressDiagnostics();
513   if (R.getResultKind() == LookupResult::Found)
514     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
515       switch (TD->getTagKind()) {
516       case TTK_Struct: return DeclSpec::TST_struct;
517       case TTK_Interface: return DeclSpec::TST_interface;
518       case TTK_Union:  return DeclSpec::TST_union;
519       case TTK_Class:  return DeclSpec::TST_class;
520       case TTK_Enum:   return DeclSpec::TST_enum;
521       }
522     }
523 
524   return DeclSpec::TST_unspecified;
525 }
526 
527 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
528 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
529 /// then downgrade the missing typename error to a warning.
530 /// This is needed for MSVC compatibility; Example:
531 /// @code
532 /// template<class T> class A {
533 /// public:
534 ///   typedef int TYPE;
535 /// };
536 /// template<class T> class B : public A<T> {
537 /// public:
538 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
539 /// };
540 /// @endcode
541 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
542   if (CurContext->isRecord()) {
543     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
544       return true;
545 
546     const Type *Ty = SS->getScopeRep()->getAsType();
547 
548     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
549     for (const auto &Base : RD->bases())
550       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
551         return true;
552     return S->isFunctionPrototypeScope();
553   }
554   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
555 }
556 
557 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
558                                    SourceLocation IILoc,
559                                    Scope *S,
560                                    CXXScopeSpec *SS,
561                                    ParsedType &SuggestedType,
562                                    bool AllowClassTemplates) {
563   // We don't have anything to suggest (yet).
564   SuggestedType = nullptr;
565 
566   // There may have been a typo in the name of the type. Look up typo
567   // results, in case we have something that we can suggest.
568   if (TypoCorrection Corrected =
569           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
570                       llvm::make_unique<TypeNameValidatorCCC>(
571                           false, false, AllowClassTemplates),
572                       CTK_ErrorRecovery)) {
573     if (Corrected.isKeyword()) {
574       // We corrected to a keyword.
575       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
576       II = Corrected.getCorrectionAsIdentifierInfo();
577     } else {
578       // We found a similarly-named type or interface; suggest that.
579       if (!SS || !SS->isSet()) {
580         diagnoseTypo(Corrected,
581                      PDiag(diag::err_unknown_typename_suggest) << II);
582       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
583         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
584         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
585                                 II->getName().equals(CorrectedStr);
586         diagnoseTypo(Corrected,
587                      PDiag(diag::err_unknown_nested_typename_suggest)
588                        << II << DC << DroppedSpecifier << SS->getRange());
589       } else {
590         llvm_unreachable("could not have corrected a typo here");
591       }
592 
593       CXXScopeSpec tmpSS;
594       if (Corrected.getCorrectionSpecifier())
595         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
596                           SourceRange(IILoc));
597       SuggestedType =
598           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
599                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
600                       /*IsCtorOrDtorName=*/false,
601                       /*NonTrivialTypeSourceInfo=*/true);
602     }
603     return;
604   }
605 
606   if (getLangOpts().CPlusPlus) {
607     // See if II is a class template that the user forgot to pass arguments to.
608     UnqualifiedId Name;
609     Name.setIdentifier(II, IILoc);
610     CXXScopeSpec EmptySS;
611     TemplateTy TemplateResult;
612     bool MemberOfUnknownSpecialization;
613     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
614                        Name, nullptr, true, TemplateResult,
615                        MemberOfUnknownSpecialization) == TNK_Type_template) {
616       TemplateName TplName = TemplateResult.get();
617       Diag(IILoc, diag::err_template_missing_args) << TplName;
618       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
619         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
620           << TplDecl->getTemplateParameters()->getSourceRange();
621       }
622       return;
623     }
624   }
625 
626   // FIXME: Should we move the logic that tries to recover from a missing tag
627   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
628 
629   if (!SS || (!SS->isSet() && !SS->isInvalid()))
630     Diag(IILoc, diag::err_unknown_typename) << II;
631   else if (DeclContext *DC = computeDeclContext(*SS, false))
632     Diag(IILoc, diag::err_typename_nested_not_found)
633       << II << DC << SS->getRange();
634   else if (isDependentScopeSpecifier(*SS)) {
635     unsigned DiagID = diag::err_typename_missing;
636     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
637       DiagID = diag::ext_typename_missing;
638 
639     Diag(SS->getRange().getBegin(), DiagID)
640       << SS->getScopeRep() << II->getName()
641       << SourceRange(SS->getRange().getBegin(), IILoc)
642       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
643     SuggestedType = ActOnTypenameType(S, SourceLocation(),
644                                       *SS, *II, IILoc).get();
645   } else {
646     assert(SS && SS->isInvalid() &&
647            "Invalid scope specifier has already been diagnosed");
648   }
649 }
650 
651 /// \brief Determine whether the given result set contains either a type name
652 /// or
653 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
654   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
655                        NextToken.is(tok::less);
656 
657   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
658     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
659       return true;
660 
661     if (CheckTemplate && isa<TemplateDecl>(*I))
662       return true;
663   }
664 
665   return false;
666 }
667 
668 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
669                                     Scope *S, CXXScopeSpec &SS,
670                                     IdentifierInfo *&Name,
671                                     SourceLocation NameLoc) {
672   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
673   SemaRef.LookupParsedName(R, S, &SS);
674   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
675     StringRef FixItTagName;
676     switch (Tag->getTagKind()) {
677       case TTK_Class:
678         FixItTagName = "class ";
679         break;
680 
681       case TTK_Enum:
682         FixItTagName = "enum ";
683         break;
684 
685       case TTK_Struct:
686         FixItTagName = "struct ";
687         break;
688 
689       case TTK_Interface:
690         FixItTagName = "__interface ";
691         break;
692 
693       case TTK_Union:
694         FixItTagName = "union ";
695         break;
696     }
697 
698     StringRef TagName = FixItTagName.drop_back();
699     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
700       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
701       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
702 
703     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
704          I != IEnd; ++I)
705       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
706         << Name << TagName;
707 
708     // Replace lookup results with just the tag decl.
709     Result.clear(Sema::LookupTagName);
710     SemaRef.LookupParsedName(Result, S, &SS);
711     return true;
712   }
713 
714   return false;
715 }
716 
717 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
718 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
719                                   QualType T, SourceLocation NameLoc) {
720   ASTContext &Context = S.Context;
721 
722   TypeLocBuilder Builder;
723   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
724 
725   T = S.getElaboratedType(ETK_None, SS, T);
726   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
727   ElabTL.setElaboratedKeywordLoc(SourceLocation());
728   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
729   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
730 }
731 
732 Sema::NameClassification
733 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
734                    SourceLocation NameLoc, const Token &NextToken,
735                    bool IsAddressOfOperand,
736                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
737   DeclarationNameInfo NameInfo(Name, NameLoc);
738   ObjCMethodDecl *CurMethod = getCurMethodDecl();
739 
740   if (NextToken.is(tok::coloncolon)) {
741     BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
742                                 QualType(), false, SS, nullptr, false);
743   }
744 
745   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
746   LookupParsedName(Result, S, &SS, !CurMethod);
747 
748   // For unqualified lookup in a class template in MSVC mode, look into
749   // dependent base classes where the primary class template is known.
750   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
751     if (ParsedType TypeInBase =
752             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
753       return TypeInBase;
754   }
755 
756   // Perform lookup for Objective-C instance variables (including automatically
757   // synthesized instance variables), if we're in an Objective-C method.
758   // FIXME: This lookup really, really needs to be folded in to the normal
759   // unqualified lookup mechanism.
760   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
761     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
762     if (E.get() || E.isInvalid())
763       return E;
764   }
765 
766   bool SecondTry = false;
767   bool IsFilteredTemplateName = false;
768 
769 Corrected:
770   switch (Result.getResultKind()) {
771   case LookupResult::NotFound:
772     // If an unqualified-id is followed by a '(', then we have a function
773     // call.
774     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
775       // In C++, this is an ADL-only call.
776       // FIXME: Reference?
777       if (getLangOpts().CPlusPlus)
778         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
779 
780       // C90 6.3.2.2:
781       //   If the expression that precedes the parenthesized argument list in a
782       //   function call consists solely of an identifier, and if no
783       //   declaration is visible for this identifier, the identifier is
784       //   implicitly declared exactly as if, in the innermost block containing
785       //   the function call, the declaration
786       //
787       //     extern int identifier ();
788       //
789       //   appeared.
790       //
791       // We also allow this in C99 as an extension.
792       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
793         Result.addDecl(D);
794         Result.resolveKind();
795         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
796       }
797     }
798 
799     // In C, we first see whether there is a tag type by the same name, in
800     // which case it's likely that the user just forgot to write "enum",
801     // "struct", or "union".
802     if (!getLangOpts().CPlusPlus && !SecondTry &&
803         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
804       break;
805     }
806 
807     // Perform typo correction to determine if there is another name that is
808     // close to this name.
809     if (!SecondTry && CCC) {
810       SecondTry = true;
811       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
812                                                  Result.getLookupKind(), S,
813                                                  &SS, std::move(CCC),
814                                                  CTK_ErrorRecovery)) {
815         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
816         unsigned QualifiedDiag = diag::err_no_member_suggest;
817 
818         NamedDecl *FirstDecl = Corrected.getFoundDecl();
819         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
820         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
821             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
822           UnqualifiedDiag = diag::err_no_template_suggest;
823           QualifiedDiag = diag::err_no_member_template_suggest;
824         } else if (UnderlyingFirstDecl &&
825                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
826                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
827                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
828           UnqualifiedDiag = diag::err_unknown_typename_suggest;
829           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
830         }
831 
832         if (SS.isEmpty()) {
833           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
834         } else {// FIXME: is this even reachable? Test it.
835           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
836           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
837                                   Name->getName().equals(CorrectedStr);
838           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
839                                     << Name << computeDeclContext(SS, false)
840                                     << DroppedSpecifier << SS.getRange());
841         }
842 
843         // Update the name, so that the caller has the new name.
844         Name = Corrected.getCorrectionAsIdentifierInfo();
845 
846         // Typo correction corrected to a keyword.
847         if (Corrected.isKeyword())
848           return Name;
849 
850         // Also update the LookupResult...
851         // FIXME: This should probably go away at some point
852         Result.clear();
853         Result.setLookupName(Corrected.getCorrection());
854         if (FirstDecl)
855           Result.addDecl(FirstDecl);
856 
857         // If we found an Objective-C instance variable, let
858         // LookupInObjCMethod build the appropriate expression to
859         // reference the ivar.
860         // FIXME: This is a gross hack.
861         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
862           Result.clear();
863           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
864           return E;
865         }
866 
867         goto Corrected;
868       }
869     }
870 
871     // We failed to correct; just fall through and let the parser deal with it.
872     Result.suppressDiagnostics();
873     return NameClassification::Unknown();
874 
875   case LookupResult::NotFoundInCurrentInstantiation: {
876     // We performed name lookup into the current instantiation, and there were
877     // dependent bases, so we treat this result the same way as any other
878     // dependent nested-name-specifier.
879 
880     // C++ [temp.res]p2:
881     //   A name used in a template declaration or definition and that is
882     //   dependent on a template-parameter is assumed not to name a type
883     //   unless the applicable name lookup finds a type name or the name is
884     //   qualified by the keyword typename.
885     //
886     // FIXME: If the next token is '<', we might want to ask the parser to
887     // perform some heroics to see if we actually have a
888     // template-argument-list, which would indicate a missing 'template'
889     // keyword here.
890     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
891                                       NameInfo, IsAddressOfOperand,
892                                       /*TemplateArgs=*/nullptr);
893   }
894 
895   case LookupResult::Found:
896   case LookupResult::FoundOverloaded:
897   case LookupResult::FoundUnresolvedValue:
898     break;
899 
900   case LookupResult::Ambiguous:
901     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
902         hasAnyAcceptableTemplateNames(Result)) {
903       // C++ [temp.local]p3:
904       //   A lookup that finds an injected-class-name (10.2) can result in an
905       //   ambiguity in certain cases (for example, if it is found in more than
906       //   one base class). If all of the injected-class-names that are found
907       //   refer to specializations of the same class template, and if the name
908       //   is followed by a template-argument-list, the reference refers to the
909       //   class template itself and not a specialization thereof, and is not
910       //   ambiguous.
911       //
912       // This filtering can make an ambiguous result into an unambiguous one,
913       // so try again after filtering out template names.
914       FilterAcceptableTemplateNames(Result);
915       if (!Result.isAmbiguous()) {
916         IsFilteredTemplateName = true;
917         break;
918       }
919     }
920 
921     // Diagnose the ambiguity and return an error.
922     return NameClassification::Error();
923   }
924 
925   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
926       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
927     // C++ [temp.names]p3:
928     //   After name lookup (3.4) finds that a name is a template-name or that
929     //   an operator-function-id or a literal- operator-id refers to a set of
930     //   overloaded functions any member of which is a function template if
931     //   this is followed by a <, the < is always taken as the delimiter of a
932     //   template-argument-list and never as the less-than operator.
933     if (!IsFilteredTemplateName)
934       FilterAcceptableTemplateNames(Result);
935 
936     if (!Result.empty()) {
937       bool IsFunctionTemplate;
938       bool IsVarTemplate;
939       TemplateName Template;
940       if (Result.end() - Result.begin() > 1) {
941         IsFunctionTemplate = true;
942         Template = Context.getOverloadedTemplateName(Result.begin(),
943                                                      Result.end());
944       } else {
945         TemplateDecl *TD
946           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
947         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
948         IsVarTemplate = isa<VarTemplateDecl>(TD);
949 
950         if (SS.isSet() && !SS.isInvalid())
951           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
952                                                     /*TemplateKeyword=*/false,
953                                                       TD);
954         else
955           Template = TemplateName(TD);
956       }
957 
958       if (IsFunctionTemplate) {
959         // Function templates always go through overload resolution, at which
960         // point we'll perform the various checks (e.g., accessibility) we need
961         // to based on which function we selected.
962         Result.suppressDiagnostics();
963 
964         return NameClassification::FunctionTemplate(Template);
965       }
966 
967       return IsVarTemplate ? NameClassification::VarTemplate(Template)
968                            : NameClassification::TypeTemplate(Template);
969     }
970   }
971 
972   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
973   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
974     DiagnoseUseOfDecl(Type, NameLoc);
975     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
976     QualType T = Context.getTypeDeclType(Type);
977     if (SS.isNotEmpty())
978       return buildNestedType(*this, SS, T, NameLoc);
979     return ParsedType::make(T);
980   }
981 
982   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
983   if (!Class) {
984     // FIXME: It's unfortunate that we don't have a Type node for handling this.
985     if (ObjCCompatibleAliasDecl *Alias =
986             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
987       Class = Alias->getClassInterface();
988   }
989 
990   if (Class) {
991     DiagnoseUseOfDecl(Class, NameLoc);
992 
993     if (NextToken.is(tok::period)) {
994       // Interface. <something> is parsed as a property reference expression.
995       // Just return "unknown" as a fall-through for now.
996       Result.suppressDiagnostics();
997       return NameClassification::Unknown();
998     }
999 
1000     QualType T = Context.getObjCInterfaceType(Class);
1001     return ParsedType::make(T);
1002   }
1003 
1004   // We can have a type template here if we're classifying a template argument.
1005   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
1006     return NameClassification::TypeTemplate(
1007         TemplateName(cast<TemplateDecl>(FirstDecl)));
1008 
1009   // Check for a tag type hidden by a non-type decl in a few cases where it
1010   // seems likely a type is wanted instead of the non-type that was found.
1011   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1012   if ((NextToken.is(tok::identifier) ||
1013        (NextIsOp &&
1014         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1015       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1016     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1017     DiagnoseUseOfDecl(Type, NameLoc);
1018     QualType T = Context.getTypeDeclType(Type);
1019     if (SS.isNotEmpty())
1020       return buildNestedType(*this, SS, T, NameLoc);
1021     return ParsedType::make(T);
1022   }
1023 
1024   if (FirstDecl->isCXXClassMember())
1025     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1026                                            nullptr, S);
1027 
1028   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1029   return BuildDeclarationNameExpr(SS, Result, ADL);
1030 }
1031 
1032 // Determines the context to return to after temporarily entering a
1033 // context.  This depends in an unnecessarily complicated way on the
1034 // exact ordering of callbacks from the parser.
1035 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1036 
1037   // Functions defined inline within classes aren't parsed until we've
1038   // finished parsing the top-level class, so the top-level class is
1039   // the context we'll need to return to.
1040   // A Lambda call operator whose parent is a class must not be treated
1041   // as an inline member function.  A Lambda can be used legally
1042   // either as an in-class member initializer or a default argument.  These
1043   // are parsed once the class has been marked complete and so the containing
1044   // context would be the nested class (when the lambda is defined in one);
1045   // If the class is not complete, then the lambda is being used in an
1046   // ill-formed fashion (such as to specify the width of a bit-field, or
1047   // in an array-bound) - in which case we still want to return the
1048   // lexically containing DC (which could be a nested class).
1049   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1050     DC = DC->getLexicalParent();
1051 
1052     // A function not defined within a class will always return to its
1053     // lexical context.
1054     if (!isa<CXXRecordDecl>(DC))
1055       return DC;
1056 
1057     // A C++ inline method/friend is parsed *after* the topmost class
1058     // it was declared in is fully parsed ("complete");  the topmost
1059     // class is the context we need to return to.
1060     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1061       DC = RD;
1062 
1063     // Return the declaration context of the topmost class the inline method is
1064     // declared in.
1065     return DC;
1066   }
1067 
1068   return DC->getLexicalParent();
1069 }
1070 
1071 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1072   assert(getContainingDC(DC) == CurContext &&
1073       "The next DeclContext should be lexically contained in the current one.");
1074   CurContext = DC;
1075   S->setEntity(DC);
1076 }
1077 
1078 void Sema::PopDeclContext() {
1079   assert(CurContext && "DeclContext imbalance!");
1080 
1081   CurContext = getContainingDC(CurContext);
1082   assert(CurContext && "Popped translation unit!");
1083 }
1084 
1085 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1086                                                                     Decl *D) {
1087   // Unlike PushDeclContext, the context to which we return is not necessarily
1088   // the containing DC of TD, because the new context will be some pre-existing
1089   // TagDecl definition instead of a fresh one.
1090   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1091   CurContext = cast<TagDecl>(D)->getDefinition();
1092   assert(CurContext && "skipping definition of undefined tag");
1093   // Start lookups from the parent of the current context; we don't want to look
1094   // into the pre-existing complete definition.
1095   S->setEntity(CurContext->getLookupParent());
1096   return Result;
1097 }
1098 
1099 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1100   CurContext = static_cast<decltype(CurContext)>(Context);
1101 }
1102 
1103 /// EnterDeclaratorContext - Used when we must lookup names in the context
1104 /// of a declarator's nested name specifier.
1105 ///
1106 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1107   // C++0x [basic.lookup.unqual]p13:
1108   //   A name used in the definition of a static data member of class
1109   //   X (after the qualified-id of the static member) is looked up as
1110   //   if the name was used in a member function of X.
1111   // C++0x [basic.lookup.unqual]p14:
1112   //   If a variable member of a namespace is defined outside of the
1113   //   scope of its namespace then any name used in the definition of
1114   //   the variable member (after the declarator-id) is looked up as
1115   //   if the definition of the variable member occurred in its
1116   //   namespace.
1117   // Both of these imply that we should push a scope whose context
1118   // is the semantic context of the declaration.  We can't use
1119   // PushDeclContext here because that context is not necessarily
1120   // lexically contained in the current context.  Fortunately,
1121   // the containing scope should have the appropriate information.
1122 
1123   assert(!S->getEntity() && "scope already has entity");
1124 
1125 #ifndef NDEBUG
1126   Scope *Ancestor = S->getParent();
1127   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1128   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1129 #endif
1130 
1131   CurContext = DC;
1132   S->setEntity(DC);
1133 }
1134 
1135 void Sema::ExitDeclaratorContext(Scope *S) {
1136   assert(S->getEntity() == CurContext && "Context imbalance!");
1137 
1138   // Switch back to the lexical context.  The safety of this is
1139   // enforced by an assert in EnterDeclaratorContext.
1140   Scope *Ancestor = S->getParent();
1141   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1142   CurContext = Ancestor->getEntity();
1143 
1144   // We don't need to do anything with the scope, which is going to
1145   // disappear.
1146 }
1147 
1148 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1149   // We assume that the caller has already called
1150   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1151   FunctionDecl *FD = D->getAsFunction();
1152   if (!FD)
1153     return;
1154 
1155   // Same implementation as PushDeclContext, but enters the context
1156   // from the lexical parent, rather than the top-level class.
1157   assert(CurContext == FD->getLexicalParent() &&
1158     "The next DeclContext should be lexically contained in the current one.");
1159   CurContext = FD;
1160   S->setEntity(CurContext);
1161 
1162   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1163     ParmVarDecl *Param = FD->getParamDecl(P);
1164     // If the parameter has an identifier, then add it to the scope
1165     if (Param->getIdentifier()) {
1166       S->AddDecl(Param);
1167       IdResolver.AddDecl(Param);
1168     }
1169   }
1170 }
1171 
1172 void Sema::ActOnExitFunctionContext() {
1173   // Same implementation as PopDeclContext, but returns to the lexical parent,
1174   // rather than the top-level class.
1175   assert(CurContext && "DeclContext imbalance!");
1176   CurContext = CurContext->getLexicalParent();
1177   assert(CurContext && "Popped translation unit!");
1178 }
1179 
1180 /// \brief Determine whether we allow overloading of the function
1181 /// PrevDecl with another declaration.
1182 ///
1183 /// This routine determines whether overloading is possible, not
1184 /// whether some new function is actually an overload. It will return
1185 /// true in C++ (where we can always provide overloads) or, as an
1186 /// extension, in C when the previous function is already an
1187 /// overloaded function declaration or has the "overloadable"
1188 /// attribute.
1189 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1190                                        ASTContext &Context) {
1191   if (Context.getLangOpts().CPlusPlus)
1192     return true;
1193 
1194   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1195     return true;
1196 
1197   return (Previous.getResultKind() == LookupResult::Found
1198           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1199 }
1200 
1201 /// Add this decl to the scope shadowed decl chains.
1202 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1203   // Move up the scope chain until we find the nearest enclosing
1204   // non-transparent context. The declaration will be introduced into this
1205   // scope.
1206   while (S->getEntity() && S->getEntity()->isTransparentContext())
1207     S = S->getParent();
1208 
1209   // Add scoped declarations into their context, so that they can be
1210   // found later. Declarations without a context won't be inserted
1211   // into any context.
1212   if (AddToContext)
1213     CurContext->addDecl(D);
1214 
1215   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1216   // are function-local declarations.
1217   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1218       !D->getDeclContext()->getRedeclContext()->Equals(
1219         D->getLexicalDeclContext()->getRedeclContext()) &&
1220       !D->getLexicalDeclContext()->isFunctionOrMethod())
1221     return;
1222 
1223   // Template instantiations should also not be pushed into scope.
1224   if (isa<FunctionDecl>(D) &&
1225       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1226     return;
1227 
1228   // If this replaces anything in the current scope,
1229   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1230                                IEnd = IdResolver.end();
1231   for (; I != IEnd; ++I) {
1232     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1233       S->RemoveDecl(*I);
1234       IdResolver.RemoveDecl(*I);
1235 
1236       // Should only need to replace one decl.
1237       break;
1238     }
1239   }
1240 
1241   S->AddDecl(D);
1242 
1243   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1244     // Implicitly-generated labels may end up getting generated in an order that
1245     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1246     // the label at the appropriate place in the identifier chain.
1247     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1248       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1249       if (IDC == CurContext) {
1250         if (!S->isDeclScope(*I))
1251           continue;
1252       } else if (IDC->Encloses(CurContext))
1253         break;
1254     }
1255 
1256     IdResolver.InsertDeclAfter(I, D);
1257   } else {
1258     IdResolver.AddDecl(D);
1259   }
1260 }
1261 
1262 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1263   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1264     TUScope->AddDecl(D);
1265 }
1266 
1267 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1268                          bool AllowInlineNamespace) {
1269   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1270 }
1271 
1272 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1273   DeclContext *TargetDC = DC->getPrimaryContext();
1274   do {
1275     if (DeclContext *ScopeDC = S->getEntity())
1276       if (ScopeDC->getPrimaryContext() == TargetDC)
1277         return S;
1278   } while ((S = S->getParent()));
1279 
1280   return nullptr;
1281 }
1282 
1283 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1284                                             DeclContext*,
1285                                             ASTContext&);
1286 
1287 /// Filters out lookup results that don't fall within the given scope
1288 /// as determined by isDeclInScope.
1289 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1290                                 bool ConsiderLinkage,
1291                                 bool AllowInlineNamespace) {
1292   LookupResult::Filter F = R.makeFilter();
1293   while (F.hasNext()) {
1294     NamedDecl *D = F.next();
1295 
1296     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1297       continue;
1298 
1299     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1300       continue;
1301 
1302     F.erase();
1303   }
1304 
1305   F.done();
1306 }
1307 
1308 static bool isUsingDecl(NamedDecl *D) {
1309   return isa<UsingShadowDecl>(D) ||
1310          isa<UnresolvedUsingTypenameDecl>(D) ||
1311          isa<UnresolvedUsingValueDecl>(D);
1312 }
1313 
1314 /// Removes using shadow declarations from the lookup results.
1315 static void RemoveUsingDecls(LookupResult &R) {
1316   LookupResult::Filter F = R.makeFilter();
1317   while (F.hasNext())
1318     if (isUsingDecl(F.next()))
1319       F.erase();
1320 
1321   F.done();
1322 }
1323 
1324 /// \brief Check for this common pattern:
1325 /// @code
1326 /// class S {
1327 ///   S(const S&); // DO NOT IMPLEMENT
1328 ///   void operator=(const S&); // DO NOT IMPLEMENT
1329 /// };
1330 /// @endcode
1331 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1332   // FIXME: Should check for private access too but access is set after we get
1333   // the decl here.
1334   if (D->doesThisDeclarationHaveABody())
1335     return false;
1336 
1337   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1338     return CD->isCopyConstructor();
1339   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1340     return Method->isCopyAssignmentOperator();
1341   return false;
1342 }
1343 
1344 // We need this to handle
1345 //
1346 // typedef struct {
1347 //   void *foo() { return 0; }
1348 // } A;
1349 //
1350 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1351 // for example. If 'A', foo will have external linkage. If we have '*A',
1352 // foo will have no linkage. Since we can't know until we get to the end
1353 // of the typedef, this function finds out if D might have non-external linkage.
1354 // Callers should verify at the end of the TU if it D has external linkage or
1355 // not.
1356 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1357   const DeclContext *DC = D->getDeclContext();
1358   while (!DC->isTranslationUnit()) {
1359     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1360       if (!RD->hasNameForLinkage())
1361         return true;
1362     }
1363     DC = DC->getParent();
1364   }
1365 
1366   return !D->isExternallyVisible();
1367 }
1368 
1369 // FIXME: This needs to be refactored; some other isInMainFile users want
1370 // these semantics.
1371 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1372   if (S.TUKind != TU_Complete)
1373     return false;
1374   return S.SourceMgr.isInMainFile(Loc);
1375 }
1376 
1377 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1378   assert(D);
1379 
1380   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1381     return false;
1382 
1383   // Ignore all entities declared within templates, and out-of-line definitions
1384   // of members of class templates.
1385   if (D->getDeclContext()->isDependentContext() ||
1386       D->getLexicalDeclContext()->isDependentContext())
1387     return false;
1388 
1389   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1390     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1391       return false;
1392 
1393     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1394       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1395         return false;
1396     } else {
1397       // 'static inline' functions are defined in headers; don't warn.
1398       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1399         return false;
1400     }
1401 
1402     if (FD->doesThisDeclarationHaveABody() &&
1403         Context.DeclMustBeEmitted(FD))
1404       return false;
1405   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1406     // Constants and utility variables are defined in headers with internal
1407     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1408     // like "inline".)
1409     if (!isMainFileLoc(*this, VD->getLocation()))
1410       return false;
1411 
1412     if (Context.DeclMustBeEmitted(VD))
1413       return false;
1414 
1415     if (VD->isStaticDataMember() &&
1416         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1417       return false;
1418   } else {
1419     return false;
1420   }
1421 
1422   // Only warn for unused decls internal to the translation unit.
1423   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1424   // for inline functions defined in the main source file, for instance.
1425   return mightHaveNonExternalLinkage(D);
1426 }
1427 
1428 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1429   if (!D)
1430     return;
1431 
1432   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1433     const FunctionDecl *First = FD->getFirstDecl();
1434     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1435       return; // First should already be in the vector.
1436   }
1437 
1438   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1439     const VarDecl *First = VD->getFirstDecl();
1440     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1441       return; // First should already be in the vector.
1442   }
1443 
1444   if (ShouldWarnIfUnusedFileScopedDecl(D))
1445     UnusedFileScopedDecls.push_back(D);
1446 }
1447 
1448 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1449   if (D->isInvalidDecl())
1450     return false;
1451 
1452   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1453       D->hasAttr<ObjCPreciseLifetimeAttr>())
1454     return false;
1455 
1456   if (isa<LabelDecl>(D))
1457     return true;
1458 
1459   // Except for labels, we only care about unused decls that are local to
1460   // functions.
1461   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1462   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1463     // For dependent types, the diagnostic is deferred.
1464     WithinFunction =
1465         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1466   if (!WithinFunction)
1467     return false;
1468 
1469   if (isa<TypedefNameDecl>(D))
1470     return true;
1471 
1472   // White-list anything that isn't a local variable.
1473   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1474     return false;
1475 
1476   // Types of valid local variables should be complete, so this should succeed.
1477   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1478 
1479     // White-list anything with an __attribute__((unused)) type.
1480     QualType Ty = VD->getType();
1481 
1482     // Only look at the outermost level of typedef.
1483     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1484       if (TT->getDecl()->hasAttr<UnusedAttr>())
1485         return false;
1486     }
1487 
1488     // If we failed to complete the type for some reason, or if the type is
1489     // dependent, don't diagnose the variable.
1490     if (Ty->isIncompleteType() || Ty->isDependentType())
1491       return false;
1492 
1493     if (const TagType *TT = Ty->getAs<TagType>()) {
1494       const TagDecl *Tag = TT->getDecl();
1495       if (Tag->hasAttr<UnusedAttr>())
1496         return false;
1497 
1498       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1499         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1500           return false;
1501 
1502         if (const Expr *Init = VD->getInit()) {
1503           if (const ExprWithCleanups *Cleanups =
1504                   dyn_cast<ExprWithCleanups>(Init))
1505             Init = Cleanups->getSubExpr();
1506           const CXXConstructExpr *Construct =
1507             dyn_cast<CXXConstructExpr>(Init);
1508           if (Construct && !Construct->isElidable()) {
1509             CXXConstructorDecl *CD = Construct->getConstructor();
1510             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1511               return false;
1512           }
1513         }
1514       }
1515     }
1516 
1517     // TODO: __attribute__((unused)) templates?
1518   }
1519 
1520   return true;
1521 }
1522 
1523 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1524                                      FixItHint &Hint) {
1525   if (isa<LabelDecl>(D)) {
1526     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1527                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1528     if (AfterColon.isInvalid())
1529       return;
1530     Hint = FixItHint::CreateRemoval(CharSourceRange::
1531                                     getCharRange(D->getLocStart(), AfterColon));
1532   }
1533 }
1534 
1535 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1536   if (D->getTypeForDecl()->isDependentType())
1537     return;
1538 
1539   for (auto *TmpD : D->decls()) {
1540     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1541       DiagnoseUnusedDecl(T);
1542     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1543       DiagnoseUnusedNestedTypedefs(R);
1544   }
1545 }
1546 
1547 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1548 /// unless they are marked attr(unused).
1549 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1550   if (!ShouldDiagnoseUnusedDecl(D))
1551     return;
1552 
1553   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1554     // typedefs can be referenced later on, so the diagnostics are emitted
1555     // at end-of-translation-unit.
1556     UnusedLocalTypedefNameCandidates.insert(TD);
1557     return;
1558   }
1559 
1560   FixItHint Hint;
1561   GenerateFixForUnusedDecl(D, Context, Hint);
1562 
1563   unsigned DiagID;
1564   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1565     DiagID = diag::warn_unused_exception_param;
1566   else if (isa<LabelDecl>(D))
1567     DiagID = diag::warn_unused_label;
1568   else
1569     DiagID = diag::warn_unused_variable;
1570 
1571   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1572 }
1573 
1574 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1575   // Verify that we have no forward references left.  If so, there was a goto
1576   // or address of a label taken, but no definition of it.  Label fwd
1577   // definitions are indicated with a null substmt which is also not a resolved
1578   // MS inline assembly label name.
1579   bool Diagnose = false;
1580   if (L->isMSAsmLabel())
1581     Diagnose = !L->isResolvedMSAsmLabel();
1582   else
1583     Diagnose = L->getStmt() == nullptr;
1584   if (Diagnose)
1585     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1586 }
1587 
1588 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1589   S->mergeNRVOIntoParent();
1590 
1591   if (S->decl_empty()) return;
1592   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1593          "Scope shouldn't contain decls!");
1594 
1595   for (auto *TmpD : S->decls()) {
1596     assert(TmpD && "This decl didn't get pushed??");
1597 
1598     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1599     NamedDecl *D = cast<NamedDecl>(TmpD);
1600 
1601     if (!D->getDeclName()) continue;
1602 
1603     // Diagnose unused variables in this scope.
1604     if (!S->hasUnrecoverableErrorOccurred()) {
1605       DiagnoseUnusedDecl(D);
1606       if (const auto *RD = dyn_cast<RecordDecl>(D))
1607         DiagnoseUnusedNestedTypedefs(RD);
1608     }
1609 
1610     // If this was a forward reference to a label, verify it was defined.
1611     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1612       CheckPoppedLabel(LD, *this);
1613 
1614     // Remove this name from our lexical scope, and warn on it if we haven't
1615     // already.
1616     IdResolver.RemoveDecl(D);
1617     auto ShadowI = ShadowingDecls.find(D);
1618     if (ShadowI != ShadowingDecls.end()) {
1619       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1620         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1621             << D << FD << FD->getParent();
1622         Diag(FD->getLocation(), diag::note_previous_declaration);
1623       }
1624       ShadowingDecls.erase(ShadowI);
1625     }
1626   }
1627 }
1628 
1629 /// \brief Look for an Objective-C class in the translation unit.
1630 ///
1631 /// \param Id The name of the Objective-C class we're looking for. If
1632 /// typo-correction fixes this name, the Id will be updated
1633 /// to the fixed name.
1634 ///
1635 /// \param IdLoc The location of the name in the translation unit.
1636 ///
1637 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1638 /// if there is no class with the given name.
1639 ///
1640 /// \returns The declaration of the named Objective-C class, or NULL if the
1641 /// class could not be found.
1642 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1643                                               SourceLocation IdLoc,
1644                                               bool DoTypoCorrection) {
1645   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1646   // creation from this context.
1647   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1648 
1649   if (!IDecl && DoTypoCorrection) {
1650     // Perform typo correction at the given location, but only if we
1651     // find an Objective-C class name.
1652     if (TypoCorrection C = CorrectTypo(
1653             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1654             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1655             CTK_ErrorRecovery)) {
1656       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1657       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1658       Id = IDecl->getIdentifier();
1659     }
1660   }
1661   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1662   // This routine must always return a class definition, if any.
1663   if (Def && Def->getDefinition())
1664       Def = Def->getDefinition();
1665   return Def;
1666 }
1667 
1668 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1669 /// from S, where a non-field would be declared. This routine copes
1670 /// with the difference between C and C++ scoping rules in structs and
1671 /// unions. For example, the following code is well-formed in C but
1672 /// ill-formed in C++:
1673 /// @code
1674 /// struct S6 {
1675 ///   enum { BAR } e;
1676 /// };
1677 ///
1678 /// void test_S6() {
1679 ///   struct S6 a;
1680 ///   a.e = BAR;
1681 /// }
1682 /// @endcode
1683 /// For the declaration of BAR, this routine will return a different
1684 /// scope. The scope S will be the scope of the unnamed enumeration
1685 /// within S6. In C++, this routine will return the scope associated
1686 /// with S6, because the enumeration's scope is a transparent
1687 /// context but structures can contain non-field names. In C, this
1688 /// routine will return the translation unit scope, since the
1689 /// enumeration's scope is a transparent context and structures cannot
1690 /// contain non-field names.
1691 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1692   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1693          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1694          (S->isClassScope() && !getLangOpts().CPlusPlus))
1695     S = S->getParent();
1696   return S;
1697 }
1698 
1699 /// \brief Looks up the declaration of "struct objc_super" and
1700 /// saves it for later use in building builtin declaration of
1701 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1702 /// pre-existing declaration exists no action takes place.
1703 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1704                                         IdentifierInfo *II) {
1705   if (!II->isStr("objc_msgSendSuper"))
1706     return;
1707   ASTContext &Context = ThisSema.Context;
1708 
1709   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1710                       SourceLocation(), Sema::LookupTagName);
1711   ThisSema.LookupName(Result, S);
1712   if (Result.getResultKind() == LookupResult::Found)
1713     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1714       Context.setObjCSuperType(Context.getTagDeclType(TD));
1715 }
1716 
1717 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1718   switch (Error) {
1719   case ASTContext::GE_None:
1720     return "";
1721   case ASTContext::GE_Missing_stdio:
1722     return "stdio.h";
1723   case ASTContext::GE_Missing_setjmp:
1724     return "setjmp.h";
1725   case ASTContext::GE_Missing_ucontext:
1726     return "ucontext.h";
1727   }
1728   llvm_unreachable("unhandled error kind");
1729 }
1730 
1731 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1732 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1733 /// if we're creating this built-in in anticipation of redeclaring the
1734 /// built-in.
1735 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1736                                      Scope *S, bool ForRedeclaration,
1737                                      SourceLocation Loc) {
1738   LookupPredefedObjCSuperType(*this, S, II);
1739 
1740   ASTContext::GetBuiltinTypeError Error;
1741   QualType R = Context.GetBuiltinType(ID, Error);
1742   if (Error) {
1743     if (ForRedeclaration)
1744       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1745           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1746     return nullptr;
1747   }
1748 
1749   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
1750     Diag(Loc, diag::ext_implicit_lib_function_decl)
1751         << Context.BuiltinInfo.getName(ID) << R;
1752     if (Context.BuiltinInfo.getHeaderName(ID) &&
1753         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1754       Diag(Loc, diag::note_include_header_or_declare)
1755           << Context.BuiltinInfo.getHeaderName(ID)
1756           << Context.BuiltinInfo.getName(ID);
1757   }
1758 
1759   if (R.isNull())
1760     return nullptr;
1761 
1762   DeclContext *Parent = Context.getTranslationUnitDecl();
1763   if (getLangOpts().CPlusPlus) {
1764     LinkageSpecDecl *CLinkageDecl =
1765         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1766                                 LinkageSpecDecl::lang_c, false);
1767     CLinkageDecl->setImplicit();
1768     Parent->addDecl(CLinkageDecl);
1769     Parent = CLinkageDecl;
1770   }
1771 
1772   FunctionDecl *New = FunctionDecl::Create(Context,
1773                                            Parent,
1774                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1775                                            SC_Extern,
1776                                            false,
1777                                            R->isFunctionProtoType());
1778   New->setImplicit();
1779 
1780   // Create Decl objects for each parameter, adding them to the
1781   // FunctionDecl.
1782   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1783     SmallVector<ParmVarDecl*, 16> Params;
1784     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1785       ParmVarDecl *parm =
1786           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1787                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1788                               SC_None, nullptr);
1789       parm->setScopeInfo(0, i);
1790       Params.push_back(parm);
1791     }
1792     New->setParams(Params);
1793   }
1794 
1795   AddKnownFunctionAttributes(New);
1796   RegisterLocallyScopedExternCDecl(New, S);
1797 
1798   // TUScope is the translation-unit scope to insert this function into.
1799   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1800   // relate Scopes to DeclContexts, and probably eliminate CurContext
1801   // entirely, but we're not there yet.
1802   DeclContext *SavedContext = CurContext;
1803   CurContext = Parent;
1804   PushOnScopeChains(New, TUScope);
1805   CurContext = SavedContext;
1806   return New;
1807 }
1808 
1809 /// Typedef declarations don't have linkage, but they still denote the same
1810 /// entity if their types are the same.
1811 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1812 /// isSameEntity.
1813 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1814                                                      TypedefNameDecl *Decl,
1815                                                      LookupResult &Previous) {
1816   // This is only interesting when modules are enabled.
1817   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1818     return;
1819 
1820   // Empty sets are uninteresting.
1821   if (Previous.empty())
1822     return;
1823 
1824   LookupResult::Filter Filter = Previous.makeFilter();
1825   while (Filter.hasNext()) {
1826     NamedDecl *Old = Filter.next();
1827 
1828     // Non-hidden declarations are never ignored.
1829     if (S.isVisible(Old))
1830       continue;
1831 
1832     // Declarations of the same entity are not ignored, even if they have
1833     // different linkages.
1834     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1835       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1836                                 Decl->getUnderlyingType()))
1837         continue;
1838 
1839       // If both declarations give a tag declaration a typedef name for linkage
1840       // purposes, then they declare the same entity.
1841       if (S.getLangOpts().CPlusPlus &&
1842           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1843           Decl->getAnonDeclWithTypedefName())
1844         continue;
1845     }
1846 
1847     Filter.erase();
1848   }
1849 
1850   Filter.done();
1851 }
1852 
1853 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1854   QualType OldType;
1855   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1856     OldType = OldTypedef->getUnderlyingType();
1857   else
1858     OldType = Context.getTypeDeclType(Old);
1859   QualType NewType = New->getUnderlyingType();
1860 
1861   if (NewType->isVariablyModifiedType()) {
1862     // Must not redefine a typedef with a variably-modified type.
1863     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1864     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1865       << Kind << NewType;
1866     if (Old->getLocation().isValid())
1867       Diag(Old->getLocation(), diag::note_previous_definition);
1868     New->setInvalidDecl();
1869     return true;
1870   }
1871 
1872   if (OldType != NewType &&
1873       !OldType->isDependentType() &&
1874       !NewType->isDependentType() &&
1875       !Context.hasSameType(OldType, NewType)) {
1876     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1877     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1878       << Kind << NewType << OldType;
1879     if (Old->getLocation().isValid())
1880       Diag(Old->getLocation(), diag::note_previous_definition);
1881     New->setInvalidDecl();
1882     return true;
1883   }
1884   return false;
1885 }
1886 
1887 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1888 /// same name and scope as a previous declaration 'Old'.  Figure out
1889 /// how to resolve this situation, merging decls or emitting
1890 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1891 ///
1892 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
1893                                 LookupResult &OldDecls) {
1894   // If the new decl is known invalid already, don't bother doing any
1895   // merging checks.
1896   if (New->isInvalidDecl()) return;
1897 
1898   // Allow multiple definitions for ObjC built-in typedefs.
1899   // FIXME: Verify the underlying types are equivalent!
1900   if (getLangOpts().ObjC1) {
1901     const IdentifierInfo *TypeID = New->getIdentifier();
1902     switch (TypeID->getLength()) {
1903     default: break;
1904     case 2:
1905       {
1906         if (!TypeID->isStr("id"))
1907           break;
1908         QualType T = New->getUnderlyingType();
1909         if (!T->isPointerType())
1910           break;
1911         if (!T->isVoidPointerType()) {
1912           QualType PT = T->getAs<PointerType>()->getPointeeType();
1913           if (!PT->isStructureType())
1914             break;
1915         }
1916         Context.setObjCIdRedefinitionType(T);
1917         // Install the built-in type for 'id', ignoring the current definition.
1918         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1919         return;
1920       }
1921     case 5:
1922       if (!TypeID->isStr("Class"))
1923         break;
1924       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1925       // Install the built-in type for 'Class', ignoring the current definition.
1926       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1927       return;
1928     case 3:
1929       if (!TypeID->isStr("SEL"))
1930         break;
1931       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1932       // Install the built-in type for 'SEL', ignoring the current definition.
1933       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1934       return;
1935     }
1936     // Fall through - the typedef name was not a builtin type.
1937   }
1938 
1939   // Verify the old decl was also a type.
1940   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1941   if (!Old) {
1942     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1943       << New->getDeclName();
1944 
1945     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1946     if (OldD->getLocation().isValid())
1947       Diag(OldD->getLocation(), diag::note_previous_definition);
1948 
1949     return New->setInvalidDecl();
1950   }
1951 
1952   // If the old declaration is invalid, just give up here.
1953   if (Old->isInvalidDecl())
1954     return New->setInvalidDecl();
1955 
1956   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1957     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
1958     auto *NewTag = New->getAnonDeclWithTypedefName();
1959     NamedDecl *Hidden = nullptr;
1960     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
1961         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
1962         !hasVisibleDefinition(OldTag, &Hidden)) {
1963       // There is a definition of this tag, but it is not visible. Use it
1964       // instead of our tag.
1965       New->setTypeForDecl(OldTD->getTypeForDecl());
1966       if (OldTD->isModed())
1967         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
1968                                     OldTD->getUnderlyingType());
1969       else
1970         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
1971 
1972       // Make the old tag definition visible.
1973       makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
1974 
1975       // If this was an unscoped enumeration, yank all of its enumerators
1976       // out of the scope.
1977       if (isa<EnumDecl>(NewTag)) {
1978         Scope *EnumScope = getNonFieldDeclScope(S);
1979         for (auto *D : NewTag->decls()) {
1980           auto *ED = cast<EnumConstantDecl>(D);
1981           assert(EnumScope->isDeclScope(ED));
1982           EnumScope->RemoveDecl(ED);
1983           IdResolver.RemoveDecl(ED);
1984           ED->getLexicalDeclContext()->removeDecl(ED);
1985         }
1986       }
1987     }
1988   }
1989 
1990   // If the typedef types are not identical, reject them in all languages and
1991   // with any extensions enabled.
1992   if (isIncompatibleTypedef(Old, New))
1993     return;
1994 
1995   // The types match.  Link up the redeclaration chain and merge attributes if
1996   // the old declaration was a typedef.
1997   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
1998     New->setPreviousDecl(Typedef);
1999     mergeDeclAttributes(New, Old);
2000   }
2001 
2002   if (getLangOpts().MicrosoftExt)
2003     return;
2004 
2005   if (getLangOpts().CPlusPlus) {
2006     // C++ [dcl.typedef]p2:
2007     //   In a given non-class scope, a typedef specifier can be used to
2008     //   redefine the name of any type declared in that scope to refer
2009     //   to the type to which it already refers.
2010     if (!isa<CXXRecordDecl>(CurContext))
2011       return;
2012 
2013     // C++0x [dcl.typedef]p4:
2014     //   In a given class scope, a typedef specifier can be used to redefine
2015     //   any class-name declared in that scope that is not also a typedef-name
2016     //   to refer to the type to which it already refers.
2017     //
2018     // This wording came in via DR424, which was a correction to the
2019     // wording in DR56, which accidentally banned code like:
2020     //
2021     //   struct S {
2022     //     typedef struct A { } A;
2023     //   };
2024     //
2025     // in the C++03 standard. We implement the C++0x semantics, which
2026     // allow the above but disallow
2027     //
2028     //   struct S {
2029     //     typedef int I;
2030     //     typedef int I;
2031     //   };
2032     //
2033     // since that was the intent of DR56.
2034     if (!isa<TypedefNameDecl>(Old))
2035       return;
2036 
2037     Diag(New->getLocation(), diag::err_redefinition)
2038       << New->getDeclName();
2039     Diag(Old->getLocation(), diag::note_previous_definition);
2040     return New->setInvalidDecl();
2041   }
2042 
2043   // Modules always permit redefinition of typedefs, as does C11.
2044   if (getLangOpts().Modules || getLangOpts().C11)
2045     return;
2046 
2047   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2048   // is normally mapped to an error, but can be controlled with
2049   // -Wtypedef-redefinition.  If either the original or the redefinition is
2050   // in a system header, don't emit this for compatibility with GCC.
2051   if (getDiagnostics().getSuppressSystemWarnings() &&
2052       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2053        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2054     return;
2055 
2056   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2057     << New->getDeclName();
2058   Diag(Old->getLocation(), diag::note_previous_definition);
2059 }
2060 
2061 /// DeclhasAttr - returns true if decl Declaration already has the target
2062 /// attribute.
2063 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2064   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2065   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2066   for (const auto *i : D->attrs())
2067     if (i->getKind() == A->getKind()) {
2068       if (Ann) {
2069         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2070           return true;
2071         continue;
2072       }
2073       // FIXME: Don't hardcode this check
2074       if (OA && isa<OwnershipAttr>(i))
2075         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2076       return true;
2077     }
2078 
2079   return false;
2080 }
2081 
2082 static bool isAttributeTargetADefinition(Decl *D) {
2083   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2084     return VD->isThisDeclarationADefinition();
2085   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2086     return TD->isCompleteDefinition() || TD->isBeingDefined();
2087   return true;
2088 }
2089 
2090 /// Merge alignment attributes from \p Old to \p New, taking into account the
2091 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2092 ///
2093 /// \return \c true if any attributes were added to \p New.
2094 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2095   // Look for alignas attributes on Old, and pick out whichever attribute
2096   // specifies the strictest alignment requirement.
2097   AlignedAttr *OldAlignasAttr = nullptr;
2098   AlignedAttr *OldStrictestAlignAttr = nullptr;
2099   unsigned OldAlign = 0;
2100   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2101     // FIXME: We have no way of representing inherited dependent alignments
2102     // in a case like:
2103     //   template<int A, int B> struct alignas(A) X;
2104     //   template<int A, int B> struct alignas(B) X {};
2105     // For now, we just ignore any alignas attributes which are not on the
2106     // definition in such a case.
2107     if (I->isAlignmentDependent())
2108       return false;
2109 
2110     if (I->isAlignas())
2111       OldAlignasAttr = I;
2112 
2113     unsigned Align = I->getAlignment(S.Context);
2114     if (Align > OldAlign) {
2115       OldAlign = Align;
2116       OldStrictestAlignAttr = I;
2117     }
2118   }
2119 
2120   // Look for alignas attributes on New.
2121   AlignedAttr *NewAlignasAttr = nullptr;
2122   unsigned NewAlign = 0;
2123   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2124     if (I->isAlignmentDependent())
2125       return false;
2126 
2127     if (I->isAlignas())
2128       NewAlignasAttr = I;
2129 
2130     unsigned Align = I->getAlignment(S.Context);
2131     if (Align > NewAlign)
2132       NewAlign = Align;
2133   }
2134 
2135   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2136     // Both declarations have 'alignas' attributes. We require them to match.
2137     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2138     // fall short. (If two declarations both have alignas, they must both match
2139     // every definition, and so must match each other if there is a definition.)
2140 
2141     // If either declaration only contains 'alignas(0)' specifiers, then it
2142     // specifies the natural alignment for the type.
2143     if (OldAlign == 0 || NewAlign == 0) {
2144       QualType Ty;
2145       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2146         Ty = VD->getType();
2147       else
2148         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2149 
2150       if (OldAlign == 0)
2151         OldAlign = S.Context.getTypeAlign(Ty);
2152       if (NewAlign == 0)
2153         NewAlign = S.Context.getTypeAlign(Ty);
2154     }
2155 
2156     if (OldAlign != NewAlign) {
2157       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2158         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2159         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2160       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2161     }
2162   }
2163 
2164   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2165     // C++11 [dcl.align]p6:
2166     //   if any declaration of an entity has an alignment-specifier,
2167     //   every defining declaration of that entity shall specify an
2168     //   equivalent alignment.
2169     // C11 6.7.5/7:
2170     //   If the definition of an object does not have an alignment
2171     //   specifier, any other declaration of that object shall also
2172     //   have no alignment specifier.
2173     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2174       << OldAlignasAttr;
2175     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2176       << OldAlignasAttr;
2177   }
2178 
2179   bool AnyAdded = false;
2180 
2181   // Ensure we have an attribute representing the strictest alignment.
2182   if (OldAlign > NewAlign) {
2183     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2184     Clone->setInherited(true);
2185     New->addAttr(Clone);
2186     AnyAdded = true;
2187   }
2188 
2189   // Ensure we have an alignas attribute if the old declaration had one.
2190   if (OldAlignasAttr && !NewAlignasAttr &&
2191       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2192     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2193     Clone->setInherited(true);
2194     New->addAttr(Clone);
2195     AnyAdded = true;
2196   }
2197 
2198   return AnyAdded;
2199 }
2200 
2201 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2202                                const InheritableAttr *Attr,
2203                                Sema::AvailabilityMergeKind AMK) {
2204   InheritableAttr *NewAttr = nullptr;
2205   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2206   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2207     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2208                                       AA->isImplicit(), AA->getIntroduced(),
2209                                       AA->getDeprecated(),
2210                                       AA->getObsoleted(), AA->getUnavailable(),
2211                                       AA->getMessage(), AA->getStrict(),
2212                                       AA->getReplacement(), AMK,
2213                                       AttrSpellingListIndex);
2214   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2215     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2216                                     AttrSpellingListIndex);
2217   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2218     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2219                                         AttrSpellingListIndex);
2220   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2221     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2222                                    AttrSpellingListIndex);
2223   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2224     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2225                                    AttrSpellingListIndex);
2226   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2227     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2228                                 FA->getFormatIdx(), FA->getFirstArg(),
2229                                 AttrSpellingListIndex);
2230   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2231     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2232                                  AttrSpellingListIndex);
2233   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2234     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2235                                        AttrSpellingListIndex,
2236                                        IA->getSemanticSpelling());
2237   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2238     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2239                                       &S.Context.Idents.get(AA->getSpelling()),
2240                                       AttrSpellingListIndex);
2241   else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2242     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2243   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2244     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2245   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2246     NewAttr = S.mergeInternalLinkageAttr(
2247         D, InternalLinkageA->getRange(),
2248         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2249         AttrSpellingListIndex);
2250   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2251     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2252                                 &S.Context.Idents.get(CommonA->getSpelling()),
2253                                 AttrSpellingListIndex);
2254   else if (isa<AlignedAttr>(Attr))
2255     // AlignedAttrs are handled separately, because we need to handle all
2256     // such attributes on a declaration at the same time.
2257     NewAttr = nullptr;
2258   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2259            (AMK == Sema::AMK_Override ||
2260             AMK == Sema::AMK_ProtocolImplementation))
2261     NewAttr = nullptr;
2262   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2263     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2264 
2265   if (NewAttr) {
2266     NewAttr->setInherited(true);
2267     D->addAttr(NewAttr);
2268     if (isa<MSInheritanceAttr>(NewAttr))
2269       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2270     return true;
2271   }
2272 
2273   return false;
2274 }
2275 
2276 static const Decl *getDefinition(const Decl *D) {
2277   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2278     return TD->getDefinition();
2279   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2280     const VarDecl *Def = VD->getDefinition();
2281     if (Def)
2282       return Def;
2283     return VD->getActingDefinition();
2284   }
2285   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2286     const FunctionDecl* Def;
2287     if (FD->isDefined(Def))
2288       return Def;
2289   }
2290   return nullptr;
2291 }
2292 
2293 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2294   for (const auto *Attribute : D->attrs())
2295     if (Attribute->getKind() == Kind)
2296       return true;
2297   return false;
2298 }
2299 
2300 /// checkNewAttributesAfterDef - If we already have a definition, check that
2301 /// there are no new attributes in this declaration.
2302 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2303   if (!New->hasAttrs())
2304     return;
2305 
2306   const Decl *Def = getDefinition(Old);
2307   if (!Def || Def == New)
2308     return;
2309 
2310   AttrVec &NewAttributes = New->getAttrs();
2311   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2312     const Attr *NewAttribute = NewAttributes[I];
2313 
2314     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2315       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2316         Sema::SkipBodyInfo SkipBody;
2317         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2318 
2319         // If we're skipping this definition, drop the "alias" attribute.
2320         if (SkipBody.ShouldSkip) {
2321           NewAttributes.erase(NewAttributes.begin() + I);
2322           --E;
2323           continue;
2324         }
2325       } else {
2326         VarDecl *VD = cast<VarDecl>(New);
2327         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2328                                 VarDecl::TentativeDefinition
2329                             ? diag::err_alias_after_tentative
2330                             : diag::err_redefinition;
2331         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2332         S.Diag(Def->getLocation(), diag::note_previous_definition);
2333         VD->setInvalidDecl();
2334       }
2335       ++I;
2336       continue;
2337     }
2338 
2339     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2340       // Tentative definitions are only interesting for the alias check above.
2341       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2342         ++I;
2343         continue;
2344       }
2345     }
2346 
2347     if (hasAttribute(Def, NewAttribute->getKind())) {
2348       ++I;
2349       continue; // regular attr merging will take care of validating this.
2350     }
2351 
2352     if (isa<C11NoReturnAttr>(NewAttribute)) {
2353       // C's _Noreturn is allowed to be added to a function after it is defined.
2354       ++I;
2355       continue;
2356     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2357       if (AA->isAlignas()) {
2358         // C++11 [dcl.align]p6:
2359         //   if any declaration of an entity has an alignment-specifier,
2360         //   every defining declaration of that entity shall specify an
2361         //   equivalent alignment.
2362         // C11 6.7.5/7:
2363         //   If the definition of an object does not have an alignment
2364         //   specifier, any other declaration of that object shall also
2365         //   have no alignment specifier.
2366         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2367           << AA;
2368         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2369           << AA;
2370         NewAttributes.erase(NewAttributes.begin() + I);
2371         --E;
2372         continue;
2373       }
2374     }
2375 
2376     S.Diag(NewAttribute->getLocation(),
2377            diag::warn_attribute_precede_definition);
2378     S.Diag(Def->getLocation(), diag::note_previous_definition);
2379     NewAttributes.erase(NewAttributes.begin() + I);
2380     --E;
2381   }
2382 }
2383 
2384 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2385 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2386                                AvailabilityMergeKind AMK) {
2387   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2388     UsedAttr *NewAttr = OldAttr->clone(Context);
2389     NewAttr->setInherited(true);
2390     New->addAttr(NewAttr);
2391   }
2392 
2393   if (!Old->hasAttrs() && !New->hasAttrs())
2394     return;
2395 
2396   // Attributes declared post-definition are currently ignored.
2397   checkNewAttributesAfterDef(*this, New, Old);
2398 
2399   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2400     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2401       if (OldA->getLabel() != NewA->getLabel()) {
2402         // This redeclaration changes __asm__ label.
2403         Diag(New->getLocation(), diag::err_different_asm_label);
2404         Diag(OldA->getLocation(), diag::note_previous_declaration);
2405       }
2406     } else if (Old->isUsed()) {
2407       // This redeclaration adds an __asm__ label to a declaration that has
2408       // already been ODR-used.
2409       Diag(New->getLocation(), diag::err_late_asm_label_name)
2410         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2411     }
2412   }
2413 
2414   // Re-declaration cannot add abi_tag's.
2415   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2416     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2417       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2418         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2419                       NewTag) == OldAbiTagAttr->tags_end()) {
2420           Diag(NewAbiTagAttr->getLocation(),
2421                diag::err_new_abi_tag_on_redeclaration)
2422               << NewTag;
2423           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2424         }
2425       }
2426     } else {
2427       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2428       Diag(Old->getLocation(), diag::note_previous_declaration);
2429     }
2430   }
2431 
2432   if (!Old->hasAttrs())
2433     return;
2434 
2435   bool foundAny = New->hasAttrs();
2436 
2437   // Ensure that any moving of objects within the allocated map is done before
2438   // we process them.
2439   if (!foundAny) New->setAttrs(AttrVec());
2440 
2441   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2442     // Ignore deprecated/unavailable/availability attributes if requested.
2443     AvailabilityMergeKind LocalAMK = AMK_None;
2444     if (isa<DeprecatedAttr>(I) ||
2445         isa<UnavailableAttr>(I) ||
2446         isa<AvailabilityAttr>(I)) {
2447       switch (AMK) {
2448       case AMK_None:
2449         continue;
2450 
2451       case AMK_Redeclaration:
2452       case AMK_Override:
2453       case AMK_ProtocolImplementation:
2454         LocalAMK = AMK;
2455         break;
2456       }
2457     }
2458 
2459     // Already handled.
2460     if (isa<UsedAttr>(I))
2461       continue;
2462 
2463     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2464       foundAny = true;
2465   }
2466 
2467   if (mergeAlignedAttrs(*this, New, Old))
2468     foundAny = true;
2469 
2470   if (!foundAny) New->dropAttrs();
2471 }
2472 
2473 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2474 /// to the new one.
2475 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2476                                      const ParmVarDecl *oldDecl,
2477                                      Sema &S) {
2478   // C++11 [dcl.attr.depend]p2:
2479   //   The first declaration of a function shall specify the
2480   //   carries_dependency attribute for its declarator-id if any declaration
2481   //   of the function specifies the carries_dependency attribute.
2482   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2483   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2484     S.Diag(CDA->getLocation(),
2485            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2486     // Find the first declaration of the parameter.
2487     // FIXME: Should we build redeclaration chains for function parameters?
2488     const FunctionDecl *FirstFD =
2489       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2490     const ParmVarDecl *FirstVD =
2491       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2492     S.Diag(FirstVD->getLocation(),
2493            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2494   }
2495 
2496   if (!oldDecl->hasAttrs())
2497     return;
2498 
2499   bool foundAny = newDecl->hasAttrs();
2500 
2501   // Ensure that any moving of objects within the allocated map is
2502   // done before we process them.
2503   if (!foundAny) newDecl->setAttrs(AttrVec());
2504 
2505   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2506     if (!DeclHasAttr(newDecl, I)) {
2507       InheritableAttr *newAttr =
2508         cast<InheritableParamAttr>(I->clone(S.Context));
2509       newAttr->setInherited(true);
2510       newDecl->addAttr(newAttr);
2511       foundAny = true;
2512     }
2513   }
2514 
2515   if (!foundAny) newDecl->dropAttrs();
2516 }
2517 
2518 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2519                                 const ParmVarDecl *OldParam,
2520                                 Sema &S) {
2521   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2522     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2523       if (*Oldnullability != *Newnullability) {
2524         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2525           << DiagNullabilityKind(
2526                *Newnullability,
2527                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2528                 != 0))
2529           << DiagNullabilityKind(
2530                *Oldnullability,
2531                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2532                 != 0));
2533         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2534       }
2535     } else {
2536       QualType NewT = NewParam->getType();
2537       NewT = S.Context.getAttributedType(
2538                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2539                          NewT, NewT);
2540       NewParam->setType(NewT);
2541     }
2542   }
2543 }
2544 
2545 namespace {
2546 
2547 /// Used in MergeFunctionDecl to keep track of function parameters in
2548 /// C.
2549 struct GNUCompatibleParamWarning {
2550   ParmVarDecl *OldParm;
2551   ParmVarDecl *NewParm;
2552   QualType PromotedType;
2553 };
2554 
2555 } // end anonymous namespace
2556 
2557 /// getSpecialMember - get the special member enum for a method.
2558 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2559   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2560     if (Ctor->isDefaultConstructor())
2561       return Sema::CXXDefaultConstructor;
2562 
2563     if (Ctor->isCopyConstructor())
2564       return Sema::CXXCopyConstructor;
2565 
2566     if (Ctor->isMoveConstructor())
2567       return Sema::CXXMoveConstructor;
2568   } else if (isa<CXXDestructorDecl>(MD)) {
2569     return Sema::CXXDestructor;
2570   } else if (MD->isCopyAssignmentOperator()) {
2571     return Sema::CXXCopyAssignment;
2572   } else if (MD->isMoveAssignmentOperator()) {
2573     return Sema::CXXMoveAssignment;
2574   }
2575 
2576   return Sema::CXXInvalid;
2577 }
2578 
2579 // Determine whether the previous declaration was a definition, implicit
2580 // declaration, or a declaration.
2581 template <typename T>
2582 static std::pair<diag::kind, SourceLocation>
2583 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2584   diag::kind PrevDiag;
2585   SourceLocation OldLocation = Old->getLocation();
2586   if (Old->isThisDeclarationADefinition())
2587     PrevDiag = diag::note_previous_definition;
2588   else if (Old->isImplicit()) {
2589     PrevDiag = diag::note_previous_implicit_declaration;
2590     if (OldLocation.isInvalid())
2591       OldLocation = New->getLocation();
2592   } else
2593     PrevDiag = diag::note_previous_declaration;
2594   return std::make_pair(PrevDiag, OldLocation);
2595 }
2596 
2597 /// canRedefineFunction - checks if a function can be redefined. Currently,
2598 /// only extern inline functions can be redefined, and even then only in
2599 /// GNU89 mode.
2600 static bool canRedefineFunction(const FunctionDecl *FD,
2601                                 const LangOptions& LangOpts) {
2602   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2603           !LangOpts.CPlusPlus &&
2604           FD->isInlineSpecified() &&
2605           FD->getStorageClass() == SC_Extern);
2606 }
2607 
2608 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2609   const AttributedType *AT = T->getAs<AttributedType>();
2610   while (AT && !AT->isCallingConv())
2611     AT = AT->getModifiedType()->getAs<AttributedType>();
2612   return AT;
2613 }
2614 
2615 template <typename T>
2616 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2617   const DeclContext *DC = Old->getDeclContext();
2618   if (DC->isRecord())
2619     return false;
2620 
2621   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2622   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2623     return true;
2624   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2625     return true;
2626   return false;
2627 }
2628 
2629 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2630 static bool isExternC(VarTemplateDecl *) { return false; }
2631 
2632 /// \brief Check whether a redeclaration of an entity introduced by a
2633 /// using-declaration is valid, given that we know it's not an overload
2634 /// (nor a hidden tag declaration).
2635 template<typename ExpectedDecl>
2636 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2637                                    ExpectedDecl *New) {
2638   // C++11 [basic.scope.declarative]p4:
2639   //   Given a set of declarations in a single declarative region, each of
2640   //   which specifies the same unqualified name,
2641   //   -- they shall all refer to the same entity, or all refer to functions
2642   //      and function templates; or
2643   //   -- exactly one declaration shall declare a class name or enumeration
2644   //      name that is not a typedef name and the other declarations shall all
2645   //      refer to the same variable or enumerator, or all refer to functions
2646   //      and function templates; in this case the class name or enumeration
2647   //      name is hidden (3.3.10).
2648 
2649   // C++11 [namespace.udecl]p14:
2650   //   If a function declaration in namespace scope or block scope has the
2651   //   same name and the same parameter-type-list as a function introduced
2652   //   by a using-declaration, and the declarations do not declare the same
2653   //   function, the program is ill-formed.
2654 
2655   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2656   if (Old &&
2657       !Old->getDeclContext()->getRedeclContext()->Equals(
2658           New->getDeclContext()->getRedeclContext()) &&
2659       !(isExternC(Old) && isExternC(New)))
2660     Old = nullptr;
2661 
2662   if (!Old) {
2663     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2664     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2665     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2666     return true;
2667   }
2668   return false;
2669 }
2670 
2671 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2672                                             const FunctionDecl *B) {
2673   assert(A->getNumParams() == B->getNumParams());
2674 
2675   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2676     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2677     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2678     if (AttrA == AttrB)
2679       return true;
2680     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2681   };
2682 
2683   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2684 }
2685 
2686 /// MergeFunctionDecl - We just parsed a function 'New' from
2687 /// declarator D which has the same name and scope as a previous
2688 /// declaration 'Old'.  Figure out how to resolve this situation,
2689 /// merging decls or emitting diagnostics as appropriate.
2690 ///
2691 /// In C++, New and Old must be declarations that are not
2692 /// overloaded. Use IsOverload to determine whether New and Old are
2693 /// overloaded, and to select the Old declaration that New should be
2694 /// merged with.
2695 ///
2696 /// Returns true if there was an error, false otherwise.
2697 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2698                              Scope *S, bool MergeTypeWithOld) {
2699   // Verify the old decl was also a function.
2700   FunctionDecl *Old = OldD->getAsFunction();
2701   if (!Old) {
2702     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2703       if (New->getFriendObjectKind()) {
2704         Diag(New->getLocation(), diag::err_using_decl_friend);
2705         Diag(Shadow->getTargetDecl()->getLocation(),
2706              diag::note_using_decl_target);
2707         Diag(Shadow->getUsingDecl()->getLocation(),
2708              diag::note_using_decl) << 0;
2709         return true;
2710       }
2711 
2712       // Check whether the two declarations might declare the same function.
2713       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2714         return true;
2715       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2716     } else {
2717       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2718         << New->getDeclName();
2719       Diag(OldD->getLocation(), diag::note_previous_definition);
2720       return true;
2721     }
2722   }
2723 
2724   // If the old declaration is invalid, just give up here.
2725   if (Old->isInvalidDecl())
2726     return true;
2727 
2728   diag::kind PrevDiag;
2729   SourceLocation OldLocation;
2730   std::tie(PrevDiag, OldLocation) =
2731       getNoteDiagForInvalidRedeclaration(Old, New);
2732 
2733   // Don't complain about this if we're in GNU89 mode and the old function
2734   // is an extern inline function.
2735   // Don't complain about specializations. They are not supposed to have
2736   // storage classes.
2737   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2738       New->getStorageClass() == SC_Static &&
2739       Old->hasExternalFormalLinkage() &&
2740       !New->getTemplateSpecializationInfo() &&
2741       !canRedefineFunction(Old, getLangOpts())) {
2742     if (getLangOpts().MicrosoftExt) {
2743       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2744       Diag(OldLocation, PrevDiag);
2745     } else {
2746       Diag(New->getLocation(), diag::err_static_non_static) << New;
2747       Diag(OldLocation, PrevDiag);
2748       return true;
2749     }
2750   }
2751 
2752   if (New->hasAttr<InternalLinkageAttr>() &&
2753       !Old->hasAttr<InternalLinkageAttr>()) {
2754     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2755         << New->getDeclName();
2756     Diag(Old->getLocation(), diag::note_previous_definition);
2757     New->dropAttr<InternalLinkageAttr>();
2758   }
2759 
2760   // If a function is first declared with a calling convention, but is later
2761   // declared or defined without one, all following decls assume the calling
2762   // convention of the first.
2763   //
2764   // It's OK if a function is first declared without a calling convention,
2765   // but is later declared or defined with the default calling convention.
2766   //
2767   // To test if either decl has an explicit calling convention, we look for
2768   // AttributedType sugar nodes on the type as written.  If they are missing or
2769   // were canonicalized away, we assume the calling convention was implicit.
2770   //
2771   // Note also that we DO NOT return at this point, because we still have
2772   // other tests to run.
2773   QualType OldQType = Context.getCanonicalType(Old->getType());
2774   QualType NewQType = Context.getCanonicalType(New->getType());
2775   const FunctionType *OldType = cast<FunctionType>(OldQType);
2776   const FunctionType *NewType = cast<FunctionType>(NewQType);
2777   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2778   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2779   bool RequiresAdjustment = false;
2780 
2781   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2782     FunctionDecl *First = Old->getFirstDecl();
2783     const FunctionType *FT =
2784         First->getType().getCanonicalType()->castAs<FunctionType>();
2785     FunctionType::ExtInfo FI = FT->getExtInfo();
2786     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2787     if (!NewCCExplicit) {
2788       // Inherit the CC from the previous declaration if it was specified
2789       // there but not here.
2790       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2791       RequiresAdjustment = true;
2792     } else {
2793       // Calling conventions aren't compatible, so complain.
2794       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2795       Diag(New->getLocation(), diag::err_cconv_change)
2796         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2797         << !FirstCCExplicit
2798         << (!FirstCCExplicit ? "" :
2799             FunctionType::getNameForCallConv(FI.getCC()));
2800 
2801       // Put the note on the first decl, since it is the one that matters.
2802       Diag(First->getLocation(), diag::note_previous_declaration);
2803       return true;
2804     }
2805   }
2806 
2807   // FIXME: diagnose the other way around?
2808   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2809     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2810     RequiresAdjustment = true;
2811   }
2812 
2813   // Merge regparm attribute.
2814   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2815       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2816     if (NewTypeInfo.getHasRegParm()) {
2817       Diag(New->getLocation(), diag::err_regparm_mismatch)
2818         << NewType->getRegParmType()
2819         << OldType->getRegParmType();
2820       Diag(OldLocation, diag::note_previous_declaration);
2821       return true;
2822     }
2823 
2824     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2825     RequiresAdjustment = true;
2826   }
2827 
2828   // Merge ns_returns_retained attribute.
2829   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2830     if (NewTypeInfo.getProducesResult()) {
2831       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2832       Diag(OldLocation, diag::note_previous_declaration);
2833       return true;
2834     }
2835 
2836     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2837     RequiresAdjustment = true;
2838   }
2839 
2840   if (RequiresAdjustment) {
2841     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2842     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2843     New->setType(QualType(AdjustedType, 0));
2844     NewQType = Context.getCanonicalType(New->getType());
2845     NewType = cast<FunctionType>(NewQType);
2846   }
2847 
2848   // If this redeclaration makes the function inline, we may need to add it to
2849   // UndefinedButUsed.
2850   if (!Old->isInlined() && New->isInlined() &&
2851       !New->hasAttr<GNUInlineAttr>() &&
2852       !getLangOpts().GNUInline &&
2853       Old->isUsed(false) &&
2854       !Old->isDefined() && !New->isThisDeclarationADefinition())
2855     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2856                                            SourceLocation()));
2857 
2858   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2859   // about it.
2860   if (New->hasAttr<GNUInlineAttr>() &&
2861       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2862     UndefinedButUsed.erase(Old->getCanonicalDecl());
2863   }
2864 
2865   // If pass_object_size params don't match up perfectly, this isn't a valid
2866   // redeclaration.
2867   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
2868       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
2869     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
2870         << New->getDeclName();
2871     Diag(OldLocation, PrevDiag) << Old << Old->getType();
2872     return true;
2873   }
2874 
2875   if (getLangOpts().CPlusPlus) {
2876     // (C++98 13.1p2):
2877     //   Certain function declarations cannot be overloaded:
2878     //     -- Function declarations that differ only in the return type
2879     //        cannot be overloaded.
2880 
2881     // Go back to the type source info to compare the declared return types,
2882     // per C++1y [dcl.type.auto]p13:
2883     //   Redeclarations or specializations of a function or function template
2884     //   with a declared return type that uses a placeholder type shall also
2885     //   use that placeholder, not a deduced type.
2886     QualType OldDeclaredReturnType =
2887         (Old->getTypeSourceInfo()
2888              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2889              : OldType)->getReturnType();
2890     QualType NewDeclaredReturnType =
2891         (New->getTypeSourceInfo()
2892              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2893              : NewType)->getReturnType();
2894     QualType ResQT;
2895     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2896         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2897           New->isLocalExternDecl())) {
2898       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2899           OldDeclaredReturnType->isObjCObjectPointerType())
2900         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2901       if (ResQT.isNull()) {
2902         if (New->isCXXClassMember() && New->isOutOfLine())
2903           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2904               << New << New->getReturnTypeSourceRange();
2905         else
2906           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2907               << New->getReturnTypeSourceRange();
2908         Diag(OldLocation, PrevDiag) << Old << Old->getType()
2909                                     << Old->getReturnTypeSourceRange();
2910         return true;
2911       }
2912       else
2913         NewQType = ResQT;
2914     }
2915 
2916     QualType OldReturnType = OldType->getReturnType();
2917     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2918     if (OldReturnType != NewReturnType) {
2919       // If this function has a deduced return type and has already been
2920       // defined, copy the deduced value from the old declaration.
2921       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2922       if (OldAT && OldAT->isDeduced()) {
2923         New->setType(
2924             SubstAutoType(New->getType(),
2925                           OldAT->isDependentType() ? Context.DependentTy
2926                                                    : OldAT->getDeducedType()));
2927         NewQType = Context.getCanonicalType(
2928             SubstAutoType(NewQType,
2929                           OldAT->isDependentType() ? Context.DependentTy
2930                                                    : OldAT->getDeducedType()));
2931       }
2932     }
2933 
2934     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2935     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2936     if (OldMethod && NewMethod) {
2937       // Preserve triviality.
2938       NewMethod->setTrivial(OldMethod->isTrivial());
2939 
2940       // MSVC allows explicit template specialization at class scope:
2941       // 2 CXXMethodDecls referring to the same function will be injected.
2942       // We don't want a redeclaration error.
2943       bool IsClassScopeExplicitSpecialization =
2944                               OldMethod->isFunctionTemplateSpecialization() &&
2945                               NewMethod->isFunctionTemplateSpecialization();
2946       bool isFriend = NewMethod->getFriendObjectKind();
2947 
2948       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2949           !IsClassScopeExplicitSpecialization) {
2950         //    -- Member function declarations with the same name and the
2951         //       same parameter types cannot be overloaded if any of them
2952         //       is a static member function declaration.
2953         if (OldMethod->isStatic() != NewMethod->isStatic()) {
2954           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2955           Diag(OldLocation, PrevDiag) << Old << Old->getType();
2956           return true;
2957         }
2958 
2959         // C++ [class.mem]p1:
2960         //   [...] A member shall not be declared twice in the
2961         //   member-specification, except that a nested class or member
2962         //   class template can be declared and then later defined.
2963         if (ActiveTemplateInstantiations.empty()) {
2964           unsigned NewDiag;
2965           if (isa<CXXConstructorDecl>(OldMethod))
2966             NewDiag = diag::err_constructor_redeclared;
2967           else if (isa<CXXDestructorDecl>(NewMethod))
2968             NewDiag = diag::err_destructor_redeclared;
2969           else if (isa<CXXConversionDecl>(NewMethod))
2970             NewDiag = diag::err_conv_function_redeclared;
2971           else
2972             NewDiag = diag::err_member_redeclared;
2973 
2974           Diag(New->getLocation(), NewDiag);
2975         } else {
2976           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2977             << New << New->getType();
2978         }
2979         Diag(OldLocation, PrevDiag) << Old << Old->getType();
2980         return true;
2981 
2982       // Complain if this is an explicit declaration of a special
2983       // member that was initially declared implicitly.
2984       //
2985       // As an exception, it's okay to befriend such methods in order
2986       // to permit the implicit constructor/destructor/operator calls.
2987       } else if (OldMethod->isImplicit()) {
2988         if (isFriend) {
2989           NewMethod->setImplicit();
2990         } else {
2991           Diag(NewMethod->getLocation(),
2992                diag::err_definition_of_implicitly_declared_member)
2993             << New << getSpecialMember(OldMethod);
2994           return true;
2995         }
2996       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
2997         Diag(NewMethod->getLocation(),
2998              diag::err_definition_of_explicitly_defaulted_member)
2999           << getSpecialMember(OldMethod);
3000         return true;
3001       }
3002     }
3003 
3004     // C++11 [dcl.attr.noreturn]p1:
3005     //   The first declaration of a function shall specify the noreturn
3006     //   attribute if any declaration of that function specifies the noreturn
3007     //   attribute.
3008     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3009     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3010       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3011       Diag(Old->getFirstDecl()->getLocation(),
3012            diag::note_noreturn_missing_first_decl);
3013     }
3014 
3015     // C++11 [dcl.attr.depend]p2:
3016     //   The first declaration of a function shall specify the
3017     //   carries_dependency attribute for its declarator-id if any declaration
3018     //   of the function specifies the carries_dependency attribute.
3019     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3020     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3021       Diag(CDA->getLocation(),
3022            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3023       Diag(Old->getFirstDecl()->getLocation(),
3024            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3025     }
3026 
3027     // (C++98 8.3.5p3):
3028     //   All declarations for a function shall agree exactly in both the
3029     //   return type and the parameter-type-list.
3030     // We also want to respect all the extended bits except noreturn.
3031 
3032     // noreturn should now match unless the old type info didn't have it.
3033     QualType OldQTypeForComparison = OldQType;
3034     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3035       assert(OldQType == QualType(OldType, 0));
3036       const FunctionType *OldTypeForComparison
3037         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3038       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3039       assert(OldQTypeForComparison.isCanonical());
3040     }
3041 
3042     if (haveIncompatibleLanguageLinkages(Old, New)) {
3043       // As a special case, retain the language linkage from previous
3044       // declarations of a friend function as an extension.
3045       //
3046       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3047       // and is useful because there's otherwise no way to specify language
3048       // linkage within class scope.
3049       //
3050       // Check cautiously as the friend object kind isn't yet complete.
3051       if (New->getFriendObjectKind() != Decl::FOK_None) {
3052         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3053         Diag(OldLocation, PrevDiag);
3054       } else {
3055         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3056         Diag(OldLocation, PrevDiag);
3057         return true;
3058       }
3059     }
3060 
3061     if (OldQTypeForComparison == NewQType)
3062       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3063 
3064     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3065         New->isLocalExternDecl()) {
3066       // It's OK if we couldn't merge types for a local function declaraton
3067       // if either the old or new type is dependent. We'll merge the types
3068       // when we instantiate the function.
3069       return false;
3070     }
3071 
3072     // Fall through for conflicting redeclarations and redefinitions.
3073   }
3074 
3075   // C: Function types need to be compatible, not identical. This handles
3076   // duplicate function decls like "void f(int); void f(enum X);" properly.
3077   if (!getLangOpts().CPlusPlus &&
3078       Context.typesAreCompatible(OldQType, NewQType)) {
3079     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3080     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3081     const FunctionProtoType *OldProto = nullptr;
3082     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3083         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3084       // The old declaration provided a function prototype, but the
3085       // new declaration does not. Merge in the prototype.
3086       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3087       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3088       NewQType =
3089           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3090                                   OldProto->getExtProtoInfo());
3091       New->setType(NewQType);
3092       New->setHasInheritedPrototype();
3093 
3094       // Synthesize parameters with the same types.
3095       SmallVector<ParmVarDecl*, 16> Params;
3096       for (const auto &ParamType : OldProto->param_types()) {
3097         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3098                                                  SourceLocation(), nullptr,
3099                                                  ParamType, /*TInfo=*/nullptr,
3100                                                  SC_None, nullptr);
3101         Param->setScopeInfo(0, Params.size());
3102         Param->setImplicit();
3103         Params.push_back(Param);
3104       }
3105 
3106       New->setParams(Params);
3107     }
3108 
3109     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3110   }
3111 
3112   // GNU C permits a K&R definition to follow a prototype declaration
3113   // if the declared types of the parameters in the K&R definition
3114   // match the types in the prototype declaration, even when the
3115   // promoted types of the parameters from the K&R definition differ
3116   // from the types in the prototype. GCC then keeps the types from
3117   // the prototype.
3118   //
3119   // If a variadic prototype is followed by a non-variadic K&R definition,
3120   // the K&R definition becomes variadic.  This is sort of an edge case, but
3121   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3122   // C99 6.9.1p8.
3123   if (!getLangOpts().CPlusPlus &&
3124       Old->hasPrototype() && !New->hasPrototype() &&
3125       New->getType()->getAs<FunctionProtoType>() &&
3126       Old->getNumParams() == New->getNumParams()) {
3127     SmallVector<QualType, 16> ArgTypes;
3128     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3129     const FunctionProtoType *OldProto
3130       = Old->getType()->getAs<FunctionProtoType>();
3131     const FunctionProtoType *NewProto
3132       = New->getType()->getAs<FunctionProtoType>();
3133 
3134     // Determine whether this is the GNU C extension.
3135     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3136                                                NewProto->getReturnType());
3137     bool LooseCompatible = !MergedReturn.isNull();
3138     for (unsigned Idx = 0, End = Old->getNumParams();
3139          LooseCompatible && Idx != End; ++Idx) {
3140       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3141       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3142       if (Context.typesAreCompatible(OldParm->getType(),
3143                                      NewProto->getParamType(Idx))) {
3144         ArgTypes.push_back(NewParm->getType());
3145       } else if (Context.typesAreCompatible(OldParm->getType(),
3146                                             NewParm->getType(),
3147                                             /*CompareUnqualified=*/true)) {
3148         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3149                                            NewProto->getParamType(Idx) };
3150         Warnings.push_back(Warn);
3151         ArgTypes.push_back(NewParm->getType());
3152       } else
3153         LooseCompatible = false;
3154     }
3155 
3156     if (LooseCompatible) {
3157       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3158         Diag(Warnings[Warn].NewParm->getLocation(),
3159              diag::ext_param_promoted_not_compatible_with_prototype)
3160           << Warnings[Warn].PromotedType
3161           << Warnings[Warn].OldParm->getType();
3162         if (Warnings[Warn].OldParm->getLocation().isValid())
3163           Diag(Warnings[Warn].OldParm->getLocation(),
3164                diag::note_previous_declaration);
3165       }
3166 
3167       if (MergeTypeWithOld)
3168         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3169                                              OldProto->getExtProtoInfo()));
3170       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3171     }
3172 
3173     // Fall through to diagnose conflicting types.
3174   }
3175 
3176   // A function that has already been declared has been redeclared or
3177   // defined with a different type; show an appropriate diagnostic.
3178 
3179   // If the previous declaration was an implicitly-generated builtin
3180   // declaration, then at the very least we should use a specialized note.
3181   unsigned BuiltinID;
3182   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3183     // If it's actually a library-defined builtin function like 'malloc'
3184     // or 'printf', just warn about the incompatible redeclaration.
3185     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3186       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3187       Diag(OldLocation, diag::note_previous_builtin_declaration)
3188         << Old << Old->getType();
3189 
3190       // If this is a global redeclaration, just forget hereafter
3191       // about the "builtin-ness" of the function.
3192       //
3193       // Doing this for local extern declarations is problematic.  If
3194       // the builtin declaration remains visible, a second invalid
3195       // local declaration will produce a hard error; if it doesn't
3196       // remain visible, a single bogus local redeclaration (which is
3197       // actually only a warning) could break all the downstream code.
3198       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3199         New->getIdentifier()->revertBuiltin();
3200 
3201       return false;
3202     }
3203 
3204     PrevDiag = diag::note_previous_builtin_declaration;
3205   }
3206 
3207   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3208   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3209   return true;
3210 }
3211 
3212 /// \brief Completes the merge of two function declarations that are
3213 /// known to be compatible.
3214 ///
3215 /// This routine handles the merging of attributes and other
3216 /// properties of function declarations from the old declaration to
3217 /// the new declaration, once we know that New is in fact a
3218 /// redeclaration of Old.
3219 ///
3220 /// \returns false
3221 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3222                                         Scope *S, bool MergeTypeWithOld) {
3223   // Merge the attributes
3224   mergeDeclAttributes(New, Old);
3225 
3226   // Merge "pure" flag.
3227   if (Old->isPure())
3228     New->setPure();
3229 
3230   // Merge "used" flag.
3231   if (Old->getMostRecentDecl()->isUsed(false))
3232     New->setIsUsed();
3233 
3234   // Merge attributes from the parameters.  These can mismatch with K&R
3235   // declarations.
3236   if (New->getNumParams() == Old->getNumParams())
3237       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3238         ParmVarDecl *NewParam = New->getParamDecl(i);
3239         ParmVarDecl *OldParam = Old->getParamDecl(i);
3240         mergeParamDeclAttributes(NewParam, OldParam, *this);
3241         mergeParamDeclTypes(NewParam, OldParam, *this);
3242       }
3243 
3244   if (getLangOpts().CPlusPlus)
3245     return MergeCXXFunctionDecl(New, Old, S);
3246 
3247   // Merge the function types so the we get the composite types for the return
3248   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3249   // was visible.
3250   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3251   if (!Merged.isNull() && MergeTypeWithOld)
3252     New->setType(Merged);
3253 
3254   return false;
3255 }
3256 
3257 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3258                                 ObjCMethodDecl *oldMethod) {
3259   // Merge the attributes, including deprecated/unavailable
3260   AvailabilityMergeKind MergeKind =
3261     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3262       ? AMK_ProtocolImplementation
3263       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3264                                                        : AMK_Override;
3265 
3266   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3267 
3268   // Merge attributes from the parameters.
3269   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3270                                        oe = oldMethod->param_end();
3271   for (ObjCMethodDecl::param_iterator
3272          ni = newMethod->param_begin(), ne = newMethod->param_end();
3273        ni != ne && oi != oe; ++ni, ++oi)
3274     mergeParamDeclAttributes(*ni, *oi, *this);
3275 
3276   CheckObjCMethodOverride(newMethod, oldMethod);
3277 }
3278 
3279 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3280   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3281 
3282   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3283          ? diag::err_redefinition_different_type
3284          : diag::err_redeclaration_different_type)
3285     << New->getDeclName() << New->getType() << Old->getType();
3286 
3287   diag::kind PrevDiag;
3288   SourceLocation OldLocation;
3289   std::tie(PrevDiag, OldLocation)
3290     = getNoteDiagForInvalidRedeclaration(Old, New);
3291   S.Diag(OldLocation, PrevDiag);
3292   New->setInvalidDecl();
3293 }
3294 
3295 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3296 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3297 /// emitting diagnostics as appropriate.
3298 ///
3299 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3300 /// to here in AddInitializerToDecl. We can't check them before the initializer
3301 /// is attached.
3302 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3303                              bool MergeTypeWithOld) {
3304   if (New->isInvalidDecl() || Old->isInvalidDecl())
3305     return;
3306 
3307   QualType MergedT;
3308   if (getLangOpts().CPlusPlus) {
3309     if (New->getType()->isUndeducedType()) {
3310       // We don't know what the new type is until the initializer is attached.
3311       return;
3312     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3313       // These could still be something that needs exception specs checked.
3314       return MergeVarDeclExceptionSpecs(New, Old);
3315     }
3316     // C++ [basic.link]p10:
3317     //   [...] the types specified by all declarations referring to a given
3318     //   object or function shall be identical, except that declarations for an
3319     //   array object can specify array types that differ by the presence or
3320     //   absence of a major array bound (8.3.4).
3321     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3322       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3323       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3324 
3325       // We are merging a variable declaration New into Old. If it has an array
3326       // bound, and that bound differs from Old's bound, we should diagnose the
3327       // mismatch.
3328       if (!NewArray->isIncompleteArrayType()) {
3329         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3330              PrevVD = PrevVD->getPreviousDecl()) {
3331           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3332           if (PrevVDTy->isIncompleteArrayType())
3333             continue;
3334 
3335           if (!Context.hasSameType(NewArray, PrevVDTy))
3336             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3337         }
3338       }
3339 
3340       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3341         if (Context.hasSameType(OldArray->getElementType(),
3342                                 NewArray->getElementType()))
3343           MergedT = New->getType();
3344       }
3345       // FIXME: Check visibility. New is hidden but has a complete type. If New
3346       // has no array bound, it should not inherit one from Old, if Old is not
3347       // visible.
3348       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3349         if (Context.hasSameType(OldArray->getElementType(),
3350                                 NewArray->getElementType()))
3351           MergedT = Old->getType();
3352       }
3353     }
3354     else if (New->getType()->isObjCObjectPointerType() &&
3355                Old->getType()->isObjCObjectPointerType()) {
3356       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3357                                               Old->getType());
3358     }
3359   } else {
3360     // C 6.2.7p2:
3361     //   All declarations that refer to the same object or function shall have
3362     //   compatible type.
3363     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3364   }
3365   if (MergedT.isNull()) {
3366     // It's OK if we couldn't merge types if either type is dependent, for a
3367     // block-scope variable. In other cases (static data members of class
3368     // templates, variable templates, ...), we require the types to be
3369     // equivalent.
3370     // FIXME: The C++ standard doesn't say anything about this.
3371     if ((New->getType()->isDependentType() ||
3372          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3373       // If the old type was dependent, we can't merge with it, so the new type
3374       // becomes dependent for now. We'll reproduce the original type when we
3375       // instantiate the TypeSourceInfo for the variable.
3376       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3377         New->setType(Context.DependentTy);
3378       return;
3379     }
3380     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3381   }
3382 
3383   // Don't actually update the type on the new declaration if the old
3384   // declaration was an extern declaration in a different scope.
3385   if (MergeTypeWithOld)
3386     New->setType(MergedT);
3387 }
3388 
3389 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3390                                   LookupResult &Previous) {
3391   // C11 6.2.7p4:
3392   //   For an identifier with internal or external linkage declared
3393   //   in a scope in which a prior declaration of that identifier is
3394   //   visible, if the prior declaration specifies internal or
3395   //   external linkage, the type of the identifier at the later
3396   //   declaration becomes the composite type.
3397   //
3398   // If the variable isn't visible, we do not merge with its type.
3399   if (Previous.isShadowed())
3400     return false;
3401 
3402   if (S.getLangOpts().CPlusPlus) {
3403     // C++11 [dcl.array]p3:
3404     //   If there is a preceding declaration of the entity in the same
3405     //   scope in which the bound was specified, an omitted array bound
3406     //   is taken to be the same as in that earlier declaration.
3407     return NewVD->isPreviousDeclInSameBlockScope() ||
3408            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3409             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3410   } else {
3411     // If the old declaration was function-local, don't merge with its
3412     // type unless we're in the same function.
3413     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3414            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3415   }
3416 }
3417 
3418 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3419 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3420 /// situation, merging decls or emitting diagnostics as appropriate.
3421 ///
3422 /// Tentative definition rules (C99 6.9.2p2) are checked by
3423 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3424 /// definitions here, since the initializer hasn't been attached.
3425 ///
3426 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3427   // If the new decl is already invalid, don't do any other checking.
3428   if (New->isInvalidDecl())
3429     return;
3430 
3431   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3432     return;
3433 
3434   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3435 
3436   // Verify the old decl was also a variable or variable template.
3437   VarDecl *Old = nullptr;
3438   VarTemplateDecl *OldTemplate = nullptr;
3439   if (Previous.isSingleResult()) {
3440     if (NewTemplate) {
3441       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3442       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3443 
3444       if (auto *Shadow =
3445               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3446         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3447           return New->setInvalidDecl();
3448     } else {
3449       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3450 
3451       if (auto *Shadow =
3452               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3453         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3454           return New->setInvalidDecl();
3455     }
3456   }
3457   if (!Old) {
3458     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3459       << New->getDeclName();
3460     Diag(Previous.getRepresentativeDecl()->getLocation(),
3461          diag::note_previous_definition);
3462     return New->setInvalidDecl();
3463   }
3464 
3465   // Ensure the template parameters are compatible.
3466   if (NewTemplate &&
3467       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3468                                       OldTemplate->getTemplateParameters(),
3469                                       /*Complain=*/true, TPL_TemplateMatch))
3470     return New->setInvalidDecl();
3471 
3472   // C++ [class.mem]p1:
3473   //   A member shall not be declared twice in the member-specification [...]
3474   //
3475   // Here, we need only consider static data members.
3476   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3477     Diag(New->getLocation(), diag::err_duplicate_member)
3478       << New->getIdentifier();
3479     Diag(Old->getLocation(), diag::note_previous_declaration);
3480     New->setInvalidDecl();
3481   }
3482 
3483   mergeDeclAttributes(New, Old);
3484   // Warn if an already-declared variable is made a weak_import in a subsequent
3485   // declaration
3486   if (New->hasAttr<WeakImportAttr>() &&
3487       Old->getStorageClass() == SC_None &&
3488       !Old->hasAttr<WeakImportAttr>()) {
3489     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3490     Diag(Old->getLocation(), diag::note_previous_definition);
3491     // Remove weak_import attribute on new declaration.
3492     New->dropAttr<WeakImportAttr>();
3493   }
3494 
3495   if (New->hasAttr<InternalLinkageAttr>() &&
3496       !Old->hasAttr<InternalLinkageAttr>()) {
3497     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3498         << New->getDeclName();
3499     Diag(Old->getLocation(), diag::note_previous_definition);
3500     New->dropAttr<InternalLinkageAttr>();
3501   }
3502 
3503   // Merge the types.
3504   VarDecl *MostRecent = Old->getMostRecentDecl();
3505   if (MostRecent != Old) {
3506     MergeVarDeclTypes(New, MostRecent,
3507                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3508     if (New->isInvalidDecl())
3509       return;
3510   }
3511 
3512   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3513   if (New->isInvalidDecl())
3514     return;
3515 
3516   diag::kind PrevDiag;
3517   SourceLocation OldLocation;
3518   std::tie(PrevDiag, OldLocation) =
3519       getNoteDiagForInvalidRedeclaration(Old, New);
3520 
3521   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3522   if (New->getStorageClass() == SC_Static &&
3523       !New->isStaticDataMember() &&
3524       Old->hasExternalFormalLinkage()) {
3525     if (getLangOpts().MicrosoftExt) {
3526       Diag(New->getLocation(), diag::ext_static_non_static)
3527           << New->getDeclName();
3528       Diag(OldLocation, PrevDiag);
3529     } else {
3530       Diag(New->getLocation(), diag::err_static_non_static)
3531           << New->getDeclName();
3532       Diag(OldLocation, PrevDiag);
3533       return New->setInvalidDecl();
3534     }
3535   }
3536   // C99 6.2.2p4:
3537   //   For an identifier declared with the storage-class specifier
3538   //   extern in a scope in which a prior declaration of that
3539   //   identifier is visible,23) if the prior declaration specifies
3540   //   internal or external linkage, the linkage of the identifier at
3541   //   the later declaration is the same as the linkage specified at
3542   //   the prior declaration. If no prior declaration is visible, or
3543   //   if the prior declaration specifies no linkage, then the
3544   //   identifier has external linkage.
3545   if (New->hasExternalStorage() && Old->hasLinkage())
3546     /* Okay */;
3547   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3548            !New->isStaticDataMember() &&
3549            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3550     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3551     Diag(OldLocation, PrevDiag);
3552     return New->setInvalidDecl();
3553   }
3554 
3555   // Check if extern is followed by non-extern and vice-versa.
3556   if (New->hasExternalStorage() &&
3557       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3558     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3559     Diag(OldLocation, PrevDiag);
3560     return New->setInvalidDecl();
3561   }
3562   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3563       !New->hasExternalStorage()) {
3564     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3565     Diag(OldLocation, PrevDiag);
3566     return New->setInvalidDecl();
3567   }
3568 
3569   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3570 
3571   // FIXME: The test for external storage here seems wrong? We still
3572   // need to check for mismatches.
3573   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3574       // Don't complain about out-of-line definitions of static members.
3575       !(Old->getLexicalDeclContext()->isRecord() &&
3576         !New->getLexicalDeclContext()->isRecord())) {
3577     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3578     Diag(OldLocation, PrevDiag);
3579     return New->setInvalidDecl();
3580   }
3581 
3582   if (New->getTLSKind() != Old->getTLSKind()) {
3583     if (!Old->getTLSKind()) {
3584       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3585       Diag(OldLocation, PrevDiag);
3586     } else if (!New->getTLSKind()) {
3587       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3588       Diag(OldLocation, PrevDiag);
3589     } else {
3590       // Do not allow redeclaration to change the variable between requiring
3591       // static and dynamic initialization.
3592       // FIXME: GCC allows this, but uses the TLS keyword on the first
3593       // declaration to determine the kind. Do we need to be compatible here?
3594       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3595         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3596       Diag(OldLocation, PrevDiag);
3597     }
3598   }
3599 
3600   // C++ doesn't have tentative definitions, so go right ahead and check here.
3601   VarDecl *Def;
3602   if (getLangOpts().CPlusPlus &&
3603       New->isThisDeclarationADefinition() == VarDecl::Definition &&
3604       (Def = Old->getDefinition())) {
3605     NamedDecl *Hidden = nullptr;
3606     if (!hasVisibleDefinition(Def, &Hidden) &&
3607         (New->getFormalLinkage() == InternalLinkage ||
3608          New->getDescribedVarTemplate() ||
3609          New->getNumTemplateParameterLists() ||
3610          New->getDeclContext()->isDependentContext())) {
3611       // The previous definition is hidden, and multiple definitions are
3612       // permitted (in separate TUs). Form another definition of it.
3613     } else {
3614       Diag(New->getLocation(), diag::err_redefinition) << New;
3615       Diag(Def->getLocation(), diag::note_previous_definition);
3616       New->setInvalidDecl();
3617       return;
3618     }
3619   }
3620 
3621   if (haveIncompatibleLanguageLinkages(Old, New)) {
3622     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3623     Diag(OldLocation, PrevDiag);
3624     New->setInvalidDecl();
3625     return;
3626   }
3627 
3628   // Merge "used" flag.
3629   if (Old->getMostRecentDecl()->isUsed(false))
3630     New->setIsUsed();
3631 
3632   // Keep a chain of previous declarations.
3633   New->setPreviousDecl(Old);
3634   if (NewTemplate)
3635     NewTemplate->setPreviousDecl(OldTemplate);
3636 
3637   // Inherit access appropriately.
3638   New->setAccess(Old->getAccess());
3639   if (NewTemplate)
3640     NewTemplate->setAccess(New->getAccess());
3641 }
3642 
3643 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3644 /// no declarator (e.g. "struct foo;") is parsed.
3645 Decl *
3646 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3647                                  RecordDecl *&AnonRecord) {
3648   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3649                                     AnonRecord);
3650 }
3651 
3652 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3653 // disambiguate entities defined in different scopes.
3654 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3655 // compatibility.
3656 // We will pick our mangling number depending on which version of MSVC is being
3657 // targeted.
3658 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3659   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3660              ? S->getMSCurManglingNumber()
3661              : S->getMSLastManglingNumber();
3662 }
3663 
3664 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3665   if (!Context.getLangOpts().CPlusPlus)
3666     return;
3667 
3668   if (isa<CXXRecordDecl>(Tag->getParent())) {
3669     // If this tag is the direct child of a class, number it if
3670     // it is anonymous.
3671     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3672       return;
3673     MangleNumberingContext &MCtx =
3674         Context.getManglingNumberContext(Tag->getParent());
3675     Context.setManglingNumber(
3676         Tag, MCtx.getManglingNumber(
3677                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3678     return;
3679   }
3680 
3681   // If this tag isn't a direct child of a class, number it if it is local.
3682   Decl *ManglingContextDecl;
3683   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3684           Tag->getDeclContext(), ManglingContextDecl)) {
3685     Context.setManglingNumber(
3686         Tag, MCtx->getManglingNumber(
3687                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3688   }
3689 }
3690 
3691 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3692                                         TypedefNameDecl *NewTD) {
3693   if (TagFromDeclSpec->isInvalidDecl())
3694     return;
3695 
3696   // Do nothing if the tag already has a name for linkage purposes.
3697   if (TagFromDeclSpec->hasNameForLinkage())
3698     return;
3699 
3700   // A well-formed anonymous tag must always be a TUK_Definition.
3701   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3702 
3703   // The type must match the tag exactly;  no qualifiers allowed.
3704   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3705                            Context.getTagDeclType(TagFromDeclSpec))) {
3706     if (getLangOpts().CPlusPlus)
3707       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3708     return;
3709   }
3710 
3711   // If we've already computed linkage for the anonymous tag, then
3712   // adding a typedef name for the anonymous decl can change that
3713   // linkage, which might be a serious problem.  Diagnose this as
3714   // unsupported and ignore the typedef name.  TODO: we should
3715   // pursue this as a language defect and establish a formal rule
3716   // for how to handle it.
3717   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3718     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3719 
3720     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3721     tagLoc = getLocForEndOfToken(tagLoc);
3722 
3723     llvm::SmallString<40> textToInsert;
3724     textToInsert += ' ';
3725     textToInsert += NewTD->getIdentifier()->getName();
3726     Diag(tagLoc, diag::note_typedef_changes_linkage)
3727         << FixItHint::CreateInsertion(tagLoc, textToInsert);
3728     return;
3729   }
3730 
3731   // Otherwise, set this is the anon-decl typedef for the tag.
3732   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3733 }
3734 
3735 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3736   switch (T) {
3737   case DeclSpec::TST_class:
3738     return 0;
3739   case DeclSpec::TST_struct:
3740     return 1;
3741   case DeclSpec::TST_interface:
3742     return 2;
3743   case DeclSpec::TST_union:
3744     return 3;
3745   case DeclSpec::TST_enum:
3746     return 4;
3747   default:
3748     llvm_unreachable("unexpected type specifier");
3749   }
3750 }
3751 
3752 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3753 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3754 /// parameters to cope with template friend declarations.
3755 Decl *
3756 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3757                                  MultiTemplateParamsArg TemplateParams,
3758                                  bool IsExplicitInstantiation,
3759                                  RecordDecl *&AnonRecord) {
3760   Decl *TagD = nullptr;
3761   TagDecl *Tag = nullptr;
3762   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3763       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3764       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3765       DS.getTypeSpecType() == DeclSpec::TST_union ||
3766       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3767     TagD = DS.getRepAsDecl();
3768 
3769     if (!TagD) // We probably had an error
3770       return nullptr;
3771 
3772     // Note that the above type specs guarantee that the
3773     // type rep is a Decl, whereas in many of the others
3774     // it's a Type.
3775     if (isa<TagDecl>(TagD))
3776       Tag = cast<TagDecl>(TagD);
3777     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3778       Tag = CTD->getTemplatedDecl();
3779   }
3780 
3781   if (Tag) {
3782     handleTagNumbering(Tag, S);
3783     Tag->setFreeStanding();
3784     if (Tag->isInvalidDecl())
3785       return Tag;
3786   }
3787 
3788   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3789     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3790     // or incomplete types shall not be restrict-qualified."
3791     if (TypeQuals & DeclSpec::TQ_restrict)
3792       Diag(DS.getRestrictSpecLoc(),
3793            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3794            << DS.getSourceRange();
3795   }
3796 
3797   if (DS.isConstexprSpecified()) {
3798     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3799     // and definitions of functions and variables.
3800     if (Tag)
3801       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3802           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3803     else
3804       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3805     // Don't emit warnings after this error.
3806     return TagD;
3807   }
3808 
3809   if (DS.isConceptSpecified()) {
3810     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3811     // either a function concept and its definition or a variable concept and
3812     // its initializer.
3813     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3814     return TagD;
3815   }
3816 
3817   DiagnoseFunctionSpecifiers(DS);
3818 
3819   if (DS.isFriendSpecified()) {
3820     // If we're dealing with a decl but not a TagDecl, assume that
3821     // whatever routines created it handled the friendship aspect.
3822     if (TagD && !Tag)
3823       return nullptr;
3824     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3825   }
3826 
3827   const CXXScopeSpec &SS = DS.getTypeSpecScope();
3828   bool IsExplicitSpecialization =
3829     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3830   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3831       !IsExplicitInstantiation && !IsExplicitSpecialization &&
3832       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
3833     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3834     // nested-name-specifier unless it is an explicit instantiation
3835     // or an explicit specialization.
3836     //
3837     // FIXME: We allow class template partial specializations here too, per the
3838     // obvious intent of DR1819.
3839     //
3840     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3841     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3842         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
3843     return nullptr;
3844   }
3845 
3846   // Track whether this decl-specifier declares anything.
3847   bool DeclaresAnything = true;
3848 
3849   // Handle anonymous struct definitions.
3850   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3851     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3852         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3853       if (getLangOpts().CPlusPlus ||
3854           Record->getDeclContext()->isRecord()) {
3855         // If CurContext is a DeclContext that can contain statements,
3856         // RecursiveASTVisitor won't visit the decls that
3857         // BuildAnonymousStructOrUnion() will put into CurContext.
3858         // Also store them here so that they can be part of the
3859         // DeclStmt that gets created in this case.
3860         // FIXME: Also return the IndirectFieldDecls created by
3861         // BuildAnonymousStructOr union, for the same reason?
3862         if (CurContext->isFunctionOrMethod())
3863           AnonRecord = Record;
3864         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3865                                            Context.getPrintingPolicy());
3866       }
3867 
3868       DeclaresAnything = false;
3869     }
3870   }
3871 
3872   // C11 6.7.2.1p2:
3873   //   A struct-declaration that does not declare an anonymous structure or
3874   //   anonymous union shall contain a struct-declarator-list.
3875   //
3876   // This rule also existed in C89 and C99; the grammar for struct-declaration
3877   // did not permit a struct-declaration without a struct-declarator-list.
3878   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3879       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3880     // Check for Microsoft C extension: anonymous struct/union member.
3881     // Handle 2 kinds of anonymous struct/union:
3882     //   struct STRUCT;
3883     //   union UNION;
3884     // and
3885     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3886     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
3887     if ((Tag && Tag->getDeclName()) ||
3888         DS.getTypeSpecType() == DeclSpec::TST_typename) {
3889       RecordDecl *Record = nullptr;
3890       if (Tag)
3891         Record = dyn_cast<RecordDecl>(Tag);
3892       else if (const RecordType *RT =
3893                    DS.getRepAsType().get()->getAsStructureType())
3894         Record = RT->getDecl();
3895       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3896         Record = UT->getDecl();
3897 
3898       if (Record && getLangOpts().MicrosoftExt) {
3899         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3900           << Record->isUnion() << DS.getSourceRange();
3901         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3902       }
3903 
3904       DeclaresAnything = false;
3905     }
3906   }
3907 
3908   // Skip all the checks below if we have a type error.
3909   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3910       (TagD && TagD->isInvalidDecl()))
3911     return TagD;
3912 
3913   if (getLangOpts().CPlusPlus &&
3914       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3915     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3916       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3917           !Enum->getIdentifier() && !Enum->isInvalidDecl())
3918         DeclaresAnything = false;
3919 
3920   if (!DS.isMissingDeclaratorOk()) {
3921     // Customize diagnostic for a typedef missing a name.
3922     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3923       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3924         << DS.getSourceRange();
3925     else
3926       DeclaresAnything = false;
3927   }
3928 
3929   if (DS.isModulePrivateSpecified() &&
3930       Tag && Tag->getDeclContext()->isFunctionOrMethod())
3931     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3932       << Tag->getTagKind()
3933       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3934 
3935   ActOnDocumentableDecl(TagD);
3936 
3937   // C 6.7/2:
3938   //   A declaration [...] shall declare at least a declarator [...], a tag,
3939   //   or the members of an enumeration.
3940   // C++ [dcl.dcl]p3:
3941   //   [If there are no declarators], and except for the declaration of an
3942   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
3943   //   names into the program, or shall redeclare a name introduced by a
3944   //   previous declaration.
3945   if (!DeclaresAnything) {
3946     // In C, we allow this as a (popular) extension / bug. Don't bother
3947     // producing further diagnostics for redundant qualifiers after this.
3948     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3949     return TagD;
3950   }
3951 
3952   // C++ [dcl.stc]p1:
3953   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3954   //   init-declarator-list of the declaration shall not be empty.
3955   // C++ [dcl.fct.spec]p1:
3956   //   If a cv-qualifier appears in a decl-specifier-seq, the
3957   //   init-declarator-list of the declaration shall not be empty.
3958   //
3959   // Spurious qualifiers here appear to be valid in C.
3960   unsigned DiagID = diag::warn_standalone_specifier;
3961   if (getLangOpts().CPlusPlus)
3962     DiagID = diag::ext_standalone_specifier;
3963 
3964   // Note that a linkage-specification sets a storage class, but
3965   // 'extern "C" struct foo;' is actually valid and not theoretically
3966   // useless.
3967   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3968     if (SCS == DeclSpec::SCS_mutable)
3969       // Since mutable is not a viable storage class specifier in C, there is
3970       // no reason to treat it as an extension. Instead, diagnose as an error.
3971       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
3972     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3973       Diag(DS.getStorageClassSpecLoc(), DiagID)
3974         << DeclSpec::getSpecifierName(SCS);
3975   }
3976 
3977   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3978     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3979       << DeclSpec::getSpecifierName(TSCS);
3980   if (DS.getTypeQualifiers()) {
3981     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3982       Diag(DS.getConstSpecLoc(), DiagID) << "const";
3983     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3984       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3985     // Restrict is covered above.
3986     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3987       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3988     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
3989       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
3990   }
3991 
3992   // Warn about ignored type attributes, for example:
3993   // __attribute__((aligned)) struct A;
3994   // Attributes should be placed after tag to apply to type declaration.
3995   if (!DS.getAttributes().empty()) {
3996     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3997     if (TypeSpecType == DeclSpec::TST_class ||
3998         TypeSpecType == DeclSpec::TST_struct ||
3999         TypeSpecType == DeclSpec::TST_interface ||
4000         TypeSpecType == DeclSpec::TST_union ||
4001         TypeSpecType == DeclSpec::TST_enum) {
4002       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4003            attrs = attrs->getNext())
4004         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4005             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4006     }
4007   }
4008 
4009   return TagD;
4010 }
4011 
4012 /// We are trying to inject an anonymous member into the given scope;
4013 /// check if there's an existing declaration that can't be overloaded.
4014 ///
4015 /// \return true if this is a forbidden redeclaration
4016 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4017                                          Scope *S,
4018                                          DeclContext *Owner,
4019                                          DeclarationName Name,
4020                                          SourceLocation NameLoc,
4021                                          bool IsUnion) {
4022   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4023                  Sema::ForRedeclaration);
4024   if (!SemaRef.LookupName(R, S)) return false;
4025 
4026   // Pick a representative declaration.
4027   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4028   assert(PrevDecl && "Expected a non-null Decl");
4029 
4030   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4031     return false;
4032 
4033   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4034     << IsUnion << Name;
4035   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4036 
4037   return true;
4038 }
4039 
4040 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4041 /// anonymous struct or union AnonRecord into the owning context Owner
4042 /// and scope S. This routine will be invoked just after we realize
4043 /// that an unnamed union or struct is actually an anonymous union or
4044 /// struct, e.g.,
4045 ///
4046 /// @code
4047 /// union {
4048 ///   int i;
4049 ///   float f;
4050 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4051 ///    // f into the surrounding scope.x
4052 /// @endcode
4053 ///
4054 /// This routine is recursive, injecting the names of nested anonymous
4055 /// structs/unions into the owning context and scope as well.
4056 static bool
4057 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4058                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4059                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4060   bool Invalid = false;
4061 
4062   // Look every FieldDecl and IndirectFieldDecl with a name.
4063   for (auto *D : AnonRecord->decls()) {
4064     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4065         cast<NamedDecl>(D)->getDeclName()) {
4066       ValueDecl *VD = cast<ValueDecl>(D);
4067       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4068                                        VD->getLocation(),
4069                                        AnonRecord->isUnion())) {
4070         // C++ [class.union]p2:
4071         //   The names of the members of an anonymous union shall be
4072         //   distinct from the names of any other entity in the
4073         //   scope in which the anonymous union is declared.
4074         Invalid = true;
4075       } else {
4076         // C++ [class.union]p2:
4077         //   For the purpose of name lookup, after the anonymous union
4078         //   definition, the members of the anonymous union are
4079         //   considered to have been defined in the scope in which the
4080         //   anonymous union is declared.
4081         unsigned OldChainingSize = Chaining.size();
4082         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4083           Chaining.append(IF->chain_begin(), IF->chain_end());
4084         else
4085           Chaining.push_back(VD);
4086 
4087         assert(Chaining.size() >= 2);
4088         NamedDecl **NamedChain =
4089           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4090         for (unsigned i = 0; i < Chaining.size(); i++)
4091           NamedChain[i] = Chaining[i];
4092 
4093         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4094             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4095             VD->getType(), NamedChain, Chaining.size());
4096 
4097         for (const auto *Attr : VD->attrs())
4098           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4099 
4100         IndirectField->setAccess(AS);
4101         IndirectField->setImplicit();
4102         SemaRef.PushOnScopeChains(IndirectField, S);
4103 
4104         // That includes picking up the appropriate access specifier.
4105         if (AS != AS_none) IndirectField->setAccess(AS);
4106 
4107         Chaining.resize(OldChainingSize);
4108       }
4109     }
4110   }
4111 
4112   return Invalid;
4113 }
4114 
4115 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4116 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4117 /// illegal input values are mapped to SC_None.
4118 static StorageClass
4119 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4120   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4121   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4122          "Parser allowed 'typedef' as storage class VarDecl.");
4123   switch (StorageClassSpec) {
4124   case DeclSpec::SCS_unspecified:    return SC_None;
4125   case DeclSpec::SCS_extern:
4126     if (DS.isExternInLinkageSpec())
4127       return SC_None;
4128     return SC_Extern;
4129   case DeclSpec::SCS_static:         return SC_Static;
4130   case DeclSpec::SCS_auto:           return SC_Auto;
4131   case DeclSpec::SCS_register:       return SC_Register;
4132   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4133     // Illegal SCSs map to None: error reporting is up to the caller.
4134   case DeclSpec::SCS_mutable:        // Fall through.
4135   case DeclSpec::SCS_typedef:        return SC_None;
4136   }
4137   llvm_unreachable("unknown storage class specifier");
4138 }
4139 
4140 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4141   assert(Record->hasInClassInitializer());
4142 
4143   for (const auto *I : Record->decls()) {
4144     const auto *FD = dyn_cast<FieldDecl>(I);
4145     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4146       FD = IFD->getAnonField();
4147     if (FD && FD->hasInClassInitializer())
4148       return FD->getLocation();
4149   }
4150 
4151   llvm_unreachable("couldn't find in-class initializer");
4152 }
4153 
4154 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4155                                       SourceLocation DefaultInitLoc) {
4156   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4157     return;
4158 
4159   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4160   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4161 }
4162 
4163 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4164                                       CXXRecordDecl *AnonUnion) {
4165   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4166     return;
4167 
4168   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4169 }
4170 
4171 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4172 /// anonymous structure or union. Anonymous unions are a C++ feature
4173 /// (C++ [class.union]) and a C11 feature; anonymous structures
4174 /// are a C11 feature and GNU C++ extension.
4175 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4176                                         AccessSpecifier AS,
4177                                         RecordDecl *Record,
4178                                         const PrintingPolicy &Policy) {
4179   DeclContext *Owner = Record->getDeclContext();
4180 
4181   // Diagnose whether this anonymous struct/union is an extension.
4182   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4183     Diag(Record->getLocation(), diag::ext_anonymous_union);
4184   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4185     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4186   else if (!Record->isUnion() && !getLangOpts().C11)
4187     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4188 
4189   // C and C++ require different kinds of checks for anonymous
4190   // structs/unions.
4191   bool Invalid = false;
4192   if (getLangOpts().CPlusPlus) {
4193     const char *PrevSpec = nullptr;
4194     unsigned DiagID;
4195     if (Record->isUnion()) {
4196       // C++ [class.union]p6:
4197       //   Anonymous unions declared in a named namespace or in the
4198       //   global namespace shall be declared static.
4199       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4200           (isa<TranslationUnitDecl>(Owner) ||
4201            (isa<NamespaceDecl>(Owner) &&
4202             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4203         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4204           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4205 
4206         // Recover by adding 'static'.
4207         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4208                                PrevSpec, DiagID, Policy);
4209       }
4210       // C++ [class.union]p6:
4211       //   A storage class is not allowed in a declaration of an
4212       //   anonymous union in a class scope.
4213       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4214                isa<RecordDecl>(Owner)) {
4215         Diag(DS.getStorageClassSpecLoc(),
4216              diag::err_anonymous_union_with_storage_spec)
4217           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4218 
4219         // Recover by removing the storage specifier.
4220         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4221                                SourceLocation(),
4222                                PrevSpec, DiagID, Context.getPrintingPolicy());
4223       }
4224     }
4225 
4226     // Ignore const/volatile/restrict qualifiers.
4227     if (DS.getTypeQualifiers()) {
4228       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4229         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4230           << Record->isUnion() << "const"
4231           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4232       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4233         Diag(DS.getVolatileSpecLoc(),
4234              diag::ext_anonymous_struct_union_qualified)
4235           << Record->isUnion() << "volatile"
4236           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4237       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4238         Diag(DS.getRestrictSpecLoc(),
4239              diag::ext_anonymous_struct_union_qualified)
4240           << Record->isUnion() << "restrict"
4241           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4242       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4243         Diag(DS.getAtomicSpecLoc(),
4244              diag::ext_anonymous_struct_union_qualified)
4245           << Record->isUnion() << "_Atomic"
4246           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4247       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4248         Diag(DS.getUnalignedSpecLoc(),
4249              diag::ext_anonymous_struct_union_qualified)
4250           << Record->isUnion() << "__unaligned"
4251           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4252 
4253       DS.ClearTypeQualifiers();
4254     }
4255 
4256     // C++ [class.union]p2:
4257     //   The member-specification of an anonymous union shall only
4258     //   define non-static data members. [Note: nested types and
4259     //   functions cannot be declared within an anonymous union. ]
4260     for (auto *Mem : Record->decls()) {
4261       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4262         // C++ [class.union]p3:
4263         //   An anonymous union shall not have private or protected
4264         //   members (clause 11).
4265         assert(FD->getAccess() != AS_none);
4266         if (FD->getAccess() != AS_public) {
4267           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4268             << Record->isUnion() << (FD->getAccess() == AS_protected);
4269           Invalid = true;
4270         }
4271 
4272         // C++ [class.union]p1
4273         //   An object of a class with a non-trivial constructor, a non-trivial
4274         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4275         //   assignment operator cannot be a member of a union, nor can an
4276         //   array of such objects.
4277         if (CheckNontrivialField(FD))
4278           Invalid = true;
4279       } else if (Mem->isImplicit()) {
4280         // Any implicit members are fine.
4281       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4282         // This is a type that showed up in an
4283         // elaborated-type-specifier inside the anonymous struct or
4284         // union, but which actually declares a type outside of the
4285         // anonymous struct or union. It's okay.
4286       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4287         if (!MemRecord->isAnonymousStructOrUnion() &&
4288             MemRecord->getDeclName()) {
4289           // Visual C++ allows type definition in anonymous struct or union.
4290           if (getLangOpts().MicrosoftExt)
4291             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4292               << Record->isUnion();
4293           else {
4294             // This is a nested type declaration.
4295             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4296               << Record->isUnion();
4297             Invalid = true;
4298           }
4299         } else {
4300           // This is an anonymous type definition within another anonymous type.
4301           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4302           // not part of standard C++.
4303           Diag(MemRecord->getLocation(),
4304                diag::ext_anonymous_record_with_anonymous_type)
4305             << Record->isUnion();
4306         }
4307       } else if (isa<AccessSpecDecl>(Mem)) {
4308         // Any access specifier is fine.
4309       } else if (isa<StaticAssertDecl>(Mem)) {
4310         // In C++1z, static_assert declarations are also fine.
4311       } else {
4312         // We have something that isn't a non-static data
4313         // member. Complain about it.
4314         unsigned DK = diag::err_anonymous_record_bad_member;
4315         if (isa<TypeDecl>(Mem))
4316           DK = diag::err_anonymous_record_with_type;
4317         else if (isa<FunctionDecl>(Mem))
4318           DK = diag::err_anonymous_record_with_function;
4319         else if (isa<VarDecl>(Mem))
4320           DK = diag::err_anonymous_record_with_static;
4321 
4322         // Visual C++ allows type definition in anonymous struct or union.
4323         if (getLangOpts().MicrosoftExt &&
4324             DK == diag::err_anonymous_record_with_type)
4325           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4326             << Record->isUnion();
4327         else {
4328           Diag(Mem->getLocation(), DK) << Record->isUnion();
4329           Invalid = true;
4330         }
4331       }
4332     }
4333 
4334     // C++11 [class.union]p8 (DR1460):
4335     //   At most one variant member of a union may have a
4336     //   brace-or-equal-initializer.
4337     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4338         Owner->isRecord())
4339       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4340                                 cast<CXXRecordDecl>(Record));
4341   }
4342 
4343   if (!Record->isUnion() && !Owner->isRecord()) {
4344     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4345       << getLangOpts().CPlusPlus;
4346     Invalid = true;
4347   }
4348 
4349   // Mock up a declarator.
4350   Declarator Dc(DS, Declarator::MemberContext);
4351   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4352   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4353 
4354   // Create a declaration for this anonymous struct/union.
4355   NamedDecl *Anon = nullptr;
4356   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4357     Anon = FieldDecl::Create(Context, OwningClass,
4358                              DS.getLocStart(),
4359                              Record->getLocation(),
4360                              /*IdentifierInfo=*/nullptr,
4361                              Context.getTypeDeclType(Record),
4362                              TInfo,
4363                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4364                              /*InitStyle=*/ICIS_NoInit);
4365     Anon->setAccess(AS);
4366     if (getLangOpts().CPlusPlus)
4367       FieldCollector->Add(cast<FieldDecl>(Anon));
4368   } else {
4369     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4370     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4371     if (SCSpec == DeclSpec::SCS_mutable) {
4372       // mutable can only appear on non-static class members, so it's always
4373       // an error here
4374       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4375       Invalid = true;
4376       SC = SC_None;
4377     }
4378 
4379     Anon = VarDecl::Create(Context, Owner,
4380                            DS.getLocStart(),
4381                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4382                            Context.getTypeDeclType(Record),
4383                            TInfo, SC);
4384 
4385     // Default-initialize the implicit variable. This initialization will be
4386     // trivial in almost all cases, except if a union member has an in-class
4387     // initializer:
4388     //   union { int n = 0; };
4389     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4390   }
4391   Anon->setImplicit();
4392 
4393   // Mark this as an anonymous struct/union type.
4394   Record->setAnonymousStructOrUnion(true);
4395 
4396   // Add the anonymous struct/union object to the current
4397   // context. We'll be referencing this object when we refer to one of
4398   // its members.
4399   Owner->addDecl(Anon);
4400 
4401   // Inject the members of the anonymous struct/union into the owning
4402   // context and into the identifier resolver chain for name lookup
4403   // purposes.
4404   SmallVector<NamedDecl*, 2> Chain;
4405   Chain.push_back(Anon);
4406 
4407   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4408     Invalid = true;
4409 
4410   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4411     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4412       Decl *ManglingContextDecl;
4413       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4414               NewVD->getDeclContext(), ManglingContextDecl)) {
4415         Context.setManglingNumber(
4416             NewVD, MCtx->getManglingNumber(
4417                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4418         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4419       }
4420     }
4421   }
4422 
4423   if (Invalid)
4424     Anon->setInvalidDecl();
4425 
4426   return Anon;
4427 }
4428 
4429 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4430 /// Microsoft C anonymous structure.
4431 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4432 /// Example:
4433 ///
4434 /// struct A { int a; };
4435 /// struct B { struct A; int b; };
4436 ///
4437 /// void foo() {
4438 ///   B var;
4439 ///   var.a = 3;
4440 /// }
4441 ///
4442 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4443                                            RecordDecl *Record) {
4444   assert(Record && "expected a record!");
4445 
4446   // Mock up a declarator.
4447   Declarator Dc(DS, Declarator::TypeNameContext);
4448   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4449   assert(TInfo && "couldn't build declarator info for anonymous struct");
4450 
4451   auto *ParentDecl = cast<RecordDecl>(CurContext);
4452   QualType RecTy = Context.getTypeDeclType(Record);
4453 
4454   // Create a declaration for this anonymous struct.
4455   NamedDecl *Anon = FieldDecl::Create(Context,
4456                              ParentDecl,
4457                              DS.getLocStart(),
4458                              DS.getLocStart(),
4459                              /*IdentifierInfo=*/nullptr,
4460                              RecTy,
4461                              TInfo,
4462                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4463                              /*InitStyle=*/ICIS_NoInit);
4464   Anon->setImplicit();
4465 
4466   // Add the anonymous struct object to the current context.
4467   CurContext->addDecl(Anon);
4468 
4469   // Inject the members of the anonymous struct into the current
4470   // context and into the identifier resolver chain for name lookup
4471   // purposes.
4472   SmallVector<NamedDecl*, 2> Chain;
4473   Chain.push_back(Anon);
4474 
4475   RecordDecl *RecordDef = Record->getDefinition();
4476   if (RequireCompleteType(Anon->getLocation(), RecTy,
4477                           diag::err_field_incomplete) ||
4478       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4479                                           AS_none, Chain)) {
4480     Anon->setInvalidDecl();
4481     ParentDecl->setInvalidDecl();
4482   }
4483 
4484   return Anon;
4485 }
4486 
4487 /// GetNameForDeclarator - Determine the full declaration name for the
4488 /// given Declarator.
4489 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4490   return GetNameFromUnqualifiedId(D.getName());
4491 }
4492 
4493 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4494 DeclarationNameInfo
4495 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4496   DeclarationNameInfo NameInfo;
4497   NameInfo.setLoc(Name.StartLocation);
4498 
4499   switch (Name.getKind()) {
4500 
4501   case UnqualifiedId::IK_ImplicitSelfParam:
4502   case UnqualifiedId::IK_Identifier:
4503     NameInfo.setName(Name.Identifier);
4504     NameInfo.setLoc(Name.StartLocation);
4505     return NameInfo;
4506 
4507   case UnqualifiedId::IK_OperatorFunctionId:
4508     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4509                                            Name.OperatorFunctionId.Operator));
4510     NameInfo.setLoc(Name.StartLocation);
4511     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4512       = Name.OperatorFunctionId.SymbolLocations[0];
4513     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4514       = Name.EndLocation.getRawEncoding();
4515     return NameInfo;
4516 
4517   case UnqualifiedId::IK_LiteralOperatorId:
4518     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4519                                                            Name.Identifier));
4520     NameInfo.setLoc(Name.StartLocation);
4521     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4522     return NameInfo;
4523 
4524   case UnqualifiedId::IK_ConversionFunctionId: {
4525     TypeSourceInfo *TInfo;
4526     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4527     if (Ty.isNull())
4528       return DeclarationNameInfo();
4529     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4530                                                Context.getCanonicalType(Ty)));
4531     NameInfo.setLoc(Name.StartLocation);
4532     NameInfo.setNamedTypeInfo(TInfo);
4533     return NameInfo;
4534   }
4535 
4536   case UnqualifiedId::IK_ConstructorName: {
4537     TypeSourceInfo *TInfo;
4538     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4539     if (Ty.isNull())
4540       return DeclarationNameInfo();
4541     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4542                                               Context.getCanonicalType(Ty)));
4543     NameInfo.setLoc(Name.StartLocation);
4544     NameInfo.setNamedTypeInfo(TInfo);
4545     return NameInfo;
4546   }
4547 
4548   case UnqualifiedId::IK_ConstructorTemplateId: {
4549     // In well-formed code, we can only have a constructor
4550     // template-id that refers to the current context, so go there
4551     // to find the actual type being constructed.
4552     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4553     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4554       return DeclarationNameInfo();
4555 
4556     // Determine the type of the class being constructed.
4557     QualType CurClassType = Context.getTypeDeclType(CurClass);
4558 
4559     // FIXME: Check two things: that the template-id names the same type as
4560     // CurClassType, and that the template-id does not occur when the name
4561     // was qualified.
4562 
4563     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4564                                     Context.getCanonicalType(CurClassType)));
4565     NameInfo.setLoc(Name.StartLocation);
4566     // FIXME: should we retrieve TypeSourceInfo?
4567     NameInfo.setNamedTypeInfo(nullptr);
4568     return NameInfo;
4569   }
4570 
4571   case UnqualifiedId::IK_DestructorName: {
4572     TypeSourceInfo *TInfo;
4573     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4574     if (Ty.isNull())
4575       return DeclarationNameInfo();
4576     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4577                                               Context.getCanonicalType(Ty)));
4578     NameInfo.setLoc(Name.StartLocation);
4579     NameInfo.setNamedTypeInfo(TInfo);
4580     return NameInfo;
4581   }
4582 
4583   case UnqualifiedId::IK_TemplateId: {
4584     TemplateName TName = Name.TemplateId->Template.get();
4585     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4586     return Context.getNameForTemplate(TName, TNameLoc);
4587   }
4588 
4589   } // switch (Name.getKind())
4590 
4591   llvm_unreachable("Unknown name kind");
4592 }
4593 
4594 static QualType getCoreType(QualType Ty) {
4595   do {
4596     if (Ty->isPointerType() || Ty->isReferenceType())
4597       Ty = Ty->getPointeeType();
4598     else if (Ty->isArrayType())
4599       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4600     else
4601       return Ty.withoutLocalFastQualifiers();
4602   } while (true);
4603 }
4604 
4605 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4606 /// and Definition have "nearly" matching parameters. This heuristic is
4607 /// used to improve diagnostics in the case where an out-of-line function
4608 /// definition doesn't match any declaration within the class or namespace.
4609 /// Also sets Params to the list of indices to the parameters that differ
4610 /// between the declaration and the definition. If hasSimilarParameters
4611 /// returns true and Params is empty, then all of the parameters match.
4612 static bool hasSimilarParameters(ASTContext &Context,
4613                                      FunctionDecl *Declaration,
4614                                      FunctionDecl *Definition,
4615                                      SmallVectorImpl<unsigned> &Params) {
4616   Params.clear();
4617   if (Declaration->param_size() != Definition->param_size())
4618     return false;
4619   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4620     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4621     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4622 
4623     // The parameter types are identical
4624     if (Context.hasSameType(DefParamTy, DeclParamTy))
4625       continue;
4626 
4627     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4628     QualType DefParamBaseTy = getCoreType(DefParamTy);
4629     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4630     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4631 
4632     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4633         (DeclTyName && DeclTyName == DefTyName))
4634       Params.push_back(Idx);
4635     else  // The two parameters aren't even close
4636       return false;
4637   }
4638 
4639   return true;
4640 }
4641 
4642 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4643 /// declarator needs to be rebuilt in the current instantiation.
4644 /// Any bits of declarator which appear before the name are valid for
4645 /// consideration here.  That's specifically the type in the decl spec
4646 /// and the base type in any member-pointer chunks.
4647 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4648                                                     DeclarationName Name) {
4649   // The types we specifically need to rebuild are:
4650   //   - typenames, typeofs, and decltypes
4651   //   - types which will become injected class names
4652   // Of course, we also need to rebuild any type referencing such a
4653   // type.  It's safest to just say "dependent", but we call out a
4654   // few cases here.
4655 
4656   DeclSpec &DS = D.getMutableDeclSpec();
4657   switch (DS.getTypeSpecType()) {
4658   case DeclSpec::TST_typename:
4659   case DeclSpec::TST_typeofType:
4660   case DeclSpec::TST_underlyingType:
4661   case DeclSpec::TST_atomic: {
4662     // Grab the type from the parser.
4663     TypeSourceInfo *TSI = nullptr;
4664     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4665     if (T.isNull() || !T->isDependentType()) break;
4666 
4667     // Make sure there's a type source info.  This isn't really much
4668     // of a waste; most dependent types should have type source info
4669     // attached already.
4670     if (!TSI)
4671       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4672 
4673     // Rebuild the type in the current instantiation.
4674     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4675     if (!TSI) return true;
4676 
4677     // Store the new type back in the decl spec.
4678     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4679     DS.UpdateTypeRep(LocType);
4680     break;
4681   }
4682 
4683   case DeclSpec::TST_decltype:
4684   case DeclSpec::TST_typeofExpr: {
4685     Expr *E = DS.getRepAsExpr();
4686     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4687     if (Result.isInvalid()) return true;
4688     DS.UpdateExprRep(Result.get());
4689     break;
4690   }
4691 
4692   default:
4693     // Nothing to do for these decl specs.
4694     break;
4695   }
4696 
4697   // It doesn't matter what order we do this in.
4698   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4699     DeclaratorChunk &Chunk = D.getTypeObject(I);
4700 
4701     // The only type information in the declarator which can come
4702     // before the declaration name is the base type of a member
4703     // pointer.
4704     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4705       continue;
4706 
4707     // Rebuild the scope specifier in-place.
4708     CXXScopeSpec &SS = Chunk.Mem.Scope();
4709     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4710       return true;
4711   }
4712 
4713   return false;
4714 }
4715 
4716 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4717   D.setFunctionDefinitionKind(FDK_Declaration);
4718   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4719 
4720   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4721       Dcl && Dcl->getDeclContext()->isFileContext())
4722     Dcl->setTopLevelDeclInObjCContainer();
4723 
4724   return Dcl;
4725 }
4726 
4727 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4728 ///   If T is the name of a class, then each of the following shall have a
4729 ///   name different from T:
4730 ///     - every static data member of class T;
4731 ///     - every member function of class T
4732 ///     - every member of class T that is itself a type;
4733 /// \returns true if the declaration name violates these rules.
4734 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4735                                    DeclarationNameInfo NameInfo) {
4736   DeclarationName Name = NameInfo.getName();
4737 
4738   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
4739   while (Record && Record->isAnonymousStructOrUnion())
4740     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
4741   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
4742     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4743     return true;
4744   }
4745 
4746   return false;
4747 }
4748 
4749 /// \brief Diagnose a declaration whose declarator-id has the given
4750 /// nested-name-specifier.
4751 ///
4752 /// \param SS The nested-name-specifier of the declarator-id.
4753 ///
4754 /// \param DC The declaration context to which the nested-name-specifier
4755 /// resolves.
4756 ///
4757 /// \param Name The name of the entity being declared.
4758 ///
4759 /// \param Loc The location of the name of the entity being declared.
4760 ///
4761 /// \returns true if we cannot safely recover from this error, false otherwise.
4762 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4763                                         DeclarationName Name,
4764                                         SourceLocation Loc) {
4765   DeclContext *Cur = CurContext;
4766   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4767     Cur = Cur->getParent();
4768 
4769   // If the user provided a superfluous scope specifier that refers back to the
4770   // class in which the entity is already declared, diagnose and ignore it.
4771   //
4772   // class X {
4773   //   void X::f();
4774   // };
4775   //
4776   // Note, it was once ill-formed to give redundant qualification in all
4777   // contexts, but that rule was removed by DR482.
4778   if (Cur->Equals(DC)) {
4779     if (Cur->isRecord()) {
4780       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4781                                       : diag::err_member_extra_qualification)
4782         << Name << FixItHint::CreateRemoval(SS.getRange());
4783       SS.clear();
4784     } else {
4785       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4786     }
4787     return false;
4788   }
4789 
4790   // Check whether the qualifying scope encloses the scope of the original
4791   // declaration.
4792   if (!Cur->Encloses(DC)) {
4793     if (Cur->isRecord())
4794       Diag(Loc, diag::err_member_qualification)
4795         << Name << SS.getRange();
4796     else if (isa<TranslationUnitDecl>(DC))
4797       Diag(Loc, diag::err_invalid_declarator_global_scope)
4798         << Name << SS.getRange();
4799     else if (isa<FunctionDecl>(Cur))
4800       Diag(Loc, diag::err_invalid_declarator_in_function)
4801         << Name << SS.getRange();
4802     else if (isa<BlockDecl>(Cur))
4803       Diag(Loc, diag::err_invalid_declarator_in_block)
4804         << Name << SS.getRange();
4805     else
4806       Diag(Loc, diag::err_invalid_declarator_scope)
4807       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4808 
4809     return true;
4810   }
4811 
4812   if (Cur->isRecord()) {
4813     // Cannot qualify members within a class.
4814     Diag(Loc, diag::err_member_qualification)
4815       << Name << SS.getRange();
4816     SS.clear();
4817 
4818     // C++ constructors and destructors with incorrect scopes can break
4819     // our AST invariants by having the wrong underlying types. If
4820     // that's the case, then drop this declaration entirely.
4821     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4822          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4823         !Context.hasSameType(Name.getCXXNameType(),
4824                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4825       return true;
4826 
4827     return false;
4828   }
4829 
4830   // C++11 [dcl.meaning]p1:
4831   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4832   //   not begin with a decltype-specifer"
4833   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4834   while (SpecLoc.getPrefix())
4835     SpecLoc = SpecLoc.getPrefix();
4836   if (dyn_cast_or_null<DecltypeType>(
4837         SpecLoc.getNestedNameSpecifier()->getAsType()))
4838     Diag(Loc, diag::err_decltype_in_declarator)
4839       << SpecLoc.getTypeLoc().getSourceRange();
4840 
4841   return false;
4842 }
4843 
4844 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4845                                   MultiTemplateParamsArg TemplateParamLists) {
4846   // TODO: consider using NameInfo for diagnostic.
4847   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4848   DeclarationName Name = NameInfo.getName();
4849 
4850   // All of these full declarators require an identifier.  If it doesn't have
4851   // one, the ParsedFreeStandingDeclSpec action should be used.
4852   if (!Name) {
4853     if (!D.isInvalidType())  // Reject this if we think it is valid.
4854       Diag(D.getDeclSpec().getLocStart(),
4855            diag::err_declarator_need_ident)
4856         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4857     return nullptr;
4858   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4859     return nullptr;
4860 
4861   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4862   // we find one that is.
4863   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4864          (S->getFlags() & Scope::TemplateParamScope) != 0)
4865     S = S->getParent();
4866 
4867   DeclContext *DC = CurContext;
4868   if (D.getCXXScopeSpec().isInvalid())
4869     D.setInvalidType();
4870   else if (D.getCXXScopeSpec().isSet()) {
4871     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4872                                         UPPC_DeclarationQualifier))
4873       return nullptr;
4874 
4875     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4876     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4877     if (!DC || isa<EnumDecl>(DC)) {
4878       // If we could not compute the declaration context, it's because the
4879       // declaration context is dependent but does not refer to a class,
4880       // class template, or class template partial specialization. Complain
4881       // and return early, to avoid the coming semantic disaster.
4882       Diag(D.getIdentifierLoc(),
4883            diag::err_template_qualified_declarator_no_match)
4884         << D.getCXXScopeSpec().getScopeRep()
4885         << D.getCXXScopeSpec().getRange();
4886       return nullptr;
4887     }
4888     bool IsDependentContext = DC->isDependentContext();
4889 
4890     if (!IsDependentContext &&
4891         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4892       return nullptr;
4893 
4894     // If a class is incomplete, do not parse entities inside it.
4895     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4896       Diag(D.getIdentifierLoc(),
4897            diag::err_member_def_undefined_record)
4898         << Name << DC << D.getCXXScopeSpec().getRange();
4899       return nullptr;
4900     }
4901     if (!D.getDeclSpec().isFriendSpecified()) {
4902       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4903                                       Name, D.getIdentifierLoc())) {
4904         if (DC->isRecord())
4905           return nullptr;
4906 
4907         D.setInvalidType();
4908       }
4909     }
4910 
4911     // Check whether we need to rebuild the type of the given
4912     // declaration in the current instantiation.
4913     if (EnteringContext && IsDependentContext &&
4914         TemplateParamLists.size() != 0) {
4915       ContextRAII SavedContext(*this, DC);
4916       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4917         D.setInvalidType();
4918     }
4919   }
4920 
4921   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4922   QualType R = TInfo->getType();
4923 
4924   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
4925     // If this is a typedef, we'll end up spewing multiple diagnostics.
4926     // Just return early; it's safer. If this is a function, let the
4927     // "constructor cannot have a return type" diagnostic handle it.
4928     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4929       return nullptr;
4930 
4931   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4932                                       UPPC_DeclarationType))
4933     D.setInvalidType();
4934 
4935   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4936                         ForRedeclaration);
4937 
4938   // See if this is a redefinition of a variable in the same scope.
4939   if (!D.getCXXScopeSpec().isSet()) {
4940     bool IsLinkageLookup = false;
4941     bool CreateBuiltins = false;
4942 
4943     // If the declaration we're planning to build will be a function
4944     // or object with linkage, then look for another declaration with
4945     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4946     //
4947     // If the declaration we're planning to build will be declared with
4948     // external linkage in the translation unit, create any builtin with
4949     // the same name.
4950     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4951       /* Do nothing*/;
4952     else if (CurContext->isFunctionOrMethod() &&
4953              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4954               R->isFunctionType())) {
4955       IsLinkageLookup = true;
4956       CreateBuiltins =
4957           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4958     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4959                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4960       CreateBuiltins = true;
4961 
4962     if (IsLinkageLookup)
4963       Previous.clear(LookupRedeclarationWithLinkage);
4964 
4965     LookupName(Previous, S, CreateBuiltins);
4966   } else { // Something like "int foo::x;"
4967     LookupQualifiedName(Previous, DC);
4968 
4969     // C++ [dcl.meaning]p1:
4970     //   When the declarator-id is qualified, the declaration shall refer to a
4971     //  previously declared member of the class or namespace to which the
4972     //  qualifier refers (or, in the case of a namespace, of an element of the
4973     //  inline namespace set of that namespace (7.3.1)) or to a specialization
4974     //  thereof; [...]
4975     //
4976     // Note that we already checked the context above, and that we do not have
4977     // enough information to make sure that Previous contains the declaration
4978     // we want to match. For example, given:
4979     //
4980     //   class X {
4981     //     void f();
4982     //     void f(float);
4983     //   };
4984     //
4985     //   void X::f(int) { } // ill-formed
4986     //
4987     // In this case, Previous will point to the overload set
4988     // containing the two f's declared in X, but neither of them
4989     // matches.
4990 
4991     // C++ [dcl.meaning]p1:
4992     //   [...] the member shall not merely have been introduced by a
4993     //   using-declaration in the scope of the class or namespace nominated by
4994     //   the nested-name-specifier of the declarator-id.
4995     RemoveUsingDecls(Previous);
4996   }
4997 
4998   if (Previous.isSingleResult() &&
4999       Previous.getFoundDecl()->isTemplateParameter()) {
5000     // Maybe we will complain about the shadowed template parameter.
5001     if (!D.isInvalidType())
5002       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5003                                       Previous.getFoundDecl());
5004 
5005     // Just pretend that we didn't see the previous declaration.
5006     Previous.clear();
5007   }
5008 
5009   // In C++, the previous declaration we find might be a tag type
5010   // (class or enum). In this case, the new declaration will hide the
5011   // tag type. Note that this does does not apply if we're declaring a
5012   // typedef (C++ [dcl.typedef]p4).
5013   if (Previous.isSingleTagDecl() &&
5014       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5015     Previous.clear();
5016 
5017   // Check that there are no default arguments other than in the parameters
5018   // of a function declaration (C++ only).
5019   if (getLangOpts().CPlusPlus)
5020     CheckExtraCXXDefaultArguments(D);
5021 
5022   if (D.getDeclSpec().isConceptSpecified()) {
5023     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5024     // applied only to the definition of a function template or variable
5025     // template, declared in namespace scope
5026     if (!TemplateParamLists.size()) {
5027       Diag(D.getDeclSpec().getConceptSpecLoc(),
5028            diag:: err_concept_wrong_decl_kind);
5029       return nullptr;
5030     }
5031 
5032     if (!DC->getRedeclContext()->isFileContext()) {
5033       Diag(D.getIdentifierLoc(),
5034            diag::err_concept_decls_may_only_appear_in_namespace_scope);
5035       return nullptr;
5036     }
5037   }
5038 
5039   NamedDecl *New;
5040 
5041   bool AddToScope = true;
5042   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5043     if (TemplateParamLists.size()) {
5044       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5045       return nullptr;
5046     }
5047 
5048     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5049   } else if (R->isFunctionType()) {
5050     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5051                                   TemplateParamLists,
5052                                   AddToScope);
5053   } else {
5054     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5055                                   AddToScope);
5056   }
5057 
5058   if (!New)
5059     return nullptr;
5060 
5061   // If this has an identifier and is not an invalid redeclaration or
5062   // function template specialization, add it to the scope stack.
5063   if (New->getDeclName() && AddToScope &&
5064        !(D.isRedeclaration() && New->isInvalidDecl())) {
5065     // Only make a locally-scoped extern declaration visible if it is the first
5066     // declaration of this entity. Qualified lookup for such an entity should
5067     // only find this declaration if there is no visible declaration of it.
5068     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5069     PushOnScopeChains(New, S, AddToContext);
5070     if (!AddToContext)
5071       CurContext->addHiddenDecl(New);
5072   }
5073 
5074   if (isInOpenMPDeclareTargetContext())
5075     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5076 
5077   return New;
5078 }
5079 
5080 /// Helper method to turn variable array types into constant array
5081 /// types in certain situations which would otherwise be errors (for
5082 /// GCC compatibility).
5083 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5084                                                     ASTContext &Context,
5085                                                     bool &SizeIsNegative,
5086                                                     llvm::APSInt &Oversized) {
5087   // This method tries to turn a variable array into a constant
5088   // array even when the size isn't an ICE.  This is necessary
5089   // for compatibility with code that depends on gcc's buggy
5090   // constant expression folding, like struct {char x[(int)(char*)2];}
5091   SizeIsNegative = false;
5092   Oversized = 0;
5093 
5094   if (T->isDependentType())
5095     return QualType();
5096 
5097   QualifierCollector Qs;
5098   const Type *Ty = Qs.strip(T);
5099 
5100   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5101     QualType Pointee = PTy->getPointeeType();
5102     QualType FixedType =
5103         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5104                                             Oversized);
5105     if (FixedType.isNull()) return FixedType;
5106     FixedType = Context.getPointerType(FixedType);
5107     return Qs.apply(Context, FixedType);
5108   }
5109   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5110     QualType Inner = PTy->getInnerType();
5111     QualType FixedType =
5112         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5113                                             Oversized);
5114     if (FixedType.isNull()) return FixedType;
5115     FixedType = Context.getParenType(FixedType);
5116     return Qs.apply(Context, FixedType);
5117   }
5118 
5119   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5120   if (!VLATy)
5121     return QualType();
5122   // FIXME: We should probably handle this case
5123   if (VLATy->getElementType()->isVariablyModifiedType())
5124     return QualType();
5125 
5126   llvm::APSInt Res;
5127   if (!VLATy->getSizeExpr() ||
5128       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5129     return QualType();
5130 
5131   // Check whether the array size is negative.
5132   if (Res.isSigned() && Res.isNegative()) {
5133     SizeIsNegative = true;
5134     return QualType();
5135   }
5136 
5137   // Check whether the array is too large to be addressed.
5138   unsigned ActiveSizeBits
5139     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5140                                               Res);
5141   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5142     Oversized = Res;
5143     return QualType();
5144   }
5145 
5146   return Context.getConstantArrayType(VLATy->getElementType(),
5147                                       Res, ArrayType::Normal, 0);
5148 }
5149 
5150 static void
5151 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5152   SrcTL = SrcTL.getUnqualifiedLoc();
5153   DstTL = DstTL.getUnqualifiedLoc();
5154   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5155     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5156     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5157                                       DstPTL.getPointeeLoc());
5158     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5159     return;
5160   }
5161   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5162     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5163     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5164                                       DstPTL.getInnerLoc());
5165     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5166     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5167     return;
5168   }
5169   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5170   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5171   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5172   TypeLoc DstElemTL = DstATL.getElementLoc();
5173   DstElemTL.initializeFullCopy(SrcElemTL);
5174   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5175   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5176   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5177 }
5178 
5179 /// Helper method to turn variable array types into constant array
5180 /// types in certain situations which would otherwise be errors (for
5181 /// GCC compatibility).
5182 static TypeSourceInfo*
5183 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5184                                               ASTContext &Context,
5185                                               bool &SizeIsNegative,
5186                                               llvm::APSInt &Oversized) {
5187   QualType FixedTy
5188     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5189                                           SizeIsNegative, Oversized);
5190   if (FixedTy.isNull())
5191     return nullptr;
5192   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5193   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5194                                     FixedTInfo->getTypeLoc());
5195   return FixedTInfo;
5196 }
5197 
5198 /// \brief Register the given locally-scoped extern "C" declaration so
5199 /// that it can be found later for redeclarations. We include any extern "C"
5200 /// declaration that is not visible in the translation unit here, not just
5201 /// function-scope declarations.
5202 void
5203 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5204   if (!getLangOpts().CPlusPlus &&
5205       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5206     // Don't need to track declarations in the TU in C.
5207     return;
5208 
5209   // Note that we have a locally-scoped external with this name.
5210   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5211 }
5212 
5213 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5214   // FIXME: We can have multiple results via __attribute__((overloadable)).
5215   auto Result = Context.getExternCContextDecl()->lookup(Name);
5216   return Result.empty() ? nullptr : *Result.begin();
5217 }
5218 
5219 /// \brief Diagnose function specifiers on a declaration of an identifier that
5220 /// does not identify a function.
5221 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5222   // FIXME: We should probably indicate the identifier in question to avoid
5223   // confusion for constructs like "inline int a(), b;"
5224   if (DS.isInlineSpecified())
5225     Diag(DS.getInlineSpecLoc(),
5226          diag::err_inline_non_function);
5227 
5228   if (DS.isVirtualSpecified())
5229     Diag(DS.getVirtualSpecLoc(),
5230          diag::err_virtual_non_function);
5231 
5232   if (DS.isExplicitSpecified())
5233     Diag(DS.getExplicitSpecLoc(),
5234          diag::err_explicit_non_function);
5235 
5236   if (DS.isNoreturnSpecified())
5237     Diag(DS.getNoreturnSpecLoc(),
5238          diag::err_noreturn_non_function);
5239 }
5240 
5241 NamedDecl*
5242 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5243                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5244   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5245   if (D.getCXXScopeSpec().isSet()) {
5246     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5247       << D.getCXXScopeSpec().getRange();
5248     D.setInvalidType();
5249     // Pretend we didn't see the scope specifier.
5250     DC = CurContext;
5251     Previous.clear();
5252   }
5253 
5254   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5255 
5256   if (D.getDeclSpec().isConstexprSpecified())
5257     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5258       << 1;
5259   if (D.getDeclSpec().isConceptSpecified())
5260     Diag(D.getDeclSpec().getConceptSpecLoc(),
5261          diag::err_concept_wrong_decl_kind);
5262 
5263   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5264     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5265       << D.getName().getSourceRange();
5266     return nullptr;
5267   }
5268 
5269   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5270   if (!NewTD) return nullptr;
5271 
5272   // Handle attributes prior to checking for duplicates in MergeVarDecl
5273   ProcessDeclAttributes(S, NewTD, D);
5274 
5275   CheckTypedefForVariablyModifiedType(S, NewTD);
5276 
5277   bool Redeclaration = D.isRedeclaration();
5278   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5279   D.setRedeclaration(Redeclaration);
5280   return ND;
5281 }
5282 
5283 void
5284 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5285   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5286   // then it shall have block scope.
5287   // Note that variably modified types must be fixed before merging the decl so
5288   // that redeclarations will match.
5289   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5290   QualType T = TInfo->getType();
5291   if (T->isVariablyModifiedType()) {
5292     getCurFunction()->setHasBranchProtectedScope();
5293 
5294     if (S->getFnParent() == nullptr) {
5295       bool SizeIsNegative;
5296       llvm::APSInt Oversized;
5297       TypeSourceInfo *FixedTInfo =
5298         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5299                                                       SizeIsNegative,
5300                                                       Oversized);
5301       if (FixedTInfo) {
5302         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5303         NewTD->setTypeSourceInfo(FixedTInfo);
5304       } else {
5305         if (SizeIsNegative)
5306           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5307         else if (T->isVariableArrayType())
5308           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5309         else if (Oversized.getBoolValue())
5310           Diag(NewTD->getLocation(), diag::err_array_too_large)
5311             << Oversized.toString(10);
5312         else
5313           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5314         NewTD->setInvalidDecl();
5315       }
5316     }
5317   }
5318 }
5319 
5320 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5321 /// declares a typedef-name, either using the 'typedef' type specifier or via
5322 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5323 NamedDecl*
5324 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5325                            LookupResult &Previous, bool &Redeclaration) {
5326   // Merge the decl with the existing one if appropriate. If the decl is
5327   // in an outer scope, it isn't the same thing.
5328   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5329                        /*AllowInlineNamespace*/false);
5330   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5331   if (!Previous.empty()) {
5332     Redeclaration = true;
5333     MergeTypedefNameDecl(S, NewTD, Previous);
5334   }
5335 
5336   // If this is the C FILE type, notify the AST context.
5337   if (IdentifierInfo *II = NewTD->getIdentifier())
5338     if (!NewTD->isInvalidDecl() &&
5339         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5340       if (II->isStr("FILE"))
5341         Context.setFILEDecl(NewTD);
5342       else if (II->isStr("jmp_buf"))
5343         Context.setjmp_bufDecl(NewTD);
5344       else if (II->isStr("sigjmp_buf"))
5345         Context.setsigjmp_bufDecl(NewTD);
5346       else if (II->isStr("ucontext_t"))
5347         Context.setucontext_tDecl(NewTD);
5348     }
5349 
5350   return NewTD;
5351 }
5352 
5353 /// \brief Determines whether the given declaration is an out-of-scope
5354 /// previous declaration.
5355 ///
5356 /// This routine should be invoked when name lookup has found a
5357 /// previous declaration (PrevDecl) that is not in the scope where a
5358 /// new declaration by the same name is being introduced. If the new
5359 /// declaration occurs in a local scope, previous declarations with
5360 /// linkage may still be considered previous declarations (C99
5361 /// 6.2.2p4-5, C++ [basic.link]p6).
5362 ///
5363 /// \param PrevDecl the previous declaration found by name
5364 /// lookup
5365 ///
5366 /// \param DC the context in which the new declaration is being
5367 /// declared.
5368 ///
5369 /// \returns true if PrevDecl is an out-of-scope previous declaration
5370 /// for a new delcaration with the same name.
5371 static bool
5372 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5373                                 ASTContext &Context) {
5374   if (!PrevDecl)
5375     return false;
5376 
5377   if (!PrevDecl->hasLinkage())
5378     return false;
5379 
5380   if (Context.getLangOpts().CPlusPlus) {
5381     // C++ [basic.link]p6:
5382     //   If there is a visible declaration of an entity with linkage
5383     //   having the same name and type, ignoring entities declared
5384     //   outside the innermost enclosing namespace scope, the block
5385     //   scope declaration declares that same entity and receives the
5386     //   linkage of the previous declaration.
5387     DeclContext *OuterContext = DC->getRedeclContext();
5388     if (!OuterContext->isFunctionOrMethod())
5389       // This rule only applies to block-scope declarations.
5390       return false;
5391 
5392     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5393     if (PrevOuterContext->isRecord())
5394       // We found a member function: ignore it.
5395       return false;
5396 
5397     // Find the innermost enclosing namespace for the new and
5398     // previous declarations.
5399     OuterContext = OuterContext->getEnclosingNamespaceContext();
5400     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5401 
5402     // The previous declaration is in a different namespace, so it
5403     // isn't the same function.
5404     if (!OuterContext->Equals(PrevOuterContext))
5405       return false;
5406   }
5407 
5408   return true;
5409 }
5410 
5411 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5412   CXXScopeSpec &SS = D.getCXXScopeSpec();
5413   if (!SS.isSet()) return;
5414   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5415 }
5416 
5417 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5418   QualType type = decl->getType();
5419   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5420   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5421     // Various kinds of declaration aren't allowed to be __autoreleasing.
5422     unsigned kind = -1U;
5423     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5424       if (var->hasAttr<BlocksAttr>())
5425         kind = 0; // __block
5426       else if (!var->hasLocalStorage())
5427         kind = 1; // global
5428     } else if (isa<ObjCIvarDecl>(decl)) {
5429       kind = 3; // ivar
5430     } else if (isa<FieldDecl>(decl)) {
5431       kind = 2; // field
5432     }
5433 
5434     if (kind != -1U) {
5435       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5436         << kind;
5437     }
5438   } else if (lifetime == Qualifiers::OCL_None) {
5439     // Try to infer lifetime.
5440     if (!type->isObjCLifetimeType())
5441       return false;
5442 
5443     lifetime = type->getObjCARCImplicitLifetime();
5444     type = Context.getLifetimeQualifiedType(type, lifetime);
5445     decl->setType(type);
5446   }
5447 
5448   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5449     // Thread-local variables cannot have lifetime.
5450     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5451         var->getTLSKind()) {
5452       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5453         << var->getType();
5454       return true;
5455     }
5456   }
5457 
5458   return false;
5459 }
5460 
5461 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5462   // Ensure that an auto decl is deduced otherwise the checks below might cache
5463   // the wrong linkage.
5464   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5465 
5466   // 'weak' only applies to declarations with external linkage.
5467   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5468     if (!ND.isExternallyVisible()) {
5469       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5470       ND.dropAttr<WeakAttr>();
5471     }
5472   }
5473   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5474     if (ND.isExternallyVisible()) {
5475       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5476       ND.dropAttr<WeakRefAttr>();
5477       ND.dropAttr<AliasAttr>();
5478     }
5479   }
5480 
5481   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5482     if (VD->hasInit()) {
5483       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5484         assert(VD->isThisDeclarationADefinition() &&
5485                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5486         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5487         VD->dropAttr<AliasAttr>();
5488       }
5489     }
5490   }
5491 
5492   // 'selectany' only applies to externally visible variable declarations.
5493   // It does not apply to functions.
5494   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5495     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5496       S.Diag(Attr->getLocation(),
5497              diag::err_attribute_selectany_non_extern_data);
5498       ND.dropAttr<SelectAnyAttr>();
5499     }
5500   }
5501 
5502   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5503     // dll attributes require external linkage. Static locals may have external
5504     // linkage but still cannot be explicitly imported or exported.
5505     auto *VD = dyn_cast<VarDecl>(&ND);
5506     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5507       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5508         << &ND << Attr;
5509       ND.setInvalidDecl();
5510     }
5511   }
5512 
5513   // Virtual functions cannot be marked as 'notail'.
5514   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5515     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5516       if (MD->isVirtual()) {
5517         S.Diag(ND.getLocation(),
5518                diag::err_invalid_attribute_on_virtual_function)
5519             << Attr;
5520         ND.dropAttr<NotTailCalledAttr>();
5521       }
5522 }
5523 
5524 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5525                                            NamedDecl *NewDecl,
5526                                            bool IsSpecialization) {
5527   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
5528     OldDecl = OldTD->getTemplatedDecl();
5529   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5530     NewDecl = NewTD->getTemplatedDecl();
5531 
5532   if (!OldDecl || !NewDecl)
5533     return;
5534 
5535   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5536   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5537   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5538   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5539 
5540   // dllimport and dllexport are inheritable attributes so we have to exclude
5541   // inherited attribute instances.
5542   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5543                     (NewExportAttr && !NewExportAttr->isInherited());
5544 
5545   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5546   // the only exception being explicit specializations.
5547   // Implicitly generated declarations are also excluded for now because there
5548   // is no other way to switch these to use dllimport or dllexport.
5549   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5550 
5551   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5552     // Allow with a warning for free functions and global variables.
5553     bool JustWarn = false;
5554     if (!OldDecl->isCXXClassMember()) {
5555       auto *VD = dyn_cast<VarDecl>(OldDecl);
5556       if (VD && !VD->getDescribedVarTemplate())
5557         JustWarn = true;
5558       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5559       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5560         JustWarn = true;
5561     }
5562 
5563     // We cannot change a declaration that's been used because IR has already
5564     // been emitted. Dllimported functions will still work though (modulo
5565     // address equality) as they can use the thunk.
5566     if (OldDecl->isUsed())
5567       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5568         JustWarn = false;
5569 
5570     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5571                                : diag::err_attribute_dll_redeclaration;
5572     S.Diag(NewDecl->getLocation(), DiagID)
5573         << NewDecl
5574         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5575     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5576     if (!JustWarn) {
5577       NewDecl->setInvalidDecl();
5578       return;
5579     }
5580   }
5581 
5582   // A redeclaration is not allowed to drop a dllimport attribute, the only
5583   // exceptions being inline function definitions, local extern declarations,
5584   // and qualified friend declarations.
5585   // NB: MSVC converts such a declaration to dllexport.
5586   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5587   if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
5588     // Ignore static data because out-of-line definitions are diagnosed
5589     // separately.
5590     IsStaticDataMember = VD->isStaticDataMember();
5591   else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5592     IsInline = FD->isInlined();
5593     IsQualifiedFriend = FD->getQualifier() &&
5594                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5595   }
5596 
5597   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5598       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5599     S.Diag(NewDecl->getLocation(),
5600            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5601       << NewDecl << OldImportAttr;
5602     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5603     S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5604     OldDecl->dropAttr<DLLImportAttr>();
5605     NewDecl->dropAttr<DLLImportAttr>();
5606   } else if (IsInline && OldImportAttr &&
5607              !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5608     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5609     OldDecl->dropAttr<DLLImportAttr>();
5610     NewDecl->dropAttr<DLLImportAttr>();
5611     S.Diag(NewDecl->getLocation(),
5612            diag::warn_dllimport_dropped_from_inline_function)
5613         << NewDecl << OldImportAttr;
5614   }
5615 }
5616 
5617 /// Given that we are within the definition of the given function,
5618 /// will that definition behave like C99's 'inline', where the
5619 /// definition is discarded except for optimization purposes?
5620 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5621   // Try to avoid calling GetGVALinkageForFunction.
5622 
5623   // All cases of this require the 'inline' keyword.
5624   if (!FD->isInlined()) return false;
5625 
5626   // This is only possible in C++ with the gnu_inline attribute.
5627   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5628     return false;
5629 
5630   // Okay, go ahead and call the relatively-more-expensive function.
5631 
5632 #ifndef NDEBUG
5633   // AST quite reasonably asserts that it's working on a function
5634   // definition.  We don't really have a way to tell it that we're
5635   // currently defining the function, so just lie to it in +Asserts
5636   // builds.  This is an awful hack.
5637   FD->setLazyBody(1);
5638 #endif
5639 
5640   bool isC99Inline =
5641       S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5642 
5643 #ifndef NDEBUG
5644   FD->setLazyBody(0);
5645 #endif
5646 
5647   return isC99Inline;
5648 }
5649 
5650 /// Determine whether a variable is extern "C" prior to attaching
5651 /// an initializer. We can't just call isExternC() here, because that
5652 /// will also compute and cache whether the declaration is externally
5653 /// visible, which might change when we attach the initializer.
5654 ///
5655 /// This can only be used if the declaration is known to not be a
5656 /// redeclaration of an internal linkage declaration.
5657 ///
5658 /// For instance:
5659 ///
5660 ///   auto x = []{};
5661 ///
5662 /// Attaching the initializer here makes this declaration not externally
5663 /// visible, because its type has internal linkage.
5664 ///
5665 /// FIXME: This is a hack.
5666 template<typename T>
5667 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5668   if (S.getLangOpts().CPlusPlus) {
5669     // In C++, the overloadable attribute negates the effects of extern "C".
5670     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5671       return false;
5672 
5673     // So do CUDA's host/device attributes.
5674     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
5675                                  D->template hasAttr<CUDAHostAttr>()))
5676       return false;
5677   }
5678   return D->isExternC();
5679 }
5680 
5681 static bool shouldConsiderLinkage(const VarDecl *VD) {
5682   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5683   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
5684     return VD->hasExternalStorage();
5685   if (DC->isFileContext())
5686     return true;
5687   if (DC->isRecord())
5688     return false;
5689   llvm_unreachable("Unexpected context");
5690 }
5691 
5692 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5693   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5694   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
5695       isa<OMPDeclareReductionDecl>(DC))
5696     return true;
5697   if (DC->isRecord())
5698     return false;
5699   llvm_unreachable("Unexpected context");
5700 }
5701 
5702 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5703                           AttributeList::Kind Kind) {
5704   for (const AttributeList *L = AttrList; L; L = L->getNext())
5705     if (L->getKind() == Kind)
5706       return true;
5707   return false;
5708 }
5709 
5710 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5711                           AttributeList::Kind Kind) {
5712   // Check decl attributes on the DeclSpec.
5713   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5714     return true;
5715 
5716   // Walk the declarator structure, checking decl attributes that were in a type
5717   // position to the decl itself.
5718   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5719     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5720       return true;
5721   }
5722 
5723   // Finally, check attributes on the decl itself.
5724   return hasParsedAttr(S, PD.getAttributes(), Kind);
5725 }
5726 
5727 /// Adjust the \c DeclContext for a function or variable that might be a
5728 /// function-local external declaration.
5729 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5730   if (!DC->isFunctionOrMethod())
5731     return false;
5732 
5733   // If this is a local extern function or variable declared within a function
5734   // template, don't add it into the enclosing namespace scope until it is
5735   // instantiated; it might have a dependent type right now.
5736   if (DC->isDependentContext())
5737     return true;
5738 
5739   // C++11 [basic.link]p7:
5740   //   When a block scope declaration of an entity with linkage is not found to
5741   //   refer to some other declaration, then that entity is a member of the
5742   //   innermost enclosing namespace.
5743   //
5744   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5745   // semantically-enclosing namespace, not a lexically-enclosing one.
5746   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5747     DC = DC->getParent();
5748   return true;
5749 }
5750 
5751 /// \brief Returns true if given declaration has external C language linkage.
5752 static bool isDeclExternC(const Decl *D) {
5753   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5754     return FD->isExternC();
5755   if (const auto *VD = dyn_cast<VarDecl>(D))
5756     return VD->isExternC();
5757 
5758   llvm_unreachable("Unknown type of decl!");
5759 }
5760 
5761 NamedDecl *
5762 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5763                               TypeSourceInfo *TInfo, LookupResult &Previous,
5764                               MultiTemplateParamsArg TemplateParamLists,
5765                               bool &AddToScope) {
5766   QualType R = TInfo->getType();
5767   DeclarationName Name = GetNameForDeclarator(D).getName();
5768 
5769   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
5770   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
5771   // argument.
5772   if (getLangOpts().OpenCL && (R->isImageType() || R->isPipeType())) {
5773     Diag(D.getIdentifierLoc(),
5774          diag::err_opencl_type_can_only_be_used_as_function_parameter)
5775         << R;
5776     D.setInvalidType();
5777     return nullptr;
5778   }
5779 
5780   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5781   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5782 
5783   // dllimport globals without explicit storage class are treated as extern. We
5784   // have to change the storage class this early to get the right DeclContext.
5785   if (SC == SC_None && !DC->isRecord() &&
5786       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5787       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5788     SC = SC_Extern;
5789 
5790   DeclContext *OriginalDC = DC;
5791   bool IsLocalExternDecl = SC == SC_Extern &&
5792                            adjustContextForLocalExternDecl(DC);
5793 
5794   if (getLangOpts().OpenCL) {
5795     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5796     QualType NR = R;
5797     while (NR->isPointerType()) {
5798       if (NR->isFunctionPointerType()) {
5799         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5800         D.setInvalidType();
5801         break;
5802       }
5803       NR = NR->getPointeeType();
5804     }
5805 
5806     if (!getOpenCLOptions().cl_khr_fp16) {
5807       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5808       // half array type (unless the cl_khr_fp16 extension is enabled).
5809       if (Context.getBaseElementType(R)->isHalfType()) {
5810         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5811         D.setInvalidType();
5812       }
5813     }
5814   }
5815 
5816   if (SCSpec == DeclSpec::SCS_mutable) {
5817     // mutable can only appear on non-static class members, so it's always
5818     // an error here
5819     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5820     D.setInvalidType();
5821     SC = SC_None;
5822   }
5823 
5824   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5825       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5826                               D.getDeclSpec().getStorageClassSpecLoc())) {
5827     // In C++11, the 'register' storage class specifier is deprecated.
5828     // Suppress the warning in system macros, it's used in macros in some
5829     // popular C system headers, such as in glibc's htonl() macro.
5830     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5831          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
5832                                    : diag::warn_deprecated_register)
5833       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5834   }
5835 
5836   IdentifierInfo *II = Name.getAsIdentifierInfo();
5837   if (!II) {
5838     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5839       << Name;
5840     return nullptr;
5841   }
5842 
5843   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5844 
5845   if (!DC->isRecord() && S->getFnParent() == nullptr) {
5846     // C99 6.9p2: The storage-class specifiers auto and register shall not
5847     // appear in the declaration specifiers in an external declaration.
5848     // Global Register+Asm is a GNU extension we support.
5849     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5850       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5851       D.setInvalidType();
5852     }
5853   }
5854 
5855   if (getLangOpts().OpenCL) {
5856     // OpenCL v1.2 s6.9.b p4:
5857     // The sampler type cannot be used with the __local and __global address
5858     // space qualifiers.
5859     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5860       R.getAddressSpace() == LangAS::opencl_global)) {
5861       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5862     }
5863 
5864     // OpenCL 1.2 spec, p6.9 r:
5865     // The event type cannot be used to declare a program scope variable.
5866     // The event type cannot be used with the __local, __constant and __global
5867     // address space qualifiers.
5868     if (R->isEventT()) {
5869       if (S->getParent() == nullptr) {
5870         Diag(D.getLocStart(), diag::err_event_t_global_var);
5871         D.setInvalidType();
5872       }
5873 
5874       if (R.getAddressSpace()) {
5875         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5876         D.setInvalidType();
5877       }
5878     }
5879   }
5880 
5881   bool IsExplicitSpecialization = false;
5882   bool IsVariableTemplateSpecialization = false;
5883   bool IsPartialSpecialization = false;
5884   bool IsVariableTemplate = false;
5885   VarDecl *NewVD = nullptr;
5886   VarTemplateDecl *NewTemplate = nullptr;
5887   TemplateParameterList *TemplateParams = nullptr;
5888   if (!getLangOpts().CPlusPlus) {
5889     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5890                             D.getIdentifierLoc(), II,
5891                             R, TInfo, SC);
5892 
5893     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5894       ParsingInitForAutoVars.insert(NewVD);
5895 
5896     if (D.isInvalidType())
5897       NewVD->setInvalidDecl();
5898   } else {
5899     bool Invalid = false;
5900 
5901     if (DC->isRecord() && !CurContext->isRecord()) {
5902       // This is an out-of-line definition of a static data member.
5903       switch (SC) {
5904       case SC_None:
5905         break;
5906       case SC_Static:
5907         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5908              diag::err_static_out_of_line)
5909           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5910         break;
5911       case SC_Auto:
5912       case SC_Register:
5913       case SC_Extern:
5914         // [dcl.stc] p2: The auto or register specifiers shall be applied only
5915         // to names of variables declared in a block or to function parameters.
5916         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5917         // of class members
5918 
5919         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5920              diag::err_storage_class_for_static_member)
5921           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5922         break;
5923       case SC_PrivateExtern:
5924         llvm_unreachable("C storage class in c++!");
5925       }
5926     }
5927 
5928     if (SC == SC_Static && CurContext->isRecord()) {
5929       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5930         if (RD->isLocalClass())
5931           Diag(D.getIdentifierLoc(),
5932                diag::err_static_data_member_not_allowed_in_local_class)
5933             << Name << RD->getDeclName();
5934 
5935         // C++98 [class.union]p1: If a union contains a static data member,
5936         // the program is ill-formed. C++11 drops this restriction.
5937         if (RD->isUnion())
5938           Diag(D.getIdentifierLoc(),
5939                getLangOpts().CPlusPlus11
5940                  ? diag::warn_cxx98_compat_static_data_member_in_union
5941                  : diag::ext_static_data_member_in_union) << Name;
5942         // We conservatively disallow static data members in anonymous structs.
5943         else if (!RD->getDeclName())
5944           Diag(D.getIdentifierLoc(),
5945                diag::err_static_data_member_not_allowed_in_anon_struct)
5946             << Name << RD->isUnion();
5947       }
5948     }
5949 
5950     // Match up the template parameter lists with the scope specifier, then
5951     // determine whether we have a template or a template specialization.
5952     TemplateParams = MatchTemplateParametersToScopeSpecifier(
5953         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5954         D.getCXXScopeSpec(),
5955         D.getName().getKind() == UnqualifiedId::IK_TemplateId
5956             ? D.getName().TemplateId
5957             : nullptr,
5958         TemplateParamLists,
5959         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5960 
5961     if (TemplateParams) {
5962       if (!TemplateParams->size() &&
5963           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5964         // There is an extraneous 'template<>' for this variable. Complain
5965         // about it, but allow the declaration of the variable.
5966         Diag(TemplateParams->getTemplateLoc(),
5967              diag::err_template_variable_noparams)
5968           << II
5969           << SourceRange(TemplateParams->getTemplateLoc(),
5970                          TemplateParams->getRAngleLoc());
5971         TemplateParams = nullptr;
5972       } else {
5973         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5974           // This is an explicit specialization or a partial specialization.
5975           // FIXME: Check that we can declare a specialization here.
5976           IsVariableTemplateSpecialization = true;
5977           IsPartialSpecialization = TemplateParams->size() > 0;
5978         } else { // if (TemplateParams->size() > 0)
5979           // This is a template declaration.
5980           IsVariableTemplate = true;
5981 
5982           // Check that we can declare a template here.
5983           if (CheckTemplateDeclScope(S, TemplateParams))
5984             return nullptr;
5985 
5986           // Only C++1y supports variable templates (N3651).
5987           Diag(D.getIdentifierLoc(),
5988                getLangOpts().CPlusPlus14
5989                    ? diag::warn_cxx11_compat_variable_template
5990                    : diag::ext_variable_template);
5991         }
5992       }
5993     } else {
5994       assert(
5995           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
5996           "should have a 'template<>' for this decl");
5997     }
5998 
5999     if (IsVariableTemplateSpecialization) {
6000       SourceLocation TemplateKWLoc =
6001           TemplateParamLists.size() > 0
6002               ? TemplateParamLists[0]->getTemplateLoc()
6003               : SourceLocation();
6004       DeclResult Res = ActOnVarTemplateSpecialization(
6005           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6006           IsPartialSpecialization);
6007       if (Res.isInvalid())
6008         return nullptr;
6009       NewVD = cast<VarDecl>(Res.get());
6010       AddToScope = false;
6011     } else
6012       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6013                               D.getIdentifierLoc(), II, R, TInfo, SC);
6014 
6015     // If this is supposed to be a variable template, create it as such.
6016     if (IsVariableTemplate) {
6017       NewTemplate =
6018           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6019                                   TemplateParams, NewVD);
6020       NewVD->setDescribedVarTemplate(NewTemplate);
6021     }
6022 
6023     // If this decl has an auto type in need of deduction, make a note of the
6024     // Decl so we can diagnose uses of it in its own initializer.
6025     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
6026       ParsingInitForAutoVars.insert(NewVD);
6027 
6028     if (D.isInvalidType() || Invalid) {
6029       NewVD->setInvalidDecl();
6030       if (NewTemplate)
6031         NewTemplate->setInvalidDecl();
6032     }
6033 
6034     SetNestedNameSpecifier(NewVD, D);
6035 
6036     // If we have any template parameter lists that don't directly belong to
6037     // the variable (matching the scope specifier), store them.
6038     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6039     if (TemplateParamLists.size() > VDTemplateParamLists)
6040       NewVD->setTemplateParameterListsInfo(
6041           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6042 
6043     if (D.getDeclSpec().isConstexprSpecified())
6044       NewVD->setConstexpr(true);
6045 
6046     if (D.getDeclSpec().isConceptSpecified()) {
6047       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6048         VTD->setConcept();
6049 
6050       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6051       // be declared with the thread_local, inline, friend, or constexpr
6052       // specifiers, [...]
6053       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6054         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6055              diag::err_concept_decl_invalid_specifiers)
6056             << 0 << 0;
6057         NewVD->setInvalidDecl(true);
6058       }
6059 
6060       if (D.getDeclSpec().isConstexprSpecified()) {
6061         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6062              diag::err_concept_decl_invalid_specifiers)
6063             << 0 << 3;
6064         NewVD->setInvalidDecl(true);
6065       }
6066 
6067       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6068       // applied only to the definition of a function template or variable
6069       // template, declared in namespace scope.
6070       if (IsVariableTemplateSpecialization) {
6071         Diag(D.getDeclSpec().getConceptSpecLoc(),
6072              diag::err_concept_specified_specialization)
6073             << (IsPartialSpecialization ? 2 : 1);
6074       }
6075 
6076       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6077       // following restrictions:
6078       // - The declared type shall have the type bool.
6079       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6080           !NewVD->isInvalidDecl()) {
6081         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6082         NewVD->setInvalidDecl(true);
6083       }
6084     }
6085   }
6086 
6087   // Set the lexical context. If the declarator has a C++ scope specifier, the
6088   // lexical context will be different from the semantic context.
6089   NewVD->setLexicalDeclContext(CurContext);
6090   if (NewTemplate)
6091     NewTemplate->setLexicalDeclContext(CurContext);
6092 
6093   if (IsLocalExternDecl)
6094     NewVD->setLocalExternDecl();
6095 
6096   bool EmitTLSUnsupportedError = false;
6097   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6098     // C++11 [dcl.stc]p4:
6099     //   When thread_local is applied to a variable of block scope the
6100     //   storage-class-specifier static is implied if it does not appear
6101     //   explicitly.
6102     // Core issue: 'static' is not implied if the variable is declared
6103     //   'extern'.
6104     if (NewVD->hasLocalStorage() &&
6105         (SCSpec != DeclSpec::SCS_unspecified ||
6106          TSCS != DeclSpec::TSCS_thread_local ||
6107          !DC->isFunctionOrMethod()))
6108       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6109            diag::err_thread_non_global)
6110         << DeclSpec::getSpecifierName(TSCS);
6111     else if (!Context.getTargetInfo().isTLSSupported()) {
6112       if (getLangOpts().CUDA) {
6113         // Postpone error emission until we've collected attributes required to
6114         // figure out whether it's a host or device variable and whether the
6115         // error should be ignored.
6116         EmitTLSUnsupportedError = true;
6117         // We still need to mark the variable as TLS so it shows up in AST with
6118         // proper storage class for other tools to use even if we're not going
6119         // to emit any code for it.
6120         NewVD->setTSCSpec(TSCS);
6121       } else
6122         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6123              diag::err_thread_unsupported);
6124     } else
6125       NewVD->setTSCSpec(TSCS);
6126   }
6127 
6128   // C99 6.7.4p3
6129   //   An inline definition of a function with external linkage shall
6130   //   not contain a definition of a modifiable object with static or
6131   //   thread storage duration...
6132   // We only apply this when the function is required to be defined
6133   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6134   // that a local variable with thread storage duration still has to
6135   // be marked 'static'.  Also note that it's possible to get these
6136   // semantics in C++ using __attribute__((gnu_inline)).
6137   if (SC == SC_Static && S->getFnParent() != nullptr &&
6138       !NewVD->getType().isConstQualified()) {
6139     FunctionDecl *CurFD = getCurFunctionDecl();
6140     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6141       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6142            diag::warn_static_local_in_extern_inline);
6143       MaybeSuggestAddingStaticToDecl(CurFD);
6144     }
6145   }
6146 
6147   if (D.getDeclSpec().isModulePrivateSpecified()) {
6148     if (IsVariableTemplateSpecialization)
6149       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6150           << (IsPartialSpecialization ? 1 : 0)
6151           << FixItHint::CreateRemoval(
6152                  D.getDeclSpec().getModulePrivateSpecLoc());
6153     else if (IsExplicitSpecialization)
6154       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6155         << 2
6156         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6157     else if (NewVD->hasLocalStorage())
6158       Diag(NewVD->getLocation(), diag::err_module_private_local)
6159         << 0 << NewVD->getDeclName()
6160         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6161         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6162     else {
6163       NewVD->setModulePrivate();
6164       if (NewTemplate)
6165         NewTemplate->setModulePrivate();
6166     }
6167   }
6168 
6169   // Handle attributes prior to checking for duplicates in MergeVarDecl
6170   ProcessDeclAttributes(S, NewVD, D);
6171 
6172   if (getLangOpts().CUDA) {
6173     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6174       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6175            diag::err_thread_unsupported);
6176     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6177     // storage [duration]."
6178     if (SC == SC_None && S->getFnParent() != nullptr &&
6179         (NewVD->hasAttr<CUDASharedAttr>() ||
6180          NewVD->hasAttr<CUDAConstantAttr>())) {
6181       NewVD->setStorageClass(SC_Static);
6182     }
6183   }
6184 
6185   // Ensure that dllimport globals without explicit storage class are treated as
6186   // extern. The storage class is set above using parsed attributes. Now we can
6187   // check the VarDecl itself.
6188   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6189          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6190          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6191 
6192   // In auto-retain/release, infer strong retension for variables of
6193   // retainable type.
6194   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6195     NewVD->setInvalidDecl();
6196 
6197   // Handle GNU asm-label extension (encoded as an attribute).
6198   if (Expr *E = (Expr*)D.getAsmLabel()) {
6199     // The parser guarantees this is a string.
6200     StringLiteral *SE = cast<StringLiteral>(E);
6201     StringRef Label = SE->getString();
6202     if (S->getFnParent() != nullptr) {
6203       switch (SC) {
6204       case SC_None:
6205       case SC_Auto:
6206         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6207         break;
6208       case SC_Register:
6209         // Local Named register
6210         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6211             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6212           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6213         break;
6214       case SC_Static:
6215       case SC_Extern:
6216       case SC_PrivateExtern:
6217         break;
6218       }
6219     } else if (SC == SC_Register) {
6220       // Global Named register
6221       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6222         const auto &TI = Context.getTargetInfo();
6223         bool HasSizeMismatch;
6224 
6225         if (!TI.isValidGCCRegisterName(Label))
6226           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6227         else if (!TI.validateGlobalRegisterVariable(Label,
6228                                                     Context.getTypeSize(R),
6229                                                     HasSizeMismatch))
6230           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6231         else if (HasSizeMismatch)
6232           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6233       }
6234 
6235       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6236         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6237         NewVD->setInvalidDecl(true);
6238       }
6239     }
6240 
6241     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6242                                                 Context, Label, 0));
6243   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6244     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6245       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6246     if (I != ExtnameUndeclaredIdentifiers.end()) {
6247       if (isDeclExternC(NewVD)) {
6248         NewVD->addAttr(I->second);
6249         ExtnameUndeclaredIdentifiers.erase(I);
6250       } else
6251         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6252             << /*Variable*/1 << NewVD;
6253     }
6254   }
6255 
6256   // Diagnose shadowed variables before filtering for scope.
6257   if (D.getCXXScopeSpec().isEmpty())
6258     CheckShadow(S, NewVD, Previous);
6259 
6260   // Don't consider existing declarations that are in a different
6261   // scope and are out-of-semantic-context declarations (if the new
6262   // declaration has linkage).
6263   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6264                        D.getCXXScopeSpec().isNotEmpty() ||
6265                        IsExplicitSpecialization ||
6266                        IsVariableTemplateSpecialization);
6267 
6268   // Check whether the previous declaration is in the same block scope. This
6269   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6270   if (getLangOpts().CPlusPlus &&
6271       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6272     NewVD->setPreviousDeclInSameBlockScope(
6273         Previous.isSingleResult() && !Previous.isShadowed() &&
6274         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6275 
6276   if (!getLangOpts().CPlusPlus) {
6277     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6278   } else {
6279     // If this is an explicit specialization of a static data member, check it.
6280     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6281         CheckMemberSpecialization(NewVD, Previous))
6282       NewVD->setInvalidDecl();
6283 
6284     // Merge the decl with the existing one if appropriate.
6285     if (!Previous.empty()) {
6286       if (Previous.isSingleResult() &&
6287           isa<FieldDecl>(Previous.getFoundDecl()) &&
6288           D.getCXXScopeSpec().isSet()) {
6289         // The user tried to define a non-static data member
6290         // out-of-line (C++ [dcl.meaning]p1).
6291         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6292           << D.getCXXScopeSpec().getRange();
6293         Previous.clear();
6294         NewVD->setInvalidDecl();
6295       }
6296     } else if (D.getCXXScopeSpec().isSet()) {
6297       // No previous declaration in the qualifying scope.
6298       Diag(D.getIdentifierLoc(), diag::err_no_member)
6299         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6300         << D.getCXXScopeSpec().getRange();
6301       NewVD->setInvalidDecl();
6302     }
6303 
6304     if (!IsVariableTemplateSpecialization)
6305       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6306 
6307     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6308     // an explicit specialization (14.8.3) or a partial specialization of a
6309     // concept definition.
6310     if (IsVariableTemplateSpecialization &&
6311         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6312         Previous.isSingleResult()) {
6313       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6314       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6315         if (VarTmpl->isConcept()) {
6316           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6317               << 1                            /*variable*/
6318               << (IsPartialSpecialization ? 2 /*partially specialized*/
6319                                           : 1 /*explicitly specialized*/);
6320           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6321           NewVD->setInvalidDecl();
6322         }
6323       }
6324     }
6325 
6326     if (NewTemplate) {
6327       VarTemplateDecl *PrevVarTemplate =
6328           NewVD->getPreviousDecl()
6329               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6330               : nullptr;
6331 
6332       // Check the template parameter list of this declaration, possibly
6333       // merging in the template parameter list from the previous variable
6334       // template declaration.
6335       if (CheckTemplateParameterList(
6336               TemplateParams,
6337               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6338                               : nullptr,
6339               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6340                DC->isDependentContext())
6341                   ? TPC_ClassTemplateMember
6342                   : TPC_VarTemplate))
6343         NewVD->setInvalidDecl();
6344 
6345       // If we are providing an explicit specialization of a static variable
6346       // template, make a note of that.
6347       if (PrevVarTemplate &&
6348           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6349         PrevVarTemplate->setMemberSpecialization();
6350     }
6351   }
6352 
6353   ProcessPragmaWeak(S, NewVD);
6354 
6355   // If this is the first declaration of an extern C variable, update
6356   // the map of such variables.
6357   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6358       isIncompleteDeclExternC(*this, NewVD))
6359     RegisterLocallyScopedExternCDecl(NewVD, S);
6360 
6361   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6362     Decl *ManglingContextDecl;
6363     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6364             NewVD->getDeclContext(), ManglingContextDecl)) {
6365       Context.setManglingNumber(
6366           NewVD, MCtx->getManglingNumber(
6367                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6368       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6369     }
6370   }
6371 
6372   // Special handling of variable named 'main'.
6373   if (Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main") &&
6374       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6375       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6376 
6377     // C++ [basic.start.main]p3
6378     // A program that declares a variable main at global scope is ill-formed.
6379     if (getLangOpts().CPlusPlus)
6380       Diag(D.getLocStart(), diag::err_main_global_variable);
6381 
6382     // In C, and external-linkage variable named main results in undefined
6383     // behavior.
6384     else if (NewVD->hasExternalFormalLinkage())
6385       Diag(D.getLocStart(), diag::warn_main_redefined);
6386   }
6387 
6388   if (D.isRedeclaration() && !Previous.empty()) {
6389     checkDLLAttributeRedeclaration(
6390         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6391         IsExplicitSpecialization);
6392   }
6393 
6394   if (NewTemplate) {
6395     if (NewVD->isInvalidDecl())
6396       NewTemplate->setInvalidDecl();
6397     ActOnDocumentableDecl(NewTemplate);
6398     return NewTemplate;
6399   }
6400 
6401   return NewVD;
6402 }
6403 
6404 /// Enum describing the %select options in diag::warn_decl_shadow.
6405 enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field };
6406 
6407 /// Determine what kind of declaration we're shadowing.
6408 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6409                                                 const DeclContext *OldDC) {
6410   if (isa<RecordDecl>(OldDC))
6411     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6412   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6413 }
6414 
6415 /// \brief Diagnose variable or built-in function shadowing.  Implements
6416 /// -Wshadow.
6417 ///
6418 /// This method is called whenever a VarDecl is added to a "useful"
6419 /// scope.
6420 ///
6421 /// \param S the scope in which the shadowing name is being declared
6422 /// \param R the lookup of the name
6423 ///
6424 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
6425   // Return if warning is ignored.
6426   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6427     return;
6428 
6429   // Don't diagnose declarations at file scope.
6430   if (D->hasGlobalStorage())
6431     return;
6432 
6433   DeclContext *NewDC = D->getDeclContext();
6434 
6435   // Only diagnose if we're shadowing an unambiguous field or variable.
6436   if (R.getResultKind() != LookupResult::Found)
6437     return;
6438 
6439   NamedDecl* ShadowedDecl = R.getFoundDecl();
6440   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
6441     return;
6442 
6443   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6444     // Fields are not shadowed by variables in C++ static methods.
6445     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6446       if (MD->isStatic())
6447         return;
6448 
6449     // Fields shadowed by constructor parameters are a special case. Usually
6450     // the constructor initializes the field with the parameter.
6451     if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) {
6452       // Remember that this was shadowed so we can either warn about its
6453       // modification or its existence depending on warning settings.
6454       D = D->getCanonicalDecl();
6455       ShadowingDecls.insert({D, FD});
6456       return;
6457     }
6458   }
6459 
6460   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6461     if (shadowedVar->isExternC()) {
6462       // For shadowing external vars, make sure that we point to the global
6463       // declaration, not a locally scoped extern declaration.
6464       for (auto I : shadowedVar->redecls())
6465         if (I->isFileVarDecl()) {
6466           ShadowedDecl = I;
6467           break;
6468         }
6469     }
6470 
6471   DeclContext *OldDC = ShadowedDecl->getDeclContext();
6472 
6473   // Only warn about certain kinds of shadowing for class members.
6474   if (NewDC && NewDC->isRecord()) {
6475     // In particular, don't warn about shadowing non-class members.
6476     if (!OldDC->isRecord())
6477       return;
6478 
6479     // TODO: should we warn about static data members shadowing
6480     // static data members from base classes?
6481 
6482     // TODO: don't diagnose for inaccessible shadowed members.
6483     // This is hard to do perfectly because we might friend the
6484     // shadowing context, but that's just a false negative.
6485   }
6486 
6487 
6488   DeclarationName Name = R.getLookupName();
6489 
6490   // Emit warning and note.
6491   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6492     return;
6493   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
6494   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
6495   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6496 }
6497 
6498 /// \brief Check -Wshadow without the advantage of a previous lookup.
6499 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6500   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6501     return;
6502 
6503   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6504                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6505   LookupName(R, S);
6506   CheckShadow(S, D, R);
6507 }
6508 
6509 /// Check if 'E', which is an expression that is about to be modified, refers
6510 /// to a constructor parameter that shadows a field.
6511 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
6512   // Quickly ignore expressions that can't be shadowing ctor parameters.
6513   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
6514     return;
6515   E = E->IgnoreParenImpCasts();
6516   auto *DRE = dyn_cast<DeclRefExpr>(E);
6517   if (!DRE)
6518     return;
6519   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
6520   auto I = ShadowingDecls.find(D);
6521   if (I == ShadowingDecls.end())
6522     return;
6523   const NamedDecl *ShadowedDecl = I->second;
6524   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6525   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
6526   Diag(D->getLocation(), diag::note_var_declared_here) << D;
6527   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6528 
6529   // Avoid issuing multiple warnings about the same decl.
6530   ShadowingDecls.erase(I);
6531 }
6532 
6533 /// Check for conflict between this global or extern "C" declaration and
6534 /// previous global or extern "C" declarations. This is only used in C++.
6535 template<typename T>
6536 static bool checkGlobalOrExternCConflict(
6537     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6538   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6539   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6540 
6541   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6542     // The common case: this global doesn't conflict with any extern "C"
6543     // declaration.
6544     return false;
6545   }
6546 
6547   if (Prev) {
6548     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6549       // Both the old and new declarations have C language linkage. This is a
6550       // redeclaration.
6551       Previous.clear();
6552       Previous.addDecl(Prev);
6553       return true;
6554     }
6555 
6556     // This is a global, non-extern "C" declaration, and there is a previous
6557     // non-global extern "C" declaration. Diagnose if this is a variable
6558     // declaration.
6559     if (!isa<VarDecl>(ND))
6560       return false;
6561   } else {
6562     // The declaration is extern "C". Check for any declaration in the
6563     // translation unit which might conflict.
6564     if (IsGlobal) {
6565       // We have already performed the lookup into the translation unit.
6566       IsGlobal = false;
6567       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6568            I != E; ++I) {
6569         if (isa<VarDecl>(*I)) {
6570           Prev = *I;
6571           break;
6572         }
6573       }
6574     } else {
6575       DeclContext::lookup_result R =
6576           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6577       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6578            I != E; ++I) {
6579         if (isa<VarDecl>(*I)) {
6580           Prev = *I;
6581           break;
6582         }
6583         // FIXME: If we have any other entity with this name in global scope,
6584         // the declaration is ill-formed, but that is a defect: it breaks the
6585         // 'stat' hack, for instance. Only variables can have mangled name
6586         // clashes with extern "C" declarations, so only they deserve a
6587         // diagnostic.
6588       }
6589     }
6590 
6591     if (!Prev)
6592       return false;
6593   }
6594 
6595   // Use the first declaration's location to ensure we point at something which
6596   // is lexically inside an extern "C" linkage-spec.
6597   assert(Prev && "should have found a previous declaration to diagnose");
6598   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6599     Prev = FD->getFirstDecl();
6600   else
6601     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6602 
6603   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6604     << IsGlobal << ND;
6605   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6606     << IsGlobal;
6607   return false;
6608 }
6609 
6610 /// Apply special rules for handling extern "C" declarations. Returns \c true
6611 /// if we have found that this is a redeclaration of some prior entity.
6612 ///
6613 /// Per C++ [dcl.link]p6:
6614 ///   Two declarations [for a function or variable] with C language linkage
6615 ///   with the same name that appear in different scopes refer to the same
6616 ///   [entity]. An entity with C language linkage shall not be declared with
6617 ///   the same name as an entity in global scope.
6618 template<typename T>
6619 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6620                                                   LookupResult &Previous) {
6621   if (!S.getLangOpts().CPlusPlus) {
6622     // In C, when declaring a global variable, look for a corresponding 'extern'
6623     // variable declared in function scope. We don't need this in C++, because
6624     // we find local extern decls in the surrounding file-scope DeclContext.
6625     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6626       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6627         Previous.clear();
6628         Previous.addDecl(Prev);
6629         return true;
6630       }
6631     }
6632     return false;
6633   }
6634 
6635   // A declaration in the translation unit can conflict with an extern "C"
6636   // declaration.
6637   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6638     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6639 
6640   // An extern "C" declaration can conflict with a declaration in the
6641   // translation unit or can be a redeclaration of an extern "C" declaration
6642   // in another scope.
6643   if (isIncompleteDeclExternC(S,ND))
6644     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6645 
6646   // Neither global nor extern "C": nothing to do.
6647   return false;
6648 }
6649 
6650 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6651   // If the decl is already known invalid, don't check it.
6652   if (NewVD->isInvalidDecl())
6653     return;
6654 
6655   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6656   QualType T = TInfo->getType();
6657 
6658   // Defer checking an 'auto' type until its initializer is attached.
6659   if (T->isUndeducedType())
6660     return;
6661 
6662   if (NewVD->hasAttrs())
6663     CheckAlignasUnderalignment(NewVD);
6664 
6665   if (T->isObjCObjectType()) {
6666     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6667       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6668     T = Context.getObjCObjectPointerType(T);
6669     NewVD->setType(T);
6670   }
6671 
6672   // Emit an error if an address space was applied to decl with local storage.
6673   // This includes arrays of objects with address space qualifiers, but not
6674   // automatic variables that point to other address spaces.
6675   // ISO/IEC TR 18037 S5.1.2
6676   if (!getLangOpts().OpenCL
6677       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6678     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6679     NewVD->setInvalidDecl();
6680     return;
6681   }
6682 
6683   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
6684   // scope.
6685   if (getLangOpts().OpenCLVersion == 120 &&
6686       !getOpenCLOptions().cl_clang_storage_class_specifiers &&
6687       NewVD->isStaticLocal()) {
6688     Diag(NewVD->getLocation(), diag::err_static_function_scope);
6689     NewVD->setInvalidDecl();
6690     return;
6691   }
6692 
6693   if (getLangOpts().OpenCL) {
6694     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
6695     if (NewVD->hasAttr<BlocksAttr>()) {
6696       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
6697       return;
6698     }
6699 
6700     if (T->isBlockPointerType()) {
6701       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
6702       // can't use 'extern' storage class.
6703       if (!T.isConstQualified()) {
6704         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
6705             << 0 /*const*/;
6706         NewVD->setInvalidDecl();
6707         return;
6708       }
6709       if (NewVD->hasExternalStorage()) {
6710         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
6711         NewVD->setInvalidDecl();
6712         return;
6713       }
6714       // OpenCL v2.0 s6.12.5 - Blocks with variadic arguments are not supported.
6715       // TODO: this check is not enough as it doesn't diagnose the typedef
6716       const BlockPointerType *BlkTy = T->getAs<BlockPointerType>();
6717       const FunctionProtoType *FTy =
6718           BlkTy->getPointeeType()->getAs<FunctionProtoType>();
6719       if (FTy && FTy->isVariadic()) {
6720         Diag(NewVD->getLocation(), diag::err_opencl_block_proto_variadic)
6721             << T << NewVD->getSourceRange();
6722         NewVD->setInvalidDecl();
6723         return;
6724       }
6725     }
6726     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6727     // __constant address space.
6728     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6729     // variables inside a function can also be declared in the global
6730     // address space.
6731     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
6732         NewVD->hasExternalStorage()) {
6733       if (!T->isSamplerT() &&
6734           !(T.getAddressSpace() == LangAS::opencl_constant ||
6735             (T.getAddressSpace() == LangAS::opencl_global &&
6736              getLangOpts().OpenCLVersion == 200))) {
6737         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
6738         if (getLangOpts().OpenCLVersion == 200)
6739           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6740               << Scope << "global or constant";
6741         else
6742           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6743               << Scope << "constant";
6744         NewVD->setInvalidDecl();
6745         return;
6746       }
6747     } else {
6748       if (T.getAddressSpace() == LangAS::opencl_global) {
6749         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6750             << 1 /*is any function*/ << "global";
6751         NewVD->setInvalidDecl();
6752         return;
6753       }
6754       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
6755       // in functions.
6756       if (T.getAddressSpace() == LangAS::opencl_constant ||
6757           T.getAddressSpace() == LangAS::opencl_local) {
6758         FunctionDecl *FD = getCurFunctionDecl();
6759         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
6760           if (T.getAddressSpace() == LangAS::opencl_constant)
6761             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6762                 << 0 /*non-kernel only*/ << "constant";
6763           else
6764             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6765                 << 0 /*non-kernel only*/ << "local";
6766           NewVD->setInvalidDecl();
6767           return;
6768         }
6769       }
6770     }
6771   }
6772 
6773   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6774       && !NewVD->hasAttr<BlocksAttr>()) {
6775     if (getLangOpts().getGC() != LangOptions::NonGC)
6776       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6777     else {
6778       assert(!getLangOpts().ObjCAutoRefCount);
6779       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6780     }
6781   }
6782 
6783   bool isVM = T->isVariablyModifiedType();
6784   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6785       NewVD->hasAttr<BlocksAttr>())
6786     getCurFunction()->setHasBranchProtectedScope();
6787 
6788   if ((isVM && NewVD->hasLinkage()) ||
6789       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6790     bool SizeIsNegative;
6791     llvm::APSInt Oversized;
6792     TypeSourceInfo *FixedTInfo =
6793       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6794                                                     SizeIsNegative, Oversized);
6795     if (!FixedTInfo && T->isVariableArrayType()) {
6796       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6797       // FIXME: This won't give the correct result for
6798       // int a[10][n];
6799       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6800 
6801       if (NewVD->isFileVarDecl())
6802         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6803         << SizeRange;
6804       else if (NewVD->isStaticLocal())
6805         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6806         << SizeRange;
6807       else
6808         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6809         << SizeRange;
6810       NewVD->setInvalidDecl();
6811       return;
6812     }
6813 
6814     if (!FixedTInfo) {
6815       if (NewVD->isFileVarDecl())
6816         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6817       else
6818         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6819       NewVD->setInvalidDecl();
6820       return;
6821     }
6822 
6823     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6824     NewVD->setType(FixedTInfo->getType());
6825     NewVD->setTypeSourceInfo(FixedTInfo);
6826   }
6827 
6828   if (T->isVoidType()) {
6829     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6830     //                    of objects and functions.
6831     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6832       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6833         << T;
6834       NewVD->setInvalidDecl();
6835       return;
6836     }
6837   }
6838 
6839   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6840     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6841     NewVD->setInvalidDecl();
6842     return;
6843   }
6844 
6845   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6846     Diag(NewVD->getLocation(), diag::err_block_on_vm);
6847     NewVD->setInvalidDecl();
6848     return;
6849   }
6850 
6851   if (NewVD->isConstexpr() && !T->isDependentType() &&
6852       RequireLiteralType(NewVD->getLocation(), T,
6853                          diag::err_constexpr_var_non_literal)) {
6854     NewVD->setInvalidDecl();
6855     return;
6856   }
6857 }
6858 
6859 /// \brief Perform semantic checking on a newly-created variable
6860 /// declaration.
6861 ///
6862 /// This routine performs all of the type-checking required for a
6863 /// variable declaration once it has been built. It is used both to
6864 /// check variables after they have been parsed and their declarators
6865 /// have been translated into a declaration, and to check variables
6866 /// that have been instantiated from a template.
6867 ///
6868 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6869 ///
6870 /// Returns true if the variable declaration is a redeclaration.
6871 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6872   CheckVariableDeclarationType(NewVD);
6873 
6874   // If the decl is already known invalid, don't check it.
6875   if (NewVD->isInvalidDecl())
6876     return false;
6877 
6878   // If we did not find anything by this name, look for a non-visible
6879   // extern "C" declaration with the same name.
6880   if (Previous.empty() &&
6881       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6882     Previous.setShadowed();
6883 
6884   if (!Previous.empty()) {
6885     MergeVarDecl(NewVD, Previous);
6886     return true;
6887   }
6888   return false;
6889 }
6890 
6891 namespace {
6892 struct FindOverriddenMethod {
6893   Sema *S;
6894   CXXMethodDecl *Method;
6895 
6896   /// Member lookup function that determines whether a given C++
6897   /// method overrides a method in a base class, to be used with
6898   /// CXXRecordDecl::lookupInBases().
6899   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
6900     RecordDecl *BaseRecord =
6901         Specifier->getType()->getAs<RecordType>()->getDecl();
6902 
6903     DeclarationName Name = Method->getDeclName();
6904 
6905     // FIXME: Do we care about other names here too?
6906     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6907       // We really want to find the base class destructor here.
6908       QualType T = S->Context.getTypeDeclType(BaseRecord);
6909       CanQualType CT = S->Context.getCanonicalType(T);
6910 
6911       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
6912     }
6913 
6914     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
6915          Path.Decls = Path.Decls.slice(1)) {
6916       NamedDecl *D = Path.Decls.front();
6917       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6918         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
6919           return true;
6920       }
6921     }
6922 
6923     return false;
6924   }
6925 };
6926 
6927 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6928 } // end anonymous namespace
6929 
6930 /// \brief Report an error regarding overriding, along with any relevant
6931 /// overriden methods.
6932 ///
6933 /// \param DiagID the primary error to report.
6934 /// \param MD the overriding method.
6935 /// \param OEK which overrides to include as notes.
6936 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6937                             OverrideErrorKind OEK = OEK_All) {
6938   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6939   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6940                                       E = MD->end_overridden_methods();
6941        I != E; ++I) {
6942     // This check (& the OEK parameter) could be replaced by a predicate, but
6943     // without lambdas that would be overkill. This is still nicer than writing
6944     // out the diag loop 3 times.
6945     if ((OEK == OEK_All) ||
6946         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6947         (OEK == OEK_Deleted && (*I)->isDeleted()))
6948       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6949   }
6950 }
6951 
6952 /// AddOverriddenMethods - See if a method overrides any in the base classes,
6953 /// and if so, check that it's a valid override and remember it.
6954 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
6955   // Look for methods in base classes that this method might override.
6956   CXXBasePaths Paths;
6957   FindOverriddenMethod FOM;
6958   FOM.Method = MD;
6959   FOM.S = this;
6960   bool hasDeletedOverridenMethods = false;
6961   bool hasNonDeletedOverridenMethods = false;
6962   bool AddedAny = false;
6963   if (DC->lookupInBases(FOM, Paths)) {
6964     for (auto *I : Paths.found_decls()) {
6965       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
6966         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
6967         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
6968             !CheckOverridingFunctionAttributes(MD, OldMD) &&
6969             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
6970             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
6971           hasDeletedOverridenMethods |= OldMD->isDeleted();
6972           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
6973           AddedAny = true;
6974         }
6975       }
6976     }
6977   }
6978 
6979   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6980     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6981   }
6982   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6983     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6984   }
6985 
6986   return AddedAny;
6987 }
6988 
6989 namespace {
6990   // Struct for holding all of the extra arguments needed by
6991   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6992   struct ActOnFDArgs {
6993     Scope *S;
6994     Declarator &D;
6995     MultiTemplateParamsArg TemplateParamLists;
6996     bool AddToScope;
6997   };
6998 } // end anonymous namespace
6999 
7000 namespace {
7001 
7002 // Callback to only accept typo corrections that have a non-zero edit distance.
7003 // Also only accept corrections that have the same parent decl.
7004 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7005  public:
7006   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7007                             CXXRecordDecl *Parent)
7008       : Context(Context), OriginalFD(TypoFD),
7009         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7010 
7011   bool ValidateCandidate(const TypoCorrection &candidate) override {
7012     if (candidate.getEditDistance() == 0)
7013       return false;
7014 
7015     SmallVector<unsigned, 1> MismatchedParams;
7016     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7017                                           CDeclEnd = candidate.end();
7018          CDecl != CDeclEnd; ++CDecl) {
7019       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7020 
7021       if (FD && !FD->hasBody() &&
7022           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7023         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7024           CXXRecordDecl *Parent = MD->getParent();
7025           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7026             return true;
7027         } else if (!ExpectedParent) {
7028           return true;
7029         }
7030       }
7031     }
7032 
7033     return false;
7034   }
7035 
7036  private:
7037   ASTContext &Context;
7038   FunctionDecl *OriginalFD;
7039   CXXRecordDecl *ExpectedParent;
7040 };
7041 
7042 } // end anonymous namespace
7043 
7044 /// \brief Generate diagnostics for an invalid function redeclaration.
7045 ///
7046 /// This routine handles generating the diagnostic messages for an invalid
7047 /// function redeclaration, including finding possible similar declarations
7048 /// or performing typo correction if there are no previous declarations with
7049 /// the same name.
7050 ///
7051 /// Returns a NamedDecl iff typo correction was performed and substituting in
7052 /// the new declaration name does not cause new errors.
7053 static NamedDecl *DiagnoseInvalidRedeclaration(
7054     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7055     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7056   DeclarationName Name = NewFD->getDeclName();
7057   DeclContext *NewDC = NewFD->getDeclContext();
7058   SmallVector<unsigned, 1> MismatchedParams;
7059   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7060   TypoCorrection Correction;
7061   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7062   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7063                                    : diag::err_member_decl_does_not_match;
7064   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7065                     IsLocalFriend ? Sema::LookupLocalFriendName
7066                                   : Sema::LookupOrdinaryName,
7067                     Sema::ForRedeclaration);
7068 
7069   NewFD->setInvalidDecl();
7070   if (IsLocalFriend)
7071     SemaRef.LookupName(Prev, S);
7072   else
7073     SemaRef.LookupQualifiedName(Prev, NewDC);
7074   assert(!Prev.isAmbiguous() &&
7075          "Cannot have an ambiguity in previous-declaration lookup");
7076   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7077   if (!Prev.empty()) {
7078     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7079          Func != FuncEnd; ++Func) {
7080       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7081       if (FD &&
7082           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7083         // Add 1 to the index so that 0 can mean the mismatch didn't
7084         // involve a parameter
7085         unsigned ParamNum =
7086             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7087         NearMatches.push_back(std::make_pair(FD, ParamNum));
7088       }
7089     }
7090   // If the qualified name lookup yielded nothing, try typo correction
7091   } else if ((Correction = SemaRef.CorrectTypo(
7092                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7093                   &ExtraArgs.D.getCXXScopeSpec(),
7094                   llvm::make_unique<DifferentNameValidatorCCC>(
7095                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7096                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7097     // Set up everything for the call to ActOnFunctionDeclarator
7098     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7099                               ExtraArgs.D.getIdentifierLoc());
7100     Previous.clear();
7101     Previous.setLookupName(Correction.getCorrection());
7102     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7103                                     CDeclEnd = Correction.end();
7104          CDecl != CDeclEnd; ++CDecl) {
7105       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7106       if (FD && !FD->hasBody() &&
7107           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7108         Previous.addDecl(FD);
7109       }
7110     }
7111     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7112 
7113     NamedDecl *Result;
7114     // Retry building the function declaration with the new previous
7115     // declarations, and with errors suppressed.
7116     {
7117       // Trap errors.
7118       Sema::SFINAETrap Trap(SemaRef);
7119 
7120       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7121       // pieces need to verify the typo-corrected C++ declaration and hopefully
7122       // eliminate the need for the parameter pack ExtraArgs.
7123       Result = SemaRef.ActOnFunctionDeclarator(
7124           ExtraArgs.S, ExtraArgs.D,
7125           Correction.getCorrectionDecl()->getDeclContext(),
7126           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7127           ExtraArgs.AddToScope);
7128 
7129       if (Trap.hasErrorOccurred())
7130         Result = nullptr;
7131     }
7132 
7133     if (Result) {
7134       // Determine which correction we picked.
7135       Decl *Canonical = Result->getCanonicalDecl();
7136       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7137            I != E; ++I)
7138         if ((*I)->getCanonicalDecl() == Canonical)
7139           Correction.setCorrectionDecl(*I);
7140 
7141       SemaRef.diagnoseTypo(
7142           Correction,
7143           SemaRef.PDiag(IsLocalFriend
7144                           ? diag::err_no_matching_local_friend_suggest
7145                           : diag::err_member_decl_does_not_match_suggest)
7146             << Name << NewDC << IsDefinition);
7147       return Result;
7148     }
7149 
7150     // Pretend the typo correction never occurred
7151     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7152                               ExtraArgs.D.getIdentifierLoc());
7153     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7154     Previous.clear();
7155     Previous.setLookupName(Name);
7156   }
7157 
7158   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7159       << Name << NewDC << IsDefinition << NewFD->getLocation();
7160 
7161   bool NewFDisConst = false;
7162   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7163     NewFDisConst = NewMD->isConst();
7164 
7165   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7166        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7167        NearMatch != NearMatchEnd; ++NearMatch) {
7168     FunctionDecl *FD = NearMatch->first;
7169     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7170     bool FDisConst = MD && MD->isConst();
7171     bool IsMember = MD || !IsLocalFriend;
7172 
7173     // FIXME: These notes are poorly worded for the local friend case.
7174     if (unsigned Idx = NearMatch->second) {
7175       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7176       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7177       if (Loc.isInvalid()) Loc = FD->getLocation();
7178       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7179                                  : diag::note_local_decl_close_param_match)
7180         << Idx << FDParam->getType()
7181         << NewFD->getParamDecl(Idx - 1)->getType();
7182     } else if (FDisConst != NewFDisConst) {
7183       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7184           << NewFDisConst << FD->getSourceRange().getEnd();
7185     } else
7186       SemaRef.Diag(FD->getLocation(),
7187                    IsMember ? diag::note_member_def_close_match
7188                             : diag::note_local_decl_close_match);
7189   }
7190   return nullptr;
7191 }
7192 
7193 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7194   switch (D.getDeclSpec().getStorageClassSpec()) {
7195   default: llvm_unreachable("Unknown storage class!");
7196   case DeclSpec::SCS_auto:
7197   case DeclSpec::SCS_register:
7198   case DeclSpec::SCS_mutable:
7199     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7200                  diag::err_typecheck_sclass_func);
7201     D.setInvalidType();
7202     break;
7203   case DeclSpec::SCS_unspecified: break;
7204   case DeclSpec::SCS_extern:
7205     if (D.getDeclSpec().isExternInLinkageSpec())
7206       return SC_None;
7207     return SC_Extern;
7208   case DeclSpec::SCS_static: {
7209     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7210       // C99 6.7.1p5:
7211       //   The declaration of an identifier for a function that has
7212       //   block scope shall have no explicit storage-class specifier
7213       //   other than extern
7214       // See also (C++ [dcl.stc]p4).
7215       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7216                    diag::err_static_block_func);
7217       break;
7218     } else
7219       return SC_Static;
7220   }
7221   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7222   }
7223 
7224   // No explicit storage class has already been returned
7225   return SC_None;
7226 }
7227 
7228 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7229                                            DeclContext *DC, QualType &R,
7230                                            TypeSourceInfo *TInfo,
7231                                            StorageClass SC,
7232                                            bool &IsVirtualOkay) {
7233   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7234   DeclarationName Name = NameInfo.getName();
7235 
7236   FunctionDecl *NewFD = nullptr;
7237   bool isInline = D.getDeclSpec().isInlineSpecified();
7238 
7239   if (!SemaRef.getLangOpts().CPlusPlus) {
7240     // Determine whether the function was written with a
7241     // prototype. This true when:
7242     //   - there is a prototype in the declarator, or
7243     //   - the type R of the function is some kind of typedef or other reference
7244     //     to a type name (which eventually refers to a function type).
7245     bool HasPrototype =
7246       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7247       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
7248 
7249     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7250                                  D.getLocStart(), NameInfo, R,
7251                                  TInfo, SC, isInline,
7252                                  HasPrototype, false);
7253     if (D.isInvalidType())
7254       NewFD->setInvalidDecl();
7255 
7256     return NewFD;
7257   }
7258 
7259   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7260   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7261 
7262   // Check that the return type is not an abstract class type.
7263   // For record types, this is done by the AbstractClassUsageDiagnoser once
7264   // the class has been completely parsed.
7265   if (!DC->isRecord() &&
7266       SemaRef.RequireNonAbstractType(
7267           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7268           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7269     D.setInvalidType();
7270 
7271   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7272     // This is a C++ constructor declaration.
7273     assert(DC->isRecord() &&
7274            "Constructors can only be declared in a member context");
7275 
7276     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7277     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7278                                       D.getLocStart(), NameInfo,
7279                                       R, TInfo, isExplicit, isInline,
7280                                       /*isImplicitlyDeclared=*/false,
7281                                       isConstexpr);
7282 
7283   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7284     // This is a C++ destructor declaration.
7285     if (DC->isRecord()) {
7286       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7287       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7288       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7289                                         SemaRef.Context, Record,
7290                                         D.getLocStart(),
7291                                         NameInfo, R, TInfo, isInline,
7292                                         /*isImplicitlyDeclared=*/false);
7293 
7294       // If the class is complete, then we now create the implicit exception
7295       // specification. If the class is incomplete or dependent, we can't do
7296       // it yet.
7297       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7298           Record->getDefinition() && !Record->isBeingDefined() &&
7299           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7300         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7301       }
7302 
7303       IsVirtualOkay = true;
7304       return NewDD;
7305 
7306     } else {
7307       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7308       D.setInvalidType();
7309 
7310       // Create a FunctionDecl to satisfy the function definition parsing
7311       // code path.
7312       return FunctionDecl::Create(SemaRef.Context, DC,
7313                                   D.getLocStart(),
7314                                   D.getIdentifierLoc(), Name, R, TInfo,
7315                                   SC, isInline,
7316                                   /*hasPrototype=*/true, isConstexpr);
7317     }
7318 
7319   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7320     if (!DC->isRecord()) {
7321       SemaRef.Diag(D.getIdentifierLoc(),
7322            diag::err_conv_function_not_member);
7323       return nullptr;
7324     }
7325 
7326     SemaRef.CheckConversionDeclarator(D, R, SC);
7327     IsVirtualOkay = true;
7328     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7329                                      D.getLocStart(), NameInfo,
7330                                      R, TInfo, isInline, isExplicit,
7331                                      isConstexpr, SourceLocation());
7332 
7333   } else if (DC->isRecord()) {
7334     // If the name of the function is the same as the name of the record,
7335     // then this must be an invalid constructor that has a return type.
7336     // (The parser checks for a return type and makes the declarator a
7337     // constructor if it has no return type).
7338     if (Name.getAsIdentifierInfo() &&
7339         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7340       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7341         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7342         << SourceRange(D.getIdentifierLoc());
7343       return nullptr;
7344     }
7345 
7346     // This is a C++ method declaration.
7347     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7348                                                cast<CXXRecordDecl>(DC),
7349                                                D.getLocStart(), NameInfo, R,
7350                                                TInfo, SC, isInline,
7351                                                isConstexpr, SourceLocation());
7352     IsVirtualOkay = !Ret->isStatic();
7353     return Ret;
7354   } else {
7355     bool isFriend =
7356         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7357     if (!isFriend && SemaRef.CurContext->isRecord())
7358       return nullptr;
7359 
7360     // Determine whether the function was written with a
7361     // prototype. This true when:
7362     //   - we're in C++ (where every function has a prototype),
7363     return FunctionDecl::Create(SemaRef.Context, DC,
7364                                 D.getLocStart(),
7365                                 NameInfo, R, TInfo, SC, isInline,
7366                                 true/*HasPrototype*/, isConstexpr);
7367   }
7368 }
7369 
7370 enum OpenCLParamType {
7371   ValidKernelParam,
7372   PtrPtrKernelParam,
7373   PtrKernelParam,
7374   PrivatePtrKernelParam,
7375   InvalidKernelParam,
7376   RecordKernelParam
7377 };
7378 
7379 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
7380   if (PT->isPointerType()) {
7381     QualType PointeeType = PT->getPointeeType();
7382     if (PointeeType->isPointerType())
7383       return PtrPtrKernelParam;
7384     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
7385                                               : PtrKernelParam;
7386   }
7387 
7388   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7389   // be used as builtin types.
7390 
7391   if (PT->isImageType())
7392     return PtrKernelParam;
7393 
7394   if (PT->isBooleanType())
7395     return InvalidKernelParam;
7396 
7397   if (PT->isEventT())
7398     return InvalidKernelParam;
7399 
7400   if (PT->isHalfType())
7401     return InvalidKernelParam;
7402 
7403   if (PT->isRecordType())
7404     return RecordKernelParam;
7405 
7406   return ValidKernelParam;
7407 }
7408 
7409 static void checkIsValidOpenCLKernelParameter(
7410   Sema &S,
7411   Declarator &D,
7412   ParmVarDecl *Param,
7413   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7414   QualType PT = Param->getType();
7415 
7416   // Cache the valid types we encounter to avoid rechecking structs that are
7417   // used again
7418   if (ValidTypes.count(PT.getTypePtr()))
7419     return;
7420 
7421   switch (getOpenCLKernelParameterType(PT)) {
7422   case PtrPtrKernelParam:
7423     // OpenCL v1.2 s6.9.a:
7424     // A kernel function argument cannot be declared as a
7425     // pointer to a pointer type.
7426     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7427     D.setInvalidType();
7428     return;
7429 
7430   case PrivatePtrKernelParam:
7431     // OpenCL v1.2 s6.9.a:
7432     // A kernel function argument cannot be declared as a
7433     // pointer to the private address space.
7434     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
7435     D.setInvalidType();
7436     return;
7437 
7438     // OpenCL v1.2 s6.9.k:
7439     // Arguments to kernel functions in a program cannot be declared with the
7440     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7441     // uintptr_t or a struct and/or union that contain fields declared to be
7442     // one of these built-in scalar types.
7443 
7444   case InvalidKernelParam:
7445     // OpenCL v1.2 s6.8 n:
7446     // A kernel function argument cannot be declared
7447     // of event_t type.
7448     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7449     D.setInvalidType();
7450     return;
7451 
7452   case PtrKernelParam:
7453   case ValidKernelParam:
7454     ValidTypes.insert(PT.getTypePtr());
7455     return;
7456 
7457   case RecordKernelParam:
7458     break;
7459   }
7460 
7461   // Track nested structs we will inspect
7462   SmallVector<const Decl *, 4> VisitStack;
7463 
7464   // Track where we are in the nested structs. Items will migrate from
7465   // VisitStack to HistoryStack as we do the DFS for bad field.
7466   SmallVector<const FieldDecl *, 4> HistoryStack;
7467   HistoryStack.push_back(nullptr);
7468 
7469   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7470   VisitStack.push_back(PD);
7471 
7472   assert(VisitStack.back() && "First decl null?");
7473 
7474   do {
7475     const Decl *Next = VisitStack.pop_back_val();
7476     if (!Next) {
7477       assert(!HistoryStack.empty());
7478       // Found a marker, we have gone up a level
7479       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7480         ValidTypes.insert(Hist->getType().getTypePtr());
7481 
7482       continue;
7483     }
7484 
7485     // Adds everything except the original parameter declaration (which is not a
7486     // field itself) to the history stack.
7487     const RecordDecl *RD;
7488     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7489       HistoryStack.push_back(Field);
7490       RD = Field->getType()->castAs<RecordType>()->getDecl();
7491     } else {
7492       RD = cast<RecordDecl>(Next);
7493     }
7494 
7495     // Add a null marker so we know when we've gone back up a level
7496     VisitStack.push_back(nullptr);
7497 
7498     for (const auto *FD : RD->fields()) {
7499       QualType QT = FD->getType();
7500 
7501       if (ValidTypes.count(QT.getTypePtr()))
7502         continue;
7503 
7504       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
7505       if (ParamType == ValidKernelParam)
7506         continue;
7507 
7508       if (ParamType == RecordKernelParam) {
7509         VisitStack.push_back(FD);
7510         continue;
7511       }
7512 
7513       // OpenCL v1.2 s6.9.p:
7514       // Arguments to kernel functions that are declared to be a struct or union
7515       // do not allow OpenCL objects to be passed as elements of the struct or
7516       // union.
7517       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7518           ParamType == PrivatePtrKernelParam) {
7519         S.Diag(Param->getLocation(),
7520                diag::err_record_with_pointers_kernel_param)
7521           << PT->isUnionType()
7522           << PT;
7523       } else {
7524         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7525       }
7526 
7527       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7528         << PD->getDeclName();
7529 
7530       // We have an error, now let's go back up through history and show where
7531       // the offending field came from
7532       for (ArrayRef<const FieldDecl *>::const_iterator
7533                I = HistoryStack.begin() + 1,
7534                E = HistoryStack.end();
7535            I != E; ++I) {
7536         const FieldDecl *OuterField = *I;
7537         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7538           << OuterField->getType();
7539       }
7540 
7541       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7542         << QT->isPointerType()
7543         << QT;
7544       D.setInvalidType();
7545       return;
7546     }
7547   } while (!VisitStack.empty());
7548 }
7549 
7550 NamedDecl*
7551 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7552                               TypeSourceInfo *TInfo, LookupResult &Previous,
7553                               MultiTemplateParamsArg TemplateParamLists,
7554                               bool &AddToScope) {
7555   QualType R = TInfo->getType();
7556 
7557   assert(R.getTypePtr()->isFunctionType());
7558 
7559   // TODO: consider using NameInfo for diagnostic.
7560   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7561   DeclarationName Name = NameInfo.getName();
7562   StorageClass SC = getFunctionStorageClass(*this, D);
7563 
7564   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7565     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7566          diag::err_invalid_thread)
7567       << DeclSpec::getSpecifierName(TSCS);
7568 
7569   if (D.isFirstDeclarationOfMember())
7570     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7571                            D.getIdentifierLoc());
7572 
7573   bool isFriend = false;
7574   FunctionTemplateDecl *FunctionTemplate = nullptr;
7575   bool isExplicitSpecialization = false;
7576   bool isFunctionTemplateSpecialization = false;
7577 
7578   bool isDependentClassScopeExplicitSpecialization = false;
7579   bool HasExplicitTemplateArgs = false;
7580   TemplateArgumentListInfo TemplateArgs;
7581 
7582   bool isVirtualOkay = false;
7583 
7584   DeclContext *OriginalDC = DC;
7585   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7586 
7587   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7588                                               isVirtualOkay);
7589   if (!NewFD) return nullptr;
7590 
7591   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7592     NewFD->setTopLevelDeclInObjCContainer();
7593 
7594   // Set the lexical context. If this is a function-scope declaration, or has a
7595   // C++ scope specifier, or is the object of a friend declaration, the lexical
7596   // context will be different from the semantic context.
7597   NewFD->setLexicalDeclContext(CurContext);
7598 
7599   if (IsLocalExternDecl)
7600     NewFD->setLocalExternDecl();
7601 
7602   if (getLangOpts().CPlusPlus) {
7603     bool isInline = D.getDeclSpec().isInlineSpecified();
7604     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7605     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7606     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7607     bool isConcept = D.getDeclSpec().isConceptSpecified();
7608     isFriend = D.getDeclSpec().isFriendSpecified();
7609     if (isFriend && !isInline && D.isFunctionDefinition()) {
7610       // C++ [class.friend]p5
7611       //   A function can be defined in a friend declaration of a
7612       //   class . . . . Such a function is implicitly inline.
7613       NewFD->setImplicitlyInline();
7614     }
7615 
7616     // If this is a method defined in an __interface, and is not a constructor
7617     // or an overloaded operator, then set the pure flag (isVirtual will already
7618     // return true).
7619     if (const CXXRecordDecl *Parent =
7620           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7621       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7622         NewFD->setPure(true);
7623 
7624       // C++ [class.union]p2
7625       //   A union can have member functions, but not virtual functions.
7626       if (isVirtual && Parent->isUnion())
7627         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7628     }
7629 
7630     SetNestedNameSpecifier(NewFD, D);
7631     isExplicitSpecialization = false;
7632     isFunctionTemplateSpecialization = false;
7633     if (D.isInvalidType())
7634       NewFD->setInvalidDecl();
7635 
7636     // Match up the template parameter lists with the scope specifier, then
7637     // determine whether we have a template or a template specialization.
7638     bool Invalid = false;
7639     if (TemplateParameterList *TemplateParams =
7640             MatchTemplateParametersToScopeSpecifier(
7641                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7642                 D.getCXXScopeSpec(),
7643                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7644                     ? D.getName().TemplateId
7645                     : nullptr,
7646                 TemplateParamLists, isFriend, isExplicitSpecialization,
7647                 Invalid)) {
7648       if (TemplateParams->size() > 0) {
7649         // This is a function template
7650 
7651         // Check that we can declare a template here.
7652         if (CheckTemplateDeclScope(S, TemplateParams))
7653           NewFD->setInvalidDecl();
7654 
7655         // A destructor cannot be a template.
7656         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7657           Diag(NewFD->getLocation(), diag::err_destructor_template);
7658           NewFD->setInvalidDecl();
7659         }
7660 
7661         // If we're adding a template to a dependent context, we may need to
7662         // rebuilding some of the types used within the template parameter list,
7663         // now that we know what the current instantiation is.
7664         if (DC->isDependentContext()) {
7665           ContextRAII SavedContext(*this, DC);
7666           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7667             Invalid = true;
7668         }
7669 
7670         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7671                                                         NewFD->getLocation(),
7672                                                         Name, TemplateParams,
7673                                                         NewFD);
7674         FunctionTemplate->setLexicalDeclContext(CurContext);
7675         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7676 
7677         // For source fidelity, store the other template param lists.
7678         if (TemplateParamLists.size() > 1) {
7679           NewFD->setTemplateParameterListsInfo(Context,
7680                                                TemplateParamLists.drop_back(1));
7681         }
7682       } else {
7683         // This is a function template specialization.
7684         isFunctionTemplateSpecialization = true;
7685         // For source fidelity, store all the template param lists.
7686         if (TemplateParamLists.size() > 0)
7687           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7688 
7689         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7690         if (isFriend) {
7691           // We want to remove the "template<>", found here.
7692           SourceRange RemoveRange = TemplateParams->getSourceRange();
7693 
7694           // If we remove the template<> and the name is not a
7695           // template-id, we're actually silently creating a problem:
7696           // the friend declaration will refer to an untemplated decl,
7697           // and clearly the user wants a template specialization.  So
7698           // we need to insert '<>' after the name.
7699           SourceLocation InsertLoc;
7700           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7701             InsertLoc = D.getName().getSourceRange().getEnd();
7702             InsertLoc = getLocForEndOfToken(InsertLoc);
7703           }
7704 
7705           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7706             << Name << RemoveRange
7707             << FixItHint::CreateRemoval(RemoveRange)
7708             << FixItHint::CreateInsertion(InsertLoc, "<>");
7709         }
7710       }
7711     }
7712     else {
7713       // All template param lists were matched against the scope specifier:
7714       // this is NOT (an explicit specialization of) a template.
7715       if (TemplateParamLists.size() > 0)
7716         // For source fidelity, store all the template param lists.
7717         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7718     }
7719 
7720     if (Invalid) {
7721       NewFD->setInvalidDecl();
7722       if (FunctionTemplate)
7723         FunctionTemplate->setInvalidDecl();
7724     }
7725 
7726     // C++ [dcl.fct.spec]p5:
7727     //   The virtual specifier shall only be used in declarations of
7728     //   nonstatic class member functions that appear within a
7729     //   member-specification of a class declaration; see 10.3.
7730     //
7731     if (isVirtual && !NewFD->isInvalidDecl()) {
7732       if (!isVirtualOkay) {
7733         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7734              diag::err_virtual_non_function);
7735       } else if (!CurContext->isRecord()) {
7736         // 'virtual' was specified outside of the class.
7737         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7738              diag::err_virtual_out_of_class)
7739           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7740       } else if (NewFD->getDescribedFunctionTemplate()) {
7741         // C++ [temp.mem]p3:
7742         //  A member function template shall not be virtual.
7743         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7744              diag::err_virtual_member_function_template)
7745           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7746       } else {
7747         // Okay: Add virtual to the method.
7748         NewFD->setVirtualAsWritten(true);
7749       }
7750 
7751       if (getLangOpts().CPlusPlus14 &&
7752           NewFD->getReturnType()->isUndeducedType())
7753         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7754     }
7755 
7756     if (getLangOpts().CPlusPlus14 &&
7757         (NewFD->isDependentContext() ||
7758          (isFriend && CurContext->isDependentContext())) &&
7759         NewFD->getReturnType()->isUndeducedType()) {
7760       // If the function template is referenced directly (for instance, as a
7761       // member of the current instantiation), pretend it has a dependent type.
7762       // This is not really justified by the standard, but is the only sane
7763       // thing to do.
7764       // FIXME: For a friend function, we have not marked the function as being
7765       // a friend yet, so 'isDependentContext' on the FD doesn't work.
7766       const FunctionProtoType *FPT =
7767           NewFD->getType()->castAs<FunctionProtoType>();
7768       QualType Result =
7769           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7770       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7771                                              FPT->getExtProtoInfo()));
7772     }
7773 
7774     // C++ [dcl.fct.spec]p3:
7775     //  The inline specifier shall not appear on a block scope function
7776     //  declaration.
7777     if (isInline && !NewFD->isInvalidDecl()) {
7778       if (CurContext->isFunctionOrMethod()) {
7779         // 'inline' is not allowed on block scope function declaration.
7780         Diag(D.getDeclSpec().getInlineSpecLoc(),
7781              diag::err_inline_declaration_block_scope) << Name
7782           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7783       }
7784     }
7785 
7786     // C++ [dcl.fct.spec]p6:
7787     //  The explicit specifier shall be used only in the declaration of a
7788     //  constructor or conversion function within its class definition;
7789     //  see 12.3.1 and 12.3.2.
7790     if (isExplicit && !NewFD->isInvalidDecl()) {
7791       if (!CurContext->isRecord()) {
7792         // 'explicit' was specified outside of the class.
7793         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7794              diag::err_explicit_out_of_class)
7795           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7796       } else if (!isa<CXXConstructorDecl>(NewFD) &&
7797                  !isa<CXXConversionDecl>(NewFD)) {
7798         // 'explicit' was specified on a function that wasn't a constructor
7799         // or conversion function.
7800         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7801              diag::err_explicit_non_ctor_or_conv_function)
7802           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7803       }
7804     }
7805 
7806     if (isConstexpr) {
7807       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7808       // are implicitly inline.
7809       NewFD->setImplicitlyInline();
7810 
7811       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7812       // be either constructors or to return a literal type. Therefore,
7813       // destructors cannot be declared constexpr.
7814       if (isa<CXXDestructorDecl>(NewFD))
7815         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7816     }
7817 
7818     if (isConcept) {
7819       // This is a function concept.
7820       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
7821         FTD->setConcept();
7822 
7823       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7824       // applied only to the definition of a function template [...]
7825       if (!D.isFunctionDefinition()) {
7826         Diag(D.getDeclSpec().getConceptSpecLoc(),
7827              diag::err_function_concept_not_defined);
7828         NewFD->setInvalidDecl();
7829       }
7830 
7831       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
7832       // have no exception-specification and is treated as if it were specified
7833       // with noexcept(true) (15.4). [...]
7834       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
7835         if (FPT->hasExceptionSpec()) {
7836           SourceRange Range;
7837           if (D.isFunctionDeclarator())
7838             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
7839           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
7840               << FixItHint::CreateRemoval(Range);
7841           NewFD->setInvalidDecl();
7842         } else {
7843           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
7844         }
7845 
7846         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7847         // following restrictions:
7848         // - The declared return type shall have the type bool.
7849         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
7850           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
7851           NewFD->setInvalidDecl();
7852         }
7853 
7854         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7855         // following restrictions:
7856         // - The declaration's parameter list shall be equivalent to an empty
7857         //   parameter list.
7858         if (FPT->getNumParams() > 0 || FPT->isVariadic())
7859           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
7860       }
7861 
7862       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
7863       // implicity defined to be a constexpr declaration (implicitly inline)
7864       NewFD->setImplicitlyInline();
7865 
7866       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
7867       // be declared with the thread_local, inline, friend, or constexpr
7868       // specifiers, [...]
7869       if (isInline) {
7870         Diag(D.getDeclSpec().getInlineSpecLoc(),
7871              diag::err_concept_decl_invalid_specifiers)
7872             << 1 << 1;
7873         NewFD->setInvalidDecl(true);
7874       }
7875 
7876       if (isFriend) {
7877         Diag(D.getDeclSpec().getFriendSpecLoc(),
7878              diag::err_concept_decl_invalid_specifiers)
7879             << 1 << 2;
7880         NewFD->setInvalidDecl(true);
7881       }
7882 
7883       if (isConstexpr) {
7884         Diag(D.getDeclSpec().getConstexprSpecLoc(),
7885              diag::err_concept_decl_invalid_specifiers)
7886             << 1 << 3;
7887         NewFD->setInvalidDecl(true);
7888       }
7889 
7890       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7891       // applied only to the definition of a function template or variable
7892       // template, declared in namespace scope.
7893       if (isFunctionTemplateSpecialization) {
7894         Diag(D.getDeclSpec().getConceptSpecLoc(),
7895              diag::err_concept_specified_specialization) << 1;
7896         NewFD->setInvalidDecl(true);
7897         return NewFD;
7898       }
7899     }
7900 
7901     // If __module_private__ was specified, mark the function accordingly.
7902     if (D.getDeclSpec().isModulePrivateSpecified()) {
7903       if (isFunctionTemplateSpecialization) {
7904         SourceLocation ModulePrivateLoc
7905           = D.getDeclSpec().getModulePrivateSpecLoc();
7906         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
7907           << 0
7908           << FixItHint::CreateRemoval(ModulePrivateLoc);
7909       } else {
7910         NewFD->setModulePrivate();
7911         if (FunctionTemplate)
7912           FunctionTemplate->setModulePrivate();
7913       }
7914     }
7915 
7916     if (isFriend) {
7917       if (FunctionTemplate) {
7918         FunctionTemplate->setObjectOfFriendDecl();
7919         FunctionTemplate->setAccess(AS_public);
7920       }
7921       NewFD->setObjectOfFriendDecl();
7922       NewFD->setAccess(AS_public);
7923     }
7924 
7925     // If a function is defined as defaulted or deleted, mark it as such now.
7926     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
7927     // definition kind to FDK_Definition.
7928     switch (D.getFunctionDefinitionKind()) {
7929       case FDK_Declaration:
7930       case FDK_Definition:
7931         break;
7932 
7933       case FDK_Defaulted:
7934         NewFD->setDefaulted();
7935         break;
7936 
7937       case FDK_Deleted:
7938         NewFD->setDeletedAsWritten();
7939         break;
7940     }
7941 
7942     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
7943         D.isFunctionDefinition()) {
7944       // C++ [class.mfct]p2:
7945       //   A member function may be defined (8.4) in its class definition, in
7946       //   which case it is an inline member function (7.1.2)
7947       NewFD->setImplicitlyInline();
7948     }
7949 
7950     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
7951         !CurContext->isRecord()) {
7952       // C++ [class.static]p1:
7953       //   A data or function member of a class may be declared static
7954       //   in a class definition, in which case it is a static member of
7955       //   the class.
7956 
7957       // Complain about the 'static' specifier if it's on an out-of-line
7958       // member function definition.
7959       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7960            diag::err_static_out_of_line)
7961         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7962     }
7963 
7964     // C++11 [except.spec]p15:
7965     //   A deallocation function with no exception-specification is treated
7966     //   as if it were specified with noexcept(true).
7967     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
7968     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
7969          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
7970         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
7971       NewFD->setType(Context.getFunctionType(
7972           FPT->getReturnType(), FPT->getParamTypes(),
7973           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
7974   }
7975 
7976   // Filter out previous declarations that don't match the scope.
7977   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
7978                        D.getCXXScopeSpec().isNotEmpty() ||
7979                        isExplicitSpecialization ||
7980                        isFunctionTemplateSpecialization);
7981 
7982   // Handle GNU asm-label extension (encoded as an attribute).
7983   if (Expr *E = (Expr*) D.getAsmLabel()) {
7984     // The parser guarantees this is a string.
7985     StringLiteral *SE = cast<StringLiteral>(E);
7986     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
7987                                                 SE->getString(), 0));
7988   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7989     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7990       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
7991     if (I != ExtnameUndeclaredIdentifiers.end()) {
7992       if (isDeclExternC(NewFD)) {
7993         NewFD->addAttr(I->second);
7994         ExtnameUndeclaredIdentifiers.erase(I);
7995       } else
7996         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
7997             << /*Variable*/0 << NewFD;
7998     }
7999   }
8000 
8001   // Copy the parameter declarations from the declarator D to the function
8002   // declaration NewFD, if they are available.  First scavenge them into Params.
8003   SmallVector<ParmVarDecl*, 16> Params;
8004   if (D.isFunctionDeclarator()) {
8005     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8006 
8007     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8008     // function that takes no arguments, not a function that takes a
8009     // single void argument.
8010     // We let through "const void" here because Sema::GetTypeForDeclarator
8011     // already checks for that case.
8012     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8013       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8014         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8015         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8016         Param->setDeclContext(NewFD);
8017         Params.push_back(Param);
8018 
8019         if (Param->isInvalidDecl())
8020           NewFD->setInvalidDecl();
8021       }
8022     }
8023   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8024     // When we're declaring a function with a typedef, typeof, etc as in the
8025     // following example, we'll need to synthesize (unnamed)
8026     // parameters for use in the declaration.
8027     //
8028     // @code
8029     // typedef void fn(int);
8030     // fn f;
8031     // @endcode
8032 
8033     // Synthesize a parameter for each argument type.
8034     for (const auto &AI : FT->param_types()) {
8035       ParmVarDecl *Param =
8036           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8037       Param->setScopeInfo(0, Params.size());
8038       Params.push_back(Param);
8039     }
8040   } else {
8041     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8042            "Should not need args for typedef of non-prototype fn");
8043   }
8044 
8045   // Finally, we know we have the right number of parameters, install them.
8046   NewFD->setParams(Params);
8047 
8048   // Find all anonymous symbols defined during the declaration of this function
8049   // and add to NewFD. This lets us track decls such 'enum Y' in:
8050   //
8051   //   void f(enum Y {AA} x) {}
8052   //
8053   // which would otherwise incorrectly end up in the translation unit scope.
8054   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
8055   DeclsInPrototypeScope.clear();
8056 
8057   if (D.getDeclSpec().isNoreturnSpecified())
8058     NewFD->addAttr(
8059         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8060                                        Context, 0));
8061 
8062   // Functions returning a variably modified type violate C99 6.7.5.2p2
8063   // because all functions have linkage.
8064   if (!NewFD->isInvalidDecl() &&
8065       NewFD->getReturnType()->isVariablyModifiedType()) {
8066     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8067     NewFD->setInvalidDecl();
8068   }
8069 
8070   // Apply an implicit SectionAttr if #pragma code_seg is active.
8071   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8072       !NewFD->hasAttr<SectionAttr>()) {
8073     NewFD->addAttr(
8074         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8075                                     CodeSegStack.CurrentValue->getString(),
8076                                     CodeSegStack.CurrentPragmaLocation));
8077     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8078                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8079                          ASTContext::PSF_Read,
8080                      NewFD))
8081       NewFD->dropAttr<SectionAttr>();
8082   }
8083 
8084   // Handle attributes.
8085   ProcessDeclAttributes(S, NewFD, D);
8086 
8087   if (getLangOpts().CUDA)
8088     maybeAddCUDAHostDeviceAttrs(S, NewFD, Previous);
8089 
8090   if (getLangOpts().OpenCL) {
8091     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8092     // type declaration will generate a compilation error.
8093     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8094     if (AddressSpace == LangAS::opencl_local ||
8095         AddressSpace == LangAS::opencl_global ||
8096         AddressSpace == LangAS::opencl_constant) {
8097       Diag(NewFD->getLocation(),
8098            diag::err_opencl_return_value_with_address_space);
8099       NewFD->setInvalidDecl();
8100     }
8101   }
8102 
8103   if (!getLangOpts().CPlusPlus) {
8104     // Perform semantic checking on the function declaration.
8105     bool isExplicitSpecialization=false;
8106     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8107       CheckMain(NewFD, D.getDeclSpec());
8108 
8109     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8110       CheckMSVCRTEntryPoint(NewFD);
8111 
8112     if (!NewFD->isInvalidDecl())
8113       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8114                                                   isExplicitSpecialization));
8115     else if (!Previous.empty())
8116       // Recover gracefully from an invalid redeclaration.
8117       D.setRedeclaration(true);
8118     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8119             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8120            "previous declaration set still overloaded");
8121 
8122     // Diagnose no-prototype function declarations with calling conventions that
8123     // don't support variadic calls. Only do this in C and do it after merging
8124     // possibly prototyped redeclarations.
8125     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8126     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8127       CallingConv CC = FT->getExtInfo().getCC();
8128       if (!supportsVariadicCall(CC)) {
8129         // Windows system headers sometimes accidentally use stdcall without
8130         // (void) parameters, so we relax this to a warning.
8131         int DiagID =
8132             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8133         Diag(NewFD->getLocation(), DiagID)
8134             << FunctionType::getNameForCallConv(CC);
8135       }
8136     }
8137   } else {
8138     // C++11 [replacement.functions]p3:
8139     //  The program's definitions shall not be specified as inline.
8140     //
8141     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8142     //
8143     // Suppress the diagnostic if the function is __attribute__((used)), since
8144     // that forces an external definition to be emitted.
8145     if (D.getDeclSpec().isInlineSpecified() &&
8146         NewFD->isReplaceableGlobalAllocationFunction() &&
8147         !NewFD->hasAttr<UsedAttr>())
8148       Diag(D.getDeclSpec().getInlineSpecLoc(),
8149            diag::ext_operator_new_delete_declared_inline)
8150         << NewFD->getDeclName();
8151 
8152     // If the declarator is a template-id, translate the parser's template
8153     // argument list into our AST format.
8154     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8155       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8156       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8157       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8158       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8159                                          TemplateId->NumArgs);
8160       translateTemplateArguments(TemplateArgsPtr,
8161                                  TemplateArgs);
8162 
8163       HasExplicitTemplateArgs = true;
8164 
8165       if (NewFD->isInvalidDecl()) {
8166         HasExplicitTemplateArgs = false;
8167       } else if (FunctionTemplate) {
8168         // Function template with explicit template arguments.
8169         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8170           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8171 
8172         HasExplicitTemplateArgs = false;
8173       } else {
8174         assert((isFunctionTemplateSpecialization ||
8175                 D.getDeclSpec().isFriendSpecified()) &&
8176                "should have a 'template<>' for this decl");
8177         // "friend void foo<>(int);" is an implicit specialization decl.
8178         isFunctionTemplateSpecialization = true;
8179       }
8180     } else if (isFriend && isFunctionTemplateSpecialization) {
8181       // This combination is only possible in a recovery case;  the user
8182       // wrote something like:
8183       //   template <> friend void foo(int);
8184       // which we're recovering from as if the user had written:
8185       //   friend void foo<>(int);
8186       // Go ahead and fake up a template id.
8187       HasExplicitTemplateArgs = true;
8188       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8189       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8190     }
8191 
8192     // If it's a friend (and only if it's a friend), it's possible
8193     // that either the specialized function type or the specialized
8194     // template is dependent, and therefore matching will fail.  In
8195     // this case, don't check the specialization yet.
8196     bool InstantiationDependent = false;
8197     if (isFunctionTemplateSpecialization && isFriend &&
8198         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8199          TemplateSpecializationType::anyDependentTemplateArguments(
8200             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
8201             InstantiationDependent))) {
8202       assert(HasExplicitTemplateArgs &&
8203              "friend function specialization without template args");
8204       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8205                                                        Previous))
8206         NewFD->setInvalidDecl();
8207     } else if (isFunctionTemplateSpecialization) {
8208       if (CurContext->isDependentContext() && CurContext->isRecord()
8209           && !isFriend) {
8210         isDependentClassScopeExplicitSpecialization = true;
8211         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8212           diag::ext_function_specialization_in_class :
8213           diag::err_function_specialization_in_class)
8214           << NewFD->getDeclName();
8215       } else if (CheckFunctionTemplateSpecialization(NewFD,
8216                                   (HasExplicitTemplateArgs ? &TemplateArgs
8217                                                            : nullptr),
8218                                                      Previous))
8219         NewFD->setInvalidDecl();
8220 
8221       // C++ [dcl.stc]p1:
8222       //   A storage-class-specifier shall not be specified in an explicit
8223       //   specialization (14.7.3)
8224       FunctionTemplateSpecializationInfo *Info =
8225           NewFD->getTemplateSpecializationInfo();
8226       if (Info && SC != SC_None) {
8227         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8228           Diag(NewFD->getLocation(),
8229                diag::err_explicit_specialization_inconsistent_storage_class)
8230             << SC
8231             << FixItHint::CreateRemoval(
8232                                       D.getDeclSpec().getStorageClassSpecLoc());
8233 
8234         else
8235           Diag(NewFD->getLocation(),
8236                diag::ext_explicit_specialization_storage_class)
8237             << FixItHint::CreateRemoval(
8238                                       D.getDeclSpec().getStorageClassSpecLoc());
8239       }
8240     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
8241       if (CheckMemberSpecialization(NewFD, Previous))
8242           NewFD->setInvalidDecl();
8243     }
8244 
8245     // Perform semantic checking on the function declaration.
8246     if (!isDependentClassScopeExplicitSpecialization) {
8247       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8248         CheckMain(NewFD, D.getDeclSpec());
8249 
8250       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8251         CheckMSVCRTEntryPoint(NewFD);
8252 
8253       if (!NewFD->isInvalidDecl())
8254         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8255                                                     isExplicitSpecialization));
8256       else if (!Previous.empty())
8257         // Recover gracefully from an invalid redeclaration.
8258         D.setRedeclaration(true);
8259     }
8260 
8261     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8262             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8263            "previous declaration set still overloaded");
8264 
8265     NamedDecl *PrincipalDecl = (FunctionTemplate
8266                                 ? cast<NamedDecl>(FunctionTemplate)
8267                                 : NewFD);
8268 
8269     if (isFriend && D.isRedeclaration()) {
8270       AccessSpecifier Access = AS_public;
8271       if (!NewFD->isInvalidDecl())
8272         Access = NewFD->getPreviousDecl()->getAccess();
8273 
8274       NewFD->setAccess(Access);
8275       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8276     }
8277 
8278     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8279         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8280       PrincipalDecl->setNonMemberOperator();
8281 
8282     // If we have a function template, check the template parameter
8283     // list. This will check and merge default template arguments.
8284     if (FunctionTemplate) {
8285       FunctionTemplateDecl *PrevTemplate =
8286                                      FunctionTemplate->getPreviousDecl();
8287       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8288                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8289                                     : nullptr,
8290                             D.getDeclSpec().isFriendSpecified()
8291                               ? (D.isFunctionDefinition()
8292                                    ? TPC_FriendFunctionTemplateDefinition
8293                                    : TPC_FriendFunctionTemplate)
8294                               : (D.getCXXScopeSpec().isSet() &&
8295                                  DC && DC->isRecord() &&
8296                                  DC->isDependentContext())
8297                                   ? TPC_ClassTemplateMember
8298                                   : TPC_FunctionTemplate);
8299     }
8300 
8301     if (NewFD->isInvalidDecl()) {
8302       // Ignore all the rest of this.
8303     } else if (!D.isRedeclaration()) {
8304       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8305                                        AddToScope };
8306       // Fake up an access specifier if it's supposed to be a class member.
8307       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8308         NewFD->setAccess(AS_public);
8309 
8310       // Qualified decls generally require a previous declaration.
8311       if (D.getCXXScopeSpec().isSet()) {
8312         // ...with the major exception of templated-scope or
8313         // dependent-scope friend declarations.
8314 
8315         // TODO: we currently also suppress this check in dependent
8316         // contexts because (1) the parameter depth will be off when
8317         // matching friend templates and (2) we might actually be
8318         // selecting a friend based on a dependent factor.  But there
8319         // are situations where these conditions don't apply and we
8320         // can actually do this check immediately.
8321         if (isFriend &&
8322             (TemplateParamLists.size() ||
8323              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8324              CurContext->isDependentContext())) {
8325           // ignore these
8326         } else {
8327           // The user tried to provide an out-of-line definition for a
8328           // function that is a member of a class or namespace, but there
8329           // was no such member function declared (C++ [class.mfct]p2,
8330           // C++ [namespace.memdef]p2). For example:
8331           //
8332           // class X {
8333           //   void f() const;
8334           // };
8335           //
8336           // void X::f() { } // ill-formed
8337           //
8338           // Complain about this problem, and attempt to suggest close
8339           // matches (e.g., those that differ only in cv-qualifiers and
8340           // whether the parameter types are references).
8341 
8342           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8343                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8344             AddToScope = ExtraArgs.AddToScope;
8345             return Result;
8346           }
8347         }
8348 
8349         // Unqualified local friend declarations are required to resolve
8350         // to something.
8351       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8352         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8353                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8354           AddToScope = ExtraArgs.AddToScope;
8355           return Result;
8356         }
8357       }
8358     } else if (!D.isFunctionDefinition() &&
8359                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8360                !isFriend && !isFunctionTemplateSpecialization &&
8361                !isExplicitSpecialization) {
8362       // An out-of-line member function declaration must also be a
8363       // definition (C++ [class.mfct]p2).
8364       // Note that this is not the case for explicit specializations of
8365       // function templates or member functions of class templates, per
8366       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8367       // extension for compatibility with old SWIG code which likes to
8368       // generate them.
8369       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8370         << D.getCXXScopeSpec().getRange();
8371     }
8372   }
8373 
8374   ProcessPragmaWeak(S, NewFD);
8375   checkAttributesAfterMerging(*this, *NewFD);
8376 
8377   AddKnownFunctionAttributes(NewFD);
8378 
8379   if (NewFD->hasAttr<OverloadableAttr>() &&
8380       !NewFD->getType()->getAs<FunctionProtoType>()) {
8381     Diag(NewFD->getLocation(),
8382          diag::err_attribute_overloadable_no_prototype)
8383       << NewFD;
8384 
8385     // Turn this into a variadic function with no parameters.
8386     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8387     FunctionProtoType::ExtProtoInfo EPI(
8388         Context.getDefaultCallingConvention(true, false));
8389     EPI.Variadic = true;
8390     EPI.ExtInfo = FT->getExtInfo();
8391 
8392     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8393     NewFD->setType(R);
8394   }
8395 
8396   // If there's a #pragma GCC visibility in scope, and this isn't a class
8397   // member, set the visibility of this function.
8398   if (!DC->isRecord() && NewFD->isExternallyVisible())
8399     AddPushedVisibilityAttribute(NewFD);
8400 
8401   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8402   // marking the function.
8403   AddCFAuditedAttribute(NewFD);
8404 
8405   // If this is a function definition, check if we have to apply optnone due to
8406   // a pragma.
8407   if(D.isFunctionDefinition())
8408     AddRangeBasedOptnone(NewFD);
8409 
8410   // If this is the first declaration of an extern C variable, update
8411   // the map of such variables.
8412   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8413       isIncompleteDeclExternC(*this, NewFD))
8414     RegisterLocallyScopedExternCDecl(NewFD, S);
8415 
8416   // Set this FunctionDecl's range up to the right paren.
8417   NewFD->setRangeEnd(D.getSourceRange().getEnd());
8418 
8419   if (D.isRedeclaration() && !Previous.empty()) {
8420     checkDLLAttributeRedeclaration(
8421         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8422         isExplicitSpecialization || isFunctionTemplateSpecialization);
8423   }
8424 
8425   if (getLangOpts().CUDA) {
8426     IdentifierInfo *II = NewFD->getIdentifier();
8427     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
8428         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8429       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8430         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8431 
8432       Context.setcudaConfigureCallDecl(NewFD);
8433     }
8434 
8435     // Variadic functions, other than a *declaration* of printf, are not allowed
8436     // in device-side CUDA code, unless someone passed
8437     // -fcuda-allow-variadic-functions.
8438     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
8439         (NewFD->hasAttr<CUDADeviceAttr>() ||
8440          NewFD->hasAttr<CUDAGlobalAttr>()) &&
8441         !(II && II->isStr("printf") && NewFD->isExternC() &&
8442           !D.isFunctionDefinition())) {
8443       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
8444     }
8445   }
8446 
8447   if (getLangOpts().CPlusPlus) {
8448     if (FunctionTemplate) {
8449       if (NewFD->isInvalidDecl())
8450         FunctionTemplate->setInvalidDecl();
8451       return FunctionTemplate;
8452     }
8453   }
8454 
8455   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8456     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8457     if ((getLangOpts().OpenCLVersion >= 120)
8458         && (SC == SC_Static)) {
8459       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8460       D.setInvalidType();
8461     }
8462 
8463     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8464     if (!NewFD->getReturnType()->isVoidType()) {
8465       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8466       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8467           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8468                                 : FixItHint());
8469       D.setInvalidType();
8470     }
8471 
8472     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8473     for (auto Param : NewFD->params())
8474       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8475   }
8476   for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
8477        PE = NewFD->param_end(); PI != PE; ++PI) {
8478     ParmVarDecl *Param = *PI;
8479     QualType PT = Param->getType();
8480 
8481     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8482     // types.
8483     if (getLangOpts().OpenCLVersion >= 200) {
8484       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8485         QualType ElemTy = PipeTy->getElementType();
8486           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8487             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8488             D.setInvalidType();
8489           }
8490       }
8491     }
8492   }
8493 
8494   MarkUnusedFileScopedDecl(NewFD);
8495 
8496   // Here we have an function template explicit specialization at class scope.
8497   // The actually specialization will be postponed to template instatiation
8498   // time via the ClassScopeFunctionSpecializationDecl node.
8499   if (isDependentClassScopeExplicitSpecialization) {
8500     ClassScopeFunctionSpecializationDecl *NewSpec =
8501                          ClassScopeFunctionSpecializationDecl::Create(
8502                                 Context, CurContext, SourceLocation(),
8503                                 cast<CXXMethodDecl>(NewFD),
8504                                 HasExplicitTemplateArgs, TemplateArgs);
8505     CurContext->addDecl(NewSpec);
8506     AddToScope = false;
8507   }
8508 
8509   return NewFD;
8510 }
8511 
8512 /// \brief Perform semantic checking of a new function declaration.
8513 ///
8514 /// Performs semantic analysis of the new function declaration
8515 /// NewFD. This routine performs all semantic checking that does not
8516 /// require the actual declarator involved in the declaration, and is
8517 /// used both for the declaration of functions as they are parsed
8518 /// (called via ActOnDeclarator) and for the declaration of functions
8519 /// that have been instantiated via C++ template instantiation (called
8520 /// via InstantiateDecl).
8521 ///
8522 /// \param IsExplicitSpecialization whether this new function declaration is
8523 /// an explicit specialization of the previous declaration.
8524 ///
8525 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8526 ///
8527 /// \returns true if the function declaration is a redeclaration.
8528 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8529                                     LookupResult &Previous,
8530                                     bool IsExplicitSpecialization) {
8531   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8532          "Variably modified return types are not handled here");
8533 
8534   // Determine whether the type of this function should be merged with
8535   // a previous visible declaration. This never happens for functions in C++,
8536   // and always happens in C if the previous declaration was visible.
8537   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8538                                !Previous.isShadowed();
8539 
8540   bool Redeclaration = false;
8541   NamedDecl *OldDecl = nullptr;
8542 
8543   // Merge or overload the declaration with an existing declaration of
8544   // the same name, if appropriate.
8545   if (!Previous.empty()) {
8546     // Determine whether NewFD is an overload of PrevDecl or
8547     // a declaration that requires merging. If it's an overload,
8548     // there's no more work to do here; we'll just add the new
8549     // function to the scope.
8550     if (!AllowOverloadingOfFunction(Previous, Context)) {
8551       NamedDecl *Candidate = Previous.getRepresentativeDecl();
8552       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8553         Redeclaration = true;
8554         OldDecl = Candidate;
8555       }
8556     } else {
8557       switch (CheckOverload(S, NewFD, Previous, OldDecl,
8558                             /*NewIsUsingDecl*/ false)) {
8559       case Ovl_Match:
8560         Redeclaration = true;
8561         break;
8562 
8563       case Ovl_NonFunction:
8564         Redeclaration = true;
8565         break;
8566 
8567       case Ovl_Overload:
8568         Redeclaration = false;
8569         break;
8570       }
8571 
8572       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8573         // If a function name is overloadable in C, then every function
8574         // with that name must be marked "overloadable".
8575         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8576           << Redeclaration << NewFD;
8577         NamedDecl *OverloadedDecl = nullptr;
8578         if (Redeclaration)
8579           OverloadedDecl = OldDecl;
8580         else if (!Previous.empty())
8581           OverloadedDecl = Previous.getRepresentativeDecl();
8582         if (OverloadedDecl)
8583           Diag(OverloadedDecl->getLocation(),
8584                diag::note_attribute_overloadable_prev_overload);
8585         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8586       }
8587     }
8588   }
8589 
8590   // Check for a previous extern "C" declaration with this name.
8591   if (!Redeclaration &&
8592       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8593     if (!Previous.empty()) {
8594       // This is an extern "C" declaration with the same name as a previous
8595       // declaration, and thus redeclares that entity...
8596       Redeclaration = true;
8597       OldDecl = Previous.getFoundDecl();
8598       MergeTypeWithPrevious = false;
8599 
8600       // ... except in the presence of __attribute__((overloadable)).
8601       if (OldDecl->hasAttr<OverloadableAttr>()) {
8602         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8603           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8604             << Redeclaration << NewFD;
8605           Diag(Previous.getFoundDecl()->getLocation(),
8606                diag::note_attribute_overloadable_prev_overload);
8607           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8608         }
8609         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8610           Redeclaration = false;
8611           OldDecl = nullptr;
8612         }
8613       }
8614     }
8615   }
8616 
8617   // C++11 [dcl.constexpr]p8:
8618   //   A constexpr specifier for a non-static member function that is not
8619   //   a constructor declares that member function to be const.
8620   //
8621   // This needs to be delayed until we know whether this is an out-of-line
8622   // definition of a static member function.
8623   //
8624   // This rule is not present in C++1y, so we produce a backwards
8625   // compatibility warning whenever it happens in C++11.
8626   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8627   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8628       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8629       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8630     CXXMethodDecl *OldMD = nullptr;
8631     if (OldDecl)
8632       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8633     if (!OldMD || !OldMD->isStatic()) {
8634       const FunctionProtoType *FPT =
8635         MD->getType()->castAs<FunctionProtoType>();
8636       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8637       EPI.TypeQuals |= Qualifiers::Const;
8638       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8639                                           FPT->getParamTypes(), EPI));
8640 
8641       // Warn that we did this, if we're not performing template instantiation.
8642       // In that case, we'll have warned already when the template was defined.
8643       if (ActiveTemplateInstantiations.empty()) {
8644         SourceLocation AddConstLoc;
8645         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
8646                 .IgnoreParens().getAs<FunctionTypeLoc>())
8647           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
8648 
8649         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
8650           << FixItHint::CreateInsertion(AddConstLoc, " const");
8651       }
8652     }
8653   }
8654 
8655   if (Redeclaration) {
8656     // NewFD and OldDecl represent declarations that need to be
8657     // merged.
8658     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
8659       NewFD->setInvalidDecl();
8660       return Redeclaration;
8661     }
8662 
8663     Previous.clear();
8664     Previous.addDecl(OldDecl);
8665 
8666     if (FunctionTemplateDecl *OldTemplateDecl
8667                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
8668       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
8669       FunctionTemplateDecl *NewTemplateDecl
8670         = NewFD->getDescribedFunctionTemplate();
8671       assert(NewTemplateDecl && "Template/non-template mismatch");
8672       if (CXXMethodDecl *Method
8673             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
8674         Method->setAccess(OldTemplateDecl->getAccess());
8675         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8676       }
8677 
8678       // If this is an explicit specialization of a member that is a function
8679       // template, mark it as a member specialization.
8680       if (IsExplicitSpecialization &&
8681           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
8682         NewTemplateDecl->setMemberSpecialization();
8683         assert(OldTemplateDecl->isMemberSpecialization());
8684         // Explicit specializations of a member template do not inherit deleted
8685         // status from the parent member template that they are specializing.
8686         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
8687           FunctionDecl *const OldTemplatedDecl =
8688               OldTemplateDecl->getTemplatedDecl();
8689           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
8690           OldTemplatedDecl->setDeletedAsWritten(false);
8691         }
8692       }
8693 
8694     } else {
8695       // This needs to happen first so that 'inline' propagates.
8696       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
8697 
8698       if (isa<CXXMethodDecl>(NewFD))
8699         NewFD->setAccess(OldDecl->getAccess());
8700     }
8701   }
8702 
8703   // Semantic checking for this function declaration (in isolation).
8704 
8705   if (getLangOpts().CPlusPlus) {
8706     // C++-specific checks.
8707     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
8708       CheckConstructor(Constructor);
8709     } else if (CXXDestructorDecl *Destructor =
8710                 dyn_cast<CXXDestructorDecl>(NewFD)) {
8711       CXXRecordDecl *Record = Destructor->getParent();
8712       QualType ClassType = Context.getTypeDeclType(Record);
8713 
8714       // FIXME: Shouldn't we be able to perform this check even when the class
8715       // type is dependent? Both gcc and edg can handle that.
8716       if (!ClassType->isDependentType()) {
8717         DeclarationName Name
8718           = Context.DeclarationNames.getCXXDestructorName(
8719                                         Context.getCanonicalType(ClassType));
8720         if (NewFD->getDeclName() != Name) {
8721           Diag(NewFD->getLocation(), diag::err_destructor_name);
8722           NewFD->setInvalidDecl();
8723           return Redeclaration;
8724         }
8725       }
8726     } else if (CXXConversionDecl *Conversion
8727                = dyn_cast<CXXConversionDecl>(NewFD)) {
8728       ActOnConversionDeclarator(Conversion);
8729     }
8730 
8731     // Find any virtual functions that this function overrides.
8732     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8733       if (!Method->isFunctionTemplateSpecialization() &&
8734           !Method->getDescribedFunctionTemplate() &&
8735           Method->isCanonicalDecl()) {
8736         if (AddOverriddenMethods(Method->getParent(), Method)) {
8737           // If the function was marked as "static", we have a problem.
8738           if (NewFD->getStorageClass() == SC_Static) {
8739             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8740           }
8741         }
8742       }
8743 
8744       if (Method->isStatic())
8745         checkThisInStaticMemberFunctionType(Method);
8746     }
8747 
8748     // Extra checking for C++ overloaded operators (C++ [over.oper]).
8749     if (NewFD->isOverloadedOperator() &&
8750         CheckOverloadedOperatorDeclaration(NewFD)) {
8751       NewFD->setInvalidDecl();
8752       return Redeclaration;
8753     }
8754 
8755     // Extra checking for C++0x literal operators (C++0x [over.literal]).
8756     if (NewFD->getLiteralIdentifier() &&
8757         CheckLiteralOperatorDeclaration(NewFD)) {
8758       NewFD->setInvalidDecl();
8759       return Redeclaration;
8760     }
8761 
8762     // In C++, check default arguments now that we have merged decls. Unless
8763     // the lexical context is the class, because in this case this is done
8764     // during delayed parsing anyway.
8765     if (!CurContext->isRecord())
8766       CheckCXXDefaultArguments(NewFD);
8767 
8768     // If this function declares a builtin function, check the type of this
8769     // declaration against the expected type for the builtin.
8770     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8771       ASTContext::GetBuiltinTypeError Error;
8772       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8773       QualType T = Context.GetBuiltinType(BuiltinID, Error);
8774       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8775         // The type of this function differs from the type of the builtin,
8776         // so forget about the builtin entirely.
8777         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
8778       }
8779     }
8780 
8781     // If this function is declared as being extern "C", then check to see if
8782     // the function returns a UDT (class, struct, or union type) that is not C
8783     // compatible, and if it does, warn the user.
8784     // But, issue any diagnostic on the first declaration only.
8785     if (Previous.empty() && NewFD->isExternC()) {
8786       QualType R = NewFD->getReturnType();
8787       if (R->isIncompleteType() && !R->isVoidType())
8788         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8789             << NewFD << R;
8790       else if (!R.isPODType(Context) && !R->isVoidType() &&
8791                !R->isObjCObjectPointerType())
8792         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8793     }
8794   }
8795   return Redeclaration;
8796 }
8797 
8798 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8799   // C++11 [basic.start.main]p3:
8800   //   A program that [...] declares main to be inline, static or
8801   //   constexpr is ill-formed.
8802   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
8803   //   appear in a declaration of main.
8804   // static main is not an error under C99, but we should warn about it.
8805   // We accept _Noreturn main as an extension.
8806   if (FD->getStorageClass() == SC_Static)
8807     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8808          ? diag::err_static_main : diag::warn_static_main)
8809       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8810   if (FD->isInlineSpecified())
8811     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8812       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8813   if (DS.isNoreturnSpecified()) {
8814     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8815     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8816     Diag(NoreturnLoc, diag::ext_noreturn_main);
8817     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8818       << FixItHint::CreateRemoval(NoreturnRange);
8819   }
8820   if (FD->isConstexpr()) {
8821     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8822       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8823     FD->setConstexpr(false);
8824   }
8825 
8826   if (getLangOpts().OpenCL) {
8827     Diag(FD->getLocation(), diag::err_opencl_no_main)
8828         << FD->hasAttr<OpenCLKernelAttr>();
8829     FD->setInvalidDecl();
8830     return;
8831   }
8832 
8833   QualType T = FD->getType();
8834   assert(T->isFunctionType() && "function decl is not of function type");
8835   const FunctionType* FT = T->castAs<FunctionType>();
8836 
8837   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8838     // In C with GNU extensions we allow main() to have non-integer return
8839     // type, but we should warn about the extension, and we disable the
8840     // implicit-return-zero rule.
8841 
8842     // GCC in C mode accepts qualified 'int'.
8843     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8844       FD->setHasImplicitReturnZero(true);
8845     else {
8846       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8847       SourceRange RTRange = FD->getReturnTypeSourceRange();
8848       if (RTRange.isValid())
8849         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8850             << FixItHint::CreateReplacement(RTRange, "int");
8851     }
8852   } else {
8853     // In C and C++, main magically returns 0 if you fall off the end;
8854     // set the flag which tells us that.
8855     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8856 
8857     // All the standards say that main() should return 'int'.
8858     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8859       FD->setHasImplicitReturnZero(true);
8860     else {
8861       // Otherwise, this is just a flat-out error.
8862       SourceRange RTRange = FD->getReturnTypeSourceRange();
8863       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8864           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8865                                 : FixItHint());
8866       FD->setInvalidDecl(true);
8867     }
8868   }
8869 
8870   // Treat protoless main() as nullary.
8871   if (isa<FunctionNoProtoType>(FT)) return;
8872 
8873   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8874   unsigned nparams = FTP->getNumParams();
8875   assert(FD->getNumParams() == nparams);
8876 
8877   bool HasExtraParameters = (nparams > 3);
8878 
8879   if (FTP->isVariadic()) {
8880     Diag(FD->getLocation(), diag::ext_variadic_main);
8881     // FIXME: if we had information about the location of the ellipsis, we
8882     // could add a FixIt hint to remove it as a parameter.
8883   }
8884 
8885   // Darwin passes an undocumented fourth argument of type char**.  If
8886   // other platforms start sprouting these, the logic below will start
8887   // getting shifty.
8888   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8889     HasExtraParameters = false;
8890 
8891   if (HasExtraParameters) {
8892     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8893     FD->setInvalidDecl(true);
8894     nparams = 3;
8895   }
8896 
8897   // FIXME: a lot of the following diagnostics would be improved
8898   // if we had some location information about types.
8899 
8900   QualType CharPP =
8901     Context.getPointerType(Context.getPointerType(Context.CharTy));
8902   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
8903 
8904   for (unsigned i = 0; i < nparams; ++i) {
8905     QualType AT = FTP->getParamType(i);
8906 
8907     bool mismatch = true;
8908 
8909     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
8910       mismatch = false;
8911     else if (Expected[i] == CharPP) {
8912       // As an extension, the following forms are okay:
8913       //   char const **
8914       //   char const * const *
8915       //   char * const *
8916 
8917       QualifierCollector qs;
8918       const PointerType* PT;
8919       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
8920           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
8921           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
8922                               Context.CharTy)) {
8923         qs.removeConst();
8924         mismatch = !qs.empty();
8925       }
8926     }
8927 
8928     if (mismatch) {
8929       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
8930       // TODO: suggest replacing given type with expected type
8931       FD->setInvalidDecl(true);
8932     }
8933   }
8934 
8935   if (nparams == 1 && !FD->isInvalidDecl()) {
8936     Diag(FD->getLocation(), diag::warn_main_one_arg);
8937   }
8938 
8939   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8940     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8941     FD->setInvalidDecl();
8942   }
8943 }
8944 
8945 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
8946   QualType T = FD->getType();
8947   assert(T->isFunctionType() && "function decl is not of function type");
8948   const FunctionType *FT = T->castAs<FunctionType>();
8949 
8950   // Set an implicit return of 'zero' if the function can return some integral,
8951   // enumeration, pointer or nullptr type.
8952   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
8953       FT->getReturnType()->isAnyPointerType() ||
8954       FT->getReturnType()->isNullPtrType())
8955     // DllMain is exempt because a return value of zero means it failed.
8956     if (FD->getName() != "DllMain")
8957       FD->setHasImplicitReturnZero(true);
8958 
8959   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8960     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8961     FD->setInvalidDecl();
8962   }
8963 }
8964 
8965 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
8966   // FIXME: Need strict checking.  In C89, we need to check for
8967   // any assignment, increment, decrement, function-calls, or
8968   // commas outside of a sizeof.  In C99, it's the same list,
8969   // except that the aforementioned are allowed in unevaluated
8970   // expressions.  Everything else falls under the
8971   // "may accept other forms of constant expressions" exception.
8972   // (We never end up here for C++, so the constant expression
8973   // rules there don't matter.)
8974   const Expr *Culprit;
8975   if (Init->isConstantInitializer(Context, false, &Culprit))
8976     return false;
8977   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
8978     << Culprit->getSourceRange();
8979   return true;
8980 }
8981 
8982 namespace {
8983   // Visits an initialization expression to see if OrigDecl is evaluated in
8984   // its own initialization and throws a warning if it does.
8985   class SelfReferenceChecker
8986       : public EvaluatedExprVisitor<SelfReferenceChecker> {
8987     Sema &S;
8988     Decl *OrigDecl;
8989     bool isRecordType;
8990     bool isPODType;
8991     bool isReferenceType;
8992 
8993     bool isInitList;
8994     llvm::SmallVector<unsigned, 4> InitFieldIndex;
8995 
8996   public:
8997     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
8998 
8999     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9000                                                     S(S), OrigDecl(OrigDecl) {
9001       isPODType = false;
9002       isRecordType = false;
9003       isReferenceType = false;
9004       isInitList = false;
9005       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9006         isPODType = VD->getType().isPODType(S.Context);
9007         isRecordType = VD->getType()->isRecordType();
9008         isReferenceType = VD->getType()->isReferenceType();
9009       }
9010     }
9011 
9012     // For most expressions, just call the visitor.  For initializer lists,
9013     // track the index of the field being initialized since fields are
9014     // initialized in order allowing use of previously initialized fields.
9015     void CheckExpr(Expr *E) {
9016       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9017       if (!InitList) {
9018         Visit(E);
9019         return;
9020       }
9021 
9022       // Track and increment the index here.
9023       isInitList = true;
9024       InitFieldIndex.push_back(0);
9025       for (auto Child : InitList->children()) {
9026         CheckExpr(cast<Expr>(Child));
9027         ++InitFieldIndex.back();
9028       }
9029       InitFieldIndex.pop_back();
9030     }
9031 
9032     // Returns true if MemberExpr is checked and no futher checking is needed.
9033     // Returns false if additional checking is required.
9034     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9035       llvm::SmallVector<FieldDecl*, 4> Fields;
9036       Expr *Base = E;
9037       bool ReferenceField = false;
9038 
9039       // Get the field memebers used.
9040       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9041         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9042         if (!FD)
9043           return false;
9044         Fields.push_back(FD);
9045         if (FD->getType()->isReferenceType())
9046           ReferenceField = true;
9047         Base = ME->getBase()->IgnoreParenImpCasts();
9048       }
9049 
9050       // Keep checking only if the base Decl is the same.
9051       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9052       if (!DRE || DRE->getDecl() != OrigDecl)
9053         return false;
9054 
9055       // A reference field can be bound to an unininitialized field.
9056       if (CheckReference && !ReferenceField)
9057         return true;
9058 
9059       // Convert FieldDecls to their index number.
9060       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9061       for (const FieldDecl *I : llvm::reverse(Fields))
9062         UsedFieldIndex.push_back(I->getFieldIndex());
9063 
9064       // See if a warning is needed by checking the first difference in index
9065       // numbers.  If field being used has index less than the field being
9066       // initialized, then the use is safe.
9067       for (auto UsedIter = UsedFieldIndex.begin(),
9068                 UsedEnd = UsedFieldIndex.end(),
9069                 OrigIter = InitFieldIndex.begin(),
9070                 OrigEnd = InitFieldIndex.end();
9071            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9072         if (*UsedIter < *OrigIter)
9073           return true;
9074         if (*UsedIter > *OrigIter)
9075           break;
9076       }
9077 
9078       // TODO: Add a different warning which will print the field names.
9079       HandleDeclRefExpr(DRE);
9080       return true;
9081     }
9082 
9083     // For most expressions, the cast is directly above the DeclRefExpr.
9084     // For conditional operators, the cast can be outside the conditional
9085     // operator if both expressions are DeclRefExpr's.
9086     void HandleValue(Expr *E) {
9087       E = E->IgnoreParens();
9088       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9089         HandleDeclRefExpr(DRE);
9090         return;
9091       }
9092 
9093       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9094         Visit(CO->getCond());
9095         HandleValue(CO->getTrueExpr());
9096         HandleValue(CO->getFalseExpr());
9097         return;
9098       }
9099 
9100       if (BinaryConditionalOperator *BCO =
9101               dyn_cast<BinaryConditionalOperator>(E)) {
9102         Visit(BCO->getCond());
9103         HandleValue(BCO->getFalseExpr());
9104         return;
9105       }
9106 
9107       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9108         HandleValue(OVE->getSourceExpr());
9109         return;
9110       }
9111 
9112       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9113         if (BO->getOpcode() == BO_Comma) {
9114           Visit(BO->getLHS());
9115           HandleValue(BO->getRHS());
9116           return;
9117         }
9118       }
9119 
9120       if (isa<MemberExpr>(E)) {
9121         if (isInitList) {
9122           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9123                                       false /*CheckReference*/))
9124             return;
9125         }
9126 
9127         Expr *Base = E->IgnoreParenImpCasts();
9128         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9129           // Check for static member variables and don't warn on them.
9130           if (!isa<FieldDecl>(ME->getMemberDecl()))
9131             return;
9132           Base = ME->getBase()->IgnoreParenImpCasts();
9133         }
9134         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9135           HandleDeclRefExpr(DRE);
9136         return;
9137       }
9138 
9139       Visit(E);
9140     }
9141 
9142     // Reference types not handled in HandleValue are handled here since all
9143     // uses of references are bad, not just r-value uses.
9144     void VisitDeclRefExpr(DeclRefExpr *E) {
9145       if (isReferenceType)
9146         HandleDeclRefExpr(E);
9147     }
9148 
9149     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9150       if (E->getCastKind() == CK_LValueToRValue) {
9151         HandleValue(E->getSubExpr());
9152         return;
9153       }
9154 
9155       Inherited::VisitImplicitCastExpr(E);
9156     }
9157 
9158     void VisitMemberExpr(MemberExpr *E) {
9159       if (isInitList) {
9160         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9161           return;
9162       }
9163 
9164       // Don't warn on arrays since they can be treated as pointers.
9165       if (E->getType()->canDecayToPointerType()) return;
9166 
9167       // Warn when a non-static method call is followed by non-static member
9168       // field accesses, which is followed by a DeclRefExpr.
9169       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9170       bool Warn = (MD && !MD->isStatic());
9171       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9172       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9173         if (!isa<FieldDecl>(ME->getMemberDecl()))
9174           Warn = false;
9175         Base = ME->getBase()->IgnoreParenImpCasts();
9176       }
9177 
9178       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9179         if (Warn)
9180           HandleDeclRefExpr(DRE);
9181         return;
9182       }
9183 
9184       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9185       // Visit that expression.
9186       Visit(Base);
9187     }
9188 
9189     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9190       Expr *Callee = E->getCallee();
9191 
9192       if (isa<UnresolvedLookupExpr>(Callee))
9193         return Inherited::VisitCXXOperatorCallExpr(E);
9194 
9195       Visit(Callee);
9196       for (auto Arg: E->arguments())
9197         HandleValue(Arg->IgnoreParenImpCasts());
9198     }
9199 
9200     void VisitUnaryOperator(UnaryOperator *E) {
9201       // For POD record types, addresses of its own members are well-defined.
9202       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9203           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9204         if (!isPODType)
9205           HandleValue(E->getSubExpr());
9206         return;
9207       }
9208 
9209       if (E->isIncrementDecrementOp()) {
9210         HandleValue(E->getSubExpr());
9211         return;
9212       }
9213 
9214       Inherited::VisitUnaryOperator(E);
9215     }
9216 
9217     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9218 
9219     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9220       if (E->getConstructor()->isCopyConstructor()) {
9221         Expr *ArgExpr = E->getArg(0);
9222         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9223           if (ILE->getNumInits() == 1)
9224             ArgExpr = ILE->getInit(0);
9225         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9226           if (ICE->getCastKind() == CK_NoOp)
9227             ArgExpr = ICE->getSubExpr();
9228         HandleValue(ArgExpr);
9229         return;
9230       }
9231       Inherited::VisitCXXConstructExpr(E);
9232     }
9233 
9234     void VisitCallExpr(CallExpr *E) {
9235       // Treat std::move as a use.
9236       if (E->getNumArgs() == 1) {
9237         if (FunctionDecl *FD = E->getDirectCallee()) {
9238           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9239               FD->getIdentifier()->isStr("move")) {
9240             HandleValue(E->getArg(0));
9241             return;
9242           }
9243         }
9244       }
9245 
9246       Inherited::VisitCallExpr(E);
9247     }
9248 
9249     void VisitBinaryOperator(BinaryOperator *E) {
9250       if (E->isCompoundAssignmentOp()) {
9251         HandleValue(E->getLHS());
9252         Visit(E->getRHS());
9253         return;
9254       }
9255 
9256       Inherited::VisitBinaryOperator(E);
9257     }
9258 
9259     // A custom visitor for BinaryConditionalOperator is needed because the
9260     // regular visitor would check the condition and true expression separately
9261     // but both point to the same place giving duplicate diagnostics.
9262     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9263       Visit(E->getCond());
9264       Visit(E->getFalseExpr());
9265     }
9266 
9267     void HandleDeclRefExpr(DeclRefExpr *DRE) {
9268       Decl* ReferenceDecl = DRE->getDecl();
9269       if (OrigDecl != ReferenceDecl) return;
9270       unsigned diag;
9271       if (isReferenceType) {
9272         diag = diag::warn_uninit_self_reference_in_reference_init;
9273       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9274         diag = diag::warn_static_self_reference_in_init;
9275       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9276                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9277                  DRE->getDecl()->getType()->isRecordType()) {
9278         diag = diag::warn_uninit_self_reference_in_init;
9279       } else {
9280         // Local variables will be handled by the CFG analysis.
9281         return;
9282       }
9283 
9284       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9285                             S.PDiag(diag)
9286                               << DRE->getNameInfo().getName()
9287                               << OrigDecl->getLocation()
9288                               << DRE->getSourceRange());
9289     }
9290   };
9291 
9292   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9293   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9294                                  bool DirectInit) {
9295     // Parameters arguments are occassionially constructed with itself,
9296     // for instance, in recursive functions.  Skip them.
9297     if (isa<ParmVarDecl>(OrigDecl))
9298       return;
9299 
9300     E = E->IgnoreParens();
9301 
9302     // Skip checking T a = a where T is not a record or reference type.
9303     // Doing so is a way to silence uninitialized warnings.
9304     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9305       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9306         if (ICE->getCastKind() == CK_LValueToRValue)
9307           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9308             if (DRE->getDecl() == OrigDecl)
9309               return;
9310 
9311     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9312   }
9313 } // end anonymous namespace
9314 
9315 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9316                                             DeclarationName Name, QualType Type,
9317                                             TypeSourceInfo *TSI,
9318                                             SourceRange Range, bool DirectInit,
9319                                             Expr *Init) {
9320   bool IsInitCapture = !VDecl;
9321   assert((!VDecl || !VDecl->isInitCapture()) &&
9322          "init captures are expected to be deduced prior to initialization");
9323 
9324   ArrayRef<Expr *> DeduceInits = Init;
9325   if (DirectInit) {
9326     if (auto *PL = dyn_cast<ParenListExpr>(Init))
9327       DeduceInits = PL->exprs();
9328     else if (auto *IL = dyn_cast<InitListExpr>(Init))
9329       DeduceInits = IL->inits();
9330   }
9331 
9332   // Deduction only works if we have exactly one source expression.
9333   if (DeduceInits.empty()) {
9334     // It isn't possible to write this directly, but it is possible to
9335     // end up in this situation with "auto x(some_pack...);"
9336     Diag(Init->getLocStart(), IsInitCapture
9337                                   ? diag::err_init_capture_no_expression
9338                                   : diag::err_auto_var_init_no_expression)
9339         << Name << Type << Range;
9340     return QualType();
9341   }
9342 
9343   if (DeduceInits.size() > 1) {
9344     Diag(DeduceInits[1]->getLocStart(),
9345          IsInitCapture ? diag::err_init_capture_multiple_expressions
9346                        : diag::err_auto_var_init_multiple_expressions)
9347         << Name << Type << Range;
9348     return QualType();
9349   }
9350 
9351   Expr *DeduceInit = DeduceInits[0];
9352   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9353     Diag(Init->getLocStart(), IsInitCapture
9354                                   ? diag::err_init_capture_paren_braces
9355                                   : diag::err_auto_var_init_paren_braces)
9356         << isa<InitListExpr>(Init) << Name << Type << Range;
9357     return QualType();
9358   }
9359 
9360   // Expressions default to 'id' when we're in a debugger.
9361   bool DefaultedAnyToId = false;
9362   if (getLangOpts().DebuggerCastResultToId &&
9363       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9364     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9365     if (Result.isInvalid()) {
9366       return QualType();
9367     }
9368     Init = Result.get();
9369     DefaultedAnyToId = true;
9370   }
9371 
9372   QualType DeducedType;
9373   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9374     if (!IsInitCapture)
9375       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9376     else if (isa<InitListExpr>(Init))
9377       Diag(Range.getBegin(),
9378            diag::err_init_capture_deduction_failure_from_init_list)
9379           << Name
9380           << (DeduceInit->getType().isNull() ? TSI->getType()
9381                                              : DeduceInit->getType())
9382           << DeduceInit->getSourceRange();
9383     else
9384       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9385           << Name << TSI->getType()
9386           << (DeduceInit->getType().isNull() ? TSI->getType()
9387                                              : DeduceInit->getType())
9388           << DeduceInit->getSourceRange();
9389   }
9390 
9391   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9392   // 'id' instead of a specific object type prevents most of our usual
9393   // checks.
9394   // We only want to warn outside of template instantiations, though:
9395   // inside a template, the 'id' could have come from a parameter.
9396   if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
9397       !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9398     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9399     Diag(Loc, diag::warn_auto_var_is_id) << Name << Range;
9400   }
9401 
9402   return DeducedType;
9403 }
9404 
9405 /// AddInitializerToDecl - Adds the initializer Init to the
9406 /// declaration dcl. If DirectInit is true, this is C++ direct
9407 /// initialization rather than copy initialization.
9408 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
9409                                 bool DirectInit, bool TypeMayContainAuto) {
9410   // If there is no declaration, there was an error parsing it.  Just ignore
9411   // the initializer.
9412   if (!RealDecl || RealDecl->isInvalidDecl()) {
9413     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
9414     return;
9415   }
9416 
9417   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
9418     // Pure-specifiers are handled in ActOnPureSpecifier.
9419     Diag(Method->getLocation(), diag::err_member_function_initialization)
9420       << Method->getDeclName() << Init->getSourceRange();
9421     Method->setInvalidDecl();
9422     return;
9423   }
9424 
9425   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9426   if (!VDecl) {
9427     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
9428     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9429     RealDecl->setInvalidDecl();
9430     return;
9431   }
9432 
9433   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9434   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
9435     // Attempt typo correction early so that the type of the init expression can
9436     // be deduced based on the chosen correction if the original init contains a
9437     // TypoExpr.
9438     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
9439     if (!Res.isUsable()) {
9440       RealDecl->setInvalidDecl();
9441       return;
9442     }
9443     Init = Res.get();
9444 
9445     QualType DeducedType = deduceVarTypeFromInitializer(
9446         VDecl, VDecl->getDeclName(), VDecl->getType(),
9447         VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
9448     if (DeducedType.isNull()) {
9449       RealDecl->setInvalidDecl();
9450       return;
9451     }
9452 
9453     VDecl->setType(DeducedType);
9454     assert(VDecl->isLinkageValid());
9455 
9456     // In ARC, infer lifetime.
9457     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9458       VDecl->setInvalidDecl();
9459 
9460     // If this is a redeclaration, check that the type we just deduced matches
9461     // the previously declared type.
9462     if (VarDecl *Old = VDecl->getPreviousDecl()) {
9463       // We never need to merge the type, because we cannot form an incomplete
9464       // array of auto, nor deduce such a type.
9465       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9466     }
9467 
9468     // Check the deduced type is valid for a variable declaration.
9469     CheckVariableDeclarationType(VDecl);
9470     if (VDecl->isInvalidDecl())
9471       return;
9472   }
9473 
9474   // dllimport cannot be used on variable definitions.
9475   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
9476     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
9477     VDecl->setInvalidDecl();
9478     return;
9479   }
9480 
9481   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
9482     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
9483     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
9484     VDecl->setInvalidDecl();
9485     return;
9486   }
9487 
9488   if (!VDecl->getType()->isDependentType()) {
9489     // A definition must end up with a complete type, which means it must be
9490     // complete with the restriction that an array type might be completed by
9491     // the initializer; note that later code assumes this restriction.
9492     QualType BaseDeclType = VDecl->getType();
9493     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
9494       BaseDeclType = Array->getElementType();
9495     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
9496                             diag::err_typecheck_decl_incomplete_type)) {
9497       RealDecl->setInvalidDecl();
9498       return;
9499     }
9500 
9501     // The variable can not have an abstract class type.
9502     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9503                                diag::err_abstract_type_in_decl,
9504                                AbstractVariableType))
9505       VDecl->setInvalidDecl();
9506   }
9507 
9508   VarDecl *Def;
9509   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
9510     NamedDecl *Hidden = nullptr;
9511     if (!hasVisibleDefinition(Def, &Hidden) &&
9512         (VDecl->getFormalLinkage() == InternalLinkage ||
9513          VDecl->getDescribedVarTemplate() ||
9514          VDecl->getNumTemplateParameterLists() ||
9515          VDecl->getDeclContext()->isDependentContext())) {
9516       // The previous definition is hidden, and multiple definitions are
9517       // permitted (in separate TUs). Form another definition of it.
9518     } else {
9519       Diag(VDecl->getLocation(), diag::err_redefinition)
9520         << VDecl->getDeclName();
9521       Diag(Def->getLocation(), diag::note_previous_definition);
9522       VDecl->setInvalidDecl();
9523       return;
9524     }
9525   }
9526 
9527   if (getLangOpts().CPlusPlus) {
9528     // C++ [class.static.data]p4
9529     //   If a static data member is of const integral or const
9530     //   enumeration type, its declaration in the class definition can
9531     //   specify a constant-initializer which shall be an integral
9532     //   constant expression (5.19). In that case, the member can appear
9533     //   in integral constant expressions. The member shall still be
9534     //   defined in a namespace scope if it is used in the program and the
9535     //   namespace scope definition shall not contain an initializer.
9536     //
9537     // We already performed a redefinition check above, but for static
9538     // data members we also need to check whether there was an in-class
9539     // declaration with an initializer.
9540     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9541       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9542           << VDecl->getDeclName();
9543       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9544            diag::note_previous_initializer)
9545           << 0;
9546       return;
9547     }
9548 
9549     if (VDecl->hasLocalStorage())
9550       getCurFunction()->setHasBranchProtectedScope();
9551 
9552     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9553       VDecl->setInvalidDecl();
9554       return;
9555     }
9556   }
9557 
9558   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9559   // a kernel function cannot be initialized."
9560   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
9561     Diag(VDecl->getLocation(), diag::err_local_cant_init);
9562     VDecl->setInvalidDecl();
9563     return;
9564   }
9565 
9566   // Get the decls type and save a reference for later, since
9567   // CheckInitializerTypes may change it.
9568   QualType DclT = VDecl->getType(), SavT = DclT;
9569 
9570   // Expressions default to 'id' when we're in a debugger
9571   // and we are assigning it to a variable of Objective-C pointer type.
9572   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9573       Init->getType() == Context.UnknownAnyTy) {
9574     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9575     if (Result.isInvalid()) {
9576       VDecl->setInvalidDecl();
9577       return;
9578     }
9579     Init = Result.get();
9580   }
9581 
9582   // Perform the initialization.
9583   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
9584   if (!VDecl->isInvalidDecl()) {
9585     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9586     InitializationKind Kind =
9587         DirectInit
9588             ? CXXDirectInit
9589                   ? InitializationKind::CreateDirect(VDecl->getLocation(),
9590                                                      Init->getLocStart(),
9591                                                      Init->getLocEnd())
9592                   : InitializationKind::CreateDirectList(VDecl->getLocation())
9593             : InitializationKind::CreateCopy(VDecl->getLocation(),
9594                                              Init->getLocStart());
9595 
9596     MultiExprArg Args = Init;
9597     if (CXXDirectInit)
9598       Args = MultiExprArg(CXXDirectInit->getExprs(),
9599                           CXXDirectInit->getNumExprs());
9600 
9601     // Try to correct any TypoExprs in the initialization arguments.
9602     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
9603       ExprResult Res = CorrectDelayedTyposInExpr(
9604           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
9605             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
9606             return Init.Failed() ? ExprError() : E;
9607           });
9608       if (Res.isInvalid()) {
9609         VDecl->setInvalidDecl();
9610       } else if (Res.get() != Args[Idx]) {
9611         Args[Idx] = Res.get();
9612       }
9613     }
9614     if (VDecl->isInvalidDecl())
9615       return;
9616 
9617     InitializationSequence InitSeq(*this, Entity, Kind, Args,
9618                                    /*TopLevelOfInitList=*/false,
9619                                    /*TreatUnavailableAsInvalid=*/false);
9620     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
9621     if (Result.isInvalid()) {
9622       VDecl->setInvalidDecl();
9623       return;
9624     }
9625 
9626     Init = Result.getAs<Expr>();
9627   }
9628 
9629   // Check for self-references within variable initializers.
9630   // Variables declared within a function/method body (except for references)
9631   // are handled by a dataflow analysis.
9632   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
9633       VDecl->getType()->isReferenceType()) {
9634     CheckSelfReference(*this, RealDecl, Init, DirectInit);
9635   }
9636 
9637   // If the type changed, it means we had an incomplete type that was
9638   // completed by the initializer. For example:
9639   //   int ary[] = { 1, 3, 5 };
9640   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
9641   if (!VDecl->isInvalidDecl() && (DclT != SavT))
9642     VDecl->setType(DclT);
9643 
9644   if (!VDecl->isInvalidDecl()) {
9645     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
9646 
9647     if (VDecl->hasAttr<BlocksAttr>())
9648       checkRetainCycles(VDecl, Init);
9649 
9650     // It is safe to assign a weak reference into a strong variable.
9651     // Although this code can still have problems:
9652     //   id x = self.weakProp;
9653     //   id y = self.weakProp;
9654     // we do not warn to warn spuriously when 'x' and 'y' are on separate
9655     // paths through the function. This should be revisited if
9656     // -Wrepeated-use-of-weak is made flow-sensitive.
9657     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
9658         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9659                          Init->getLocStart()))
9660       getCurFunction()->markSafeWeakUse(Init);
9661   }
9662 
9663   // The initialization is usually a full-expression.
9664   //
9665   // FIXME: If this is a braced initialization of an aggregate, it is not
9666   // an expression, and each individual field initializer is a separate
9667   // full-expression. For instance, in:
9668   //
9669   //   struct Temp { ~Temp(); };
9670   //   struct S { S(Temp); };
9671   //   struct T { S a, b; } t = { Temp(), Temp() }
9672   //
9673   // we should destroy the first Temp before constructing the second.
9674   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
9675                                           false,
9676                                           VDecl->isConstexpr());
9677   if (Result.isInvalid()) {
9678     VDecl->setInvalidDecl();
9679     return;
9680   }
9681   Init = Result.get();
9682 
9683   // Attach the initializer to the decl.
9684   VDecl->setInit(Init);
9685 
9686   if (VDecl->isLocalVarDecl()) {
9687     // C99 6.7.8p4: All the expressions in an initializer for an object that has
9688     // static storage duration shall be constant expressions or string literals.
9689     // C++ does not have this restriction.
9690     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
9691       const Expr *Culprit;
9692       if (VDecl->getStorageClass() == SC_Static)
9693         CheckForConstantInitializer(Init, DclT);
9694       // C89 is stricter than C99 for non-static aggregate types.
9695       // C89 6.5.7p3: All the expressions [...] in an initializer list
9696       // for an object that has aggregate or union type shall be
9697       // constant expressions.
9698       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
9699                isa<InitListExpr>(Init) &&
9700                !Init->isConstantInitializer(Context, false, &Culprit))
9701         Diag(Culprit->getExprLoc(),
9702              diag::ext_aggregate_init_not_constant)
9703           << Culprit->getSourceRange();
9704     }
9705   } else if (VDecl->isStaticDataMember() &&
9706              VDecl->getLexicalDeclContext()->isRecord()) {
9707     // This is an in-class initialization for a static data member, e.g.,
9708     //
9709     // struct S {
9710     //   static const int value = 17;
9711     // };
9712 
9713     // C++ [class.mem]p4:
9714     //   A member-declarator can contain a constant-initializer only
9715     //   if it declares a static member (9.4) of const integral or
9716     //   const enumeration type, see 9.4.2.
9717     //
9718     // C++11 [class.static.data]p3:
9719     //   If a non-volatile const static data member is of integral or
9720     //   enumeration type, its declaration in the class definition can
9721     //   specify a brace-or-equal-initializer in which every initalizer-clause
9722     //   that is an assignment-expression is a constant expression. A static
9723     //   data member of literal type can be declared in the class definition
9724     //   with the constexpr specifier; if so, its declaration shall specify a
9725     //   brace-or-equal-initializer in which every initializer-clause that is
9726     //   an assignment-expression is a constant expression.
9727 
9728     // Do nothing on dependent types.
9729     if (DclT->isDependentType()) {
9730 
9731     // Allow any 'static constexpr' members, whether or not they are of literal
9732     // type. We separately check that every constexpr variable is of literal
9733     // type.
9734     } else if (VDecl->isConstexpr()) {
9735 
9736     // Require constness.
9737     } else if (!DclT.isConstQualified()) {
9738       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
9739         << Init->getSourceRange();
9740       VDecl->setInvalidDecl();
9741 
9742     // We allow integer constant expressions in all cases.
9743     } else if (DclT->isIntegralOrEnumerationType()) {
9744       // Check whether the expression is a constant expression.
9745       SourceLocation Loc;
9746       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
9747         // In C++11, a non-constexpr const static data member with an
9748         // in-class initializer cannot be volatile.
9749         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
9750       else if (Init->isValueDependent())
9751         ; // Nothing to check.
9752       else if (Init->isIntegerConstantExpr(Context, &Loc))
9753         ; // Ok, it's an ICE!
9754       else if (Init->isEvaluatable(Context)) {
9755         // If we can constant fold the initializer through heroics, accept it,
9756         // but report this as a use of an extension for -pedantic.
9757         Diag(Loc, diag::ext_in_class_initializer_non_constant)
9758           << Init->getSourceRange();
9759       } else {
9760         // Otherwise, this is some crazy unknown case.  Report the issue at the
9761         // location provided by the isIntegerConstantExpr failed check.
9762         Diag(Loc, diag::err_in_class_initializer_non_constant)
9763           << Init->getSourceRange();
9764         VDecl->setInvalidDecl();
9765       }
9766 
9767     // We allow foldable floating-point constants as an extension.
9768     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
9769       // In C++98, this is a GNU extension. In C++11, it is not, but we support
9770       // it anyway and provide a fixit to add the 'constexpr'.
9771       if (getLangOpts().CPlusPlus11) {
9772         Diag(VDecl->getLocation(),
9773              diag::ext_in_class_initializer_float_type_cxx11)
9774             << DclT << Init->getSourceRange();
9775         Diag(VDecl->getLocStart(),
9776              diag::note_in_class_initializer_float_type_cxx11)
9777             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9778       } else {
9779         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
9780           << DclT << Init->getSourceRange();
9781 
9782         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
9783           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
9784             << Init->getSourceRange();
9785           VDecl->setInvalidDecl();
9786         }
9787       }
9788 
9789     // Suggest adding 'constexpr' in C++11 for literal types.
9790     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9791       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9792         << DclT << Init->getSourceRange()
9793         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9794       VDecl->setConstexpr(true);
9795 
9796     } else {
9797       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9798         << DclT << Init->getSourceRange();
9799       VDecl->setInvalidDecl();
9800     }
9801   } else if (VDecl->isFileVarDecl()) {
9802     if (VDecl->getStorageClass() == SC_Extern &&
9803         (!getLangOpts().CPlusPlus ||
9804          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
9805            VDecl->isExternC())) &&
9806         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
9807       Diag(VDecl->getLocation(), diag::warn_extern_init);
9808 
9809     // C99 6.7.8p4. All file scoped initializers need to be constant.
9810     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9811       CheckForConstantInitializer(Init, DclT);
9812   }
9813 
9814   // We will represent direct-initialization similarly to copy-initialization:
9815   //    int x(1);  -as-> int x = 1;
9816   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9817   //
9818   // Clients that want to distinguish between the two forms, can check for
9819   // direct initializer using VarDecl::getInitStyle().
9820   // A major benefit is that clients that don't particularly care about which
9821   // exactly form was it (like the CodeGen) can handle both cases without
9822   // special case code.
9823 
9824   // C++ 8.5p11:
9825   // The form of initialization (using parentheses or '=') is generally
9826   // insignificant, but does matter when the entity being initialized has a
9827   // class type.
9828   if (CXXDirectInit) {
9829     assert(DirectInit && "Call-style initializer must be direct init.");
9830     VDecl->setInitStyle(VarDecl::CallInit);
9831   } else if (DirectInit) {
9832     // This must be list-initialization. No other way is direct-initialization.
9833     VDecl->setInitStyle(VarDecl::ListInit);
9834   }
9835 
9836   CheckCompleteVariableDeclaration(VDecl);
9837 }
9838 
9839 /// ActOnInitializerError - Given that there was an error parsing an
9840 /// initializer for the given declaration, try to return to some form
9841 /// of sanity.
9842 void Sema::ActOnInitializerError(Decl *D) {
9843   // Our main concern here is re-establishing invariants like "a
9844   // variable's type is either dependent or complete".
9845   if (!D || D->isInvalidDecl()) return;
9846 
9847   VarDecl *VD = dyn_cast<VarDecl>(D);
9848   if (!VD) return;
9849 
9850   // Auto types are meaningless if we can't make sense of the initializer.
9851   if (ParsingInitForAutoVars.count(D)) {
9852     D->setInvalidDecl();
9853     return;
9854   }
9855 
9856   QualType Ty = VD->getType();
9857   if (Ty->isDependentType()) return;
9858 
9859   // Require a complete type.
9860   if (RequireCompleteType(VD->getLocation(),
9861                           Context.getBaseElementType(Ty),
9862                           diag::err_typecheck_decl_incomplete_type)) {
9863     VD->setInvalidDecl();
9864     return;
9865   }
9866 
9867   // Require a non-abstract type.
9868   if (RequireNonAbstractType(VD->getLocation(), Ty,
9869                              diag::err_abstract_type_in_decl,
9870                              AbstractVariableType)) {
9871     VD->setInvalidDecl();
9872     return;
9873   }
9874 
9875   // Don't bother complaining about constructors or destructors,
9876   // though.
9877 }
9878 
9879 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
9880                                   bool TypeMayContainAuto) {
9881   // If there is no declaration, there was an error parsing it. Just ignore it.
9882   if (!RealDecl)
9883     return;
9884 
9885   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9886     QualType Type = Var->getType();
9887 
9888     // C++11 [dcl.spec.auto]p3
9889     if (TypeMayContainAuto && Type->getContainedAutoType()) {
9890       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
9891         << Var->getDeclName() << Type;
9892       Var->setInvalidDecl();
9893       return;
9894     }
9895 
9896     // C++11 [class.static.data]p3: A static data member can be declared with
9897     // the constexpr specifier; if so, its declaration shall specify
9898     // a brace-or-equal-initializer.
9899     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
9900     // the definition of a variable [...] or the declaration of a static data
9901     // member.
9902     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
9903       if (Var->isStaticDataMember())
9904         Diag(Var->getLocation(),
9905              diag::err_constexpr_static_mem_var_requires_init)
9906           << Var->getDeclName();
9907       else
9908         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
9909       Var->setInvalidDecl();
9910       return;
9911     }
9912 
9913     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
9914     // definition having the concept specifier is called a variable concept. A
9915     // concept definition refers to [...] a variable concept and its initializer.
9916     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
9917       if (VTD->isConcept()) {
9918         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
9919         Var->setInvalidDecl();
9920         return;
9921       }
9922     }
9923 
9924     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
9925     // be initialized.
9926     if (!Var->isInvalidDecl() &&
9927         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
9928         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
9929       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
9930       Var->setInvalidDecl();
9931       return;
9932     }
9933 
9934     switch (Var->isThisDeclarationADefinition()) {
9935     case VarDecl::Definition:
9936       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
9937         break;
9938 
9939       // We have an out-of-line definition of a static data member
9940       // that has an in-class initializer, so we type-check this like
9941       // a declaration.
9942       //
9943       // Fall through
9944 
9945     case VarDecl::DeclarationOnly:
9946       // It's only a declaration.
9947 
9948       // Block scope. C99 6.7p7: If an identifier for an object is
9949       // declared with no linkage (C99 6.2.2p6), the type for the
9950       // object shall be complete.
9951       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
9952           !Var->hasLinkage() && !Var->isInvalidDecl() &&
9953           RequireCompleteType(Var->getLocation(), Type,
9954                               diag::err_typecheck_decl_incomplete_type))
9955         Var->setInvalidDecl();
9956 
9957       // Make sure that the type is not abstract.
9958       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9959           RequireNonAbstractType(Var->getLocation(), Type,
9960                                  diag::err_abstract_type_in_decl,
9961                                  AbstractVariableType))
9962         Var->setInvalidDecl();
9963       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9964           Var->getStorageClass() == SC_PrivateExtern) {
9965         Diag(Var->getLocation(), diag::warn_private_extern);
9966         Diag(Var->getLocation(), diag::note_private_extern);
9967       }
9968 
9969       return;
9970 
9971     case VarDecl::TentativeDefinition:
9972       // File scope. C99 6.9.2p2: A declaration of an identifier for an
9973       // object that has file scope without an initializer, and without a
9974       // storage-class specifier or with the storage-class specifier "static",
9975       // constitutes a tentative definition. Note: A tentative definition with
9976       // external linkage is valid (C99 6.2.2p5).
9977       if (!Var->isInvalidDecl()) {
9978         if (const IncompleteArrayType *ArrayT
9979                                     = Context.getAsIncompleteArrayType(Type)) {
9980           if (RequireCompleteType(Var->getLocation(),
9981                                   ArrayT->getElementType(),
9982                                   diag::err_illegal_decl_array_incomplete_type))
9983             Var->setInvalidDecl();
9984         } else if (Var->getStorageClass() == SC_Static) {
9985           // C99 6.9.2p3: If the declaration of an identifier for an object is
9986           // a tentative definition and has internal linkage (C99 6.2.2p3), the
9987           // declared type shall not be an incomplete type.
9988           // NOTE: code such as the following
9989           //     static struct s;
9990           //     struct s { int a; };
9991           // is accepted by gcc. Hence here we issue a warning instead of
9992           // an error and we do not invalidate the static declaration.
9993           // NOTE: to avoid multiple warnings, only check the first declaration.
9994           if (Var->isFirstDecl())
9995             RequireCompleteType(Var->getLocation(), Type,
9996                                 diag::ext_typecheck_decl_incomplete_type);
9997         }
9998       }
9999 
10000       // Record the tentative definition; we're done.
10001       if (!Var->isInvalidDecl())
10002         TentativeDefinitions.push_back(Var);
10003       return;
10004     }
10005 
10006     // Provide a specific diagnostic for uninitialized variable
10007     // definitions with incomplete array type.
10008     if (Type->isIncompleteArrayType()) {
10009       Diag(Var->getLocation(),
10010            diag::err_typecheck_incomplete_array_needs_initializer);
10011       Var->setInvalidDecl();
10012       return;
10013     }
10014 
10015     // Provide a specific diagnostic for uninitialized variable
10016     // definitions with reference type.
10017     if (Type->isReferenceType()) {
10018       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10019         << Var->getDeclName()
10020         << SourceRange(Var->getLocation(), Var->getLocation());
10021       Var->setInvalidDecl();
10022       return;
10023     }
10024 
10025     // Do not attempt to type-check the default initializer for a
10026     // variable with dependent type.
10027     if (Type->isDependentType())
10028       return;
10029 
10030     if (Var->isInvalidDecl())
10031       return;
10032 
10033     if (!Var->hasAttr<AliasAttr>()) {
10034       if (RequireCompleteType(Var->getLocation(),
10035                               Context.getBaseElementType(Type),
10036                               diag::err_typecheck_decl_incomplete_type)) {
10037         Var->setInvalidDecl();
10038         return;
10039       }
10040     } else {
10041       return;
10042     }
10043 
10044     // The variable can not have an abstract class type.
10045     if (RequireNonAbstractType(Var->getLocation(), Type,
10046                                diag::err_abstract_type_in_decl,
10047                                AbstractVariableType)) {
10048       Var->setInvalidDecl();
10049       return;
10050     }
10051 
10052     // Check for jumps past the implicit initializer.  C++0x
10053     // clarifies that this applies to a "variable with automatic
10054     // storage duration", not a "local variable".
10055     // C++11 [stmt.dcl]p3
10056     //   A program that jumps from a point where a variable with automatic
10057     //   storage duration is not in scope to a point where it is in scope is
10058     //   ill-formed unless the variable has scalar type, class type with a
10059     //   trivial default constructor and a trivial destructor, a cv-qualified
10060     //   version of one of these types, or an array of one of the preceding
10061     //   types and is declared without an initializer.
10062     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10063       if (const RecordType *Record
10064             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10065         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10066         // Mark the function for further checking even if the looser rules of
10067         // C++11 do not require such checks, so that we can diagnose
10068         // incompatibilities with C++98.
10069         if (!CXXRecord->isPOD())
10070           getCurFunction()->setHasBranchProtectedScope();
10071       }
10072     }
10073 
10074     // C++03 [dcl.init]p9:
10075     //   If no initializer is specified for an object, and the
10076     //   object is of (possibly cv-qualified) non-POD class type (or
10077     //   array thereof), the object shall be default-initialized; if
10078     //   the object is of const-qualified type, the underlying class
10079     //   type shall have a user-declared default
10080     //   constructor. Otherwise, if no initializer is specified for
10081     //   a non- static object, the object and its subobjects, if
10082     //   any, have an indeterminate initial value); if the object
10083     //   or any of its subobjects are of const-qualified type, the
10084     //   program is ill-formed.
10085     // C++0x [dcl.init]p11:
10086     //   If no initializer is specified for an object, the object is
10087     //   default-initialized; [...].
10088     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10089     InitializationKind Kind
10090       = InitializationKind::CreateDefault(Var->getLocation());
10091 
10092     InitializationSequence InitSeq(*this, Entity, Kind, None);
10093     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10094     if (Init.isInvalid())
10095       Var->setInvalidDecl();
10096     else if (Init.get()) {
10097       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10098       // This is important for template substitution.
10099       Var->setInitStyle(VarDecl::CallInit);
10100     }
10101 
10102     CheckCompleteVariableDeclaration(Var);
10103   }
10104 }
10105 
10106 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10107   // If there is no declaration, there was an error parsing it. Ignore it.
10108   if (!D)
10109     return;
10110 
10111   VarDecl *VD = dyn_cast<VarDecl>(D);
10112   if (!VD) {
10113     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10114     D->setInvalidDecl();
10115     return;
10116   }
10117 
10118   VD->setCXXForRangeDecl(true);
10119 
10120   // for-range-declaration cannot be given a storage class specifier.
10121   int Error = -1;
10122   switch (VD->getStorageClass()) {
10123   case SC_None:
10124     break;
10125   case SC_Extern:
10126     Error = 0;
10127     break;
10128   case SC_Static:
10129     Error = 1;
10130     break;
10131   case SC_PrivateExtern:
10132     Error = 2;
10133     break;
10134   case SC_Auto:
10135     Error = 3;
10136     break;
10137   case SC_Register:
10138     Error = 4;
10139     break;
10140   }
10141   if (Error != -1) {
10142     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10143       << VD->getDeclName() << Error;
10144     D->setInvalidDecl();
10145   }
10146 }
10147 
10148 StmtResult
10149 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10150                                  IdentifierInfo *Ident,
10151                                  ParsedAttributes &Attrs,
10152                                  SourceLocation AttrEnd) {
10153   // C++1y [stmt.iter]p1:
10154   //   A range-based for statement of the form
10155   //      for ( for-range-identifier : for-range-initializer ) statement
10156   //   is equivalent to
10157   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
10158   DeclSpec DS(Attrs.getPool().getFactory());
10159 
10160   const char *PrevSpec;
10161   unsigned DiagID;
10162   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10163                      getPrintingPolicy());
10164 
10165   Declarator D(DS, Declarator::ForContext);
10166   D.SetIdentifier(Ident, IdentLoc);
10167   D.takeAttributes(Attrs, AttrEnd);
10168 
10169   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10170   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10171                 EmptyAttrs, IdentLoc);
10172   Decl *Var = ActOnDeclarator(S, D);
10173   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10174   FinalizeDeclaration(Var);
10175   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10176                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
10177 }
10178 
10179 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10180   if (var->isInvalidDecl()) return;
10181 
10182   if (getLangOpts().OpenCL) {
10183     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10184     // initialiser
10185     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10186         !var->hasInit()) {
10187       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10188           << 1 /*Init*/;
10189       var->setInvalidDecl();
10190       return;
10191     }
10192   }
10193 
10194   // In Objective-C, don't allow jumps past the implicit initialization of a
10195   // local retaining variable.
10196   if (getLangOpts().ObjC1 &&
10197       var->hasLocalStorage()) {
10198     switch (var->getType().getObjCLifetime()) {
10199     case Qualifiers::OCL_None:
10200     case Qualifiers::OCL_ExplicitNone:
10201     case Qualifiers::OCL_Autoreleasing:
10202       break;
10203 
10204     case Qualifiers::OCL_Weak:
10205     case Qualifiers::OCL_Strong:
10206       getCurFunction()->setHasBranchProtectedScope();
10207       break;
10208     }
10209   }
10210 
10211   // Warn about externally-visible variables being defined without a
10212   // prior declaration.  We only want to do this for global
10213   // declarations, but we also specifically need to avoid doing it for
10214   // class members because the linkage of an anonymous class can
10215   // change if it's later given a typedef name.
10216   if (var->isThisDeclarationADefinition() &&
10217       var->getDeclContext()->getRedeclContext()->isFileContext() &&
10218       var->isExternallyVisible() && var->hasLinkage() &&
10219       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10220                                   var->getLocation())) {
10221     // Find a previous declaration that's not a definition.
10222     VarDecl *prev = var->getPreviousDecl();
10223     while (prev && prev->isThisDeclarationADefinition())
10224       prev = prev->getPreviousDecl();
10225 
10226     if (!prev)
10227       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10228   }
10229 
10230   if (var->getTLSKind() == VarDecl::TLS_Static) {
10231     const Expr *Culprit;
10232     if (var->getType().isDestructedType()) {
10233       // GNU C++98 edits for __thread, [basic.start.term]p3:
10234       //   The type of an object with thread storage duration shall not
10235       //   have a non-trivial destructor.
10236       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10237       if (getLangOpts().CPlusPlus11)
10238         Diag(var->getLocation(), diag::note_use_thread_local);
10239     } else if (getLangOpts().CPlusPlus && var->hasInit() &&
10240                !var->getInit()->isConstantInitializer(
10241                    Context, var->getType()->isReferenceType(), &Culprit)) {
10242       // GNU C++98 edits for __thread, [basic.start.init]p4:
10243       //   An object of thread storage duration shall not require dynamic
10244       //   initialization.
10245       // FIXME: Need strict checking here.
10246       Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
10247         << Culprit->getSourceRange();
10248       if (getLangOpts().CPlusPlus11)
10249         Diag(var->getLocation(), diag::note_use_thread_local);
10250     }
10251   }
10252 
10253   // Apply section attributes and pragmas to global variables.
10254   bool GlobalStorage = var->hasGlobalStorage();
10255   if (GlobalStorage && var->isThisDeclarationADefinition() &&
10256       ActiveTemplateInstantiations.empty()) {
10257     PragmaStack<StringLiteral *> *Stack = nullptr;
10258     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10259     if (var->getType().isConstQualified())
10260       Stack = &ConstSegStack;
10261     else if (!var->getInit()) {
10262       Stack = &BSSSegStack;
10263       SectionFlags |= ASTContext::PSF_Write;
10264     } else {
10265       Stack = &DataSegStack;
10266       SectionFlags |= ASTContext::PSF_Write;
10267     }
10268     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10269       var->addAttr(SectionAttr::CreateImplicit(
10270           Context, SectionAttr::Declspec_allocate,
10271           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10272     }
10273     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10274       if (UnifySection(SA->getName(), SectionFlags, var))
10275         var->dropAttr<SectionAttr>();
10276 
10277     // Apply the init_seg attribute if this has an initializer.  If the
10278     // initializer turns out to not be dynamic, we'll end up ignoring this
10279     // attribute.
10280     if (CurInitSeg && var->getInit())
10281       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10282                                                CurInitSegLoc));
10283   }
10284 
10285   // All the following checks are C++ only.
10286   if (!getLangOpts().CPlusPlus) return;
10287 
10288   QualType type = var->getType();
10289   if (type->isDependentType()) return;
10290 
10291   // __block variables might require us to capture a copy-initializer.
10292   if (var->hasAttr<BlocksAttr>()) {
10293     // It's currently invalid to ever have a __block variable with an
10294     // array type; should we diagnose that here?
10295 
10296     // Regardless, we don't want to ignore array nesting when
10297     // constructing this copy.
10298     if (type->isStructureOrClassType()) {
10299       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10300       SourceLocation poi = var->getLocation();
10301       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10302       ExprResult result
10303         = PerformMoveOrCopyInitialization(
10304             InitializedEntity::InitializeBlock(poi, type, false),
10305             var, var->getType(), varRef, /*AllowNRVO=*/true);
10306       if (!result.isInvalid()) {
10307         result = MaybeCreateExprWithCleanups(result);
10308         Expr *init = result.getAs<Expr>();
10309         Context.setBlockVarCopyInits(var, init);
10310       }
10311     }
10312   }
10313 
10314   Expr *Init = var->getInit();
10315   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10316   QualType baseType = Context.getBaseElementType(type);
10317 
10318   if (!var->getDeclContext()->isDependentContext() &&
10319       Init && !Init->isValueDependent()) {
10320     if (IsGlobal && !var->isConstexpr() &&
10321         !getDiagnostics().isIgnored(diag::warn_global_constructor,
10322                                     var->getLocation())) {
10323       // Warn about globals which don't have a constant initializer.  Don't
10324       // warn about globals with a non-trivial destructor because we already
10325       // warned about them.
10326       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10327       if (!(RD && !RD->hasTrivialDestructor()) &&
10328           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
10329         Diag(var->getLocation(), diag::warn_global_constructor)
10330           << Init->getSourceRange();
10331     }
10332 
10333     if (var->isConstexpr()) {
10334       SmallVector<PartialDiagnosticAt, 8> Notes;
10335       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10336         SourceLocation DiagLoc = var->getLocation();
10337         // If the note doesn't add any useful information other than a source
10338         // location, fold it into the primary diagnostic.
10339         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10340               diag::note_invalid_subexpr_in_const_expr) {
10341           DiagLoc = Notes[0].first;
10342           Notes.clear();
10343         }
10344         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10345           << var << Init->getSourceRange();
10346         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10347           Diag(Notes[I].first, Notes[I].second);
10348       }
10349     } else if (var->isUsableInConstantExpressions(Context)) {
10350       // Check whether the initializer of a const variable of integral or
10351       // enumeration type is an ICE now, since we can't tell whether it was
10352       // initialized by a constant expression if we check later.
10353       var->checkInitIsICE();
10354     }
10355   }
10356 
10357   // Require the destructor.
10358   if (const RecordType *recordType = baseType->getAs<RecordType>())
10359     FinalizeVarWithDestructor(var, recordType);
10360 }
10361 
10362 /// \brief Determines if a variable's alignment is dependent.
10363 static bool hasDependentAlignment(VarDecl *VD) {
10364   if (VD->getType()->isDependentType())
10365     return true;
10366   for (auto *I : VD->specific_attrs<AlignedAttr>())
10367     if (I->isAlignmentDependent())
10368       return true;
10369   return false;
10370 }
10371 
10372 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10373 /// any semantic actions necessary after any initializer has been attached.
10374 void
10375 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10376   // Note that we are no longer parsing the initializer for this declaration.
10377   ParsingInitForAutoVars.erase(ThisDecl);
10378 
10379   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10380   if (!VD)
10381     return;
10382 
10383   checkAttributesAfterMerging(*this, *VD);
10384 
10385   // Perform TLS alignment check here after attributes attached to the variable
10386   // which may affect the alignment have been processed. Only perform the check
10387   // if the target has a maximum TLS alignment (zero means no constraints).
10388   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
10389     // Protect the check so that it's not performed on dependent types and
10390     // dependent alignments (we can't determine the alignment in that case).
10391     if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
10392       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
10393       if (Context.getDeclAlign(VD) > MaxAlignChars) {
10394         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
10395           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
10396           << (unsigned)MaxAlignChars.getQuantity();
10397       }
10398     }
10399   }
10400 
10401   if (VD->isStaticLocal()) {
10402     if (FunctionDecl *FD =
10403             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
10404       // Static locals inherit dll attributes from their function.
10405       if (Attr *A = getDLLAttr(FD)) {
10406         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
10407         NewAttr->setInherited(true);
10408         VD->addAttr(NewAttr);
10409       }
10410       // CUDA E.2.9.4: Within the body of a __device__ or __global__
10411       // function, only __shared__ variables may be declared with
10412       // static storage class.
10413       if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
10414           (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>()) &&
10415           !VD->hasAttr<CUDASharedAttr>()) {
10416         Diag(VD->getLocation(), diag::err_device_static_local_var);
10417         VD->setInvalidDecl();
10418       }
10419     }
10420   }
10421 
10422   // Perform check for initializers of device-side global variables.
10423   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
10424   // 7.5). We must also apply the same checks to all __shared__
10425   // variables whether they are local or not. CUDA also allows
10426   // constant initializers for __constant__ and __device__ variables.
10427   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
10428     const Expr *Init = VD->getInit();
10429     if (Init && VD->hasGlobalStorage() &&
10430         (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
10431          VD->hasAttr<CUDASharedAttr>())) {
10432       assert((!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()));
10433       bool AllowedInit = false;
10434       if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
10435         AllowedInit =
10436             isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
10437       // We'll allow constant initializers even if it's a non-empty
10438       // constructor according to CUDA rules. This deviates from NVCC,
10439       // but allows us to handle things like constexpr constructors.
10440       if (!AllowedInit &&
10441           (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
10442         AllowedInit = VD->getInit()->isConstantInitializer(
10443             Context, VD->getType()->isReferenceType());
10444 
10445       // Also make sure that destructor, if there is one, is empty.
10446       if (AllowedInit)
10447         if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
10448           AllowedInit =
10449               isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
10450 
10451       if (!AllowedInit) {
10452         Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
10453                                     ? diag::err_shared_var_init
10454                                     : diag::err_dynamic_var_init)
10455             << Init->getSourceRange();
10456         VD->setInvalidDecl();
10457       }
10458     }
10459   }
10460 
10461   // Grab the dllimport or dllexport attribute off of the VarDecl.
10462   const InheritableAttr *DLLAttr = getDLLAttr(VD);
10463 
10464   // Imported static data members cannot be defined out-of-line.
10465   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
10466     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
10467         VD->isThisDeclarationADefinition()) {
10468       // We allow definitions of dllimport class template static data members
10469       // with a warning.
10470       CXXRecordDecl *Context =
10471         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
10472       bool IsClassTemplateMember =
10473           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
10474           Context->getDescribedClassTemplate();
10475 
10476       Diag(VD->getLocation(),
10477            IsClassTemplateMember
10478                ? diag::warn_attribute_dllimport_static_field_definition
10479                : diag::err_attribute_dllimport_static_field_definition);
10480       Diag(IA->getLocation(), diag::note_attribute);
10481       if (!IsClassTemplateMember)
10482         VD->setInvalidDecl();
10483     }
10484   }
10485 
10486   // dllimport/dllexport variables cannot be thread local, their TLS index
10487   // isn't exported with the variable.
10488   if (DLLAttr && VD->getTLSKind()) {
10489     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
10490     if (F && getDLLAttr(F)) {
10491       assert(VD->isStaticLocal());
10492       // But if this is a static local in a dlimport/dllexport function, the
10493       // function will never be inlined, which means the var would never be
10494       // imported, so having it marked import/export is safe.
10495     } else {
10496       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
10497                                                                     << DLLAttr;
10498       VD->setInvalidDecl();
10499     }
10500   }
10501 
10502   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
10503     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
10504       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
10505       VD->dropAttr<UsedAttr>();
10506     }
10507   }
10508 
10509   const DeclContext *DC = VD->getDeclContext();
10510   // If there's a #pragma GCC visibility in scope, and this isn't a class
10511   // member, set the visibility of this variable.
10512   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
10513     AddPushedVisibilityAttribute(VD);
10514 
10515   // FIXME: Warn on unused templates.
10516   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
10517       !isa<VarTemplatePartialSpecializationDecl>(VD))
10518     MarkUnusedFileScopedDecl(VD);
10519 
10520   // Now we have parsed the initializer and can update the table of magic
10521   // tag values.
10522   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
10523       !VD->getType()->isIntegralOrEnumerationType())
10524     return;
10525 
10526   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
10527     const Expr *MagicValueExpr = VD->getInit();
10528     if (!MagicValueExpr) {
10529       continue;
10530     }
10531     llvm::APSInt MagicValueInt;
10532     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
10533       Diag(I->getRange().getBegin(),
10534            diag::err_type_tag_for_datatype_not_ice)
10535         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10536       continue;
10537     }
10538     if (MagicValueInt.getActiveBits() > 64) {
10539       Diag(I->getRange().getBegin(),
10540            diag::err_type_tag_for_datatype_too_large)
10541         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10542       continue;
10543     }
10544     uint64_t MagicValue = MagicValueInt.getZExtValue();
10545     RegisterTypeTagForDatatype(I->getArgumentKind(),
10546                                MagicValue,
10547                                I->getMatchingCType(),
10548                                I->getLayoutCompatible(),
10549                                I->getMustBeNull());
10550   }
10551 }
10552 
10553 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
10554                                                    ArrayRef<Decl *> Group) {
10555   SmallVector<Decl*, 8> Decls;
10556 
10557   if (DS.isTypeSpecOwned())
10558     Decls.push_back(DS.getRepAsDecl());
10559 
10560   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
10561   for (unsigned i = 0, e = Group.size(); i != e; ++i)
10562     if (Decl *D = Group[i]) {
10563       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
10564         if (!FirstDeclaratorInGroup)
10565           FirstDeclaratorInGroup = DD;
10566       Decls.push_back(D);
10567     }
10568 
10569   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
10570     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
10571       handleTagNumbering(Tag, S);
10572       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
10573           getLangOpts().CPlusPlus)
10574         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
10575     }
10576   }
10577 
10578   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
10579 }
10580 
10581 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
10582 /// group, performing any necessary semantic checking.
10583 Sema::DeclGroupPtrTy
10584 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
10585                            bool TypeMayContainAuto) {
10586   // C++0x [dcl.spec.auto]p7:
10587   //   If the type deduced for the template parameter U is not the same in each
10588   //   deduction, the program is ill-formed.
10589   // FIXME: When initializer-list support is added, a distinction is needed
10590   // between the deduced type U and the deduced type which 'auto' stands for.
10591   //   auto a = 0, b = { 1, 2, 3 };
10592   // is legal because the deduced type U is 'int' in both cases.
10593   if (TypeMayContainAuto && Group.size() > 1) {
10594     QualType Deduced;
10595     CanQualType DeducedCanon;
10596     VarDecl *DeducedDecl = nullptr;
10597     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
10598       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
10599         AutoType *AT = D->getType()->getContainedAutoType();
10600         // Don't reissue diagnostics when instantiating a template.
10601         if (AT && D->isInvalidDecl())
10602           break;
10603         QualType U = AT ? AT->getDeducedType() : QualType();
10604         if (!U.isNull()) {
10605           CanQualType UCanon = Context.getCanonicalType(U);
10606           if (Deduced.isNull()) {
10607             Deduced = U;
10608             DeducedCanon = UCanon;
10609             DeducedDecl = D;
10610           } else if (DeducedCanon != UCanon) {
10611             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
10612                  diag::err_auto_different_deductions)
10613               << (unsigned)AT->getKeyword()
10614               << Deduced << DeducedDecl->getDeclName()
10615               << U << D->getDeclName()
10616               << DeducedDecl->getInit()->getSourceRange()
10617               << D->getInit()->getSourceRange();
10618             D->setInvalidDecl();
10619             break;
10620           }
10621         }
10622       }
10623     }
10624   }
10625 
10626   ActOnDocumentableDecls(Group);
10627 
10628   return DeclGroupPtrTy::make(
10629       DeclGroupRef::Create(Context, Group.data(), Group.size()));
10630 }
10631 
10632 void Sema::ActOnDocumentableDecl(Decl *D) {
10633   ActOnDocumentableDecls(D);
10634 }
10635 
10636 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
10637   // Don't parse the comment if Doxygen diagnostics are ignored.
10638   if (Group.empty() || !Group[0])
10639     return;
10640 
10641   if (Diags.isIgnored(diag::warn_doc_param_not_found,
10642                       Group[0]->getLocation()) &&
10643       Diags.isIgnored(diag::warn_unknown_comment_command_name,
10644                       Group[0]->getLocation()))
10645     return;
10646 
10647   if (Group.size() >= 2) {
10648     // This is a decl group.  Normally it will contain only declarations
10649     // produced from declarator list.  But in case we have any definitions or
10650     // additional declaration references:
10651     //   'typedef struct S {} S;'
10652     //   'typedef struct S *S;'
10653     //   'struct S *pS;'
10654     // FinalizeDeclaratorGroup adds these as separate declarations.
10655     Decl *MaybeTagDecl = Group[0];
10656     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
10657       Group = Group.slice(1);
10658     }
10659   }
10660 
10661   // See if there are any new comments that are not attached to a decl.
10662   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
10663   if (!Comments.empty() &&
10664       !Comments.back()->isAttached()) {
10665     // There is at least one comment that not attached to a decl.
10666     // Maybe it should be attached to one of these decls?
10667     //
10668     // Note that this way we pick up not only comments that precede the
10669     // declaration, but also comments that *follow* the declaration -- thanks to
10670     // the lookahead in the lexer: we've consumed the semicolon and looked
10671     // ahead through comments.
10672     for (unsigned i = 0, e = Group.size(); i != e; ++i)
10673       Context.getCommentForDecl(Group[i], &PP);
10674   }
10675 }
10676 
10677 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
10678 /// to introduce parameters into function prototype scope.
10679 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
10680   const DeclSpec &DS = D.getDeclSpec();
10681 
10682   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
10683 
10684   // C++03 [dcl.stc]p2 also permits 'auto'.
10685   StorageClass SC = SC_None;
10686   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
10687     SC = SC_Register;
10688   } else if (getLangOpts().CPlusPlus &&
10689              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
10690     SC = SC_Auto;
10691   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
10692     Diag(DS.getStorageClassSpecLoc(),
10693          diag::err_invalid_storage_class_in_func_decl);
10694     D.getMutableDeclSpec().ClearStorageClassSpecs();
10695   }
10696 
10697   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
10698     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
10699       << DeclSpec::getSpecifierName(TSCS);
10700   if (DS.isConstexprSpecified())
10701     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
10702       << 0;
10703   if (DS.isConceptSpecified())
10704     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
10705 
10706   DiagnoseFunctionSpecifiers(DS);
10707 
10708   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10709   QualType parmDeclType = TInfo->getType();
10710 
10711   if (getLangOpts().CPlusPlus) {
10712     // Check that there are no default arguments inside the type of this
10713     // parameter.
10714     CheckExtraCXXDefaultArguments(D);
10715 
10716     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
10717     if (D.getCXXScopeSpec().isSet()) {
10718       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
10719         << D.getCXXScopeSpec().getRange();
10720       D.getCXXScopeSpec().clear();
10721     }
10722   }
10723 
10724   // Ensure we have a valid name
10725   IdentifierInfo *II = nullptr;
10726   if (D.hasName()) {
10727     II = D.getIdentifier();
10728     if (!II) {
10729       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
10730         << GetNameForDeclarator(D).getName();
10731       D.setInvalidType(true);
10732     }
10733   }
10734 
10735   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
10736   if (II) {
10737     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
10738                    ForRedeclaration);
10739     LookupName(R, S);
10740     if (R.isSingleResult()) {
10741       NamedDecl *PrevDecl = R.getFoundDecl();
10742       if (PrevDecl->isTemplateParameter()) {
10743         // Maybe we will complain about the shadowed template parameter.
10744         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10745         // Just pretend that we didn't see the previous declaration.
10746         PrevDecl = nullptr;
10747       } else if (S->isDeclScope(PrevDecl)) {
10748         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
10749         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10750 
10751         // Recover by removing the name
10752         II = nullptr;
10753         D.SetIdentifier(nullptr, D.getIdentifierLoc());
10754         D.setInvalidType(true);
10755       }
10756     }
10757   }
10758 
10759   // Temporarily put parameter variables in the translation unit, not
10760   // the enclosing context.  This prevents them from accidentally
10761   // looking like class members in C++.
10762   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
10763                                     D.getLocStart(),
10764                                     D.getIdentifierLoc(), II,
10765                                     parmDeclType, TInfo,
10766                                     SC);
10767 
10768   if (D.isInvalidType())
10769     New->setInvalidDecl();
10770 
10771   assert(S->isFunctionPrototypeScope());
10772   assert(S->getFunctionPrototypeDepth() >= 1);
10773   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
10774                     S->getNextFunctionPrototypeIndex());
10775 
10776   // Add the parameter declaration into this scope.
10777   S->AddDecl(New);
10778   if (II)
10779     IdResolver.AddDecl(New);
10780 
10781   ProcessDeclAttributes(S, New, D);
10782 
10783   if (D.getDeclSpec().isModulePrivateSpecified())
10784     Diag(New->getLocation(), diag::err_module_private_local)
10785       << 1 << New->getDeclName()
10786       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10787       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10788 
10789   if (New->hasAttr<BlocksAttr>()) {
10790     Diag(New->getLocation(), diag::err_block_on_nonlocal);
10791   }
10792   return New;
10793 }
10794 
10795 /// \brief Synthesizes a variable for a parameter arising from a
10796 /// typedef.
10797 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
10798                                               SourceLocation Loc,
10799                                               QualType T) {
10800   /* FIXME: setting StartLoc == Loc.
10801      Would it be worth to modify callers so as to provide proper source
10802      location for the unnamed parameters, embedding the parameter's type? */
10803   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
10804                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
10805                                            SC_None, nullptr);
10806   Param->setImplicit();
10807   return Param;
10808 }
10809 
10810 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
10811                                     ParmVarDecl * const *ParamEnd) {
10812   // Don't diagnose unused-parameter errors in template instantiations; we
10813   // will already have done so in the template itself.
10814   if (!ActiveTemplateInstantiations.empty())
10815     return;
10816 
10817   for (; Param != ParamEnd; ++Param) {
10818     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
10819         !(*Param)->hasAttr<UnusedAttr>()) {
10820       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
10821         << (*Param)->getDeclName();
10822     }
10823   }
10824 }
10825 
10826 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
10827                                                   ParmVarDecl * const *ParamEnd,
10828                                                   QualType ReturnTy,
10829                                                   NamedDecl *D) {
10830   if (LangOpts.NumLargeByValueCopy == 0) // No check.
10831     return;
10832 
10833   // Warn if the return value is pass-by-value and larger than the specified
10834   // threshold.
10835   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
10836     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
10837     if (Size > LangOpts.NumLargeByValueCopy)
10838       Diag(D->getLocation(), diag::warn_return_value_size)
10839           << D->getDeclName() << Size;
10840   }
10841 
10842   // Warn if any parameter is pass-by-value and larger than the specified
10843   // threshold.
10844   for (; Param != ParamEnd; ++Param) {
10845     QualType T = (*Param)->getType();
10846     if (T->isDependentType() || !T.isPODType(Context))
10847       continue;
10848     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
10849     if (Size > LangOpts.NumLargeByValueCopy)
10850       Diag((*Param)->getLocation(), diag::warn_parameter_size)
10851           << (*Param)->getDeclName() << Size;
10852   }
10853 }
10854 
10855 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
10856                                   SourceLocation NameLoc, IdentifierInfo *Name,
10857                                   QualType T, TypeSourceInfo *TSInfo,
10858                                   StorageClass SC) {
10859   // In ARC, infer a lifetime qualifier for appropriate parameter types.
10860   if (getLangOpts().ObjCAutoRefCount &&
10861       T.getObjCLifetime() == Qualifiers::OCL_None &&
10862       T->isObjCLifetimeType()) {
10863 
10864     Qualifiers::ObjCLifetime lifetime;
10865 
10866     // Special cases for arrays:
10867     //   - if it's const, use __unsafe_unretained
10868     //   - otherwise, it's an error
10869     if (T->isArrayType()) {
10870       if (!T.isConstQualified()) {
10871         DelayedDiagnostics.add(
10872             sema::DelayedDiagnostic::makeForbiddenType(
10873             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
10874       }
10875       lifetime = Qualifiers::OCL_ExplicitNone;
10876     } else {
10877       lifetime = T->getObjCARCImplicitLifetime();
10878     }
10879     T = Context.getLifetimeQualifiedType(T, lifetime);
10880   }
10881 
10882   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
10883                                          Context.getAdjustedParameterType(T),
10884                                          TSInfo, SC, nullptr);
10885 
10886   // Parameters can not be abstract class types.
10887   // For record types, this is done by the AbstractClassUsageDiagnoser once
10888   // the class has been completely parsed.
10889   if (!CurContext->isRecord() &&
10890       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
10891                              AbstractParamType))
10892     New->setInvalidDecl();
10893 
10894   // Parameter declarators cannot be interface types. All ObjC objects are
10895   // passed by reference.
10896   if (T->isObjCObjectType()) {
10897     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
10898     Diag(NameLoc,
10899          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
10900       << FixItHint::CreateInsertion(TypeEndLoc, "*");
10901     T = Context.getObjCObjectPointerType(T);
10902     New->setType(T);
10903   }
10904 
10905   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
10906   // duration shall not be qualified by an address-space qualifier."
10907   // Since all parameters have automatic store duration, they can not have
10908   // an address space.
10909   if (T.getAddressSpace() != 0) {
10910     // OpenCL allows function arguments declared to be an array of a type
10911     // to be qualified with an address space.
10912     if (!(getLangOpts().OpenCL && T->isArrayType())) {
10913       Diag(NameLoc, diag::err_arg_with_address_space);
10914       New->setInvalidDecl();
10915     }
10916   }
10917 
10918   // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
10919   // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
10920   if (getLangOpts().OpenCL && T->isPointerType()) {
10921     const QualType PTy = T->getPointeeType();
10922     if (PTy->isImageType() || PTy->isSamplerT() || PTy->isPipeType()) {
10923       Diag(NameLoc, diag::err_opencl_pointer_to_type) << PTy;
10924       New->setInvalidDecl();
10925     }
10926   }
10927 
10928   return New;
10929 }
10930 
10931 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
10932                                            SourceLocation LocAfterDecls) {
10933   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10934 
10935   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
10936   // for a K&R function.
10937   if (!FTI.hasPrototype) {
10938     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
10939       --i;
10940       if (FTI.Params[i].Param == nullptr) {
10941         SmallString<256> Code;
10942         llvm::raw_svector_ostream(Code)
10943             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
10944         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
10945             << FTI.Params[i].Ident
10946             << FixItHint::CreateInsertion(LocAfterDecls, Code);
10947 
10948         // Implicitly declare the argument as type 'int' for lack of a better
10949         // type.
10950         AttributeFactory attrs;
10951         DeclSpec DS(attrs);
10952         const char* PrevSpec; // unused
10953         unsigned DiagID; // unused
10954         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
10955                            DiagID, Context.getPrintingPolicy());
10956         // Use the identifier location for the type source range.
10957         DS.SetRangeStart(FTI.Params[i].IdentLoc);
10958         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
10959         Declarator ParamD(DS, Declarator::KNRTypeListContext);
10960         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
10961         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
10962       }
10963     }
10964   }
10965 }
10966 
10967 Decl *
10968 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
10969                               MultiTemplateParamsArg TemplateParameterLists,
10970                               SkipBodyInfo *SkipBody) {
10971   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
10972   assert(D.isFunctionDeclarator() && "Not a function declarator!");
10973   Scope *ParentScope = FnBodyScope->getParent();
10974 
10975   D.setFunctionDefinitionKind(FDK_Definition);
10976   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
10977   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
10978 }
10979 
10980 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
10981   Consumer.HandleInlineFunctionDefinition(D);
10982 }
10983 
10984 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
10985                              const FunctionDecl*& PossibleZeroParamPrototype) {
10986   // Don't warn about invalid declarations.
10987   if (FD->isInvalidDecl())
10988     return false;
10989 
10990   // Or declarations that aren't global.
10991   if (!FD->isGlobal())
10992     return false;
10993 
10994   // Don't warn about C++ member functions.
10995   if (isa<CXXMethodDecl>(FD))
10996     return false;
10997 
10998   // Don't warn about 'main'.
10999   if (FD->isMain())
11000     return false;
11001 
11002   // Don't warn about inline functions.
11003   if (FD->isInlined())
11004     return false;
11005 
11006   // Don't warn about function templates.
11007   if (FD->getDescribedFunctionTemplate())
11008     return false;
11009 
11010   // Don't warn about function template specializations.
11011   if (FD->isFunctionTemplateSpecialization())
11012     return false;
11013 
11014   // Don't warn for OpenCL kernels.
11015   if (FD->hasAttr<OpenCLKernelAttr>())
11016     return false;
11017 
11018   // Don't warn on explicitly deleted functions.
11019   if (FD->isDeleted())
11020     return false;
11021 
11022   bool MissingPrototype = true;
11023   for (const FunctionDecl *Prev = FD->getPreviousDecl();
11024        Prev; Prev = Prev->getPreviousDecl()) {
11025     // Ignore any declarations that occur in function or method
11026     // scope, because they aren't visible from the header.
11027     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11028       continue;
11029 
11030     MissingPrototype = !Prev->getType()->isFunctionProtoType();
11031     if (FD->getNumParams() == 0)
11032       PossibleZeroParamPrototype = Prev;
11033     break;
11034   }
11035 
11036   return MissingPrototype;
11037 }
11038 
11039 void
11040 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11041                                    const FunctionDecl *EffectiveDefinition,
11042                                    SkipBodyInfo *SkipBody) {
11043   // Don't complain if we're in GNU89 mode and the previous definition
11044   // was an extern inline function.
11045   const FunctionDecl *Definition = EffectiveDefinition;
11046   if (!Definition)
11047     if (!FD->isDefined(Definition))
11048       return;
11049 
11050   if (canRedefineFunction(Definition, getLangOpts()))
11051     return;
11052 
11053   // If we don't have a visible definition of the function, and it's inline or
11054   // a template, skip the new definition.
11055   if (SkipBody && !hasVisibleDefinition(Definition) &&
11056       (Definition->getFormalLinkage() == InternalLinkage ||
11057        Definition->isInlined() ||
11058        Definition->getDescribedFunctionTemplate() ||
11059        Definition->getNumTemplateParameterLists())) {
11060     SkipBody->ShouldSkip = true;
11061     if (auto *TD = Definition->getDescribedFunctionTemplate())
11062       makeMergedDefinitionVisible(TD, FD->getLocation());
11063     else
11064       makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
11065                                   FD->getLocation());
11066     return;
11067   }
11068 
11069   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11070       Definition->getStorageClass() == SC_Extern)
11071     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11072         << FD->getDeclName() << getLangOpts().CPlusPlus;
11073   else
11074     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11075 
11076   Diag(Definition->getLocation(), diag::note_previous_definition);
11077   FD->setInvalidDecl();
11078 }
11079 
11080 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11081                                    Sema &S) {
11082   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11083 
11084   LambdaScopeInfo *LSI = S.PushLambdaScope();
11085   LSI->CallOperator = CallOperator;
11086   LSI->Lambda = LambdaClass;
11087   LSI->ReturnType = CallOperator->getReturnType();
11088   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11089 
11090   if (LCD == LCD_None)
11091     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
11092   else if (LCD == LCD_ByCopy)
11093     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
11094   else if (LCD == LCD_ByRef)
11095     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
11096   DeclarationNameInfo DNI = CallOperator->getNameInfo();
11097 
11098   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
11099   LSI->Mutable = !CallOperator->isConst();
11100 
11101   // Add the captures to the LSI so they can be noted as already
11102   // captured within tryCaptureVar.
11103   auto I = LambdaClass->field_begin();
11104   for (const auto &C : LambdaClass->captures()) {
11105     if (C.capturesVariable()) {
11106       VarDecl *VD = C.getCapturedVar();
11107       if (VD->isInitCapture())
11108         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11109       QualType CaptureType = VD->getType();
11110       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11111       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11112           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11113           /*EllipsisLoc*/C.isPackExpansion()
11114                          ? C.getEllipsisLoc() : SourceLocation(),
11115           CaptureType, /*Expr*/ nullptr);
11116 
11117     } else if (C.capturesThis()) {
11118       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11119                               S.getCurrentThisType(), /*Expr*/ nullptr,
11120                               C.getCaptureKind() == LCK_StarThis);
11121     } else {
11122       LSI->addVLATypeCapture(C.getLocation(), I->getType());
11123     }
11124     ++I;
11125   }
11126 }
11127 
11128 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
11129                                     SkipBodyInfo *SkipBody) {
11130   // Clear the last template instantiation error context.
11131   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
11132 
11133   if (!D)
11134     return D;
11135   FunctionDecl *FD = nullptr;
11136 
11137   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
11138     FD = FunTmpl->getTemplatedDecl();
11139   else
11140     FD = cast<FunctionDecl>(D);
11141 
11142   // See if this is a redefinition.
11143   if (!FD->isLateTemplateParsed()) {
11144     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
11145 
11146     // If we're skipping the body, we're done. Don't enter the scope.
11147     if (SkipBody && SkipBody->ShouldSkip)
11148       return D;
11149   }
11150 
11151   // If we are instantiating a generic lambda call operator, push
11152   // a LambdaScopeInfo onto the function stack.  But use the information
11153   // that's already been calculated (ActOnLambdaExpr) to prime the current
11154   // LambdaScopeInfo.
11155   // When the template operator is being specialized, the LambdaScopeInfo,
11156   // has to be properly restored so that tryCaptureVariable doesn't try
11157   // and capture any new variables. In addition when calculating potential
11158   // captures during transformation of nested lambdas, it is necessary to
11159   // have the LSI properly restored.
11160   if (isGenericLambdaCallOperatorSpecialization(FD)) {
11161     assert(ActiveTemplateInstantiations.size() &&
11162       "There should be an active template instantiation on the stack "
11163       "when instantiating a generic lambda!");
11164     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
11165   }
11166   else
11167     // Enter a new function scope
11168     PushFunctionScope();
11169 
11170   // Builtin functions cannot be defined.
11171   if (unsigned BuiltinID = FD->getBuiltinID()) {
11172     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
11173         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
11174       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
11175       FD->setInvalidDecl();
11176     }
11177   }
11178 
11179   // The return type of a function definition must be complete
11180   // (C99 6.9.1p3, C++ [dcl.fct]p6).
11181   QualType ResultType = FD->getReturnType();
11182   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
11183       !FD->isInvalidDecl() &&
11184       RequireCompleteType(FD->getLocation(), ResultType,
11185                           diag::err_func_def_incomplete_result))
11186     FD->setInvalidDecl();
11187 
11188   if (FnBodyScope)
11189     PushDeclContext(FnBodyScope, FD);
11190 
11191   // Check the validity of our function parameters
11192   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
11193                            /*CheckParameterNames=*/true);
11194 
11195   // Introduce our parameters into the function scope
11196   for (auto Param : FD->params()) {
11197     Param->setOwningFunction(FD);
11198 
11199     // If this has an identifier, add it to the scope stack.
11200     if (Param->getIdentifier() && FnBodyScope) {
11201       CheckShadow(FnBodyScope, Param);
11202 
11203       PushOnScopeChains(Param, FnBodyScope);
11204     }
11205   }
11206 
11207   // If we had any tags defined in the function prototype,
11208   // introduce them into the function scope.
11209   if (FnBodyScope) {
11210     for (ArrayRef<NamedDecl *>::iterator
11211              I = FD->getDeclsInPrototypeScope().begin(),
11212              E = FD->getDeclsInPrototypeScope().end();
11213          I != E; ++I) {
11214       NamedDecl *D = *I;
11215 
11216       // Some of these decls (like enums) may have been pinned to the
11217       // translation unit for lack of a real context earlier. If so, remove
11218       // from the translation unit and reattach to the current context.
11219       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
11220         // Is the decl actually in the context?
11221         if (Context.getTranslationUnitDecl()->containsDecl(D))
11222           Context.getTranslationUnitDecl()->removeDecl(D);
11223         // Either way, reassign the lexical decl context to our FunctionDecl.
11224         D->setLexicalDeclContext(CurContext);
11225       }
11226 
11227       // If the decl has a non-null name, make accessible in the current scope.
11228       if (!D->getName().empty())
11229         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
11230 
11231       // Similarly, dive into enums and fish their constants out, making them
11232       // accessible in this scope.
11233       if (auto *ED = dyn_cast<EnumDecl>(D)) {
11234         for (auto *EI : ED->enumerators())
11235           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
11236       }
11237     }
11238   }
11239 
11240   // Ensure that the function's exception specification is instantiated.
11241   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
11242     ResolveExceptionSpec(D->getLocation(), FPT);
11243 
11244   // dllimport cannot be applied to non-inline function definitions.
11245   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
11246       !FD->isTemplateInstantiation()) {
11247     assert(!FD->hasAttr<DLLExportAttr>());
11248     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
11249     FD->setInvalidDecl();
11250     return D;
11251   }
11252   // We want to attach documentation to original Decl (which might be
11253   // a function template).
11254   ActOnDocumentableDecl(D);
11255   if (getCurLexicalContext()->isObjCContainer() &&
11256       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
11257       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
11258     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
11259 
11260   return D;
11261 }
11262 
11263 /// \brief Given the set of return statements within a function body,
11264 /// compute the variables that are subject to the named return value
11265 /// optimization.
11266 ///
11267 /// Each of the variables that is subject to the named return value
11268 /// optimization will be marked as NRVO variables in the AST, and any
11269 /// return statement that has a marked NRVO variable as its NRVO candidate can
11270 /// use the named return value optimization.
11271 ///
11272 /// This function applies a very simplistic algorithm for NRVO: if every return
11273 /// statement in the scope of a variable has the same NRVO candidate, that
11274 /// candidate is an NRVO variable.
11275 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
11276   ReturnStmt **Returns = Scope->Returns.data();
11277 
11278   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
11279     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
11280       if (!NRVOCandidate->isNRVOVariable())
11281         Returns[I]->setNRVOCandidate(nullptr);
11282     }
11283   }
11284 }
11285 
11286 bool Sema::canDelayFunctionBody(const Declarator &D) {
11287   // We can't delay parsing the body of a constexpr function template (yet).
11288   if (D.getDeclSpec().isConstexprSpecified())
11289     return false;
11290 
11291   // We can't delay parsing the body of a function template with a deduced
11292   // return type (yet).
11293   if (D.getDeclSpec().containsPlaceholderType()) {
11294     // If the placeholder introduces a non-deduced trailing return type,
11295     // we can still delay parsing it.
11296     if (D.getNumTypeObjects()) {
11297       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11298       if (Outer.Kind == DeclaratorChunk::Function &&
11299           Outer.Fun.hasTrailingReturnType()) {
11300         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11301         return Ty.isNull() || !Ty->isUndeducedType();
11302       }
11303     }
11304     return false;
11305   }
11306 
11307   return true;
11308 }
11309 
11310 bool Sema::canSkipFunctionBody(Decl *D) {
11311   // We cannot skip the body of a function (or function template) which is
11312   // constexpr, since we may need to evaluate its body in order to parse the
11313   // rest of the file.
11314   // We cannot skip the body of a function with an undeduced return type,
11315   // because any callers of that function need to know the type.
11316   if (const FunctionDecl *FD = D->getAsFunction())
11317     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11318       return false;
11319   return Consumer.shouldSkipFunctionBody(D);
11320 }
11321 
11322 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11323   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11324     FD->setHasSkippedBody();
11325   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11326     MD->setHasSkippedBody();
11327   return ActOnFinishFunctionBody(Decl, nullptr);
11328 }
11329 
11330 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11331   return ActOnFinishFunctionBody(D, BodyArg, false);
11332 }
11333 
11334 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
11335                                     bool IsInstantiation) {
11336   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
11337 
11338   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11339   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
11340 
11341   if (getLangOpts().Coroutines && !getCurFunction()->CoroutineStmts.empty())
11342     CheckCompletedCoroutineBody(FD, Body);
11343 
11344   if (FD) {
11345     FD->setBody(Body);
11346 
11347     if (getLangOpts().CPlusPlus14) {
11348       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
11349           FD->getReturnType()->isUndeducedType()) {
11350         // If the function has a deduced result type but contains no 'return'
11351         // statements, the result type as written must be exactly 'auto', and
11352         // the deduced result type is 'void'.
11353         if (!FD->getReturnType()->getAs<AutoType>()) {
11354           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
11355               << FD->getReturnType();
11356           FD->setInvalidDecl();
11357         } else {
11358           // Substitute 'void' for the 'auto' in the type.
11359           TypeLoc ResultType = getReturnTypeLoc(FD);
11360           Context.adjustDeducedFunctionResultType(
11361               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
11362         }
11363       }
11364     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
11365       // In C++11, we don't use 'auto' deduction rules for lambda call
11366       // operators because we don't support return type deduction.
11367       auto *LSI = getCurLambda();
11368       if (LSI->HasImplicitReturnType) {
11369         deduceClosureReturnType(*LSI);
11370 
11371         // C++11 [expr.prim.lambda]p4:
11372         //   [...] if there are no return statements in the compound-statement
11373         //   [the deduced type is] the type void
11374         QualType RetType =
11375             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
11376 
11377         // Update the return type to the deduced type.
11378         const FunctionProtoType *Proto =
11379             FD->getType()->getAs<FunctionProtoType>();
11380         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
11381                                             Proto->getExtProtoInfo()));
11382       }
11383     }
11384 
11385     // The only way to be included in UndefinedButUsed is if there is an
11386     // ODR use before the definition. Avoid the expensive map lookup if this
11387     // is the first declaration.
11388     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
11389       if (!FD->isExternallyVisible())
11390         UndefinedButUsed.erase(FD);
11391       else if (FD->isInlined() &&
11392                !LangOpts.GNUInline &&
11393                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
11394         UndefinedButUsed.erase(FD);
11395     }
11396 
11397     // If the function implicitly returns zero (like 'main') or is naked,
11398     // don't complain about missing return statements.
11399     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
11400       WP.disableCheckFallThrough();
11401 
11402     // MSVC permits the use of pure specifier (=0) on function definition,
11403     // defined at class scope, warn about this non-standard construct.
11404     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
11405       Diag(FD->getLocation(), diag::ext_pure_function_definition);
11406 
11407     if (!FD->isInvalidDecl()) {
11408       // Don't diagnose unused parameters of defaulted or deleted functions.
11409       if (!FD->isDeleted() && !FD->isDefaulted())
11410         DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
11411       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
11412                                              FD->getReturnType(), FD);
11413 
11414       // If this is a structor, we need a vtable.
11415       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
11416         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
11417       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
11418         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
11419 
11420       // Try to apply the named return value optimization. We have to check
11421       // if we can do this here because lambdas keep return statements around
11422       // to deduce an implicit return type.
11423       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
11424           !FD->isDependentContext())
11425         computeNRVO(Body, getCurFunction());
11426     }
11427 
11428     // GNU warning -Wmissing-prototypes:
11429     //   Warn if a global function is defined without a previous
11430     //   prototype declaration. This warning is issued even if the
11431     //   definition itself provides a prototype. The aim is to detect
11432     //   global functions that fail to be declared in header files.
11433     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
11434     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
11435       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
11436 
11437       if (PossibleZeroParamPrototype) {
11438         // We found a declaration that is not a prototype,
11439         // but that could be a zero-parameter prototype
11440         if (TypeSourceInfo *TI =
11441                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
11442           TypeLoc TL = TI->getTypeLoc();
11443           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
11444             Diag(PossibleZeroParamPrototype->getLocation(),
11445                  diag::note_declaration_not_a_prototype)
11446                 << PossibleZeroParamPrototype
11447                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
11448         }
11449       }
11450     }
11451 
11452     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11453       const CXXMethodDecl *KeyFunction;
11454       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
11455           MD->isVirtual() &&
11456           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
11457           MD == KeyFunction->getCanonicalDecl()) {
11458         // Update the key-function state if necessary for this ABI.
11459         if (FD->isInlined() &&
11460             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11461           Context.setNonKeyFunction(MD);
11462 
11463           // If the newly-chosen key function is already defined, then we
11464           // need to mark the vtable as used retroactively.
11465           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
11466           const FunctionDecl *Definition;
11467           if (KeyFunction && KeyFunction->isDefined(Definition))
11468             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
11469         } else {
11470           // We just defined they key function; mark the vtable as used.
11471           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
11472         }
11473       }
11474     }
11475 
11476     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
11477            "Function parsing confused");
11478   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
11479     assert(MD == getCurMethodDecl() && "Method parsing confused");
11480     MD->setBody(Body);
11481     if (!MD->isInvalidDecl()) {
11482       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
11483       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
11484                                              MD->getReturnType(), MD);
11485 
11486       if (Body)
11487         computeNRVO(Body, getCurFunction());
11488     }
11489     if (getCurFunction()->ObjCShouldCallSuper) {
11490       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
11491         << MD->getSelector().getAsString();
11492       getCurFunction()->ObjCShouldCallSuper = false;
11493     }
11494     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
11495       const ObjCMethodDecl *InitMethod = nullptr;
11496       bool isDesignated =
11497           MD->isDesignatedInitializerForTheInterface(&InitMethod);
11498       assert(isDesignated && InitMethod);
11499       (void)isDesignated;
11500 
11501       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
11502         auto IFace = MD->getClassInterface();
11503         if (!IFace)
11504           return false;
11505         auto SuperD = IFace->getSuperClass();
11506         if (!SuperD)
11507           return false;
11508         return SuperD->getIdentifier() ==
11509             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
11510       };
11511       // Don't issue this warning for unavailable inits or direct subclasses
11512       // of NSObject.
11513       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
11514         Diag(MD->getLocation(),
11515              diag::warn_objc_designated_init_missing_super_call);
11516         Diag(InitMethod->getLocation(),
11517              diag::note_objc_designated_init_marked_here);
11518       }
11519       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
11520     }
11521     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
11522       // Don't issue this warning for unavaialable inits.
11523       if (!MD->isUnavailable())
11524         Diag(MD->getLocation(),
11525              diag::warn_objc_secondary_init_missing_init_call);
11526       getCurFunction()->ObjCWarnForNoInitDelegation = false;
11527     }
11528   } else {
11529     return nullptr;
11530   }
11531 
11532   assert(!getCurFunction()->ObjCShouldCallSuper &&
11533          "This should only be set for ObjC methods, which should have been "
11534          "handled in the block above.");
11535 
11536   // Verify and clean out per-function state.
11537   if (Body && (!FD || !FD->isDefaulted())) {
11538     // C++ constructors that have function-try-blocks can't have return
11539     // statements in the handlers of that block. (C++ [except.handle]p14)
11540     // Verify this.
11541     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
11542       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
11543 
11544     // Verify that gotos and switch cases don't jump into scopes illegally.
11545     if (getCurFunction()->NeedsScopeChecking() &&
11546         !PP.isCodeCompletionEnabled())
11547       DiagnoseInvalidJumps(Body);
11548 
11549     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
11550       if (!Destructor->getParent()->isDependentType())
11551         CheckDestructor(Destructor);
11552 
11553       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11554                                              Destructor->getParent());
11555     }
11556 
11557     // If any errors have occurred, clear out any temporaries that may have
11558     // been leftover. This ensures that these temporaries won't be picked up for
11559     // deletion in some later function.
11560     if (getDiagnostics().hasErrorOccurred() ||
11561         getDiagnostics().getSuppressAllDiagnostics()) {
11562       DiscardCleanupsInEvaluationContext();
11563     }
11564     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
11565         !isa<FunctionTemplateDecl>(dcl)) {
11566       // Since the body is valid, issue any analysis-based warnings that are
11567       // enabled.
11568       ActivePolicy = &WP;
11569     }
11570 
11571     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
11572         (!CheckConstexprFunctionDecl(FD) ||
11573          !CheckConstexprFunctionBody(FD, Body)))
11574       FD->setInvalidDecl();
11575 
11576     if (FD && FD->hasAttr<NakedAttr>()) {
11577       for (const Stmt *S : Body->children()) {
11578         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
11579           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
11580           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
11581           FD->setInvalidDecl();
11582           break;
11583         }
11584       }
11585     }
11586 
11587     assert(ExprCleanupObjects.size() ==
11588                ExprEvalContexts.back().NumCleanupObjects &&
11589            "Leftover temporaries in function");
11590     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
11591     assert(MaybeODRUseExprs.empty() &&
11592            "Leftover expressions for odr-use checking");
11593   }
11594 
11595   if (!IsInstantiation)
11596     PopDeclContext();
11597 
11598   PopFunctionScopeInfo(ActivePolicy, dcl);
11599   // If any errors have occurred, clear out any temporaries that may have
11600   // been leftover. This ensures that these temporaries won't be picked up for
11601   // deletion in some later function.
11602   if (getDiagnostics().hasErrorOccurred()) {
11603     DiscardCleanupsInEvaluationContext();
11604   }
11605 
11606   return dcl;
11607 }
11608 
11609 /// When we finish delayed parsing of an attribute, we must attach it to the
11610 /// relevant Decl.
11611 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
11612                                        ParsedAttributes &Attrs) {
11613   // Always attach attributes to the underlying decl.
11614   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
11615     D = TD->getTemplatedDecl();
11616   ProcessDeclAttributeList(S, D, Attrs.getList());
11617 
11618   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
11619     if (Method->isStatic())
11620       checkThisInStaticMemberFunctionAttributes(Method);
11621 }
11622 
11623 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
11624 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
11625 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
11626                                           IdentifierInfo &II, Scope *S) {
11627   // Before we produce a declaration for an implicitly defined
11628   // function, see whether there was a locally-scoped declaration of
11629   // this name as a function or variable. If so, use that
11630   // (non-visible) declaration, and complain about it.
11631   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
11632     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
11633     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
11634     return ExternCPrev;
11635   }
11636 
11637   // Extension in C99.  Legal in C90, but warn about it.
11638   unsigned diag_id;
11639   if (II.getName().startswith("__builtin_"))
11640     diag_id = diag::warn_builtin_unknown;
11641   else if (getLangOpts().C99)
11642     diag_id = diag::ext_implicit_function_decl;
11643   else
11644     diag_id = diag::warn_implicit_function_decl;
11645   Diag(Loc, diag_id) << &II;
11646 
11647   // Because typo correction is expensive, only do it if the implicit
11648   // function declaration is going to be treated as an error.
11649   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
11650     TypoCorrection Corrected;
11651     if (S &&
11652         (Corrected = CorrectTypo(
11653              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
11654              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
11655       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
11656                    /*ErrorRecovery*/false);
11657   }
11658 
11659   // Set a Declarator for the implicit definition: int foo();
11660   const char *Dummy;
11661   AttributeFactory attrFactory;
11662   DeclSpec DS(attrFactory);
11663   unsigned DiagID;
11664   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
11665                                   Context.getPrintingPolicy());
11666   (void)Error; // Silence warning.
11667   assert(!Error && "Error setting up implicit decl!");
11668   SourceLocation NoLoc;
11669   Declarator D(DS, Declarator::BlockContext);
11670   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
11671                                              /*IsAmbiguous=*/false,
11672                                              /*LParenLoc=*/NoLoc,
11673                                              /*Params=*/nullptr,
11674                                              /*NumParams=*/0,
11675                                              /*EllipsisLoc=*/NoLoc,
11676                                              /*RParenLoc=*/NoLoc,
11677                                              /*TypeQuals=*/0,
11678                                              /*RefQualifierIsLvalueRef=*/true,
11679                                              /*RefQualifierLoc=*/NoLoc,
11680                                              /*ConstQualifierLoc=*/NoLoc,
11681                                              /*VolatileQualifierLoc=*/NoLoc,
11682                                              /*RestrictQualifierLoc=*/NoLoc,
11683                                              /*MutableLoc=*/NoLoc,
11684                                              EST_None,
11685                                              /*ESpecRange=*/SourceRange(),
11686                                              /*Exceptions=*/nullptr,
11687                                              /*ExceptionRanges=*/nullptr,
11688                                              /*NumExceptions=*/0,
11689                                              /*NoexceptExpr=*/nullptr,
11690                                              /*ExceptionSpecTokens=*/nullptr,
11691                                              Loc, Loc, D),
11692                 DS.getAttributes(),
11693                 SourceLocation());
11694   D.SetIdentifier(&II, Loc);
11695 
11696   // Insert this function into translation-unit scope.
11697 
11698   DeclContext *PrevDC = CurContext;
11699   CurContext = Context.getTranslationUnitDecl();
11700 
11701   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
11702   FD->setImplicit();
11703 
11704   CurContext = PrevDC;
11705 
11706   AddKnownFunctionAttributes(FD);
11707 
11708   return FD;
11709 }
11710 
11711 /// \brief Adds any function attributes that we know a priori based on
11712 /// the declaration of this function.
11713 ///
11714 /// These attributes can apply both to implicitly-declared builtins
11715 /// (like __builtin___printf_chk) or to library-declared functions
11716 /// like NSLog or printf.
11717 ///
11718 /// We need to check for duplicate attributes both here and where user-written
11719 /// attributes are applied to declarations.
11720 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
11721   if (FD->isInvalidDecl())
11722     return;
11723 
11724   // If this is a built-in function, map its builtin attributes to
11725   // actual attributes.
11726   if (unsigned BuiltinID = FD->getBuiltinID()) {
11727     // Handle printf-formatting attributes.
11728     unsigned FormatIdx;
11729     bool HasVAListArg;
11730     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
11731       if (!FD->hasAttr<FormatAttr>()) {
11732         const char *fmt = "printf";
11733         unsigned int NumParams = FD->getNumParams();
11734         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
11735             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
11736           fmt = "NSString";
11737         FD->addAttr(FormatAttr::CreateImplicit(Context,
11738                                                &Context.Idents.get(fmt),
11739                                                FormatIdx+1,
11740                                                HasVAListArg ? 0 : FormatIdx+2,
11741                                                FD->getLocation()));
11742       }
11743     }
11744     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
11745                                              HasVAListArg)) {
11746      if (!FD->hasAttr<FormatAttr>())
11747        FD->addAttr(FormatAttr::CreateImplicit(Context,
11748                                               &Context.Idents.get("scanf"),
11749                                               FormatIdx+1,
11750                                               HasVAListArg ? 0 : FormatIdx+2,
11751                                               FD->getLocation()));
11752     }
11753 
11754     // Mark const if we don't care about errno and that is the only
11755     // thing preventing the function from being const. This allows
11756     // IRgen to use LLVM intrinsics for such functions.
11757     if (!getLangOpts().MathErrno &&
11758         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
11759       if (!FD->hasAttr<ConstAttr>())
11760         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11761     }
11762 
11763     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
11764         !FD->hasAttr<ReturnsTwiceAttr>())
11765       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
11766                                          FD->getLocation()));
11767     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
11768       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11769     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
11770       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
11771     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
11772       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11773     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
11774         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
11775       // Add the appropriate attribute, depending on the CUDA compilation mode
11776       // and which target the builtin belongs to. For example, during host
11777       // compilation, aux builtins are __device__, while the rest are __host__.
11778       if (getLangOpts().CUDAIsDevice !=
11779           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
11780         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
11781       else
11782         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
11783     }
11784   }
11785 
11786   // If C++ exceptions are enabled but we are told extern "C" functions cannot
11787   // throw, add an implicit nothrow attribute to any extern "C" function we come
11788   // across.
11789   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
11790       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
11791     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
11792     if (!FPT || FPT->getExceptionSpecType() == EST_None)
11793       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11794   }
11795 
11796   IdentifierInfo *Name = FD->getIdentifier();
11797   if (!Name)
11798     return;
11799   if ((!getLangOpts().CPlusPlus &&
11800        FD->getDeclContext()->isTranslationUnit()) ||
11801       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
11802        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
11803        LinkageSpecDecl::lang_c)) {
11804     // Okay: this could be a libc/libm/Objective-C function we know
11805     // about.
11806   } else
11807     return;
11808 
11809   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
11810     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
11811     // target-specific builtins, perhaps?
11812     if (!FD->hasAttr<FormatAttr>())
11813       FD->addAttr(FormatAttr::CreateImplicit(Context,
11814                                              &Context.Idents.get("printf"), 2,
11815                                              Name->isStr("vasprintf") ? 0 : 3,
11816                                              FD->getLocation()));
11817   }
11818 
11819   if (Name->isStr("__CFStringMakeConstantString")) {
11820     // We already have a __builtin___CFStringMakeConstantString,
11821     // but builds that use -fno-constant-cfstrings don't go through that.
11822     if (!FD->hasAttr<FormatArgAttr>())
11823       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
11824                                                 FD->getLocation()));
11825   }
11826 }
11827 
11828 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
11829                                     TypeSourceInfo *TInfo) {
11830   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
11831   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
11832 
11833   if (!TInfo) {
11834     assert(D.isInvalidType() && "no declarator info for valid type");
11835     TInfo = Context.getTrivialTypeSourceInfo(T);
11836   }
11837 
11838   // Scope manipulation handled by caller.
11839   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
11840                                            D.getLocStart(),
11841                                            D.getIdentifierLoc(),
11842                                            D.getIdentifier(),
11843                                            TInfo);
11844 
11845   // Bail out immediately if we have an invalid declaration.
11846   if (D.isInvalidType()) {
11847     NewTD->setInvalidDecl();
11848     return NewTD;
11849   }
11850 
11851   if (D.getDeclSpec().isModulePrivateSpecified()) {
11852     if (CurContext->isFunctionOrMethod())
11853       Diag(NewTD->getLocation(), diag::err_module_private_local)
11854         << 2 << NewTD->getDeclName()
11855         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11856         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11857     else
11858       NewTD->setModulePrivate();
11859   }
11860 
11861   // C++ [dcl.typedef]p8:
11862   //   If the typedef declaration defines an unnamed class (or
11863   //   enum), the first typedef-name declared by the declaration
11864   //   to be that class type (or enum type) is used to denote the
11865   //   class type (or enum type) for linkage purposes only.
11866   // We need to check whether the type was declared in the declaration.
11867   switch (D.getDeclSpec().getTypeSpecType()) {
11868   case TST_enum:
11869   case TST_struct:
11870   case TST_interface:
11871   case TST_union:
11872   case TST_class: {
11873     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
11874     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
11875     break;
11876   }
11877 
11878   default:
11879     break;
11880   }
11881 
11882   return NewTD;
11883 }
11884 
11885 /// \brief Check that this is a valid underlying type for an enum declaration.
11886 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
11887   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
11888   QualType T = TI->getType();
11889 
11890   if (T->isDependentType())
11891     return false;
11892 
11893   if (const BuiltinType *BT = T->getAs<BuiltinType>())
11894     if (BT->isInteger())
11895       return false;
11896 
11897   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
11898   return true;
11899 }
11900 
11901 /// Check whether this is a valid redeclaration of a previous enumeration.
11902 /// \return true if the redeclaration was invalid.
11903 bool Sema::CheckEnumRedeclaration(
11904     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
11905     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
11906   bool IsFixed = !EnumUnderlyingTy.isNull();
11907 
11908   if (IsScoped != Prev->isScoped()) {
11909     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
11910       << Prev->isScoped();
11911     Diag(Prev->getLocation(), diag::note_previous_declaration);
11912     return true;
11913   }
11914 
11915   if (IsFixed && Prev->isFixed()) {
11916     if (!EnumUnderlyingTy->isDependentType() &&
11917         !Prev->getIntegerType()->isDependentType() &&
11918         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
11919                                         Prev->getIntegerType())) {
11920       // TODO: Highlight the underlying type of the redeclaration.
11921       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
11922         << EnumUnderlyingTy << Prev->getIntegerType();
11923       Diag(Prev->getLocation(), diag::note_previous_declaration)
11924           << Prev->getIntegerTypeRange();
11925       return true;
11926     }
11927   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
11928     ;
11929   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
11930     ;
11931   } else if (IsFixed != Prev->isFixed()) {
11932     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
11933       << Prev->isFixed();
11934     Diag(Prev->getLocation(), diag::note_previous_declaration);
11935     return true;
11936   }
11937 
11938   return false;
11939 }
11940 
11941 /// \brief Get diagnostic %select index for tag kind for
11942 /// redeclaration diagnostic message.
11943 /// WARNING: Indexes apply to particular diagnostics only!
11944 ///
11945 /// \returns diagnostic %select index.
11946 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
11947   switch (Tag) {
11948   case TTK_Struct: return 0;
11949   case TTK_Interface: return 1;
11950   case TTK_Class:  return 2;
11951   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
11952   }
11953 }
11954 
11955 /// \brief Determine if tag kind is a class-key compatible with
11956 /// class for redeclaration (class, struct, or __interface).
11957 ///
11958 /// \returns true iff the tag kind is compatible.
11959 static bool isClassCompatTagKind(TagTypeKind Tag)
11960 {
11961   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
11962 }
11963 
11964 /// \brief Determine whether a tag with a given kind is acceptable
11965 /// as a redeclaration of the given tag declaration.
11966 ///
11967 /// \returns true if the new tag kind is acceptable, false otherwise.
11968 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
11969                                         TagTypeKind NewTag, bool isDefinition,
11970                                         SourceLocation NewTagLoc,
11971                                         const IdentifierInfo *Name) {
11972   // C++ [dcl.type.elab]p3:
11973   //   The class-key or enum keyword present in the
11974   //   elaborated-type-specifier shall agree in kind with the
11975   //   declaration to which the name in the elaborated-type-specifier
11976   //   refers. This rule also applies to the form of
11977   //   elaborated-type-specifier that declares a class-name or
11978   //   friend class since it can be construed as referring to the
11979   //   definition of the class. Thus, in any
11980   //   elaborated-type-specifier, the enum keyword shall be used to
11981   //   refer to an enumeration (7.2), the union class-key shall be
11982   //   used to refer to a union (clause 9), and either the class or
11983   //   struct class-key shall be used to refer to a class (clause 9)
11984   //   declared using the class or struct class-key.
11985   TagTypeKind OldTag = Previous->getTagKind();
11986   if (!isDefinition || !isClassCompatTagKind(NewTag))
11987     if (OldTag == NewTag)
11988       return true;
11989 
11990   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
11991     // Warn about the struct/class tag mismatch.
11992     bool isTemplate = false;
11993     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
11994       isTemplate = Record->getDescribedClassTemplate();
11995 
11996     if (!ActiveTemplateInstantiations.empty()) {
11997       // In a template instantiation, do not offer fix-its for tag mismatches
11998       // since they usually mess up the template instead of fixing the problem.
11999       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12000         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12001         << getRedeclDiagFromTagKind(OldTag);
12002       return true;
12003     }
12004 
12005     if (isDefinition) {
12006       // On definitions, check previous tags and issue a fix-it for each
12007       // one that doesn't match the current tag.
12008       if (Previous->getDefinition()) {
12009         // Don't suggest fix-its for redefinitions.
12010         return true;
12011       }
12012 
12013       bool previousMismatch = false;
12014       for (auto I : Previous->redecls()) {
12015         if (I->getTagKind() != NewTag) {
12016           if (!previousMismatch) {
12017             previousMismatch = true;
12018             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
12019               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12020               << getRedeclDiagFromTagKind(I->getTagKind());
12021           }
12022           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
12023             << getRedeclDiagFromTagKind(NewTag)
12024             << FixItHint::CreateReplacement(I->getInnerLocStart(),
12025                  TypeWithKeyword::getTagTypeKindName(NewTag));
12026         }
12027       }
12028       return true;
12029     }
12030 
12031     // Check for a previous definition.  If current tag and definition
12032     // are same type, do nothing.  If no definition, but disagree with
12033     // with previous tag type, give a warning, but no fix-it.
12034     const TagDecl *Redecl = Previous->getDefinition() ?
12035                             Previous->getDefinition() : Previous;
12036     if (Redecl->getTagKind() == NewTag) {
12037       return true;
12038     }
12039 
12040     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12041       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12042       << getRedeclDiagFromTagKind(OldTag);
12043     Diag(Redecl->getLocation(), diag::note_previous_use);
12044 
12045     // If there is a previous definition, suggest a fix-it.
12046     if (Previous->getDefinition()) {
12047         Diag(NewTagLoc, diag::note_struct_class_suggestion)
12048           << getRedeclDiagFromTagKind(Redecl->getTagKind())
12049           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
12050                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
12051     }
12052 
12053     return true;
12054   }
12055   return false;
12056 }
12057 
12058 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
12059 /// from an outer enclosing namespace or file scope inside a friend declaration.
12060 /// This should provide the commented out code in the following snippet:
12061 ///   namespace N {
12062 ///     struct X;
12063 ///     namespace M {
12064 ///       struct Y { friend struct /*N::*/ X; };
12065 ///     }
12066 ///   }
12067 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
12068                                          SourceLocation NameLoc) {
12069   // While the decl is in a namespace, do repeated lookup of that name and see
12070   // if we get the same namespace back.  If we do not, continue until
12071   // translation unit scope, at which point we have a fully qualified NNS.
12072   SmallVector<IdentifierInfo *, 4> Namespaces;
12073   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12074   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
12075     // This tag should be declared in a namespace, which can only be enclosed by
12076     // other namespaces.  Bail if there's an anonymous namespace in the chain.
12077     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
12078     if (!Namespace || Namespace->isAnonymousNamespace())
12079       return FixItHint();
12080     IdentifierInfo *II = Namespace->getIdentifier();
12081     Namespaces.push_back(II);
12082     NamedDecl *Lookup = SemaRef.LookupSingleName(
12083         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
12084     if (Lookup == Namespace)
12085       break;
12086   }
12087 
12088   // Once we have all the namespaces, reverse them to go outermost first, and
12089   // build an NNS.
12090   SmallString<64> Insertion;
12091   llvm::raw_svector_ostream OS(Insertion);
12092   if (DC->isTranslationUnit())
12093     OS << "::";
12094   std::reverse(Namespaces.begin(), Namespaces.end());
12095   for (auto *II : Namespaces)
12096     OS << II->getName() << "::";
12097   return FixItHint::CreateInsertion(NameLoc, Insertion);
12098 }
12099 
12100 /// \brief Determine whether a tag originally declared in context \p OldDC can
12101 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
12102 /// found a declaration in \p OldDC as a previous decl, perhaps through a
12103 /// using-declaration).
12104 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
12105                                          DeclContext *NewDC) {
12106   OldDC = OldDC->getRedeclContext();
12107   NewDC = NewDC->getRedeclContext();
12108 
12109   if (OldDC->Equals(NewDC))
12110     return true;
12111 
12112   // In MSVC mode, we allow a redeclaration if the contexts are related (either
12113   // encloses the other).
12114   if (S.getLangOpts().MSVCCompat &&
12115       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
12116     return true;
12117 
12118   return false;
12119 }
12120 
12121 /// Find the DeclContext in which a tag is implicitly declared if we see an
12122 /// elaborated type specifier in the specified context, and lookup finds
12123 /// nothing.
12124 static DeclContext *getTagInjectionContext(DeclContext *DC) {
12125   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
12126     DC = DC->getParent();
12127   return DC;
12128 }
12129 
12130 /// Find the Scope in which a tag is implicitly declared if we see an
12131 /// elaborated type specifier in the specified context, and lookup finds
12132 /// nothing.
12133 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
12134   while (S->isClassScope() ||
12135          (LangOpts.CPlusPlus &&
12136           S->isFunctionPrototypeScope()) ||
12137          ((S->getFlags() & Scope::DeclScope) == 0) ||
12138          (S->getEntity() && S->getEntity()->isTransparentContext()))
12139     S = S->getParent();
12140   return S;
12141 }
12142 
12143 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
12144 /// former case, Name will be non-null.  In the later case, Name will be null.
12145 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
12146 /// reference/declaration/definition of a tag.
12147 ///
12148 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
12149 /// trailing-type-specifier) other than one in an alias-declaration.
12150 ///
12151 /// \param SkipBody If non-null, will be set to indicate if the caller should
12152 /// skip the definition of this tag and treat it as if it were a declaration.
12153 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12154                      SourceLocation KWLoc, CXXScopeSpec &SS,
12155                      IdentifierInfo *Name, SourceLocation NameLoc,
12156                      AttributeList *Attr, AccessSpecifier AS,
12157                      SourceLocation ModulePrivateLoc,
12158                      MultiTemplateParamsArg TemplateParameterLists,
12159                      bool &OwnedDecl, bool &IsDependent,
12160                      SourceLocation ScopedEnumKWLoc,
12161                      bool ScopedEnumUsesClassTag,
12162                      TypeResult UnderlyingType,
12163                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
12164   // If this is not a definition, it must have a name.
12165   IdentifierInfo *OrigName = Name;
12166   assert((Name != nullptr || TUK == TUK_Definition) &&
12167          "Nameless record must be a definition!");
12168   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
12169 
12170   OwnedDecl = false;
12171   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12172   bool ScopedEnum = ScopedEnumKWLoc.isValid();
12173 
12174   // FIXME: Check explicit specializations more carefully.
12175   bool isExplicitSpecialization = false;
12176   bool Invalid = false;
12177 
12178   // We only need to do this matching if we have template parameters
12179   // or a scope specifier, which also conveniently avoids this work
12180   // for non-C++ cases.
12181   if (TemplateParameterLists.size() > 0 ||
12182       (SS.isNotEmpty() && TUK != TUK_Reference)) {
12183     if (TemplateParameterList *TemplateParams =
12184             MatchTemplateParametersToScopeSpecifier(
12185                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
12186                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
12187       if (Kind == TTK_Enum) {
12188         Diag(KWLoc, diag::err_enum_template);
12189         return nullptr;
12190       }
12191 
12192       if (TemplateParams->size() > 0) {
12193         // This is a declaration or definition of a class template (which may
12194         // be a member of another template).
12195 
12196         if (Invalid)
12197           return nullptr;
12198 
12199         OwnedDecl = false;
12200         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
12201                                                SS, Name, NameLoc, Attr,
12202                                                TemplateParams, AS,
12203                                                ModulePrivateLoc,
12204                                                /*FriendLoc*/SourceLocation(),
12205                                                TemplateParameterLists.size()-1,
12206                                                TemplateParameterLists.data(),
12207                                                SkipBody);
12208         return Result.get();
12209       } else {
12210         // The "template<>" header is extraneous.
12211         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12212           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12213         isExplicitSpecialization = true;
12214       }
12215     }
12216   }
12217 
12218   // Figure out the underlying type if this a enum declaration. We need to do
12219   // this early, because it's needed to detect if this is an incompatible
12220   // redeclaration.
12221   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
12222   bool EnumUnderlyingIsImplicit = false;
12223 
12224   if (Kind == TTK_Enum) {
12225     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
12226       // No underlying type explicitly specified, or we failed to parse the
12227       // type, default to int.
12228       EnumUnderlying = Context.IntTy.getTypePtr();
12229     else if (UnderlyingType.get()) {
12230       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
12231       // integral type; any cv-qualification is ignored.
12232       TypeSourceInfo *TI = nullptr;
12233       GetTypeFromParser(UnderlyingType.get(), &TI);
12234       EnumUnderlying = TI;
12235 
12236       if (CheckEnumUnderlyingType(TI))
12237         // Recover by falling back to int.
12238         EnumUnderlying = Context.IntTy.getTypePtr();
12239 
12240       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
12241                                           UPPC_FixedUnderlyingType))
12242         EnumUnderlying = Context.IntTy.getTypePtr();
12243 
12244     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12245       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
12246         // Microsoft enums are always of int type.
12247         EnumUnderlying = Context.IntTy.getTypePtr();
12248         EnumUnderlyingIsImplicit = true;
12249       }
12250     }
12251   }
12252 
12253   DeclContext *SearchDC = CurContext;
12254   DeclContext *DC = CurContext;
12255   bool isStdBadAlloc = false;
12256 
12257   RedeclarationKind Redecl = ForRedeclaration;
12258   if (TUK == TUK_Friend || TUK == TUK_Reference)
12259     Redecl = NotForRedeclaration;
12260 
12261   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
12262   if (Name && SS.isNotEmpty()) {
12263     // We have a nested-name tag ('struct foo::bar').
12264 
12265     // Check for invalid 'foo::'.
12266     if (SS.isInvalid()) {
12267       Name = nullptr;
12268       goto CreateNewDecl;
12269     }
12270 
12271     // If this is a friend or a reference to a class in a dependent
12272     // context, don't try to make a decl for it.
12273     if (TUK == TUK_Friend || TUK == TUK_Reference) {
12274       DC = computeDeclContext(SS, false);
12275       if (!DC) {
12276         IsDependent = true;
12277         return nullptr;
12278       }
12279     } else {
12280       DC = computeDeclContext(SS, true);
12281       if (!DC) {
12282         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
12283           << SS.getRange();
12284         return nullptr;
12285       }
12286     }
12287 
12288     if (RequireCompleteDeclContext(SS, DC))
12289       return nullptr;
12290 
12291     SearchDC = DC;
12292     // Look-up name inside 'foo::'.
12293     LookupQualifiedName(Previous, DC);
12294 
12295     if (Previous.isAmbiguous())
12296       return nullptr;
12297 
12298     if (Previous.empty()) {
12299       // Name lookup did not find anything. However, if the
12300       // nested-name-specifier refers to the current instantiation,
12301       // and that current instantiation has any dependent base
12302       // classes, we might find something at instantiation time: treat
12303       // this as a dependent elaborated-type-specifier.
12304       // But this only makes any sense for reference-like lookups.
12305       if (Previous.wasNotFoundInCurrentInstantiation() &&
12306           (TUK == TUK_Reference || TUK == TUK_Friend)) {
12307         IsDependent = true;
12308         return nullptr;
12309       }
12310 
12311       // A tag 'foo::bar' must already exist.
12312       Diag(NameLoc, diag::err_not_tag_in_scope)
12313         << Kind << Name << DC << SS.getRange();
12314       Name = nullptr;
12315       Invalid = true;
12316       goto CreateNewDecl;
12317     }
12318   } else if (Name) {
12319     // C++14 [class.mem]p14:
12320     //   If T is the name of a class, then each of the following shall have a
12321     //   name different from T:
12322     //    -- every member of class T that is itself a type
12323     if (TUK != TUK_Reference && TUK != TUK_Friend &&
12324         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
12325       return nullptr;
12326 
12327     // If this is a named struct, check to see if there was a previous forward
12328     // declaration or definition.
12329     // FIXME: We're looking into outer scopes here, even when we
12330     // shouldn't be. Doing so can result in ambiguities that we
12331     // shouldn't be diagnosing.
12332     LookupName(Previous, S);
12333 
12334     // When declaring or defining a tag, ignore ambiguities introduced
12335     // by types using'ed into this scope.
12336     if (Previous.isAmbiguous() &&
12337         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
12338       LookupResult::Filter F = Previous.makeFilter();
12339       while (F.hasNext()) {
12340         NamedDecl *ND = F.next();
12341         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
12342           F.erase();
12343       }
12344       F.done();
12345     }
12346 
12347     // C++11 [namespace.memdef]p3:
12348     //   If the name in a friend declaration is neither qualified nor
12349     //   a template-id and the declaration is a function or an
12350     //   elaborated-type-specifier, the lookup to determine whether
12351     //   the entity has been previously declared shall not consider
12352     //   any scopes outside the innermost enclosing namespace.
12353     //
12354     // MSVC doesn't implement the above rule for types, so a friend tag
12355     // declaration may be a redeclaration of a type declared in an enclosing
12356     // scope.  They do implement this rule for friend functions.
12357     //
12358     // Does it matter that this should be by scope instead of by
12359     // semantic context?
12360     if (!Previous.empty() && TUK == TUK_Friend) {
12361       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
12362       LookupResult::Filter F = Previous.makeFilter();
12363       bool FriendSawTagOutsideEnclosingNamespace = false;
12364       while (F.hasNext()) {
12365         NamedDecl *ND = F.next();
12366         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12367         if (DC->isFileContext() &&
12368             !EnclosingNS->Encloses(ND->getDeclContext())) {
12369           if (getLangOpts().MSVCCompat)
12370             FriendSawTagOutsideEnclosingNamespace = true;
12371           else
12372             F.erase();
12373         }
12374       }
12375       F.done();
12376 
12377       // Diagnose this MSVC extension in the easy case where lookup would have
12378       // unambiguously found something outside the enclosing namespace.
12379       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
12380         NamedDecl *ND = Previous.getFoundDecl();
12381         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
12382             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
12383       }
12384     }
12385 
12386     // Note:  there used to be some attempt at recovery here.
12387     if (Previous.isAmbiguous())
12388       return nullptr;
12389 
12390     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
12391       // FIXME: This makes sure that we ignore the contexts associated
12392       // with C structs, unions, and enums when looking for a matching
12393       // tag declaration or definition. See the similar lookup tweak
12394       // in Sema::LookupName; is there a better way to deal with this?
12395       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
12396         SearchDC = SearchDC->getParent();
12397     }
12398   }
12399 
12400   if (Previous.isSingleResult() &&
12401       Previous.getFoundDecl()->isTemplateParameter()) {
12402     // Maybe we will complain about the shadowed template parameter.
12403     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
12404     // Just pretend that we didn't see the previous declaration.
12405     Previous.clear();
12406   }
12407 
12408   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
12409       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
12410     // This is a declaration of or a reference to "std::bad_alloc".
12411     isStdBadAlloc = true;
12412 
12413     if (Previous.empty() && StdBadAlloc) {
12414       // std::bad_alloc has been implicitly declared (but made invisible to
12415       // name lookup). Fill in this implicit declaration as the previous
12416       // declaration, so that the declarations get chained appropriately.
12417       Previous.addDecl(getStdBadAlloc());
12418     }
12419   }
12420 
12421   // If we didn't find a previous declaration, and this is a reference
12422   // (or friend reference), move to the correct scope.  In C++, we
12423   // also need to do a redeclaration lookup there, just in case
12424   // there's a shadow friend decl.
12425   if (Name && Previous.empty() &&
12426       (TUK == TUK_Reference || TUK == TUK_Friend)) {
12427     if (Invalid) goto CreateNewDecl;
12428     assert(SS.isEmpty());
12429 
12430     if (TUK == TUK_Reference) {
12431       // C++ [basic.scope.pdecl]p5:
12432       //   -- for an elaborated-type-specifier of the form
12433       //
12434       //          class-key identifier
12435       //
12436       //      if the elaborated-type-specifier is used in the
12437       //      decl-specifier-seq or parameter-declaration-clause of a
12438       //      function defined in namespace scope, the identifier is
12439       //      declared as a class-name in the namespace that contains
12440       //      the declaration; otherwise, except as a friend
12441       //      declaration, the identifier is declared in the smallest
12442       //      non-class, non-function-prototype scope that contains the
12443       //      declaration.
12444       //
12445       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
12446       // C structs and unions.
12447       //
12448       // It is an error in C++ to declare (rather than define) an enum
12449       // type, including via an elaborated type specifier.  We'll
12450       // diagnose that later; for now, declare the enum in the same
12451       // scope as we would have picked for any other tag type.
12452       //
12453       // GNU C also supports this behavior as part of its incomplete
12454       // enum types extension, while GNU C++ does not.
12455       //
12456       // Find the context where we'll be declaring the tag.
12457       // FIXME: We would like to maintain the current DeclContext as the
12458       // lexical context,
12459       SearchDC = getTagInjectionContext(SearchDC);
12460 
12461       // Find the scope where we'll be declaring the tag.
12462       S = getTagInjectionScope(S, getLangOpts());
12463     } else {
12464       assert(TUK == TUK_Friend);
12465       // C++ [namespace.memdef]p3:
12466       //   If a friend declaration in a non-local class first declares a
12467       //   class or function, the friend class or function is a member of
12468       //   the innermost enclosing namespace.
12469       SearchDC = SearchDC->getEnclosingNamespaceContext();
12470     }
12471 
12472     // In C++, we need to do a redeclaration lookup to properly
12473     // diagnose some problems.
12474     // FIXME: redeclaration lookup is also used (with and without C++) to find a
12475     // hidden declaration so that we don't get ambiguity errors when using a
12476     // type declared by an elaborated-type-specifier.  In C that is not correct
12477     // and we should instead merge compatible types found by lookup.
12478     if (getLangOpts().CPlusPlus) {
12479       Previous.setRedeclarationKind(ForRedeclaration);
12480       LookupQualifiedName(Previous, SearchDC);
12481     } else {
12482       Previous.setRedeclarationKind(ForRedeclaration);
12483       LookupName(Previous, S);
12484     }
12485   }
12486 
12487   // If we have a known previous declaration to use, then use it.
12488   if (Previous.empty() && SkipBody && SkipBody->Previous)
12489     Previous.addDecl(SkipBody->Previous);
12490 
12491   if (!Previous.empty()) {
12492     NamedDecl *PrevDecl = Previous.getFoundDecl();
12493     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
12494 
12495     // It's okay to have a tag decl in the same scope as a typedef
12496     // which hides a tag decl in the same scope.  Finding this
12497     // insanity with a redeclaration lookup can only actually happen
12498     // in C++.
12499     //
12500     // This is also okay for elaborated-type-specifiers, which is
12501     // technically forbidden by the current standard but which is
12502     // okay according to the likely resolution of an open issue;
12503     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
12504     if (getLangOpts().CPlusPlus) {
12505       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12506         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
12507           TagDecl *Tag = TT->getDecl();
12508           if (Tag->getDeclName() == Name &&
12509               Tag->getDeclContext()->getRedeclContext()
12510                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
12511             PrevDecl = Tag;
12512             Previous.clear();
12513             Previous.addDecl(Tag);
12514             Previous.resolveKind();
12515           }
12516         }
12517       }
12518     }
12519 
12520     // If this is a redeclaration of a using shadow declaration, it must
12521     // declare a tag in the same context. In MSVC mode, we allow a
12522     // redefinition if either context is within the other.
12523     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
12524       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
12525       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
12526           isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
12527           !(OldTag && isAcceptableTagRedeclContext(
12528                           *this, OldTag->getDeclContext(), SearchDC))) {
12529         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
12530         Diag(Shadow->getTargetDecl()->getLocation(),
12531              diag::note_using_decl_target);
12532         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
12533             << 0;
12534         // Recover by ignoring the old declaration.
12535         Previous.clear();
12536         goto CreateNewDecl;
12537       }
12538     }
12539 
12540     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
12541       // If this is a use of a previous tag, or if the tag is already declared
12542       // in the same scope (so that the definition/declaration completes or
12543       // rementions the tag), reuse the decl.
12544       if (TUK == TUK_Reference || TUK == TUK_Friend ||
12545           isDeclInScope(DirectPrevDecl, SearchDC, S,
12546                         SS.isNotEmpty() || isExplicitSpecialization)) {
12547         // Make sure that this wasn't declared as an enum and now used as a
12548         // struct or something similar.
12549         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
12550                                           TUK == TUK_Definition, KWLoc,
12551                                           Name)) {
12552           bool SafeToContinue
12553             = (PrevTagDecl->getTagKind() != TTK_Enum &&
12554                Kind != TTK_Enum);
12555           if (SafeToContinue)
12556             Diag(KWLoc, diag::err_use_with_wrong_tag)
12557               << Name
12558               << FixItHint::CreateReplacement(SourceRange(KWLoc),
12559                                               PrevTagDecl->getKindName());
12560           else
12561             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
12562           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
12563 
12564           if (SafeToContinue)
12565             Kind = PrevTagDecl->getTagKind();
12566           else {
12567             // Recover by making this an anonymous redefinition.
12568             Name = nullptr;
12569             Previous.clear();
12570             Invalid = true;
12571           }
12572         }
12573 
12574         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
12575           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
12576 
12577           // If this is an elaborated-type-specifier for a scoped enumeration,
12578           // the 'class' keyword is not necessary and not permitted.
12579           if (TUK == TUK_Reference || TUK == TUK_Friend) {
12580             if (ScopedEnum)
12581               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
12582                 << PrevEnum->isScoped()
12583                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
12584             return PrevTagDecl;
12585           }
12586 
12587           QualType EnumUnderlyingTy;
12588           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12589             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
12590           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
12591             EnumUnderlyingTy = QualType(T, 0);
12592 
12593           // All conflicts with previous declarations are recovered by
12594           // returning the previous declaration, unless this is a definition,
12595           // in which case we want the caller to bail out.
12596           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
12597                                      ScopedEnum, EnumUnderlyingTy,
12598                                      EnumUnderlyingIsImplicit, PrevEnum))
12599             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
12600         }
12601 
12602         // C++11 [class.mem]p1:
12603         //   A member shall not be declared twice in the member-specification,
12604         //   except that a nested class or member class template can be declared
12605         //   and then later defined.
12606         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
12607             S->isDeclScope(PrevDecl)) {
12608           Diag(NameLoc, diag::ext_member_redeclared);
12609           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
12610         }
12611 
12612         if (!Invalid) {
12613           // If this is a use, just return the declaration we found, unless
12614           // we have attributes.
12615           if (TUK == TUK_Reference || TUK == TUK_Friend) {
12616             if (Attr) {
12617               // FIXME: Diagnose these attributes. For now, we create a new
12618               // declaration to hold them.
12619             } else if (TUK == TUK_Reference &&
12620                        (PrevTagDecl->getFriendObjectKind() ==
12621                             Decl::FOK_Undeclared ||
12622                         PP.getModuleContainingLocation(
12623                             PrevDecl->getLocation()) !=
12624                             PP.getModuleContainingLocation(KWLoc)) &&
12625                        SS.isEmpty()) {
12626               // This declaration is a reference to an existing entity, but
12627               // has different visibility from that entity: it either makes
12628               // a friend visible or it makes a type visible in a new module.
12629               // In either case, create a new declaration. We only do this if
12630               // the declaration would have meant the same thing if no prior
12631               // declaration were found, that is, if it was found in the same
12632               // scope where we would have injected a declaration.
12633               if (!getTagInjectionContext(CurContext)->getRedeclContext()
12634                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
12635                 return PrevTagDecl;
12636               // This is in the injected scope, create a new declaration in
12637               // that scope.
12638               S = getTagInjectionScope(S, getLangOpts());
12639             } else {
12640               return PrevTagDecl;
12641             }
12642           }
12643 
12644           // Diagnose attempts to redefine a tag.
12645           if (TUK == TUK_Definition) {
12646             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
12647               // If we're defining a specialization and the previous definition
12648               // is from an implicit instantiation, don't emit an error
12649               // here; we'll catch this in the general case below.
12650               bool IsExplicitSpecializationAfterInstantiation = false;
12651               if (isExplicitSpecialization) {
12652                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
12653                   IsExplicitSpecializationAfterInstantiation =
12654                     RD->getTemplateSpecializationKind() !=
12655                     TSK_ExplicitSpecialization;
12656                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
12657                   IsExplicitSpecializationAfterInstantiation =
12658                     ED->getTemplateSpecializationKind() !=
12659                     TSK_ExplicitSpecialization;
12660               }
12661 
12662               NamedDecl *Hidden = nullptr;
12663               if (SkipBody && getLangOpts().CPlusPlus &&
12664                   !hasVisibleDefinition(Def, &Hidden)) {
12665                 // There is a definition of this tag, but it is not visible. We
12666                 // explicitly make use of C++'s one definition rule here, and
12667                 // assume that this definition is identical to the hidden one
12668                 // we already have. Make the existing definition visible and
12669                 // use it in place of this one.
12670                 SkipBody->ShouldSkip = true;
12671                 makeMergedDefinitionVisible(Hidden, KWLoc);
12672                 return Def;
12673               } else if (!IsExplicitSpecializationAfterInstantiation) {
12674                 // A redeclaration in function prototype scope in C isn't
12675                 // visible elsewhere, so merely issue a warning.
12676                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
12677                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
12678                 else
12679                   Diag(NameLoc, diag::err_redefinition) << Name;
12680                 Diag(Def->getLocation(), diag::note_previous_definition);
12681                 // If this is a redefinition, recover by making this
12682                 // struct be anonymous, which will make any later
12683                 // references get the previous definition.
12684                 Name = nullptr;
12685                 Previous.clear();
12686                 Invalid = true;
12687               }
12688             } else {
12689               // If the type is currently being defined, complain
12690               // about a nested redefinition.
12691               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
12692               if (TD->isBeingDefined()) {
12693                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
12694                 Diag(PrevTagDecl->getLocation(),
12695                      diag::note_previous_definition);
12696                 Name = nullptr;
12697                 Previous.clear();
12698                 Invalid = true;
12699               }
12700             }
12701 
12702             // Okay, this is definition of a previously declared or referenced
12703             // tag. We're going to create a new Decl for it.
12704           }
12705 
12706           // Okay, we're going to make a redeclaration.  If this is some kind
12707           // of reference, make sure we build the redeclaration in the same DC
12708           // as the original, and ignore the current access specifier.
12709           if (TUK == TUK_Friend || TUK == TUK_Reference) {
12710             SearchDC = PrevTagDecl->getDeclContext();
12711             AS = AS_none;
12712           }
12713         }
12714         // If we get here we have (another) forward declaration or we
12715         // have a definition.  Just create a new decl.
12716 
12717       } else {
12718         // If we get here, this is a definition of a new tag type in a nested
12719         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
12720         // new decl/type.  We set PrevDecl to NULL so that the entities
12721         // have distinct types.
12722         Previous.clear();
12723       }
12724       // If we get here, we're going to create a new Decl. If PrevDecl
12725       // is non-NULL, it's a definition of the tag declared by
12726       // PrevDecl. If it's NULL, we have a new definition.
12727 
12728     // Otherwise, PrevDecl is not a tag, but was found with tag
12729     // lookup.  This is only actually possible in C++, where a few
12730     // things like templates still live in the tag namespace.
12731     } else {
12732       // Use a better diagnostic if an elaborated-type-specifier
12733       // found the wrong kind of type on the first
12734       // (non-redeclaration) lookup.
12735       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
12736           !Previous.isForRedeclaration()) {
12737         unsigned Kind = 0;
12738         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12739         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12740         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12741         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
12742         Diag(PrevDecl->getLocation(), diag::note_declared_at);
12743         Invalid = true;
12744 
12745       // Otherwise, only diagnose if the declaration is in scope.
12746       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
12747                                 SS.isNotEmpty() || isExplicitSpecialization)) {
12748         // do nothing
12749 
12750       // Diagnose implicit declarations introduced by elaborated types.
12751       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
12752         unsigned Kind = 0;
12753         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12754         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12755         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12756         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
12757         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12758         Invalid = true;
12759 
12760       // Otherwise it's a declaration.  Call out a particularly common
12761       // case here.
12762       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12763         unsigned Kind = 0;
12764         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
12765         Diag(NameLoc, diag::err_tag_definition_of_typedef)
12766           << Name << Kind << TND->getUnderlyingType();
12767         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12768         Invalid = true;
12769 
12770       // Otherwise, diagnose.
12771       } else {
12772         // The tag name clashes with something else in the target scope,
12773         // issue an error and recover by making this tag be anonymous.
12774         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
12775         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12776         Name = nullptr;
12777         Invalid = true;
12778       }
12779 
12780       // The existing declaration isn't relevant to us; we're in a
12781       // new scope, so clear out the previous declaration.
12782       Previous.clear();
12783     }
12784   }
12785 
12786 CreateNewDecl:
12787 
12788   TagDecl *PrevDecl = nullptr;
12789   if (Previous.isSingleResult())
12790     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
12791 
12792   // If there is an identifier, use the location of the identifier as the
12793   // location of the decl, otherwise use the location of the struct/union
12794   // keyword.
12795   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
12796 
12797   // Otherwise, create a new declaration. If there is a previous
12798   // declaration of the same entity, the two will be linked via
12799   // PrevDecl.
12800   TagDecl *New;
12801 
12802   bool IsForwardReference = false;
12803   if (Kind == TTK_Enum) {
12804     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12805     // enum X { A, B, C } D;    D should chain to X.
12806     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
12807                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
12808                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
12809     // If this is an undefined enum, warn.
12810     if (TUK != TUK_Definition && !Invalid) {
12811       TagDecl *Def;
12812       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
12813           cast<EnumDecl>(New)->isFixed()) {
12814         // C++0x: 7.2p2: opaque-enum-declaration.
12815         // Conflicts are diagnosed above. Do nothing.
12816       }
12817       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
12818         Diag(Loc, diag::ext_forward_ref_enum_def)
12819           << New;
12820         Diag(Def->getLocation(), diag::note_previous_definition);
12821       } else {
12822         unsigned DiagID = diag::ext_forward_ref_enum;
12823         if (getLangOpts().MSVCCompat)
12824           DiagID = diag::ext_ms_forward_ref_enum;
12825         else if (getLangOpts().CPlusPlus)
12826           DiagID = diag::err_forward_ref_enum;
12827         Diag(Loc, DiagID);
12828 
12829         // If this is a forward-declared reference to an enumeration, make a
12830         // note of it; we won't actually be introducing the declaration into
12831         // the declaration context.
12832         if (TUK == TUK_Reference)
12833           IsForwardReference = true;
12834       }
12835     }
12836 
12837     if (EnumUnderlying) {
12838       EnumDecl *ED = cast<EnumDecl>(New);
12839       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12840         ED->setIntegerTypeSourceInfo(TI);
12841       else
12842         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
12843       ED->setPromotionType(ED->getIntegerType());
12844     }
12845   } else {
12846     // struct/union/class
12847 
12848     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12849     // struct X { int A; } D;    D should chain to X.
12850     if (getLangOpts().CPlusPlus) {
12851       // FIXME: Look for a way to use RecordDecl for simple structs.
12852       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12853                                   cast_or_null<CXXRecordDecl>(PrevDecl));
12854 
12855       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
12856         StdBadAlloc = cast<CXXRecordDecl>(New);
12857     } else
12858       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12859                                cast_or_null<RecordDecl>(PrevDecl));
12860   }
12861 
12862   // C++11 [dcl.type]p3:
12863   //   A type-specifier-seq shall not define a class or enumeration [...].
12864   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
12865     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
12866       << Context.getTagDeclType(New);
12867     Invalid = true;
12868   }
12869 
12870   // Maybe add qualifier info.
12871   if (SS.isNotEmpty()) {
12872     if (SS.isSet()) {
12873       // If this is either a declaration or a definition, check the
12874       // nested-name-specifier against the current context. We don't do this
12875       // for explicit specializations, because they have similar checking
12876       // (with more specific diagnostics) in the call to
12877       // CheckMemberSpecialization, below.
12878       if (!isExplicitSpecialization &&
12879           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
12880           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
12881         Invalid = true;
12882 
12883       New->setQualifierInfo(SS.getWithLocInContext(Context));
12884       if (TemplateParameterLists.size() > 0) {
12885         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
12886       }
12887     }
12888     else
12889       Invalid = true;
12890   }
12891 
12892   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
12893     // Add alignment attributes if necessary; these attributes are checked when
12894     // the ASTContext lays out the structure.
12895     //
12896     // It is important for implementing the correct semantics that this
12897     // happen here (in act on tag decl). The #pragma pack stack is
12898     // maintained as a result of parser callbacks which can occur at
12899     // many points during the parsing of a struct declaration (because
12900     // the #pragma tokens are effectively skipped over during the
12901     // parsing of the struct).
12902     if (TUK == TUK_Definition) {
12903       AddAlignmentAttributesForRecord(RD);
12904       AddMsStructLayoutForRecord(RD);
12905     }
12906   }
12907 
12908   if (ModulePrivateLoc.isValid()) {
12909     if (isExplicitSpecialization)
12910       Diag(New->getLocation(), diag::err_module_private_specialization)
12911         << 2
12912         << FixItHint::CreateRemoval(ModulePrivateLoc);
12913     // __module_private__ does not apply to local classes. However, we only
12914     // diagnose this as an error when the declaration specifiers are
12915     // freestanding. Here, we just ignore the __module_private__.
12916     else if (!SearchDC->isFunctionOrMethod())
12917       New->setModulePrivate();
12918   }
12919 
12920   // If this is a specialization of a member class (of a class template),
12921   // check the specialization.
12922   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
12923     Invalid = true;
12924 
12925   // If we're declaring or defining a tag in function prototype scope in C,
12926   // note that this type can only be used within the function and add it to
12927   // the list of decls to inject into the function definition scope.
12928   if ((Name || Kind == TTK_Enum) &&
12929       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
12930     if (getLangOpts().CPlusPlus) {
12931       // C++ [dcl.fct]p6:
12932       //   Types shall not be defined in return or parameter types.
12933       if (TUK == TUK_Definition && !IsTypeSpecifier) {
12934         Diag(Loc, diag::err_type_defined_in_param_type)
12935             << Name;
12936         Invalid = true;
12937       }
12938     } else if (!PrevDecl) {
12939       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
12940     }
12941     DeclsInPrototypeScope.push_back(New);
12942   }
12943 
12944   if (Invalid)
12945     New->setInvalidDecl();
12946 
12947   if (Attr)
12948     ProcessDeclAttributeList(S, New, Attr);
12949 
12950   // Set the lexical context. If the tag has a C++ scope specifier, the
12951   // lexical context will be different from the semantic context.
12952   New->setLexicalDeclContext(CurContext);
12953 
12954   // Mark this as a friend decl if applicable.
12955   // In Microsoft mode, a friend declaration also acts as a forward
12956   // declaration so we always pass true to setObjectOfFriendDecl to make
12957   // the tag name visible.
12958   if (TUK == TUK_Friend)
12959     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
12960 
12961   // Set the access specifier.
12962   if (!Invalid && SearchDC->isRecord())
12963     SetMemberAccessSpecifier(New, PrevDecl, AS);
12964 
12965   if (TUK == TUK_Definition)
12966     New->startDefinition();
12967 
12968   // If this has an identifier, add it to the scope stack.
12969   if (TUK == TUK_Friend) {
12970     // We might be replacing an existing declaration in the lookup tables;
12971     // if so, borrow its access specifier.
12972     if (PrevDecl)
12973       New->setAccess(PrevDecl->getAccess());
12974 
12975     DeclContext *DC = New->getDeclContext()->getRedeclContext();
12976     DC->makeDeclVisibleInContext(New);
12977     if (Name) // can be null along some error paths
12978       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12979         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
12980   } else if (Name) {
12981     S = getNonFieldDeclScope(S);
12982     PushOnScopeChains(New, S, !IsForwardReference);
12983     if (IsForwardReference)
12984       SearchDC->makeDeclVisibleInContext(New);
12985   } else {
12986     CurContext->addDecl(New);
12987   }
12988 
12989   // If this is the C FILE type, notify the AST context.
12990   if (IdentifierInfo *II = New->getIdentifier())
12991     if (!New->isInvalidDecl() &&
12992         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
12993         II->isStr("FILE"))
12994       Context.setFILEDecl(New);
12995 
12996   if (PrevDecl)
12997     mergeDeclAttributes(New, PrevDecl);
12998 
12999   // If there's a #pragma GCC visibility in scope, set the visibility of this
13000   // record.
13001   AddPushedVisibilityAttribute(New);
13002 
13003   OwnedDecl = true;
13004   // In C++, don't return an invalid declaration. We can't recover well from
13005   // the cases where we make the type anonymous.
13006   return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
13007 }
13008 
13009 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
13010   AdjustDeclIfTemplate(TagD);
13011   TagDecl *Tag = cast<TagDecl>(TagD);
13012 
13013   // Enter the tag context.
13014   PushDeclContext(S, Tag);
13015 
13016   ActOnDocumentableDecl(TagD);
13017 
13018   // If there's a #pragma GCC visibility in scope, set the visibility of this
13019   // record.
13020   AddPushedVisibilityAttribute(Tag);
13021 }
13022 
13023 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
13024   assert(isa<ObjCContainerDecl>(IDecl) &&
13025          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
13026   DeclContext *OCD = cast<DeclContext>(IDecl);
13027   assert(getContainingDC(OCD) == CurContext &&
13028       "The next DeclContext should be lexically contained in the current one.");
13029   CurContext = OCD;
13030   return IDecl;
13031 }
13032 
13033 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
13034                                            SourceLocation FinalLoc,
13035                                            bool IsFinalSpelledSealed,
13036                                            SourceLocation LBraceLoc) {
13037   AdjustDeclIfTemplate(TagD);
13038   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
13039 
13040   FieldCollector->StartClass();
13041 
13042   if (!Record->getIdentifier())
13043     return;
13044 
13045   if (FinalLoc.isValid())
13046     Record->addAttr(new (Context)
13047                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
13048 
13049   // C++ [class]p2:
13050   //   [...] The class-name is also inserted into the scope of the
13051   //   class itself; this is known as the injected-class-name. For
13052   //   purposes of access checking, the injected-class-name is treated
13053   //   as if it were a public member name.
13054   CXXRecordDecl *InjectedClassName
13055     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
13056                             Record->getLocStart(), Record->getLocation(),
13057                             Record->getIdentifier(),
13058                             /*PrevDecl=*/nullptr,
13059                             /*DelayTypeCreation=*/true);
13060   Context.getTypeDeclType(InjectedClassName, Record);
13061   InjectedClassName->setImplicit();
13062   InjectedClassName->setAccess(AS_public);
13063   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
13064       InjectedClassName->setDescribedClassTemplate(Template);
13065   PushOnScopeChains(InjectedClassName, S);
13066   assert(InjectedClassName->isInjectedClassName() &&
13067          "Broken injected-class-name");
13068 }
13069 
13070 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
13071                                     SourceLocation RBraceLoc) {
13072   AdjustDeclIfTemplate(TagD);
13073   TagDecl *Tag = cast<TagDecl>(TagD);
13074   Tag->setRBraceLoc(RBraceLoc);
13075 
13076   // Make sure we "complete" the definition even it is invalid.
13077   if (Tag->isBeingDefined()) {
13078     assert(Tag->isInvalidDecl() && "We should already have completed it");
13079     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13080       RD->completeDefinition();
13081   }
13082 
13083   if (isa<CXXRecordDecl>(Tag))
13084     FieldCollector->FinishClass();
13085 
13086   // Exit this scope of this tag's definition.
13087   PopDeclContext();
13088 
13089   if (getCurLexicalContext()->isObjCContainer() &&
13090       Tag->getDeclContext()->isFileContext())
13091     Tag->setTopLevelDeclInObjCContainer();
13092 
13093   // Notify the consumer that we've defined a tag.
13094   if (!Tag->isInvalidDecl())
13095     Consumer.HandleTagDeclDefinition(Tag);
13096 }
13097 
13098 void Sema::ActOnObjCContainerFinishDefinition() {
13099   // Exit this scope of this interface definition.
13100   PopDeclContext();
13101 }
13102 
13103 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
13104   assert(DC == CurContext && "Mismatch of container contexts");
13105   OriginalLexicalContext = DC;
13106   ActOnObjCContainerFinishDefinition();
13107 }
13108 
13109 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
13110   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
13111   OriginalLexicalContext = nullptr;
13112 }
13113 
13114 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
13115   AdjustDeclIfTemplate(TagD);
13116   TagDecl *Tag = cast<TagDecl>(TagD);
13117   Tag->setInvalidDecl();
13118 
13119   // Make sure we "complete" the definition even it is invalid.
13120   if (Tag->isBeingDefined()) {
13121     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13122       RD->completeDefinition();
13123   }
13124 
13125   // We're undoing ActOnTagStartDefinition here, not
13126   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
13127   // the FieldCollector.
13128 
13129   PopDeclContext();
13130 }
13131 
13132 // Note that FieldName may be null for anonymous bitfields.
13133 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
13134                                 IdentifierInfo *FieldName,
13135                                 QualType FieldTy, bool IsMsStruct,
13136                                 Expr *BitWidth, bool *ZeroWidth) {
13137   // Default to true; that shouldn't confuse checks for emptiness
13138   if (ZeroWidth)
13139     *ZeroWidth = true;
13140 
13141   // C99 6.7.2.1p4 - verify the field type.
13142   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
13143   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
13144     // Handle incomplete types with specific error.
13145     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
13146       return ExprError();
13147     if (FieldName)
13148       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
13149         << FieldName << FieldTy << BitWidth->getSourceRange();
13150     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
13151       << FieldTy << BitWidth->getSourceRange();
13152   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
13153                                              UPPC_BitFieldWidth))
13154     return ExprError();
13155 
13156   // If the bit-width is type- or value-dependent, don't try to check
13157   // it now.
13158   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
13159     return BitWidth;
13160 
13161   llvm::APSInt Value;
13162   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
13163   if (ICE.isInvalid())
13164     return ICE;
13165   BitWidth = ICE.get();
13166 
13167   if (Value != 0 && ZeroWidth)
13168     *ZeroWidth = false;
13169 
13170   // Zero-width bitfield is ok for anonymous field.
13171   if (Value == 0 && FieldName)
13172     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
13173 
13174   if (Value.isSigned() && Value.isNegative()) {
13175     if (FieldName)
13176       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
13177                << FieldName << Value.toString(10);
13178     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
13179       << Value.toString(10);
13180   }
13181 
13182   if (!FieldTy->isDependentType()) {
13183     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
13184     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
13185     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
13186 
13187     // Over-wide bitfields are an error in C or when using the MSVC bitfield
13188     // ABI.
13189     bool CStdConstraintViolation =
13190         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
13191     bool MSBitfieldViolation =
13192         Value.ugt(TypeStorageSize) &&
13193         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
13194     if (CStdConstraintViolation || MSBitfieldViolation) {
13195       unsigned DiagWidth =
13196           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
13197       if (FieldName)
13198         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
13199                << FieldName << (unsigned)Value.getZExtValue()
13200                << !CStdConstraintViolation << DiagWidth;
13201 
13202       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
13203              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
13204              << DiagWidth;
13205     }
13206 
13207     // Warn on types where the user might conceivably expect to get all
13208     // specified bits as value bits: that's all integral types other than
13209     // 'bool'.
13210     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
13211       if (FieldName)
13212         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
13213             << FieldName << (unsigned)Value.getZExtValue()
13214             << (unsigned)TypeWidth;
13215       else
13216         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
13217             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
13218     }
13219   }
13220 
13221   return BitWidth;
13222 }
13223 
13224 /// ActOnField - Each field of a C struct/union is passed into this in order
13225 /// to create a FieldDecl object for it.
13226 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
13227                        Declarator &D, Expr *BitfieldWidth) {
13228   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
13229                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
13230                                /*InitStyle=*/ICIS_NoInit, AS_public);
13231   return Res;
13232 }
13233 
13234 /// HandleField - Analyze a field of a C struct or a C++ data member.
13235 ///
13236 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
13237                              SourceLocation DeclStart,
13238                              Declarator &D, Expr *BitWidth,
13239                              InClassInitStyle InitStyle,
13240                              AccessSpecifier AS) {
13241   IdentifierInfo *II = D.getIdentifier();
13242   SourceLocation Loc = DeclStart;
13243   if (II) Loc = D.getIdentifierLoc();
13244 
13245   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13246   QualType T = TInfo->getType();
13247   if (getLangOpts().CPlusPlus) {
13248     CheckExtraCXXDefaultArguments(D);
13249 
13250     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13251                                         UPPC_DataMemberType)) {
13252       D.setInvalidType();
13253       T = Context.IntTy;
13254       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13255     }
13256   }
13257 
13258   // TR 18037 does not allow fields to be declared with address spaces.
13259   if (T.getQualifiers().hasAddressSpace()) {
13260     Diag(Loc, diag::err_field_with_address_space);
13261     D.setInvalidType();
13262   }
13263 
13264   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
13265   // used as structure or union field: image, sampler, event or block types.
13266   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
13267                           T->isSamplerT() || T->isBlockPointerType())) {
13268     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
13269     D.setInvalidType();
13270   }
13271 
13272   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13273 
13274   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13275     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13276          diag::err_invalid_thread)
13277       << DeclSpec::getSpecifierName(TSCS);
13278 
13279   // Check to see if this name was declared as a member previously
13280   NamedDecl *PrevDecl = nullptr;
13281   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13282   LookupName(Previous, S);
13283   switch (Previous.getResultKind()) {
13284     case LookupResult::Found:
13285     case LookupResult::FoundUnresolvedValue:
13286       PrevDecl = Previous.getAsSingle<NamedDecl>();
13287       break;
13288 
13289     case LookupResult::FoundOverloaded:
13290       PrevDecl = Previous.getRepresentativeDecl();
13291       break;
13292 
13293     case LookupResult::NotFound:
13294     case LookupResult::NotFoundInCurrentInstantiation:
13295     case LookupResult::Ambiguous:
13296       break;
13297   }
13298   Previous.suppressDiagnostics();
13299 
13300   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13301     // Maybe we will complain about the shadowed template parameter.
13302     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13303     // Just pretend that we didn't see the previous declaration.
13304     PrevDecl = nullptr;
13305   }
13306 
13307   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13308     PrevDecl = nullptr;
13309 
13310   bool Mutable
13311     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
13312   SourceLocation TSSL = D.getLocStart();
13313   FieldDecl *NewFD
13314     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
13315                      TSSL, AS, PrevDecl, &D);
13316 
13317   if (NewFD->isInvalidDecl())
13318     Record->setInvalidDecl();
13319 
13320   if (D.getDeclSpec().isModulePrivateSpecified())
13321     NewFD->setModulePrivate();
13322 
13323   if (NewFD->isInvalidDecl() && PrevDecl) {
13324     // Don't introduce NewFD into scope; there's already something
13325     // with the same name in the same scope.
13326   } else if (II) {
13327     PushOnScopeChains(NewFD, S);
13328   } else
13329     Record->addDecl(NewFD);
13330 
13331   return NewFD;
13332 }
13333 
13334 /// \brief Build a new FieldDecl and check its well-formedness.
13335 ///
13336 /// This routine builds a new FieldDecl given the fields name, type,
13337 /// record, etc. \p PrevDecl should refer to any previous declaration
13338 /// with the same name and in the same scope as the field to be
13339 /// created.
13340 ///
13341 /// \returns a new FieldDecl.
13342 ///
13343 /// \todo The Declarator argument is a hack. It will be removed once
13344 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
13345                                 TypeSourceInfo *TInfo,
13346                                 RecordDecl *Record, SourceLocation Loc,
13347                                 bool Mutable, Expr *BitWidth,
13348                                 InClassInitStyle InitStyle,
13349                                 SourceLocation TSSL,
13350                                 AccessSpecifier AS, NamedDecl *PrevDecl,
13351                                 Declarator *D) {
13352   IdentifierInfo *II = Name.getAsIdentifierInfo();
13353   bool InvalidDecl = false;
13354   if (D) InvalidDecl = D->isInvalidType();
13355 
13356   // If we receive a broken type, recover by assuming 'int' and
13357   // marking this declaration as invalid.
13358   if (T.isNull()) {
13359     InvalidDecl = true;
13360     T = Context.IntTy;
13361   }
13362 
13363   QualType EltTy = Context.getBaseElementType(T);
13364   if (!EltTy->isDependentType()) {
13365     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
13366       // Fields of incomplete type force their record to be invalid.
13367       Record->setInvalidDecl();
13368       InvalidDecl = true;
13369     } else {
13370       NamedDecl *Def;
13371       EltTy->isIncompleteType(&Def);
13372       if (Def && Def->isInvalidDecl()) {
13373         Record->setInvalidDecl();
13374         InvalidDecl = true;
13375       }
13376     }
13377   }
13378 
13379   // OpenCL v1.2 s6.9.c: bitfields are not supported.
13380   if (BitWidth && getLangOpts().OpenCL) {
13381     Diag(Loc, diag::err_opencl_bitfields);
13382     InvalidDecl = true;
13383   }
13384 
13385   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13386   // than a variably modified type.
13387   if (!InvalidDecl && T->isVariablyModifiedType()) {
13388     bool SizeIsNegative;
13389     llvm::APSInt Oversized;
13390 
13391     TypeSourceInfo *FixedTInfo =
13392       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
13393                                                     SizeIsNegative,
13394                                                     Oversized);
13395     if (FixedTInfo) {
13396       Diag(Loc, diag::warn_illegal_constant_array_size);
13397       TInfo = FixedTInfo;
13398       T = FixedTInfo->getType();
13399     } else {
13400       if (SizeIsNegative)
13401         Diag(Loc, diag::err_typecheck_negative_array_size);
13402       else if (Oversized.getBoolValue())
13403         Diag(Loc, diag::err_array_too_large)
13404           << Oversized.toString(10);
13405       else
13406         Diag(Loc, diag::err_typecheck_field_variable_size);
13407       InvalidDecl = true;
13408     }
13409   }
13410 
13411   // Fields can not have abstract class types
13412   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
13413                                              diag::err_abstract_type_in_decl,
13414                                              AbstractFieldType))
13415     InvalidDecl = true;
13416 
13417   bool ZeroWidth = false;
13418   if (InvalidDecl)
13419     BitWidth = nullptr;
13420   // If this is declared as a bit-field, check the bit-field.
13421   if (BitWidth) {
13422     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
13423                               &ZeroWidth).get();
13424     if (!BitWidth) {
13425       InvalidDecl = true;
13426       BitWidth = nullptr;
13427       ZeroWidth = false;
13428     }
13429   }
13430 
13431   // Check that 'mutable' is consistent with the type of the declaration.
13432   if (!InvalidDecl && Mutable) {
13433     unsigned DiagID = 0;
13434     if (T->isReferenceType())
13435       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
13436                                         : diag::err_mutable_reference;
13437     else if (T.isConstQualified())
13438       DiagID = diag::err_mutable_const;
13439 
13440     if (DiagID) {
13441       SourceLocation ErrLoc = Loc;
13442       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
13443         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
13444       Diag(ErrLoc, DiagID);
13445       if (DiagID != diag::ext_mutable_reference) {
13446         Mutable = false;
13447         InvalidDecl = true;
13448       }
13449     }
13450   }
13451 
13452   // C++11 [class.union]p8 (DR1460):
13453   //   At most one variant member of a union may have a
13454   //   brace-or-equal-initializer.
13455   if (InitStyle != ICIS_NoInit)
13456     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
13457 
13458   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
13459                                        BitWidth, Mutable, InitStyle);
13460   if (InvalidDecl)
13461     NewFD->setInvalidDecl();
13462 
13463   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
13464     Diag(Loc, diag::err_duplicate_member) << II;
13465     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13466     NewFD->setInvalidDecl();
13467   }
13468 
13469   if (!InvalidDecl && getLangOpts().CPlusPlus) {
13470     if (Record->isUnion()) {
13471       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13472         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
13473         if (RDecl->getDefinition()) {
13474           // C++ [class.union]p1: An object of a class with a non-trivial
13475           // constructor, a non-trivial copy constructor, a non-trivial
13476           // destructor, or a non-trivial copy assignment operator
13477           // cannot be a member of a union, nor can an array of such
13478           // objects.
13479           if (CheckNontrivialField(NewFD))
13480             NewFD->setInvalidDecl();
13481         }
13482       }
13483 
13484       // C++ [class.union]p1: If a union contains a member of reference type,
13485       // the program is ill-formed, except when compiling with MSVC extensions
13486       // enabled.
13487       if (EltTy->isReferenceType()) {
13488         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
13489                                     diag::ext_union_member_of_reference_type :
13490                                     diag::err_union_member_of_reference_type)
13491           << NewFD->getDeclName() << EltTy;
13492         if (!getLangOpts().MicrosoftExt)
13493           NewFD->setInvalidDecl();
13494       }
13495     }
13496   }
13497 
13498   // FIXME: We need to pass in the attributes given an AST
13499   // representation, not a parser representation.
13500   if (D) {
13501     // FIXME: The current scope is almost... but not entirely... correct here.
13502     ProcessDeclAttributes(getCurScope(), NewFD, *D);
13503 
13504     if (NewFD->hasAttrs())
13505       CheckAlignasUnderalignment(NewFD);
13506   }
13507 
13508   // In auto-retain/release, infer strong retension for fields of
13509   // retainable type.
13510   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
13511     NewFD->setInvalidDecl();
13512 
13513   if (T.isObjCGCWeak())
13514     Diag(Loc, diag::warn_attribute_weak_on_field);
13515 
13516   NewFD->setAccess(AS);
13517   return NewFD;
13518 }
13519 
13520 bool Sema::CheckNontrivialField(FieldDecl *FD) {
13521   assert(FD);
13522   assert(getLangOpts().CPlusPlus && "valid check only for C++");
13523 
13524   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
13525     return false;
13526 
13527   QualType EltTy = Context.getBaseElementType(FD->getType());
13528   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13529     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
13530     if (RDecl->getDefinition()) {
13531       // We check for copy constructors before constructors
13532       // because otherwise we'll never get complaints about
13533       // copy constructors.
13534 
13535       CXXSpecialMember member = CXXInvalid;
13536       // We're required to check for any non-trivial constructors. Since the
13537       // implicit default constructor is suppressed if there are any
13538       // user-declared constructors, we just need to check that there is a
13539       // trivial default constructor and a trivial copy constructor. (We don't
13540       // worry about move constructors here, since this is a C++98 check.)
13541       if (RDecl->hasNonTrivialCopyConstructor())
13542         member = CXXCopyConstructor;
13543       else if (!RDecl->hasTrivialDefaultConstructor())
13544         member = CXXDefaultConstructor;
13545       else if (RDecl->hasNonTrivialCopyAssignment())
13546         member = CXXCopyAssignment;
13547       else if (RDecl->hasNonTrivialDestructor())
13548         member = CXXDestructor;
13549 
13550       if (member != CXXInvalid) {
13551         if (!getLangOpts().CPlusPlus11 &&
13552             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
13553           // Objective-C++ ARC: it is an error to have a non-trivial field of
13554           // a union. However, system headers in Objective-C programs
13555           // occasionally have Objective-C lifetime objects within unions,
13556           // and rather than cause the program to fail, we make those
13557           // members unavailable.
13558           SourceLocation Loc = FD->getLocation();
13559           if (getSourceManager().isInSystemHeader(Loc)) {
13560             if (!FD->hasAttr<UnavailableAttr>())
13561               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13562                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
13563             return false;
13564           }
13565         }
13566 
13567         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
13568                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
13569                diag::err_illegal_union_or_anon_struct_member)
13570           << FD->getParent()->isUnion() << FD->getDeclName() << member;
13571         DiagnoseNontrivial(RDecl, member);
13572         return !getLangOpts().CPlusPlus11;
13573       }
13574     }
13575   }
13576 
13577   return false;
13578 }
13579 
13580 /// TranslateIvarVisibility - Translate visibility from a token ID to an
13581 ///  AST enum value.
13582 static ObjCIvarDecl::AccessControl
13583 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
13584   switch (ivarVisibility) {
13585   default: llvm_unreachable("Unknown visitibility kind");
13586   case tok::objc_private: return ObjCIvarDecl::Private;
13587   case tok::objc_public: return ObjCIvarDecl::Public;
13588   case tok::objc_protected: return ObjCIvarDecl::Protected;
13589   case tok::objc_package: return ObjCIvarDecl::Package;
13590   }
13591 }
13592 
13593 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
13594 /// in order to create an IvarDecl object for it.
13595 Decl *Sema::ActOnIvar(Scope *S,
13596                                 SourceLocation DeclStart,
13597                                 Declarator &D, Expr *BitfieldWidth,
13598                                 tok::ObjCKeywordKind Visibility) {
13599 
13600   IdentifierInfo *II = D.getIdentifier();
13601   Expr *BitWidth = (Expr*)BitfieldWidth;
13602   SourceLocation Loc = DeclStart;
13603   if (II) Loc = D.getIdentifierLoc();
13604 
13605   // FIXME: Unnamed fields can be handled in various different ways, for
13606   // example, unnamed unions inject all members into the struct namespace!
13607 
13608   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13609   QualType T = TInfo->getType();
13610 
13611   if (BitWidth) {
13612     // 6.7.2.1p3, 6.7.2.1p4
13613     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
13614     if (!BitWidth)
13615       D.setInvalidType();
13616   } else {
13617     // Not a bitfield.
13618 
13619     // validate II.
13620 
13621   }
13622   if (T->isReferenceType()) {
13623     Diag(Loc, diag::err_ivar_reference_type);
13624     D.setInvalidType();
13625   }
13626   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13627   // than a variably modified type.
13628   else if (T->isVariablyModifiedType()) {
13629     Diag(Loc, diag::err_typecheck_ivar_variable_size);
13630     D.setInvalidType();
13631   }
13632 
13633   // Get the visibility (access control) for this ivar.
13634   ObjCIvarDecl::AccessControl ac =
13635     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
13636                                         : ObjCIvarDecl::None;
13637   // Must set ivar's DeclContext to its enclosing interface.
13638   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
13639   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
13640     return nullptr;
13641   ObjCContainerDecl *EnclosingContext;
13642   if (ObjCImplementationDecl *IMPDecl =
13643       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13644     if (LangOpts.ObjCRuntime.isFragile()) {
13645     // Case of ivar declared in an implementation. Context is that of its class.
13646       EnclosingContext = IMPDecl->getClassInterface();
13647       assert(EnclosingContext && "Implementation has no class interface!");
13648     }
13649     else
13650       EnclosingContext = EnclosingDecl;
13651   } else {
13652     if (ObjCCategoryDecl *CDecl =
13653         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13654       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
13655         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
13656         return nullptr;
13657       }
13658     }
13659     EnclosingContext = EnclosingDecl;
13660   }
13661 
13662   // Construct the decl.
13663   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
13664                                              DeclStart, Loc, II, T,
13665                                              TInfo, ac, (Expr *)BitfieldWidth);
13666 
13667   if (II) {
13668     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
13669                                            ForRedeclaration);
13670     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
13671         && !isa<TagDecl>(PrevDecl)) {
13672       Diag(Loc, diag::err_duplicate_member) << II;
13673       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13674       NewID->setInvalidDecl();
13675     }
13676   }
13677 
13678   // Process attributes attached to the ivar.
13679   ProcessDeclAttributes(S, NewID, D);
13680 
13681   if (D.isInvalidType())
13682     NewID->setInvalidDecl();
13683 
13684   // In ARC, infer 'retaining' for ivars of retainable type.
13685   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
13686     NewID->setInvalidDecl();
13687 
13688   if (D.getDeclSpec().isModulePrivateSpecified())
13689     NewID->setModulePrivate();
13690 
13691   if (II) {
13692     // FIXME: When interfaces are DeclContexts, we'll need to add
13693     // these to the interface.
13694     S->AddDecl(NewID);
13695     IdResolver.AddDecl(NewID);
13696   }
13697 
13698   if (LangOpts.ObjCRuntime.isNonFragile() &&
13699       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
13700     Diag(Loc, diag::warn_ivars_in_interface);
13701 
13702   return NewID;
13703 }
13704 
13705 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
13706 /// class and class extensions. For every class \@interface and class
13707 /// extension \@interface, if the last ivar is a bitfield of any type,
13708 /// then add an implicit `char :0` ivar to the end of that interface.
13709 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
13710                              SmallVectorImpl<Decl *> &AllIvarDecls) {
13711   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
13712     return;
13713 
13714   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
13715   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
13716 
13717   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
13718     return;
13719   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
13720   if (!ID) {
13721     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
13722       if (!CD->IsClassExtension())
13723         return;
13724     }
13725     // No need to add this to end of @implementation.
13726     else
13727       return;
13728   }
13729   // All conditions are met. Add a new bitfield to the tail end of ivars.
13730   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
13731   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
13732 
13733   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
13734                               DeclLoc, DeclLoc, nullptr,
13735                               Context.CharTy,
13736                               Context.getTrivialTypeSourceInfo(Context.CharTy,
13737                                                                DeclLoc),
13738                               ObjCIvarDecl::Private, BW,
13739                               true);
13740   AllIvarDecls.push_back(Ivar);
13741 }
13742 
13743 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
13744                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
13745                        SourceLocation RBrac, AttributeList *Attr) {
13746   assert(EnclosingDecl && "missing record or interface decl");
13747 
13748   // If this is an Objective-C @implementation or category and we have
13749   // new fields here we should reset the layout of the interface since
13750   // it will now change.
13751   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
13752     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
13753     switch (DC->getKind()) {
13754     default: break;
13755     case Decl::ObjCCategory:
13756       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
13757       break;
13758     case Decl::ObjCImplementation:
13759       Context.
13760         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
13761       break;
13762     }
13763   }
13764 
13765   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
13766 
13767   // Start counting up the number of named members; make sure to include
13768   // members of anonymous structs and unions in the total.
13769   unsigned NumNamedMembers = 0;
13770   if (Record) {
13771     for (const auto *I : Record->decls()) {
13772       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
13773         if (IFD->getDeclName())
13774           ++NumNamedMembers;
13775     }
13776   }
13777 
13778   // Verify that all the fields are okay.
13779   SmallVector<FieldDecl*, 32> RecFields;
13780 
13781   bool ARCErrReported = false;
13782   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
13783        i != end; ++i) {
13784     FieldDecl *FD = cast<FieldDecl>(*i);
13785 
13786     // Get the type for the field.
13787     const Type *FDTy = FD->getType().getTypePtr();
13788 
13789     if (!FD->isAnonymousStructOrUnion()) {
13790       // Remember all fields written by the user.
13791       RecFields.push_back(FD);
13792     }
13793 
13794     // If the field is already invalid for some reason, don't emit more
13795     // diagnostics about it.
13796     if (FD->isInvalidDecl()) {
13797       EnclosingDecl->setInvalidDecl();
13798       continue;
13799     }
13800 
13801     // C99 6.7.2.1p2:
13802     //   A structure or union shall not contain a member with
13803     //   incomplete or function type (hence, a structure shall not
13804     //   contain an instance of itself, but may contain a pointer to
13805     //   an instance of itself), except that the last member of a
13806     //   structure with more than one named member may have incomplete
13807     //   array type; such a structure (and any union containing,
13808     //   possibly recursively, a member that is such a structure)
13809     //   shall not be a member of a structure or an element of an
13810     //   array.
13811     if (FDTy->isFunctionType()) {
13812       // Field declared as a function.
13813       Diag(FD->getLocation(), diag::err_field_declared_as_function)
13814         << FD->getDeclName();
13815       FD->setInvalidDecl();
13816       EnclosingDecl->setInvalidDecl();
13817       continue;
13818     } else if (FDTy->isIncompleteArrayType() && Record &&
13819                ((i + 1 == Fields.end() && !Record->isUnion()) ||
13820                 ((getLangOpts().MicrosoftExt ||
13821                   getLangOpts().CPlusPlus) &&
13822                  (i + 1 == Fields.end() || Record->isUnion())))) {
13823       // Flexible array member.
13824       // Microsoft and g++ is more permissive regarding flexible array.
13825       // It will accept flexible array in union and also
13826       // as the sole element of a struct/class.
13827       unsigned DiagID = 0;
13828       if (Record->isUnion())
13829         DiagID = getLangOpts().MicrosoftExt
13830                      ? diag::ext_flexible_array_union_ms
13831                      : getLangOpts().CPlusPlus
13832                            ? diag::ext_flexible_array_union_gnu
13833                            : diag::err_flexible_array_union;
13834       else if (Fields.size() == 1)
13835         DiagID = getLangOpts().MicrosoftExt
13836                      ? diag::ext_flexible_array_empty_aggregate_ms
13837                      : getLangOpts().CPlusPlus
13838                            ? diag::ext_flexible_array_empty_aggregate_gnu
13839                            : NumNamedMembers < 1
13840                                  ? diag::err_flexible_array_empty_aggregate
13841                                  : 0;
13842 
13843       if (DiagID)
13844         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
13845                                         << Record->getTagKind();
13846       // While the layout of types that contain virtual bases is not specified
13847       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
13848       // virtual bases after the derived members.  This would make a flexible
13849       // array member declared at the end of an object not adjacent to the end
13850       // of the type.
13851       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
13852         if (RD->getNumVBases() != 0)
13853           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
13854             << FD->getDeclName() << Record->getTagKind();
13855       if (!getLangOpts().C99)
13856         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
13857           << FD->getDeclName() << Record->getTagKind();
13858 
13859       // If the element type has a non-trivial destructor, we would not
13860       // implicitly destroy the elements, so disallow it for now.
13861       //
13862       // FIXME: GCC allows this. We should probably either implicitly delete
13863       // the destructor of the containing class, or just allow this.
13864       QualType BaseElem = Context.getBaseElementType(FD->getType());
13865       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
13866         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
13867           << FD->getDeclName() << FD->getType();
13868         FD->setInvalidDecl();
13869         EnclosingDecl->setInvalidDecl();
13870         continue;
13871       }
13872       // Okay, we have a legal flexible array member at the end of the struct.
13873       Record->setHasFlexibleArrayMember(true);
13874     } else if (!FDTy->isDependentType() &&
13875                RequireCompleteType(FD->getLocation(), FD->getType(),
13876                                    diag::err_field_incomplete)) {
13877       // Incomplete type
13878       FD->setInvalidDecl();
13879       EnclosingDecl->setInvalidDecl();
13880       continue;
13881     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
13882       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
13883         // A type which contains a flexible array member is considered to be a
13884         // flexible array member.
13885         Record->setHasFlexibleArrayMember(true);
13886         if (!Record->isUnion()) {
13887           // If this is a struct/class and this is not the last element, reject
13888           // it.  Note that GCC supports variable sized arrays in the middle of
13889           // structures.
13890           if (i + 1 != Fields.end())
13891             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
13892               << FD->getDeclName() << FD->getType();
13893           else {
13894             // We support flexible arrays at the end of structs in
13895             // other structs as an extension.
13896             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
13897               << FD->getDeclName();
13898           }
13899         }
13900       }
13901       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
13902           RequireNonAbstractType(FD->getLocation(), FD->getType(),
13903                                  diag::err_abstract_type_in_decl,
13904                                  AbstractIvarType)) {
13905         // Ivars can not have abstract class types
13906         FD->setInvalidDecl();
13907       }
13908       if (Record && FDTTy->getDecl()->hasObjectMember())
13909         Record->setHasObjectMember(true);
13910       if (Record && FDTTy->getDecl()->hasVolatileMember())
13911         Record->setHasVolatileMember(true);
13912     } else if (FDTy->isObjCObjectType()) {
13913       /// A field cannot be an Objective-c object
13914       Diag(FD->getLocation(), diag::err_statically_allocated_object)
13915         << FixItHint::CreateInsertion(FD->getLocation(), "*");
13916       QualType T = Context.getObjCObjectPointerType(FD->getType());
13917       FD->setType(T);
13918     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
13919                (!getLangOpts().CPlusPlus || Record->isUnion())) {
13920       // It's an error in ARC if a field has lifetime.
13921       // We don't want to report this in a system header, though,
13922       // so we just make the field unavailable.
13923       // FIXME: that's really not sufficient; we need to make the type
13924       // itself invalid to, say, initialize or copy.
13925       QualType T = FD->getType();
13926       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
13927       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
13928         SourceLocation loc = FD->getLocation();
13929         if (getSourceManager().isInSystemHeader(loc)) {
13930           if (!FD->hasAttr<UnavailableAttr>()) {
13931             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13932                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
13933           }
13934         } else {
13935           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
13936             << T->isBlockPointerType() << Record->getTagKind();
13937         }
13938         ARCErrReported = true;
13939       }
13940     } else if (getLangOpts().ObjC1 &&
13941                getLangOpts().getGC() != LangOptions::NonGC &&
13942                Record && !Record->hasObjectMember()) {
13943       if (FD->getType()->isObjCObjectPointerType() ||
13944           FD->getType().isObjCGCStrong())
13945         Record->setHasObjectMember(true);
13946       else if (Context.getAsArrayType(FD->getType())) {
13947         QualType BaseType = Context.getBaseElementType(FD->getType());
13948         if (BaseType->isRecordType() &&
13949             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
13950           Record->setHasObjectMember(true);
13951         else if (BaseType->isObjCObjectPointerType() ||
13952                  BaseType.isObjCGCStrong())
13953                Record->setHasObjectMember(true);
13954       }
13955     }
13956     if (Record && FD->getType().isVolatileQualified())
13957       Record->setHasVolatileMember(true);
13958     // Keep track of the number of named members.
13959     if (FD->getIdentifier())
13960       ++NumNamedMembers;
13961   }
13962 
13963   // Okay, we successfully defined 'Record'.
13964   if (Record) {
13965     bool Completed = false;
13966     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
13967       if (!CXXRecord->isInvalidDecl()) {
13968         // Set access bits correctly on the directly-declared conversions.
13969         for (CXXRecordDecl::conversion_iterator
13970                I = CXXRecord->conversion_begin(),
13971                E = CXXRecord->conversion_end(); I != E; ++I)
13972           I.setAccess((*I)->getAccess());
13973       }
13974 
13975       if (!CXXRecord->isDependentType()) {
13976         if (CXXRecord->hasUserDeclaredDestructor()) {
13977           // Adjust user-defined destructor exception spec.
13978           if (getLangOpts().CPlusPlus11)
13979             AdjustDestructorExceptionSpec(CXXRecord,
13980                                           CXXRecord->getDestructor());
13981         }
13982 
13983         if (!CXXRecord->isInvalidDecl()) {
13984           // Add any implicitly-declared members to this class.
13985           AddImplicitlyDeclaredMembersToClass(CXXRecord);
13986 
13987           // If we have virtual base classes, we may end up finding multiple
13988           // final overriders for a given virtual function. Check for this
13989           // problem now.
13990           if (CXXRecord->getNumVBases()) {
13991             CXXFinalOverriderMap FinalOverriders;
13992             CXXRecord->getFinalOverriders(FinalOverriders);
13993 
13994             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
13995                                              MEnd = FinalOverriders.end();
13996                  M != MEnd; ++M) {
13997               for (OverridingMethods::iterator SO = M->second.begin(),
13998                                             SOEnd = M->second.end();
13999                    SO != SOEnd; ++SO) {
14000                 assert(SO->second.size() > 0 &&
14001                        "Virtual function without overridding functions?");
14002                 if (SO->second.size() == 1)
14003                   continue;
14004 
14005                 // C++ [class.virtual]p2:
14006                 //   In a derived class, if a virtual member function of a base
14007                 //   class subobject has more than one final overrider the
14008                 //   program is ill-formed.
14009                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
14010                   << (const NamedDecl *)M->first << Record;
14011                 Diag(M->first->getLocation(),
14012                      diag::note_overridden_virtual_function);
14013                 for (OverridingMethods::overriding_iterator
14014                           OM = SO->second.begin(),
14015                        OMEnd = SO->second.end();
14016                      OM != OMEnd; ++OM)
14017                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
14018                     << (const NamedDecl *)M->first << OM->Method->getParent();
14019 
14020                 Record->setInvalidDecl();
14021               }
14022             }
14023             CXXRecord->completeDefinition(&FinalOverriders);
14024             Completed = true;
14025           }
14026         }
14027       }
14028     }
14029 
14030     if (!Completed)
14031       Record->completeDefinition();
14032 
14033     if (Record->hasAttrs()) {
14034       CheckAlignasUnderalignment(Record);
14035 
14036       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
14037         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
14038                                            IA->getRange(), IA->getBestCase(),
14039                                            IA->getSemanticSpelling());
14040     }
14041 
14042     // Check if the structure/union declaration is a type that can have zero
14043     // size in C. For C this is a language extension, for C++ it may cause
14044     // compatibility problems.
14045     bool CheckForZeroSize;
14046     if (!getLangOpts().CPlusPlus) {
14047       CheckForZeroSize = true;
14048     } else {
14049       // For C++ filter out types that cannot be referenced in C code.
14050       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
14051       CheckForZeroSize =
14052           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
14053           !CXXRecord->isDependentType() &&
14054           CXXRecord->isCLike();
14055     }
14056     if (CheckForZeroSize) {
14057       bool ZeroSize = true;
14058       bool IsEmpty = true;
14059       unsigned NonBitFields = 0;
14060       for (RecordDecl::field_iterator I = Record->field_begin(),
14061                                       E = Record->field_end();
14062            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
14063         IsEmpty = false;
14064         if (I->isUnnamedBitfield()) {
14065           if (I->getBitWidthValue(Context) > 0)
14066             ZeroSize = false;
14067         } else {
14068           ++NonBitFields;
14069           QualType FieldType = I->getType();
14070           if (FieldType->isIncompleteType() ||
14071               !Context.getTypeSizeInChars(FieldType).isZero())
14072             ZeroSize = false;
14073         }
14074       }
14075 
14076       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
14077       // allowed in C++, but warn if its declaration is inside
14078       // extern "C" block.
14079       if (ZeroSize) {
14080         Diag(RecLoc, getLangOpts().CPlusPlus ?
14081                          diag::warn_zero_size_struct_union_in_extern_c :
14082                          diag::warn_zero_size_struct_union_compat)
14083           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
14084       }
14085 
14086       // Structs without named members are extension in C (C99 6.7.2.1p7),
14087       // but are accepted by GCC.
14088       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
14089         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
14090                                diag::ext_no_named_members_in_struct_union)
14091           << Record->isUnion();
14092       }
14093     }
14094   } else {
14095     ObjCIvarDecl **ClsFields =
14096       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
14097     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
14098       ID->setEndOfDefinitionLoc(RBrac);
14099       // Add ivar's to class's DeclContext.
14100       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14101         ClsFields[i]->setLexicalDeclContext(ID);
14102         ID->addDecl(ClsFields[i]);
14103       }
14104       // Must enforce the rule that ivars in the base classes may not be
14105       // duplicates.
14106       if (ID->getSuperClass())
14107         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
14108     } else if (ObjCImplementationDecl *IMPDecl =
14109                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14110       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
14111       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
14112         // Ivar declared in @implementation never belongs to the implementation.
14113         // Only it is in implementation's lexical context.
14114         ClsFields[I]->setLexicalDeclContext(IMPDecl);
14115       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
14116       IMPDecl->setIvarLBraceLoc(LBrac);
14117       IMPDecl->setIvarRBraceLoc(RBrac);
14118     } else if (ObjCCategoryDecl *CDecl =
14119                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14120       // case of ivars in class extension; all other cases have been
14121       // reported as errors elsewhere.
14122       // FIXME. Class extension does not have a LocEnd field.
14123       // CDecl->setLocEnd(RBrac);
14124       // Add ivar's to class extension's DeclContext.
14125       // Diagnose redeclaration of private ivars.
14126       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
14127       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14128         if (IDecl) {
14129           if (const ObjCIvarDecl *ClsIvar =
14130               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
14131             Diag(ClsFields[i]->getLocation(),
14132                  diag::err_duplicate_ivar_declaration);
14133             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
14134             continue;
14135           }
14136           for (const auto *Ext : IDecl->known_extensions()) {
14137             if (const ObjCIvarDecl *ClsExtIvar
14138                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
14139               Diag(ClsFields[i]->getLocation(),
14140                    diag::err_duplicate_ivar_declaration);
14141               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
14142               continue;
14143             }
14144           }
14145         }
14146         ClsFields[i]->setLexicalDeclContext(CDecl);
14147         CDecl->addDecl(ClsFields[i]);
14148       }
14149       CDecl->setIvarLBraceLoc(LBrac);
14150       CDecl->setIvarRBraceLoc(RBrac);
14151     }
14152   }
14153 
14154   if (Attr)
14155     ProcessDeclAttributeList(S, Record, Attr);
14156 }
14157 
14158 /// \brief Determine whether the given integral value is representable within
14159 /// the given type T.
14160 static bool isRepresentableIntegerValue(ASTContext &Context,
14161                                         llvm::APSInt &Value,
14162                                         QualType T) {
14163   assert(T->isIntegralType(Context) && "Integral type required!");
14164   unsigned BitWidth = Context.getIntWidth(T);
14165 
14166   if (Value.isUnsigned() || Value.isNonNegative()) {
14167     if (T->isSignedIntegerOrEnumerationType())
14168       --BitWidth;
14169     return Value.getActiveBits() <= BitWidth;
14170   }
14171   return Value.getMinSignedBits() <= BitWidth;
14172 }
14173 
14174 // \brief Given an integral type, return the next larger integral type
14175 // (or a NULL type of no such type exists).
14176 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
14177   // FIXME: Int128/UInt128 support, which also needs to be introduced into
14178   // enum checking below.
14179   assert(T->isIntegralType(Context) && "Integral type required!");
14180   const unsigned NumTypes = 4;
14181   QualType SignedIntegralTypes[NumTypes] = {
14182     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
14183   };
14184   QualType UnsignedIntegralTypes[NumTypes] = {
14185     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
14186     Context.UnsignedLongLongTy
14187   };
14188 
14189   unsigned BitWidth = Context.getTypeSize(T);
14190   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
14191                                                         : UnsignedIntegralTypes;
14192   for (unsigned I = 0; I != NumTypes; ++I)
14193     if (Context.getTypeSize(Types[I]) > BitWidth)
14194       return Types[I];
14195 
14196   return QualType();
14197 }
14198 
14199 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
14200                                           EnumConstantDecl *LastEnumConst,
14201                                           SourceLocation IdLoc,
14202                                           IdentifierInfo *Id,
14203                                           Expr *Val) {
14204   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14205   llvm::APSInt EnumVal(IntWidth);
14206   QualType EltTy;
14207 
14208   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
14209     Val = nullptr;
14210 
14211   if (Val)
14212     Val = DefaultLvalueConversion(Val).get();
14213 
14214   if (Val) {
14215     if (Enum->isDependentType() || Val->isTypeDependent())
14216       EltTy = Context.DependentTy;
14217     else {
14218       SourceLocation ExpLoc;
14219       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
14220           !getLangOpts().MSVCCompat) {
14221         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
14222         // constant-expression in the enumerator-definition shall be a converted
14223         // constant expression of the underlying type.
14224         EltTy = Enum->getIntegerType();
14225         ExprResult Converted =
14226           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
14227                                            CCEK_Enumerator);
14228         if (Converted.isInvalid())
14229           Val = nullptr;
14230         else
14231           Val = Converted.get();
14232       } else if (!Val->isValueDependent() &&
14233                  !(Val = VerifyIntegerConstantExpression(Val,
14234                                                          &EnumVal).get())) {
14235         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
14236       } else {
14237         if (Enum->isFixed()) {
14238           EltTy = Enum->getIntegerType();
14239 
14240           // In Obj-C and Microsoft mode, require the enumeration value to be
14241           // representable in the underlying type of the enumeration. In C++11,
14242           // we perform a non-narrowing conversion as part of converted constant
14243           // expression checking.
14244           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14245             if (getLangOpts().MSVCCompat) {
14246               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
14247               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
14248             } else
14249               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
14250           } else
14251             Val = ImpCastExprToType(Val, EltTy,
14252                                     EltTy->isBooleanType() ?
14253                                     CK_IntegralToBoolean : CK_IntegralCast)
14254                     .get();
14255         } else if (getLangOpts().CPlusPlus) {
14256           // C++11 [dcl.enum]p5:
14257           //   If the underlying type is not fixed, the type of each enumerator
14258           //   is the type of its initializing value:
14259           //     - If an initializer is specified for an enumerator, the
14260           //       initializing value has the same type as the expression.
14261           EltTy = Val->getType();
14262         } else {
14263           // C99 6.7.2.2p2:
14264           //   The expression that defines the value of an enumeration constant
14265           //   shall be an integer constant expression that has a value
14266           //   representable as an int.
14267 
14268           // Complain if the value is not representable in an int.
14269           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
14270             Diag(IdLoc, diag::ext_enum_value_not_int)
14271               << EnumVal.toString(10) << Val->getSourceRange()
14272               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
14273           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
14274             // Force the type of the expression to 'int'.
14275             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
14276           }
14277           EltTy = Val->getType();
14278         }
14279       }
14280     }
14281   }
14282 
14283   if (!Val) {
14284     if (Enum->isDependentType())
14285       EltTy = Context.DependentTy;
14286     else if (!LastEnumConst) {
14287       // C++0x [dcl.enum]p5:
14288       //   If the underlying type is not fixed, the type of each enumerator
14289       //   is the type of its initializing value:
14290       //     - If no initializer is specified for the first enumerator, the
14291       //       initializing value has an unspecified integral type.
14292       //
14293       // GCC uses 'int' for its unspecified integral type, as does
14294       // C99 6.7.2.2p3.
14295       if (Enum->isFixed()) {
14296         EltTy = Enum->getIntegerType();
14297       }
14298       else {
14299         EltTy = Context.IntTy;
14300       }
14301     } else {
14302       // Assign the last value + 1.
14303       EnumVal = LastEnumConst->getInitVal();
14304       ++EnumVal;
14305       EltTy = LastEnumConst->getType();
14306 
14307       // Check for overflow on increment.
14308       if (EnumVal < LastEnumConst->getInitVal()) {
14309         // C++0x [dcl.enum]p5:
14310         //   If the underlying type is not fixed, the type of each enumerator
14311         //   is the type of its initializing value:
14312         //
14313         //     - Otherwise the type of the initializing value is the same as
14314         //       the type of the initializing value of the preceding enumerator
14315         //       unless the incremented value is not representable in that type,
14316         //       in which case the type is an unspecified integral type
14317         //       sufficient to contain the incremented value. If no such type
14318         //       exists, the program is ill-formed.
14319         QualType T = getNextLargerIntegralType(Context, EltTy);
14320         if (T.isNull() || Enum->isFixed()) {
14321           // There is no integral type larger enough to represent this
14322           // value. Complain, then allow the value to wrap around.
14323           EnumVal = LastEnumConst->getInitVal();
14324           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
14325           ++EnumVal;
14326           if (Enum->isFixed())
14327             // When the underlying type is fixed, this is ill-formed.
14328             Diag(IdLoc, diag::err_enumerator_wrapped)
14329               << EnumVal.toString(10)
14330               << EltTy;
14331           else
14332             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
14333               << EnumVal.toString(10);
14334         } else {
14335           EltTy = T;
14336         }
14337 
14338         // Retrieve the last enumerator's value, extent that type to the
14339         // type that is supposed to be large enough to represent the incremented
14340         // value, then increment.
14341         EnumVal = LastEnumConst->getInitVal();
14342         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14343         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
14344         ++EnumVal;
14345 
14346         // If we're not in C++, diagnose the overflow of enumerator values,
14347         // which in C99 means that the enumerator value is not representable in
14348         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
14349         // permits enumerator values that are representable in some larger
14350         // integral type.
14351         if (!getLangOpts().CPlusPlus && !T.isNull())
14352           Diag(IdLoc, diag::warn_enum_value_overflow);
14353       } else if (!getLangOpts().CPlusPlus &&
14354                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14355         // Enforce C99 6.7.2.2p2 even when we compute the next value.
14356         Diag(IdLoc, diag::ext_enum_value_not_int)
14357           << EnumVal.toString(10) << 1;
14358       }
14359     }
14360   }
14361 
14362   if (!EltTy->isDependentType()) {
14363     // Make the enumerator value match the signedness and size of the
14364     // enumerator's type.
14365     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
14366     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14367   }
14368 
14369   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
14370                                   Val, EnumVal);
14371 }
14372 
14373 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
14374                                                 SourceLocation IILoc) {
14375   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
14376       !getLangOpts().CPlusPlus)
14377     return SkipBodyInfo();
14378 
14379   // We have an anonymous enum definition. Look up the first enumerator to
14380   // determine if we should merge the definition with an existing one and
14381   // skip the body.
14382   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
14383                                          ForRedeclaration);
14384   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
14385   if (!PrevECD)
14386     return SkipBodyInfo();
14387 
14388   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
14389   NamedDecl *Hidden;
14390   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
14391     SkipBodyInfo Skip;
14392     Skip.Previous = Hidden;
14393     return Skip;
14394   }
14395 
14396   return SkipBodyInfo();
14397 }
14398 
14399 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
14400                               SourceLocation IdLoc, IdentifierInfo *Id,
14401                               AttributeList *Attr,
14402                               SourceLocation EqualLoc, Expr *Val) {
14403   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
14404   EnumConstantDecl *LastEnumConst =
14405     cast_or_null<EnumConstantDecl>(lastEnumConst);
14406 
14407   // The scope passed in may not be a decl scope.  Zip up the scope tree until
14408   // we find one that is.
14409   S = getNonFieldDeclScope(S);
14410 
14411   // Verify that there isn't already something declared with this name in this
14412   // scope.
14413   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
14414                                          ForRedeclaration);
14415   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14416     // Maybe we will complain about the shadowed template parameter.
14417     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
14418     // Just pretend that we didn't see the previous declaration.
14419     PrevDecl = nullptr;
14420   }
14421 
14422   // C++ [class.mem]p15:
14423   // If T is the name of a class, then each of the following shall have a name
14424   // different from T:
14425   // - every enumerator of every member of class T that is an unscoped
14426   // enumerated type
14427   if (!TheEnumDecl->isScoped())
14428     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
14429                             DeclarationNameInfo(Id, IdLoc));
14430 
14431   EnumConstantDecl *New =
14432     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
14433   if (!New)
14434     return nullptr;
14435 
14436   if (PrevDecl) {
14437     // When in C++, we may get a TagDecl with the same name; in this case the
14438     // enum constant will 'hide' the tag.
14439     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
14440            "Received TagDecl when not in C++!");
14441     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
14442         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
14443       if (isa<EnumConstantDecl>(PrevDecl))
14444         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
14445       else
14446         Diag(IdLoc, diag::err_redefinition) << Id;
14447       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14448       return nullptr;
14449     }
14450   }
14451 
14452   // Process attributes.
14453   if (Attr) ProcessDeclAttributeList(S, New, Attr);
14454 
14455   // Register this decl in the current scope stack.
14456   New->setAccess(TheEnumDecl->getAccess());
14457   PushOnScopeChains(New, S);
14458 
14459   ActOnDocumentableDecl(New);
14460 
14461   return New;
14462 }
14463 
14464 // Returns true when the enum initial expression does not trigger the
14465 // duplicate enum warning.  A few common cases are exempted as follows:
14466 // Element2 = Element1
14467 // Element2 = Element1 + 1
14468 // Element2 = Element1 - 1
14469 // Where Element2 and Element1 are from the same enum.
14470 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
14471   Expr *InitExpr = ECD->getInitExpr();
14472   if (!InitExpr)
14473     return true;
14474   InitExpr = InitExpr->IgnoreImpCasts();
14475 
14476   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
14477     if (!BO->isAdditiveOp())
14478       return true;
14479     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
14480     if (!IL)
14481       return true;
14482     if (IL->getValue() != 1)
14483       return true;
14484 
14485     InitExpr = BO->getLHS();
14486   }
14487 
14488   // This checks if the elements are from the same enum.
14489   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
14490   if (!DRE)
14491     return true;
14492 
14493   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
14494   if (!EnumConstant)
14495     return true;
14496 
14497   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
14498       Enum)
14499     return true;
14500 
14501   return false;
14502 }
14503 
14504 namespace {
14505 struct DupKey {
14506   int64_t val;
14507   bool isTombstoneOrEmptyKey;
14508   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
14509     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
14510 };
14511 
14512 static DupKey GetDupKey(const llvm::APSInt& Val) {
14513   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
14514                 false);
14515 }
14516 
14517 struct DenseMapInfoDupKey {
14518   static DupKey getEmptyKey() { return DupKey(0, true); }
14519   static DupKey getTombstoneKey() { return DupKey(1, true); }
14520   static unsigned getHashValue(const DupKey Key) {
14521     return (unsigned)(Key.val * 37);
14522   }
14523   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
14524     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
14525            LHS.val == RHS.val;
14526   }
14527 };
14528 } // end anonymous namespace
14529 
14530 // Emits a warning when an element is implicitly set a value that
14531 // a previous element has already been set to.
14532 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
14533                                         EnumDecl *Enum,
14534                                         QualType EnumType) {
14535   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
14536     return;
14537   // Avoid anonymous enums
14538   if (!Enum->getIdentifier())
14539     return;
14540 
14541   // Only check for small enums.
14542   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
14543     return;
14544 
14545   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
14546   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
14547 
14548   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
14549   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
14550           ValueToVectorMap;
14551 
14552   DuplicatesVector DupVector;
14553   ValueToVectorMap EnumMap;
14554 
14555   // Populate the EnumMap with all values represented by enum constants without
14556   // an initialier.
14557   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14558     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
14559 
14560     // Null EnumConstantDecl means a previous diagnostic has been emitted for
14561     // this constant.  Skip this enum since it may be ill-formed.
14562     if (!ECD) {
14563       return;
14564     }
14565 
14566     if (ECD->getInitExpr())
14567       continue;
14568 
14569     DupKey Key = GetDupKey(ECD->getInitVal());
14570     DeclOrVector &Entry = EnumMap[Key];
14571 
14572     // First time encountering this value.
14573     if (Entry.isNull())
14574       Entry = ECD;
14575   }
14576 
14577   // Create vectors for any values that has duplicates.
14578   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14579     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
14580     if (!ValidDuplicateEnum(ECD, Enum))
14581       continue;
14582 
14583     DupKey Key = GetDupKey(ECD->getInitVal());
14584 
14585     DeclOrVector& Entry = EnumMap[Key];
14586     if (Entry.isNull())
14587       continue;
14588 
14589     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
14590       // Ensure constants are different.
14591       if (D == ECD)
14592         continue;
14593 
14594       // Create new vector and push values onto it.
14595       ECDVector *Vec = new ECDVector();
14596       Vec->push_back(D);
14597       Vec->push_back(ECD);
14598 
14599       // Update entry to point to the duplicates vector.
14600       Entry = Vec;
14601 
14602       // Store the vector somewhere we can consult later for quick emission of
14603       // diagnostics.
14604       DupVector.push_back(Vec);
14605       continue;
14606     }
14607 
14608     ECDVector *Vec = Entry.get<ECDVector*>();
14609     // Make sure constants are not added more than once.
14610     if (*Vec->begin() == ECD)
14611       continue;
14612 
14613     Vec->push_back(ECD);
14614   }
14615 
14616   // Emit diagnostics.
14617   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
14618                                   DupVectorEnd = DupVector.end();
14619        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
14620     ECDVector *Vec = *DupVectorIter;
14621     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
14622 
14623     // Emit warning for one enum constant.
14624     ECDVector::iterator I = Vec->begin();
14625     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
14626       << (*I)->getName() << (*I)->getInitVal().toString(10)
14627       << (*I)->getSourceRange();
14628     ++I;
14629 
14630     // Emit one note for each of the remaining enum constants with
14631     // the same value.
14632     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
14633       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
14634         << (*I)->getName() << (*I)->getInitVal().toString(10)
14635         << (*I)->getSourceRange();
14636     delete Vec;
14637   }
14638 }
14639 
14640 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
14641                              bool AllowMask) const {
14642   assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
14643   assert(ED->isCompleteDefinition() && "expected enum definition");
14644 
14645   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
14646   llvm::APInt &FlagBits = R.first->second;
14647 
14648   if (R.second) {
14649     for (auto *E : ED->enumerators()) {
14650       const auto &EVal = E->getInitVal();
14651       // Only single-bit enumerators introduce new flag values.
14652       if (EVal.isPowerOf2())
14653         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
14654     }
14655   }
14656 
14657   // A value is in a flag enum if either its bits are a subset of the enum's
14658   // flag bits (the first condition) or we are allowing masks and the same is
14659   // true of its complement (the second condition). When masks are allowed, we
14660   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
14661   //
14662   // While it's true that any value could be used as a mask, the assumption is
14663   // that a mask will have all of the insignificant bits set. Anything else is
14664   // likely a logic error.
14665   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
14666   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
14667 }
14668 
14669 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
14670                          SourceLocation RBraceLoc, Decl *EnumDeclX,
14671                          ArrayRef<Decl *> Elements,
14672                          Scope *S, AttributeList *Attr) {
14673   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
14674   QualType EnumType = Context.getTypeDeclType(Enum);
14675 
14676   if (Attr)
14677     ProcessDeclAttributeList(S, Enum, Attr);
14678 
14679   if (Enum->isDependentType()) {
14680     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14681       EnumConstantDecl *ECD =
14682         cast_or_null<EnumConstantDecl>(Elements[i]);
14683       if (!ECD) continue;
14684 
14685       ECD->setType(EnumType);
14686     }
14687 
14688     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
14689     return;
14690   }
14691 
14692   // TODO: If the result value doesn't fit in an int, it must be a long or long
14693   // long value.  ISO C does not support this, but GCC does as an extension,
14694   // emit a warning.
14695   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14696   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
14697   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
14698 
14699   // Verify that all the values are okay, compute the size of the values, and
14700   // reverse the list.
14701   unsigned NumNegativeBits = 0;
14702   unsigned NumPositiveBits = 0;
14703 
14704   // Keep track of whether all elements have type int.
14705   bool AllElementsInt = true;
14706 
14707   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14708     EnumConstantDecl *ECD =
14709       cast_or_null<EnumConstantDecl>(Elements[i]);
14710     if (!ECD) continue;  // Already issued a diagnostic.
14711 
14712     const llvm::APSInt &InitVal = ECD->getInitVal();
14713 
14714     // Keep track of the size of positive and negative values.
14715     if (InitVal.isUnsigned() || InitVal.isNonNegative())
14716       NumPositiveBits = std::max(NumPositiveBits,
14717                                  (unsigned)InitVal.getActiveBits());
14718     else
14719       NumNegativeBits = std::max(NumNegativeBits,
14720                                  (unsigned)InitVal.getMinSignedBits());
14721 
14722     // Keep track of whether every enum element has type int (very commmon).
14723     if (AllElementsInt)
14724       AllElementsInt = ECD->getType() == Context.IntTy;
14725   }
14726 
14727   // Figure out the type that should be used for this enum.
14728   QualType BestType;
14729   unsigned BestWidth;
14730 
14731   // C++0x N3000 [conv.prom]p3:
14732   //   An rvalue of an unscoped enumeration type whose underlying
14733   //   type is not fixed can be converted to an rvalue of the first
14734   //   of the following types that can represent all the values of
14735   //   the enumeration: int, unsigned int, long int, unsigned long
14736   //   int, long long int, or unsigned long long int.
14737   // C99 6.4.4.3p2:
14738   //   An identifier declared as an enumeration constant has type int.
14739   // The C99 rule is modified by a gcc extension
14740   QualType BestPromotionType;
14741 
14742   bool Packed = Enum->hasAttr<PackedAttr>();
14743   // -fshort-enums is the equivalent to specifying the packed attribute on all
14744   // enum definitions.
14745   if (LangOpts.ShortEnums)
14746     Packed = true;
14747 
14748   if (Enum->isFixed()) {
14749     BestType = Enum->getIntegerType();
14750     if (BestType->isPromotableIntegerType())
14751       BestPromotionType = Context.getPromotedIntegerType(BestType);
14752     else
14753       BestPromotionType = BestType;
14754 
14755     BestWidth = Context.getIntWidth(BestType);
14756   }
14757   else if (NumNegativeBits) {
14758     // If there is a negative value, figure out the smallest integer type (of
14759     // int/long/longlong) that fits.
14760     // If it's packed, check also if it fits a char or a short.
14761     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
14762       BestType = Context.SignedCharTy;
14763       BestWidth = CharWidth;
14764     } else if (Packed && NumNegativeBits <= ShortWidth &&
14765                NumPositiveBits < ShortWidth) {
14766       BestType = Context.ShortTy;
14767       BestWidth = ShortWidth;
14768     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
14769       BestType = Context.IntTy;
14770       BestWidth = IntWidth;
14771     } else {
14772       BestWidth = Context.getTargetInfo().getLongWidth();
14773 
14774       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
14775         BestType = Context.LongTy;
14776       } else {
14777         BestWidth = Context.getTargetInfo().getLongLongWidth();
14778 
14779         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
14780           Diag(Enum->getLocation(), diag::ext_enum_too_large);
14781         BestType = Context.LongLongTy;
14782       }
14783     }
14784     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
14785   } else {
14786     // If there is no negative value, figure out the smallest type that fits
14787     // all of the enumerator values.
14788     // If it's packed, check also if it fits a char or a short.
14789     if (Packed && NumPositiveBits <= CharWidth) {
14790       BestType = Context.UnsignedCharTy;
14791       BestPromotionType = Context.IntTy;
14792       BestWidth = CharWidth;
14793     } else if (Packed && NumPositiveBits <= ShortWidth) {
14794       BestType = Context.UnsignedShortTy;
14795       BestPromotionType = Context.IntTy;
14796       BestWidth = ShortWidth;
14797     } else if (NumPositiveBits <= IntWidth) {
14798       BestType = Context.UnsignedIntTy;
14799       BestWidth = IntWidth;
14800       BestPromotionType
14801         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14802                            ? Context.UnsignedIntTy : Context.IntTy;
14803     } else if (NumPositiveBits <=
14804                (BestWidth = Context.getTargetInfo().getLongWidth())) {
14805       BestType = Context.UnsignedLongTy;
14806       BestPromotionType
14807         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14808                            ? Context.UnsignedLongTy : Context.LongTy;
14809     } else {
14810       BestWidth = Context.getTargetInfo().getLongLongWidth();
14811       assert(NumPositiveBits <= BestWidth &&
14812              "How could an initializer get larger than ULL?");
14813       BestType = Context.UnsignedLongLongTy;
14814       BestPromotionType
14815         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14816                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
14817     }
14818   }
14819 
14820   // Loop over all of the enumerator constants, changing their types to match
14821   // the type of the enum if needed.
14822   for (auto *D : Elements) {
14823     auto *ECD = cast_or_null<EnumConstantDecl>(D);
14824     if (!ECD) continue;  // Already issued a diagnostic.
14825 
14826     // Standard C says the enumerators have int type, but we allow, as an
14827     // extension, the enumerators to be larger than int size.  If each
14828     // enumerator value fits in an int, type it as an int, otherwise type it the
14829     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
14830     // that X has type 'int', not 'unsigned'.
14831 
14832     // Determine whether the value fits into an int.
14833     llvm::APSInt InitVal = ECD->getInitVal();
14834 
14835     // If it fits into an integer type, force it.  Otherwise force it to match
14836     // the enum decl type.
14837     QualType NewTy;
14838     unsigned NewWidth;
14839     bool NewSign;
14840     if (!getLangOpts().CPlusPlus &&
14841         !Enum->isFixed() &&
14842         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
14843       NewTy = Context.IntTy;
14844       NewWidth = IntWidth;
14845       NewSign = true;
14846     } else if (ECD->getType() == BestType) {
14847       // Already the right type!
14848       if (getLangOpts().CPlusPlus)
14849         // C++ [dcl.enum]p4: Following the closing brace of an
14850         // enum-specifier, each enumerator has the type of its
14851         // enumeration.
14852         ECD->setType(EnumType);
14853       continue;
14854     } else {
14855       NewTy = BestType;
14856       NewWidth = BestWidth;
14857       NewSign = BestType->isSignedIntegerOrEnumerationType();
14858     }
14859 
14860     // Adjust the APSInt value.
14861     InitVal = InitVal.extOrTrunc(NewWidth);
14862     InitVal.setIsSigned(NewSign);
14863     ECD->setInitVal(InitVal);
14864 
14865     // Adjust the Expr initializer and type.
14866     if (ECD->getInitExpr() &&
14867         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
14868       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
14869                                                 CK_IntegralCast,
14870                                                 ECD->getInitExpr(),
14871                                                 /*base paths*/ nullptr,
14872                                                 VK_RValue));
14873     if (getLangOpts().CPlusPlus)
14874       // C++ [dcl.enum]p4: Following the closing brace of an
14875       // enum-specifier, each enumerator has the type of its
14876       // enumeration.
14877       ECD->setType(EnumType);
14878     else
14879       ECD->setType(NewTy);
14880   }
14881 
14882   Enum->completeDefinition(BestType, BestPromotionType,
14883                            NumPositiveBits, NumNegativeBits);
14884 
14885   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
14886 
14887   if (Enum->hasAttr<FlagEnumAttr>()) {
14888     for (Decl *D : Elements) {
14889       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
14890       if (!ECD) continue;  // Already issued a diagnostic.
14891 
14892       llvm::APSInt InitVal = ECD->getInitVal();
14893       if (InitVal != 0 && !InitVal.isPowerOf2() &&
14894           !IsValueInFlagEnum(Enum, InitVal, true))
14895         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
14896           << ECD << Enum;
14897     }
14898   }
14899 
14900   // Now that the enum type is defined, ensure it's not been underaligned.
14901   if (Enum->hasAttrs())
14902     CheckAlignasUnderalignment(Enum);
14903 }
14904 
14905 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
14906                                   SourceLocation StartLoc,
14907                                   SourceLocation EndLoc) {
14908   StringLiteral *AsmString = cast<StringLiteral>(expr);
14909 
14910   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
14911                                                    AsmString, StartLoc,
14912                                                    EndLoc);
14913   CurContext->addDecl(New);
14914   return New;
14915 }
14916 
14917 static void checkModuleImportContext(Sema &S, Module *M,
14918                                      SourceLocation ImportLoc, DeclContext *DC,
14919                                      bool FromInclude = false) {
14920   SourceLocation ExternCLoc;
14921 
14922   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
14923     switch (LSD->getLanguage()) {
14924     case LinkageSpecDecl::lang_c:
14925       if (ExternCLoc.isInvalid())
14926         ExternCLoc = LSD->getLocStart();
14927       break;
14928     case LinkageSpecDecl::lang_cxx:
14929       break;
14930     }
14931     DC = LSD->getParent();
14932   }
14933 
14934   while (isa<LinkageSpecDecl>(DC))
14935     DC = DC->getParent();
14936 
14937   if (!isa<TranslationUnitDecl>(DC)) {
14938     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
14939                           ? diag::ext_module_import_not_at_top_level_noop
14940                           : diag::err_module_import_not_at_top_level_fatal)
14941         << M->getFullModuleName() << DC;
14942     S.Diag(cast<Decl>(DC)->getLocStart(),
14943            diag::note_module_import_not_at_top_level) << DC;
14944   } else if (!M->IsExternC && ExternCLoc.isValid()) {
14945     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
14946       << M->getFullModuleName();
14947     S.Diag(ExternCLoc, diag::note_module_import_in_extern_c);
14948   }
14949 }
14950 
14951 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) {
14952   return checkModuleImportContext(*this, M, ImportLoc, CurContext);
14953 }
14954 
14955 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
14956                                    SourceLocation ImportLoc,
14957                                    ModuleIdPath Path) {
14958   Module *Mod =
14959       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
14960                                    /*IsIncludeDirective=*/false);
14961   if (!Mod)
14962     return true;
14963 
14964   VisibleModules.setVisible(Mod, ImportLoc);
14965 
14966   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
14967 
14968   // FIXME: we should support importing a submodule within a different submodule
14969   // of the same top-level module. Until we do, make it an error rather than
14970   // silently ignoring the import.
14971   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
14972     Diag(ImportLoc, getLangOpts().CompilingModule
14973                         ? diag::err_module_self_import
14974                         : diag::err_module_import_in_implementation)
14975         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
14976 
14977   SmallVector<SourceLocation, 2> IdentifierLocs;
14978   Module *ModCheck = Mod;
14979   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
14980     // If we've run out of module parents, just drop the remaining identifiers.
14981     // We need the length to be consistent.
14982     if (!ModCheck)
14983       break;
14984     ModCheck = ModCheck->Parent;
14985 
14986     IdentifierLocs.push_back(Path[I].second);
14987   }
14988 
14989   ImportDecl *Import = ImportDecl::Create(Context,
14990                                           Context.getTranslationUnitDecl(),
14991                                           AtLoc.isValid()? AtLoc : ImportLoc,
14992                                           Mod, IdentifierLocs);
14993   Context.getTranslationUnitDecl()->addDecl(Import);
14994   return Import;
14995 }
14996 
14997 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
14998   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
14999 
15000   // Determine whether we're in the #include buffer for a module. The #includes
15001   // in that buffer do not qualify as module imports; they're just an
15002   // implementation detail of us building the module.
15003   //
15004   // FIXME: Should we even get ActOnModuleInclude calls for those?
15005   bool IsInModuleIncludes =
15006       TUKind == TU_Module &&
15007       getSourceManager().isWrittenInMainFile(DirectiveLoc);
15008 
15009   // Similarly, if we're in the implementation of a module, don't
15010   // synthesize an illegal module import. FIXME: Why not?
15011   bool ShouldAddImport =
15012       !IsInModuleIncludes &&
15013       (getLangOpts().CompilingModule ||
15014        getLangOpts().CurrentModule.empty() ||
15015        getLangOpts().CurrentModule != Mod->getTopLevelModuleName());
15016 
15017   // If this module import was due to an inclusion directive, create an
15018   // implicit import declaration to capture it in the AST.
15019   if (ShouldAddImport) {
15020     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15021     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15022                                                      DirectiveLoc, Mod,
15023                                                      DirectiveLoc);
15024     TU->addDecl(ImportD);
15025     Consumer.HandleImplicitImportDecl(ImportD);
15026   }
15027 
15028   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
15029   VisibleModules.setVisible(Mod, DirectiveLoc);
15030 }
15031 
15032 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
15033   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
15034 
15035   if (getLangOpts().ModulesLocalVisibility)
15036     VisibleModulesStack.push_back(std::move(VisibleModules));
15037   VisibleModules.setVisible(Mod, DirectiveLoc);
15038 }
15039 
15040 void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) {
15041   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
15042 
15043   if (getLangOpts().ModulesLocalVisibility) {
15044     VisibleModules = std::move(VisibleModulesStack.back());
15045     VisibleModulesStack.pop_back();
15046     VisibleModules.setVisible(Mod, DirectiveLoc);
15047     // Leaving a module hides namespace names, so our visible namespace cache
15048     // is now out of date.
15049     VisibleNamespaceCache.clear();
15050   }
15051 }
15052 
15053 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
15054                                                       Module *Mod) {
15055   // Bail if we're not allowed to implicitly import a module here.
15056   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
15057     return;
15058 
15059   // Create the implicit import declaration.
15060   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15061   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15062                                                    Loc, Mod, Loc);
15063   TU->addDecl(ImportD);
15064   Consumer.HandleImplicitImportDecl(ImportD);
15065 
15066   // Make the module visible.
15067   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
15068   VisibleModules.setVisible(Mod, Loc);
15069 }
15070 
15071 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
15072                                       IdentifierInfo* AliasName,
15073                                       SourceLocation PragmaLoc,
15074                                       SourceLocation NameLoc,
15075                                       SourceLocation AliasNameLoc) {
15076   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
15077                                          LookupOrdinaryName);
15078   AsmLabelAttr *Attr =
15079       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
15080 
15081   // If a declaration that:
15082   // 1) declares a function or a variable
15083   // 2) has external linkage
15084   // already exists, add a label attribute to it.
15085   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15086     if (isDeclExternC(PrevDecl))
15087       PrevDecl->addAttr(Attr);
15088     else
15089       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
15090           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
15091   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
15092   } else
15093     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
15094 }
15095 
15096 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
15097                              SourceLocation PragmaLoc,
15098                              SourceLocation NameLoc) {
15099   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
15100 
15101   if (PrevDecl) {
15102     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
15103   } else {
15104     (void)WeakUndeclaredIdentifiers.insert(
15105       std::pair<IdentifierInfo*,WeakInfo>
15106         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
15107   }
15108 }
15109 
15110 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
15111                                 IdentifierInfo* AliasName,
15112                                 SourceLocation PragmaLoc,
15113                                 SourceLocation NameLoc,
15114                                 SourceLocation AliasNameLoc) {
15115   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
15116                                     LookupOrdinaryName);
15117   WeakInfo W = WeakInfo(Name, NameLoc);
15118 
15119   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15120     if (!PrevDecl->hasAttr<AliasAttr>())
15121       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
15122         DeclApplyPragmaWeak(TUScope, ND, W);
15123   } else {
15124     (void)WeakUndeclaredIdentifiers.insert(
15125       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
15126   }
15127 }
15128 
15129 Decl *Sema::getObjCDeclContext() const {
15130   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
15131 }
15132 
15133 AvailabilityResult Sema::getCurContextAvailability() const {
15134   const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
15135   if (!D)
15136     return AR_Available;
15137 
15138   // If we are within an Objective-C method, we should consult
15139   // both the availability of the method as well as the
15140   // enclosing class.  If the class is (say) deprecated,
15141   // the entire method is considered deprecated from the
15142   // purpose of checking if the current context is deprecated.
15143   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
15144     AvailabilityResult R = MD->getAvailability();
15145     if (R != AR_Available)
15146       return R;
15147     D = MD->getClassInterface();
15148   }
15149   // If we are within an Objective-c @implementation, it
15150   // gets the same availability context as the @interface.
15151   else if (const ObjCImplementationDecl *ID =
15152             dyn_cast<ObjCImplementationDecl>(D)) {
15153     D = ID->getClassInterface();
15154   }
15155   // Recover from user error.
15156   return D ? D->getAvailability() : AR_Available;
15157 }
15158